Open History to see the last commit
1import { requireSettingsSecretLiteral, SourceControlProviderKind } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import {
6 GraphQL,
7 GraphQLClient,
8 GraphQLClientError,
9 GraphQLGroup,
10 GraphQLResolver,
11} from "effect/graphql";
12import * as Option from "effect/Option";
13import * as RequestResolver from "effect/RequestResolver";
14import * as Result from "effect/Result";
15import * as Schema from "effect/Schema";
16import {
17 SourceControlProviderError,
18 TrimmedNonEmptyString,
19 type ChangeRequest,
20 type SourceControlProviderDiscoveryItem,
21 type SourceControlRepositoryCloneUrls,
22} from "@t3tools/contracts";
23import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
24import * as HostProcess from "@t3tools/shared/HostProcess";
25import { decodeJsonResult } from "@t3tools/shared/schemaJson";
26import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
27
28import { GH_PROCESS_CONCURRENCY } from "./GitHubCredentials.ts";
29import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
30import * as GitHubRest from "./GitHubRest.ts";
31import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
32import * as GitHubChangeRequestTemplate from "./gitHubChangeRequestTemplate.ts";
33import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
34import {
35 normalizeGitHubPullRequestRecord,
36 type NormalizedGitHubPullRequestRecord,
37} from "./gitHubPullRequests.ts";
38import {
39 gitHubApiHostForRemote,
40 parseFetchRemotes,
41 parseGitHubRepositorySelector,
42 parsePullRequestReference,
43 resolveGitHubRepository,
44 type GitHubRepositoryLocator,
45} from "./gitHubRepositoryResolution.ts";
46import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
47import {
48 effectiveGitHubAccount,
49 findAuthenticatedGitHubAccount,
50 parseGitHubAuthStatus,
51 type GitHubAuthStatusAccount,
52} from "./gitHubAuthStatus.ts";
53import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
54import {
55 combinedAuthOutput,
56 firstSafeAuthLine,
57 probeSourceControlProvider,
58 providerAuth,
59 type SourceControlAuthProbeInput,
60 type SourceControlCliDiscoverySpec,
61 type SourceControlManagedCliDiscoverySpec,
62} from "@t3tools/source-control-core/server/discovery";
63import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
64import {
65 parseGitRemoteHost,
66 readSourceControlHostSettings,
67 unknownRemoteProvider,
68} from "@t3tools/source-control-core/shared/definition";
69
70import * as GitHubClient from "../shared/definition.ts";
71import {
72 PullRequestByNumber,
73 PullRequestNode,
74 PullRequestsByHead,
75} from "./sourceControlProvider.graphql.ts";
76
77// Decode rows separately to isolate malformed PRs within shared documents.
78const LenientPullRequestsByHead = GraphQL.query(PullRequestsByHead.name, {
79 // `GraphQLResolver.aliased` needs a template per lookup.
80 document: PullRequestsByHead.template!,
81 variables: PullRequestsByHead.variables,
82 result: Schema.Struct({
83 repository: Schema.NullOr(
84 Schema.Struct({
85 pullRequests: Schema.Struct({ nodes: Schema.NullOr(Schema.Array(Schema.Unknown)) }),
86 }),
87 ),
88 }),
89});
90const decodePullRequestNode = Schema.decodeUnknownOption(PullRequestNode);
91
92const decodeLinkSubject = Schema.decodeUnknownEffect(
93 Schema.fromJsonString(
94 Schema.Struct({ title: Schema.String, body: Schema.optional(Schema.NullOr(Schema.String)) }),
95 ),
96);
97
98function toChangeRequest(record: NormalizedGitHubPullRequestRecord): ChangeRequest {
99 return { provider: SourceControlProviderKind.make("github"), ...record };
100}
101
102function authAccounts(accounts: ReadonlyArray<GitHubAuthStatusAccount>) {
103 return accounts.map((entry) => ({
104 host: entry.host,
105 account: entry.account,
106 active: entry.active,
107 authenticated: entry.authenticated,
108 ...(entry.error === null ? {} : { error: entry.error }),
109 ...(entry.environmentVariable === null
110 ? {}
111 : { environmentVariable: entry.environmentVariable }),
112 }));
113}
114
115export function parseGitHubAuth(
116 input: SourceControlAuthProbeInput,
117 settings: GitHubClient.GitHubSettings = readSourceControlHostSettings(GitHubClient.settings, {}),
118) {
119 const output = combinedAuthOutput(input);
120 const authStatus = parseGitHubAuthStatus(input.stdout);
121 const hosts = [...new Set(authStatus.accounts.map((entry) => entry.host))];
122 const fallback = findAuthenticatedGitHubAccount(authStatus.accounts);
123 const orderedHosts = fallback
124 ? [fallback.host, ...hosts.filter((host) => host !== fallback.host)]
125 : hosts;
126 const chosen = orderedHosts
127 .map((host) => effectiveGitHubAccount(host, authStatus.accounts, settings))
128 .find((entry) => entry !== undefined);
129 const accounts = authStatus.parsed ? { accounts: authAccounts(authStatus.accounts) } : {};
130
131 if (chosen) {
132 return {
133 ...providerAuth({
134 status: "authenticated",
135 account: chosen.account,
136 host: chosen.host,
137 detail:
138 chosen.environmentVariable === null
139 ? undefined
140 : `Using ${chosen.environmentVariable} from the server environment; it overrides the account chosen in Settings.`,
141 }),
142 ...accounts,
143 };
144 }
145
146 if (fallback) {
147 return {
148 ...providerAuth({
149 status: "unauthenticated",
150 host: fallback.host,
151 detail:
152 "Every GitHub host gh is signed in to is turned off in Settings → Source control & issues.",
153 }),
154 ...accounts,
155 };
156 }
157
158 const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
159 if (authStatus.parsed) {
160 return {
161 ...providerAuth({
162 status: "unauthenticated",
163 host: failedAccount?.host,
164 detail:
165 failedAccount?.error ??
166 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
167 }),
168 ...accounts,
169 };
170 }
171
172 // gh before 2.81.0 rejects --json with a nonzero exit that resembles a signed-out CLI.
173 if (input.exitCode !== 0 && output.includes("unknown flag: --json")) {
174 return providerAuth({
175 status: "unknown",
176 detail:
177 "GitHub CLI is too old to report sign-in status. Update `gh` to 2.81.0 or newer (for example `brew upgrade gh`) and rescan.",
178 });
179 }
180
181 if (input.exitCode !== 0) {
182 return providerAuth({
183 status: "unauthenticated",
184 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
185 });
186 }
187
188 return providerAuth({
189 status: "unknown",
190 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
191 });
192}
193
194export const discovery = {
195 type: "cli",
196 kind: SourceControlProviderKind.make("github"),
197 label: "GitHub",
198 executable: "gh",
199 versionArgs: ["--version"],
200 authArgs: ["auth", "status", "--json", "hosts"],
201 parseAuth: parseGitHubAuth,
202 installHint:
203 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
204} satisfies SourceControlCliDiscoverySpec;
205
206const decodeViewer = Schema.decodeUnknownOption(
207 Schema.fromJsonString(Schema.Struct({ login: Schema.String })),
208);
209
210function environmentTokenVariable(environment: NodeJS.ProcessEnv): string | null {
211 return ["GH_TOKEN", "GITHUB_TOKEN"].find((name) => environment[name]?.trim()) ?? null;
212}
213
214// `gh auth status` may not know environment tokens; check the API.
215export const makeDiscovery = Effect.gen(function* () {
216 const api = yield* GitHubRest.GitHubRest;
217 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
218 const process = sourceControlHost.process;
219 const environment = yield* HostProcess.Environment;
220 const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn;
221 const offerAppSignIn = <A extends SourceControlProviderDiscoveryItem>(item: A): A =>
222 appSignIn.enabled ? { ...item, appSignIn: true } : item;
223
224 return {
225 type: "managed-cli",
226 kind: discovery.kind,
227 label: discovery.label,
228 installHint: discovery.installHint,
229 probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {
230 const current = yield* sourceControlHost.settings
231 .getWithSecrets(GitHubClient.definition.kind)
232 .pipe(Effect.orElseSucceed(() => undefined));
233 const settings = readSourceControlHostSettings(
234 GitHubClient.settings,
235 current?.sourceControlHosts[GitHubClient.definition.kind],
236 );
237 const cli = yield* probeSourceControlProvider({
238 cwd,
239 process: {
240 run: (input) => process.run({ ...input, concurrency: GH_PROCESS_CONCURRENCY }),
241 },
242 spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },
243 });
244 const saved = yield* Effect.result(
245 requireSettingsSecretLiteral(settings.tokens["github.com"], current?.secretProviders ?? {}),
246 );
247 if (Result.isFailure(saved) && settings.hosts["github.com"]?.enabled !== false) {
248 return offerAppSignIn({
249 ...cli,
250 status: "available" as const,
251 auth: providerAuth({
252 status: "unauthenticated",
253 host: "github.com",
254 detail: saved.failure.message,
255 }),
256 });
257 }
258 const savedToken = Result.isSuccess(saved) && saved.success.trim() !== "";
259 const signedIn =
260 appSignIn.enabled && !savedToken && (settings.signIns["github.com"] ?? "").trim() !== "";
261 const variable = environmentTokenVariable(environment);
262 const appName = GitHubClient.APP_SIGN_IN.appName;
263 const tokenSource = savedToken
264 ? "the token saved in Settings"
265 : signedIn
266 ? `the ${appName} sign-in`
267 : variable;
268 if (tokenSource === null || settings.hosts["github.com"]?.enabled === false) {
269 return offerAppSignIn(cli);
270 }
271 const viewer = yield* api
272 .rest({ host: "github.com", operation: "discovery", path: "user" })
273 .pipe(Effect.result);
274 const login = Result.isSuccess(viewer)
275 ? Option.getOrUndefined(decodeViewer(viewer.success.body))?.login
276 : undefined;
277 const accounts = cli.auth.accounts === undefined ? {} : { accounts: cli.auth.accounts };
278 return offerAppSignIn({
279 ...cli,
280 status: "available" as const,
281 auth: {
282 ...(login !== undefined
283 ? providerAuth({
284 status: "authenticated",
285 account: login,
286 host: "github.com",
287 detail: savedToken
288 ? "Using the token saved in Settings; it overrides GH_TOKEN and the gh login."
289 : signedIn
290 ? `Signed in with ${appName}.`
291 : `Using ${variable} from the server environment; it overrides the account chosen in Settings.`,
292 })
293 : Result.isFailure(viewer) && viewer.failure._tag !== "GitHubApiAuthenticationError"
294 ? providerAuth({
295 status: "unknown",
296 host: "github.com",
297 detail: `Could not check ${savedToken || signedIn ? tokenSource : `the token in ${tokenSource}`}: ${viewer.failure.message}`,
298 })
299 : providerAuth({
300 status: "unauthenticated",
301 host: "github.com",
302 detail: savedToken
303 ? "GitHub refused the token saved in Settings. Replace or remove it in Settings → Source control & issues."
304 : signedIn
305 ? `GitHub refused the ${appName} sign-in. Sign in again in Settings → Source control & issues.`
306 : `GitHub refused the token in ${tokenSource}. Replace it, or unset it to use \`gh auth login\`.`,
307 })),
308 ...accounts,
309 },
310 } satisfies SourceControlProviderDiscoveryItem);
311 }),
312 // Claim disabled hosts so errors identify the setting.
313 refineUnknownRemote: ({ context }) => {
314 const url = URL.parse(context.provider.baseUrl);
315 if (!url?.host) return Effect.succeed(null);
316 const host = gitHubApiHostForRemote(context.remoteUrl) ?? url.host;
317 // A timeout or keyring failure propagates: the registry does not keep that answer.
318 return api.credential(host).pipe(
319 Effect.as(true),
320 Effect.catchTags({
321 GitHubCliMissingError: () => Effect.succeed(false),
322 GitHubHostDisabledError: () => Effect.succeed(true),
323 GitHubNotSignedInError: () => Effect.succeed(false),
324 }),
325 Effect.map((known) =>
326 known
327 ? ({
328 kind: SourceControlProviderKind.make("github"),
329 name: host === "github.com" ? "GitHub" : "GitHub Self-Hosted",
330 baseUrl: host === url.host ? context.provider.baseUrl : `https://${host}`,
331 } as const)
332 : null,
333 ),
334 );
335 },
336 } satisfies SourceControlManagedCliDiscoverySpec;
337});
338
339class GitHubFailure extends Schema.TaggedError<GitHubFailure>()("GitHubFailure", {
340 detail: Schema.String,
341 cause: Schema.Defect(),
342}) {}
343
344const failure = (detail: string, cause?: unknown) => new GitHubFailure({ detail, cause });
345
346// A gh login confirms a GitHub Enterprise Server whose hostname does not identify its provider.
347const refineRepositoryIdentity: NonNullable<
348 SourceControlProvider.SourceControlProvider["Service"]["refineRepositoryIdentity"]
349> = Effect.fn("GitHubSourceControlProvider.refineRepositoryIdentity")(function* ({
350 identity,
351 resolveContext,
352}) {
353 if (!identity.rootPath || (identity.provider !== undefined && identity.provider !== "unknown"))
354 return identity;
355 const remote = parseGitRemoteHost(identity.locator.remoteUrl);
356 if (remote === null) return identity;
357 const context = yield* resolveContext({
358 cwd: identity.rootPath,
359 context: {
360 provider: unknownRemoteProvider(remote),
361 remoteName: identity.locator.remoteName,
362 remoteUrl: identity.locator.remoteUrl,
363 },
364 });
365 return context?.provider.kind === "github"
366 ? { ...identity, provider: SourceControlProviderKind.make("github") }
367 : identity;
368});
369
370const PULL_REQUEST_NOT_FOUND = "Pull request not found. Check the PR number or URL and try again.";
371const REPOSITORY_NOT_FOUND = "Repository not found. Check the owner and name and try again.";
372
373function fromGitHubApiError(
374 error: GitHubRequestPolicy.GitHubApiError,
375 notFound = PULL_REQUEST_NOT_FOUND,
376): GitHubFailure {
377 switch (error._tag) {
378 case "GitHubCliMissingError":
379 return failure(
380 "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
381 error,
382 );
383 case "GitHubNotSignedInError":
384 case "GitHubHostDisabledError":
385 case "SettingsSecretUnresolvedError":
386 return failure(error.message, error);
387 case "GitHubApiAuthenticationError":
388 return failure(
389 "GitHub is not authenticated. Run `gh auth login` (or set GH_TOKEN) and retry.",
390 error,
391 );
392 case "GitHubApiRateLimitError":
393 case "SourceControlRateLimitPausedError":
394 return failure(
395 "GitHub API rate limit exceeded. Requests resume when the limit resets.",
396 error,
397 );
398 case "GitHubApiNotFoundError":
399 return failure(notFound, error);
400 case "GitHubCliFailedError":
401 case "GitHubAppSessionError":
402 case "GitHubApiResponseError":
403 case "GitHubApiRequestError":
404 return failure(error.message.trim() || "GitHub request failed.", error);
405 }
406}
407
408const notFound = (cause: string) => failure(PULL_REQUEST_NOT_FOUND, new Error(cause));
409
410const RawRepositorySchema = Schema.Struct({
411 full_name: TrimmedNonEmptyString,
412 html_url: TrimmedNonEmptyString,
413 ssh_url: TrimmedNonEmptyString,
414 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
415});
416const decodeRawRepository = decodeJsonResult(RawRepositorySchema);
417
418function repositoryCloneUrls(
419 raw: Schema.Schema.Type<typeof RawRepositorySchema>,
420): SourceControlRepositoryCloneUrls {
421 return { nameWithOwner: raw.full_name, url: raw.html_url, sshUrl: raw.ssh_url };
422}
423
424const decodeViewerLogin = decodeJsonResult(Schema.Struct({ login: TrimmedNonEmptyString }));
425
426const decodeRestPullRequests = decodeJsonResult(Schema.Array(Schema.Unknown));
427const decodeRestPullRequest = Schema.decodeUnknownOption(
428 Schema.Struct({
429 number: Schema.Number,
430 title: Schema.String,
431 html_url: Schema.String,
432 state: Schema.String,
433 draft: Schema.optional(Schema.Boolean),
434 merged_at: Schema.NullOr(Schema.String),
435 closed_at: Schema.NullOr(Schema.String),
436 updated_at: Schema.String,
437 base: Schema.Struct({ ref: Schema.String, repo: Schema.Struct({ full_name: Schema.String }) }),
438 head: Schema.Struct({
439 ref: Schema.String,
440 sha: Schema.String,
441 repo: Schema.NullOr(
442 Schema.Struct({
443 name: Schema.String,
444 full_name: Schema.String,
445 owner: Schema.Struct({ login: Schema.String, type: Schema.String }),
446 }),
447 ),
448 }),
449 }),
450);
451
452/** Reshapes a REST pull request into the GraphQL node so both decode the same way. */
453function restPullRequestNode(entry: unknown) {
454 const pr = Option.getOrNull(decodeRestPullRequest(entry));
455 if (pr === null) return null;
456 return {
457 number: pr.number,
458 title: pr.title,
459 url: pr.html_url,
460 baseRefName: pr.base.ref,
461 headRefName: pr.head.ref,
462 headRefOid: pr.head.sha,
463 state: pr.merged_at === null ? pr.state.toUpperCase() : "MERGED",
464 isDraft: pr.draft === true,
465 mergedAt: pr.merged_at,
466 closedAt: pr.closed_at,
467 updatedAt: pr.updated_at,
468 isCrossRepository: pr.head.repo?.full_name !== pr.base.repo.full_name,
469 headRepository: pr.head.repo && {
470 name: pr.head.repo.name,
471 nameWithOwner: pr.head.repo.full_name,
472 },
473 headRepositoryOwner: pr.head.repo && {
474 __typename: pr.head.repo.owner.type,
475 login: pr.head.repo.owner.login,
476 },
477 };
478}
479
480type PullRequestListState = "open" | "closed" | "merged" | "all";
481
482const GRAPHQL_STATES: Record<
483 PullRequestListState,
484 NonNullable<PullRequestsByHead.Variables["states"]>
485> = {
486 open: ["OPEN"],
487 closed: ["CLOSED"],
488 merged: ["MERGED"],
489 all: ["OPEN", "CLOSED", "MERGED"],
490};
491/** 50 lookups keeps responses near 0.5s at the same one-point cost as 100. */
492const HEAD_LOOKUPS_PER_DOCUMENT = 50;
493/** Git reads stagger background lookups by ~300ms; gather batches before spending quota. */
494const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
495const BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW = "500 millis";
496/** For heads matching 100 PRs each, 50 lookups approached GitHub's ~10s limit; 25 took ~7s. */
497const BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT = 25;
498const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
499const OWNER_HEAD_SCAN_LIMIT = 100;
500
501function trimmed(value: string): string | null {
502 const text = value.trim();
503 return text.length > 0 ? text : null;
504}
505
506/** Null isolates unusable PRs from the rest of a listing. */
507function toPullRequestRecord(node: PullRequestNode): NormalizedGitHubPullRequestRecord | null {
508 const title = trimmed(node.title);
509 const url = trimmed(node.url);
510 const baseRefName = trimmed(node.baseRefName);
511 const headRefName = trimmed(node.headRefName);
512 const updatedAt = DateTime.make(node.updatedAt);
513 if (node.number < 1 || !title || !url || !baseRefName || !headRefName) return null;
514 if (Option.isNone(updatedAt)) return null;
515 return normalizeGitHubPullRequestRecord({
516 ...node,
517 title,
518 url,
519 baseRefName,
520 headRefName,
521 updatedAt: Option.some(DateTime.toUtc(updatedAt.value)),
522 });
523}
524
525export function pullRequestCheckoutBranchName(input: {
526 readonly headRefName: string;
527 readonly headOwner: string | null;
528 readonly isCrossRepository: boolean;
529 readonly defaultBranch: string | null;
530}): string {
531 return input.isCrossRepository &&
532 input.headOwner !== null &&
533 input.defaultBranch !== null &&
534 input.headRefName === input.defaultBranch
535 ? `${input.headOwner}/${input.headRefName}`
536 : input.headRefName;
537}
538
539const contextHost = (context: SourceControlProvider.SourceControlProviderContext | undefined) =>
540 context === undefined ? undefined : new URL(context.provider.baseUrl).host;
541
542export const make = Effect.gen(function* () {
543 const api = yield* GitHubRest.GitHubRest;
544 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
545 const process = sourceControlHost.process;
546 const environment = yield* HostProcess.Environment;
547 const git = sourceControlHost.git;
548 const fileSystem = yield* FileSystem.FileSystem;
549
550 const gitRead = (cwd: string, args: ReadonlyArray<string>) =>
551 process.run({
552 operation: "GitHubSourceControlProvider.resolveRepository",
553 command: "git",
554 args,
555 cwd,
556 allowNonZeroExit: true,
557 timeoutMs: 5_000,
558 });
559
560 const readRemotes = (cwd: string) =>
561 Effect.all([
562 gitRead(cwd, ["remote", "-v"]),
563 gitRead(cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
564 ]).pipe(
565 Effect.orElseSucceed(() => [null, null] as const),
566 Effect.map(([remotes, resolved]) => ({
567 remotes: remotes?.exitCode === 0 ? remotes.stdout : "",
568 resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
569 })),
570 );
571
572 const resolveRepository = Effect.fn("GitHubSourceControlProvider.resolveRepository")(
573 function* (input: {
574 readonly cwd: string;
575 readonly host?: string | undefined;
576 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
577 }) {
578 const envRepository = environment.GH_REPO?.trim();
579 const hostHint = input.host ?? contextHost(input.context);
580 const defaultHost = (hostHint ?? environment.GH_HOST ?? "github.com").toLowerCase();
581 if (envRepository) {
582 const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
583 if (locator !== null) return locator;
584 }
585 const { host, locator } = resolveGitHubRepository({
586 ...(yield* readRemotes(input.cwd)),
587 hostHint,
588 defaultHost,
589 });
590 if (locator !== null) return locator;
591 if (input.context) {
592 const remote = normalizeGitRemoteUrl(input.context.remoteUrl);
593 const fallback = parseGitHubRepositorySelector(
594 `${host}/${remote.slice(remote.indexOf("/") + 1)}`,
595 host,
596 );
597 if (fallback !== null) return fallback;
598 }
599 return yield* failure(
600 `No GitHub repository on ${host} was found among this checkout's git remotes.`,
601 );
602 },
603 );
604
605 const client = yield* GraphQLClient.make(
606 GraphQLGroup.make(LenientPullRequestsByHead, PullRequestByNumber).middleware(
607 GitHubGraphQlClient.GitHubGraphQlAuth,
608 ),
609 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
610
611 const graphqlRead = <A, E, R>(
612 target: GitHubGraphQlClient.GitHubGraphQlTarget["Service"],
613 decodeDetail: string,
614 effect: Effect.Effect<A, E, R>,
615 ) =>
616 effect.pipe(
617 GitHubGraphQlClient.call(target),
618 Effect.mapError((error) =>
619 GraphQLClientError.isGraphQLClientError(error)
620 ? failure(decodeDetail, error)
621 : fromGitHubApiError(error as GitHubRequestPolicy.GitHubApiError),
622 ),
623 );
624
625 const rest = (input: GitHubRest.GitHubRestInput, notFoundDetail?: string) =>
626 api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(error, notFoundDetail)));
627
628 // Batch by host/credential; isolate missing repositories and interactive/background reserves.
629 const headResolver = GraphQLResolver.aliased(client.PullRequestsByHead, {
630 batchKey: GitHubGraphQlClient.batchKey,
631 }).pipe(RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT));
632 const interactiveHeadResolver = headResolver.pipe(
633 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
634 );
635 const backgroundHeadResolver = headResolver.pipe(
636 RequestResolver.batchN(BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT),
637 RequestResolver.setDelay(BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW),
638 );
639
640 const listByHead = Effect.fn("GitHubSourceControlProvider.listByHead")(function* (input: {
641 readonly cwd: string;
642 readonly headSelector: string;
643 readonly state: PullRequestListState;
644 readonly limit: number;
645 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
646 readonly host?: string | undefined;
647 readonly allowReserve: boolean;
648 }) {
649 const locator = yield* resolveRepository(input);
650 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
651 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
652 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
653 if (ownerMatch) {
654 // GraphQL cannot filter heads by owner, and names like a fork's `main` match thousands.
655 const query = new URLSearchParams({
656 head: `${ownerMatch[1]}:${headRefName}`,
657 state: input.state === "all" || input.state === "open" ? input.state : "closed",
658 sort: "created",
659 direction: "desc",
660 per_page: String(OWNER_HEAD_SCAN_LIMIT),
661 });
662 const response = yield* rest({
663 host: locator.host,
664 operation: "listPullRequestsByHead",
665 allowReserve: input.allowReserve,
666 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls?${query}`,
667 });
668 const decoded = decodeRestPullRequests(response.body);
669 if (Result.isFailure(decoded)) {
670 return yield* failure("GitHub returned an invalid change request list.", decoded.failure);
671 }
672 return decoded.success
673 .flatMap((entry) => {
674 const node = Option.getOrNull(decodePullRequestNode(restPullRequestNode(entry)));
675 const record = node === null ? null : toPullRequestRecord(node);
676 return record === null ? [] : [record];
677 })
678 .filter((row) => input.state === "all" || row.state === input.state)
679 .slice(0, limit);
680 }
681 const result = yield* graphqlRead(
682 {
683 host: locator.host,
684 operation: "listPullRequestsByHead",
685 allowReserve: input.allowReserve,
686 // 50 default-branch lookups can each match 100 fork PRs and exceed the usual cap.
687 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
688 },
689 "GitHub returned an invalid change request list.",
690 GraphQLResolver.request(
691 {
692 owner: locator.owner,
693 name: locator.name,
694 head: headRefName,
695 states: GRAPHQL_STATES[input.state],
696 first: limit,
697 },
698 input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
699 ),
700 );
701 if (result.repository === null) return yield* notFound("The repository could not be read.");
702 return (result.repository.pullRequests.nodes ?? []).flatMap((entry) => {
703 const node = Option.getOrNull(decodePullRequestNode(entry));
704 const record = node === null ? null : toPullRequestRecord(node);
705 return record === null ? [] : [record];
706 });
707 });
708
709 const readPullRequest = Effect.fn("GitHubSourceControlProvider.readPullRequest")(
710 function* (input: {
711 readonly cwd: string;
712 readonly reference: string;
713 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
714 readonly host?: string | undefined;
715 }) {
716 const parsed = parsePullRequestReference(input.reference);
717 if (parsed.kind === "branch") {
718 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
719 const lookup = (state: PullRequestListState) =>
720 listByHead({
721 cwd: input.cwd,
722 headSelector: parsed.headSelector,
723 state,
724 limit: 1,
725 host: input.host,
726 context: input.context,
727 allowReserve: true,
728 });
729 const [open] = yield* lookup("open");
730 const found = open ?? (yield* lookup("all"))[0];
731 if (found === undefined) return yield* notFound("No pull request has this head branch.");
732 return found;
733 }
734 const locator = parsed.kind === "url" ? parsed.locator : yield* resolveRepository(input);
735 const decodeDetail = "GitHub returned an invalid pull request.";
736 const result = yield* graphqlRead(
737 { host: locator.host, operation: "getPullRequest", allowReserve: true },
738 decodeDetail,
739 client.PullRequestByNumber({
740 owner: locator.owner,
741 name: locator.name,
742 number: parsed.number,
743 }),
744 );
745 const node = result.repository?.pullRequest;
746 if (node == null) return yield* notFound("The pull request does not exist.");
747 const record = toPullRequestRecord(node);
748 if (record === null)
749 return yield* failure(decodeDetail, new Error("Malformed pull request."));
750 return record;
751 },
752 );
753
754 const readRepository = Effect.fn("GitHubSourceControlProvider.readRepository")(function* (
755 locator: GitHubRepositoryLocator,
756 ) {
757 const response = yield* rest(
758 {
759 host: locator.host,
760 operation: "getRepository",
761 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
762 allowReserve: true,
763 },
764 REPOSITORY_NOT_FOUND,
765 );
766 const decoded = decodeRawRepository(response.body);
767 if (Result.isFailure(decoded)) {
768 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
769 }
770 return decoded.success;
771 });
772
773 const readViewerLogin = Effect.fn("GitHubSourceControlProvider.readViewerLogin")(function* (
774 host: string,
775 ) {
776 const response = yield* rest({
777 host,
778 operation: "getViewer",
779 path: "user",
780 allowReserve: true,
781 });
782 const decoded = decodeViewerLogin(response.body);
783 if (Result.isFailure(decoded)) {
784 return yield* failure("GitHub request failed.", decoded.failure);
785 }
786 return decoded.success.login;
787 });
788
789 // Keep paths, argv and stderr in cause; expose only a fixed checkout error to clients.
790 const gitFailure = (cause: unknown) =>
791 failure("The pull request could not be checked out with git.", cause);
792
793 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
794 git.execute({
795 operation: `GitHubSourceControlProvider.checkoutPullRequest.${operation}`,
796 cwd,
797 args,
798 });
799
800 const checkoutPullRequest = Effect.fn("GitHubSourceControlProvider.checkoutPullRequest")(
801 function* (input: {
802 readonly cwd: string;
803 readonly reference: string;
804 readonly force?: boolean;
805 readonly context?: SourceControlProvider.SourceControlProviderContext;
806 }) {
807 const reference = parsePullRequestReference(input.reference);
808 const pullRequest = yield* readPullRequest(input);
809 const base = reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
810 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
811 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
812 const isCrossRepository =
813 pullRequest.isCrossRepository ??
814 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
815 const headOwner =
816 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
817
818 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
819 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
820 Effect.mapError(gitFailure),
821 );
822 const remoteFor = (nameWithOwner: string) =>
823 parseFetchRemotes(remotes).find(
824 (remote) =>
825 (gitHubApiHostForRemote(remote.url) ??
826 normalizeGitRemoteUrl(remote.url).split("/")[0]) === base.host &&
827 normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
828 nameWithOwner.toLowerCase(),
829 )?.name ?? null;
830 const baseRemote = Effect.suspend(() => {
831 const known = remoteFor(baseNameWithOwner);
832 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
833 });
834 // Avoid resetting the default branch; prefix colliding forks and fail if it is unknown.
835 const defaultBranch = isCrossRepository
836 ? yield* readRepository(base).pipe(
837 Effect.map((repository) => repository.default_branch ?? null),
838 )
839 : null;
840 const localBranch = pullRequestCheckoutBranchName({
841 headRefName: pullRequest.headRefName,
842 headOwner,
843 isCrossRepository,
844 defaultBranch,
845 });
846
847 const headRemote = Effect.gen(function* () {
848 if (!isCrossRepository) return yield* baseRemote;
849 if (headNameWithOwner === null) return yield* failure("The fork is gone.");
850 const known = remoteFor(headNameWithOwner);
851 if (known !== null) return known;
852 const [owner, name] = headNameWithOwner.split("/");
853 const fork = yield* readRepository({ host: base.host, owner: owner!, name: name! });
854 // Git fetches from a remote's first URL; `config --get` returns the last of several, and
855 // `git remote -v` applies `insteadOf` rewrites.
856 const originUrl = yield* runGit(input.cwd, "readOriginUrl", [
857 "config",
858 "--get-all",
859 "remote.origin.url",
860 ]).pipe(
861 Effect.map((result) => result.stdout.split("\n", 1)[0]?.trim() || null),
862 Effect.orElseSucceed(() => null),
863 );
864 return yield* git.ensureRemote({
865 cwd: input.cwd,
866 preferredName: headOwner ?? "fork",
867 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
868 });
869 });
870
871 const exists = (yield* git
872 .listLocalBranchNames(input.cwd)
873 .pipe(Effect.mapError(gitFailure))).includes(localBranch);
874
875 const target = yield* Effect.gen(function* () {
876 const remoteName = yield* headRemote;
877 yield* git.fetchRemoteTrackingBranch({
878 cwd: input.cwd,
879 remoteName,
880 remoteBranch: pullRequest.headRefName,
881 });
882 return {
883 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
884 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
885 };
886 }).pipe(
887 Effect.catch(() =>
888 Effect.gen(function* () {
889 yield* runGit(input.cwd, "fetchPullRef", [
890 "fetch",
891 "--quiet",
892 "--no-tags",
893 "--",
894 yield* baseRemote,
895 `refs/pull/${pullRequest.number}/head`,
896 ]);
897 const { commitSha } = yield* git.resolveCommit({
898 cwd: input.cwd,
899 revision: "FETCH_HEAD",
900 });
901 return { ref: commitSha, upstream: null };
902 }),
903 ),
904 Effect.mapError(gitFailure),
905 );
906
907 yield* Effect.gen(function* () {
908 if (!exists) {
909 yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: target.ref });
910 }
911 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
912 if (exists) {
913 yield* runGit(
914 input.cwd,
915 "sync",
916 input.force === true
917 ? ["reset", "--hard", "--quiet", target.ref]
918 : ["merge", "--ff-only", "--quiet", target.ref],
919 );
920 }
921 // Set tracking after sync succeeds so a failed checkout preserves the existing upstream.
922 if (target.upstream !== null) {
923 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
924 }
925 }).pipe(Effect.mapError(gitFailure));
926 },
927 );
928
929 const providerError =
930 (
931 operation: string,
932 cwd: string,
933 context?: { readonly reference?: string; readonly repository?: string },
934 ) =>
935 (error: GitHubFailure) =>
936 new SourceControlProviderError({
937 provider: SourceControlProviderKind.make("github"),
938 operation,
939 cwd,
940 ...(context?.reference === undefined
941 ? {}
942 : {
943 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
944 context.reference,
945 ),
946 }),
947 ...(context?.repository === undefined
948 ? {}
949 : {
950 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
951 context.repository,
952 ),
953 }),
954 detail: error.detail,
955 cause: error.cause,
956 });
957
958 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
959 input: { readonly cwd: string; readonly url: URL },
960 endpoint: string,
961 ) {
962 const result = yield* api
963 .rest({
964 host: input.url.host,
965 operation: "resolveLink",
966 path: endpoint,
967 maxResponseBytes: 1_000_000,
968 })
969 .pipe(
970 Effect.timeout("3 seconds"),
971 Effect.mapError(
972 (cause) =>
973 new SourceControlProviderError({
974 provider: SourceControlProviderKind.make("github"),
975 operation: "resolveLink",
976 cwd: input.cwd,
977 detail: "The linked subject could not be read.",
978 cause,
979 }),
980 ),
981 );
982 const subject = yield* decodeLinkSubject(result.body).pipe(
983 Effect.mapError(
984 (cause) =>
985 new SourceControlProviderError({
986 provider: SourceControlProviderKind.make("github"),
987 operation: "resolveLink.decode",
988 cwd: input.cwd,
989 detail: "The linked subject could not be read.",
990 cause,
991 }),
992 ),
993 );
994 return { title: subject.title, body: subject.body ?? null };
995 });
996
997 return SourceControlProvider.SourceControlProvider.of({
998 kind: SourceControlProviderKind.make("github"),
999 refineRepositoryIdentity,
1000 resolveRemoteWebHost: Effect.fn("GitHubSourceControlProvider.resolveRemoteWebHost")(
1001 ({ context }) => Effect.succeed(gitHubApiHostForRemote(context.remoteUrl)),
1002 ),
1003 // GitHub matches bare heads; read a full page to disambiguate forks by owner. A default branch
1004 // collides with most forks, so its owner-qualified lookup has GitHub filter by owner instead.
1005 headBranchProbe: ({ headSelectors, ownerHeadSelector }) => ({
1006 headSelectors: ownerHeadSelector
1007 ? [ownerHeadSelector]
1008 : headSelectors.filter((selector) => !selector.includes(":")),
1009 limit: 100,
1010 }),
1011 readChangeRequestTemplate: Effect.fn("GitHubSourceControlProvider.readChangeRequestTemplate")(
1012 function ({ cwd, treeish }) {
1013 return GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
1014 },
1015 ),
1016 // `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
1017 // gh's pick among the checkout's remotes, led by the one `gh repo set-default` marked
1018 // (`gh-resolved`). An HTTPS remote keeps a non-default port in the context's host, and the
1019 // mark is then ignored.
1020 createsChangeRequestsIn: Effect.fn("GitHubSourceControlProvider.createsChangeRequestsIn")(
1021 function* ({ cwd, context, repository }) {
1022 const host = URL.canParse(context.provider.baseUrl)
1023 ? new URL(context.provider.baseUrl).host
1024 : null;
1025 const target = repository?.toLowerCase();
1026 const fromEnvironment = parseGitHubRepositorySelector(
1027 environment.GH_REPO ?? "",
1028 host ?? "",
1029 );
1030 if (fromEnvironment !== null) {
1031 const { host: targetHost, owner, name } = fromEnvironment;
1032 return (
1033 host !== null &&
1034 URL.canParse(`https://${targetHost}`) &&
1035 new URL(`https://${targetHost}`).host === host &&
1036 `${owner}/${name}`.toLowerCase() === target
1037 );
1038 }
1039 const { locator } = resolveGitHubRepository({
1040 ...(yield* readRemotes(cwd)),
1041 hostHint: host ?? undefined,
1042 defaultHost: host ?? "github.com",
1043 });
1044 return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === target;
1045 },
1046 ),
1047 // `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
1048 // from this key.
1049 recordBranchBase: Effect.fn("GitHubSourceControlProvider.recordBranchBase")(function ({
1050 cwd,
1051 branch,
1052 baseBranch,
1053 }) {
1054 return git
1055 .writeConfigValue({ cwd, key: `branch.${branch}.gh-merge-base`, value: baseBranch })
1056 .pipe(
1057 Effect.catch((cause) =>
1058 Effect.logWarning("Could not record the branch base for gh", { cause }),
1059 ),
1060 );
1061 }),
1062 resolveLink: (input) => {
1063 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
1064 if (input.url.host !== "github.com") return undefined;
1065 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
1066 input.url.pathname,
1067 );
1068 if (!match) return undefined;
1069 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
1070 },
1071 listChangeRequests: Effect.fn("GitHubSourceControlProvider.listChangeRequests")(
1072 function (input) {
1073 return (
1074 input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive
1075 ).pipe(
1076 Effect.flatMap((allowReserve) =>
1077 listByHead({
1078 cwd: input.cwd,
1079 headSelector: input.headSelector,
1080 state: input.state,
1081 limit: input.limit ?? (input.state === "open" ? 1 : 20),
1082 host: contextHost(input.context),
1083 context: input.context,
1084 allowReserve,
1085 }),
1086 ),
1087 Effect.map((records) => records.map(toChangeRequest)),
1088 Effect.mapError(
1089 providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
1090 ),
1091 );
1092 },
1093 ),
1094 getChangeRequest: Effect.fn("GitHubSourceControlProvider.getChangeRequest")(function (input) {
1095 return readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
1096 Effect.map(toChangeRequest),
1097 Effect.mapError(
1098 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
1099 ),
1100 );
1101 }),
1102 createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(
1103 function* (input) {
1104 const locator = yield* resolveRepository(input);
1105 const body = yield* fileSystem
1106 .readFileString(input.bodyFile)
1107 .pipe(
1108 Effect.mapError((cause) =>
1109 failure("The pull request description could not be read.", cause),
1110 ),
1111 );
1112 yield* rest({
1113 host: locator.host,
1114 operation: "createPullRequest",
1115 method: "POST",
1116 allowReserve: true,
1117 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
1118 // Explicitly allow maintainer edits to match gh; the API default is undocumented.
1119 body: {
1120 base: input.baseRefName,
1121 head: input.headSelector,
1122 title: input.title,
1123 body,
1124 maintainer_can_modify: true,
1125 },
1126 });
1127 },
1128 (effect, input) =>
1129 effect.pipe(
1130 Effect.mapError(
1131 providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
1132 ),
1133 ),
1134 ),
1135 getRepositoryCloneUrls: Effect.fn("GitHubSourceControlProvider.getRepositoryCloneUrls")(
1136 function* (input) {
1137 const fallbackHost = (
1138 input.host ??
1139 (yield* resolveRepository(input).pipe(
1140 Effect.map((locator) => locator.host),
1141 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
1142 ))
1143 ).toLowerCase();
1144 const bareName = input.repository.trim().replace(/\.git$/i, "");
1145 const locator =
1146 parseGitHubRepositorySelector(input.repository, fallbackHost) ??
1147 (/^[^/\s]+$/.test(bareName)
1148 ? {
1149 host: fallbackHost,
1150 owner: yield* readViewerLogin(fallbackHost),
1151 name: bareName,
1152 }
1153 : null);
1154 if (locator === null) return yield* failure("Repositories are named owner/name.");
1155 return repositoryCloneUrls(yield* readRepository(locator));
1156 },
1157 (effect, input) =>
1158 effect.pipe(
1159 Effect.mapError(
1160 providerError("getRepositoryCloneUrls", input.cwd, {
1161 repository: input.repository,
1162 }),
1163 ),
1164 ),
1165 ),
1166 createRepository: Effect.fn("GitHubSourceControlProvider.createRepository")(
1167 function* (input) {
1168 const locator = parseGitHubRepositorySelector(
1169 input.repository,
1170 (environment.GH_HOST ?? "github.com").toLowerCase(),
1171 );
1172 const viewer = locator === null ? null : yield* readViewerLogin(locator.host);
1173 const owner = locator?.owner ?? viewer;
1174 const name = locator?.name ?? input.repository.trim();
1175 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
1176 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
1177 const response = yield* rest(
1178 {
1179 host,
1180 operation: "createRepository",
1181 method: "POST",
1182 allowReserve: true,
1183 path:
1184 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1185 body: { name, private: input.visibility === "private" },
1186 },
1187 `No organization named ${owner ?? "that"} that this account can create repositories in.`,
1188 );
1189 const decoded = decodeRawRepository(response.body);
1190 if (Result.isFailure(decoded)) {
1191 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1192 }
1193 return repositoryCloneUrls(decoded.success);
1194 },
1195 (effect, input) =>
1196 effect.pipe(
1197 Effect.mapError(
1198 providerError("createRepository", input.cwd, { repository: input.repository }),
1199 ),
1200 ),
1201 ),
1202 getDefaultBranch: Effect.fn("GitHubSourceControlProvider.getDefaultBranch")(
1203 function* (input) {
1204 const locator = yield* resolveRepository({
1205 cwd: input.cwd,
1206 host: contextHost(input.context),
1207 context: input.context,
1208 });
1209 const repository = yield* readRepository(locator);
1210 const branch = repository.default_branch?.trim() ?? "";
1211 return branch.length > 0 ? branch : null;
1212 },
1213 (effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1214 ),
1215 checkoutChangeRequest: Effect.fn("GitHubSourceControlProvider.checkoutChangeRequest")(
1216 function (input) {
1217 return checkoutPullRequest(input).pipe(
1218 Effect.mapError(
1219 providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1220 ),
1221 );
1222 },
1223 ),
1224 });
1225});