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 "GitHubCliTimeoutError":
402 case "GitHubAppSessionError":
403 case "GitHubApiResponseError":
404 case "GitHubApiRequestError":
405 return failure(error.message.trim() || "GitHub request failed.", error);
406 }
407}
408
409const notFound = (cause: string) => failure(PULL_REQUEST_NOT_FOUND, new Error(cause));
410
411const RawRepositorySchema = Schema.Struct({
412 full_name: TrimmedNonEmptyString,
413 html_url: TrimmedNonEmptyString,
414 ssh_url: TrimmedNonEmptyString,
415 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
416});
417const decodeRawRepository = decodeJsonResult(RawRepositorySchema);
418
419function repositoryCloneUrls(
420 raw: Schema.Schema.Type<typeof RawRepositorySchema>,
421): SourceControlRepositoryCloneUrls {
422 return { nameWithOwner: raw.full_name, url: raw.html_url, sshUrl: raw.ssh_url };
423}
424
425const decodeViewerLogin = decodeJsonResult(Schema.Struct({ login: TrimmedNonEmptyString }));
426
427const decodeRestPullRequests = decodeJsonResult(Schema.Array(Schema.Unknown));
428const decodeRestPullRequest = Schema.decodeUnknownOption(
429 Schema.Struct({
430 number: Schema.Number,
431 title: Schema.String,
432 html_url: Schema.String,
433 state: Schema.String,
434 draft: Schema.optional(Schema.Boolean),
435 merged_at: Schema.NullOr(Schema.String),
436 closed_at: Schema.NullOr(Schema.String),
437 updated_at: Schema.String,
438 base: Schema.Struct({ ref: Schema.String, repo: Schema.Struct({ full_name: Schema.String }) }),
439 head: Schema.Struct({
440 ref: Schema.String,
441 sha: Schema.String,
442 repo: Schema.NullOr(
443 Schema.Struct({
444 name: Schema.String,
445 full_name: Schema.String,
446 owner: Schema.Struct({ login: Schema.String, type: Schema.String }),
447 }),
448 ),
449 }),
450 }),
451);
452
453/** Reshapes a REST pull request into the GraphQL node so both decode the same way. */
454function restPullRequestNode(entry: unknown) {
455 const pr = Option.getOrNull(decodeRestPullRequest(entry));
456 if (pr === null) return null;
457 return {
458 number: pr.number,
459 title: pr.title,
460 url: pr.html_url,
461 baseRefName: pr.base.ref,
462 headRefName: pr.head.ref,
463 headRefOid: pr.head.sha,
464 state: pr.merged_at === null ? pr.state.toUpperCase() : "MERGED",
465 isDraft: pr.draft === true,
466 mergedAt: pr.merged_at,
467 closedAt: pr.closed_at,
468 updatedAt: pr.updated_at,
469 isCrossRepository: pr.head.repo?.full_name !== pr.base.repo.full_name,
470 headRepository: pr.head.repo && {
471 name: pr.head.repo.name,
472 nameWithOwner: pr.head.repo.full_name,
473 },
474 headRepositoryOwner: pr.head.repo && {
475 __typename: pr.head.repo.owner.type,
476 login: pr.head.repo.owner.login,
477 },
478 };
479}
480
481type PullRequestListState = "open" | "closed" | "merged" | "all";
482
483const GRAPHQL_STATES: Record<
484 PullRequestListState,
485 NonNullable<PullRequestsByHead.Variables["states"]>
486> = {
487 open: ["OPEN"],
488 closed: ["CLOSED"],
489 merged: ["MERGED"],
490 all: ["OPEN", "CLOSED", "MERGED"],
491};
492/** 50 lookups keeps responses near 0.5s at the same one-point cost as 100. */
493const HEAD_LOOKUPS_PER_DOCUMENT = 50;
494/** Git reads stagger background lookups by ~300ms; gather batches before spending quota. */
495const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
496const BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW = "500 millis";
497/** For heads matching 100 PRs each, 50 lookups approached GitHub's ~10s limit; 25 took ~7s. */
498const BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT = 25;
499const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
500const OWNER_HEAD_SCAN_LIMIT = 100;
501
502function trimmed(value: string): string | null {
503 const text = value.trim();
504 return text.length > 0 ? text : null;
505}
506
507/** Null isolates unusable PRs from the rest of a listing. */
508function toPullRequestRecord(node: PullRequestNode): NormalizedGitHubPullRequestRecord | null {
509 const title = trimmed(node.title);
510 const url = trimmed(node.url);
511 const baseRefName = trimmed(node.baseRefName);
512 const headRefName = trimmed(node.headRefName);
513 const updatedAt = DateTime.make(node.updatedAt);
514 if (node.number < 1 || !title || !url || !baseRefName || !headRefName) return null;
515 if (Option.isNone(updatedAt)) return null;
516 return normalizeGitHubPullRequestRecord({
517 ...node,
518 title,
519 url,
520 baseRefName,
521 headRefName,
522 updatedAt: Option.some(DateTime.toUtc(updatedAt.value)),
523 });
524}
525
526export function pullRequestCheckoutBranchName(input: {
527 readonly headRefName: string;
528 readonly headOwner: string | null;
529 readonly isCrossRepository: boolean;
530 readonly defaultBranch: string | null;
531}): string {
532 return input.isCrossRepository &&
533 input.headOwner !== null &&
534 input.defaultBranch !== null &&
535 input.headRefName === input.defaultBranch
536 ? `${input.headOwner}/${input.headRefName}`
537 : input.headRefName;
538}
539
540const contextHost = (context: SourceControlProvider.SourceControlProviderContext | undefined) =>
541 context === undefined ? undefined : new URL(context.provider.baseUrl).host;
542
543export const make = Effect.gen(function* () {
544 const api = yield* GitHubRest.GitHubRest;
545 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
546 const process = sourceControlHost.process;
547 const environment = yield* HostProcess.Environment;
548 const git = sourceControlHost.git;
549 const fileSystem = yield* FileSystem.FileSystem;
550
551 const gitRead = (cwd: string, args: ReadonlyArray<string>) =>
552 process.run({
553 operation: "GitHubSourceControlProvider.resolveRepository",
554 command: "git",
555 args,
556 cwd,
557 allowNonZeroExit: true,
558 timeoutMs: 5_000,
559 });
560
561 const readRemotes = (cwd: string) =>
562 Effect.all([
563 gitRead(cwd, ["remote", "-v"]),
564 gitRead(cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
565 ]).pipe(
566 Effect.orElseSucceed(() => [null, null] as const),
567 Effect.map(([remotes, resolved]) => ({
568 remotes: remotes?.exitCode === 0 ? remotes.stdout : "",
569 resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
570 })),
571 );
572
573 const resolveRepository = Effect.fn("GitHubSourceControlProvider.resolveRepository")(
574 function* (input: {
575 readonly cwd: string;
576 readonly host?: string | undefined;
577 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
578 }) {
579 const envRepository = environment.GH_REPO?.trim();
580 const hostHint = input.host ?? contextHost(input.context);
581 const defaultHost = (hostHint ?? environment.GH_HOST ?? "github.com").toLowerCase();
582 if (envRepository) {
583 const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
584 if (locator !== null) return locator;
585 }
586 const { host, locator } = resolveGitHubRepository({
587 ...(yield* readRemotes(input.cwd)),
588 hostHint,
589 defaultHost,
590 });
591 if (locator !== null) return locator;
592 if (input.context) {
593 const remote = normalizeGitRemoteUrl(input.context.remoteUrl);
594 const fallback = parseGitHubRepositorySelector(
595 `${host}/${remote.slice(remote.indexOf("/") + 1)}`,
596 host,
597 );
598 if (fallback !== null) return fallback;
599 }
600 return yield* failure(
601 `No GitHub repository on ${host} was found among this checkout's git remotes.`,
602 );
603 },
604 );
605
606 const client = yield* GraphQLClient.make(
607 GraphQLGroup.make(LenientPullRequestsByHead, PullRequestByNumber).middleware(
608 GitHubGraphQlClient.GitHubGraphQlAuth,
609 ),
610 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
611
612 const graphqlRead = <A, E, R>(
613 target: GitHubGraphQlClient.GitHubGraphQlTarget["Service"],
614 decodeDetail: string,
615 effect: Effect.Effect<A, E, R>,
616 ) =>
617 effect.pipe(
618 GitHubGraphQlClient.call(target),
619 Effect.mapError((error) =>
620 GraphQLClientError.isGraphQLClientError(error)
621 ? failure(decodeDetail, error)
622 : fromGitHubApiError(error as GitHubRequestPolicy.GitHubApiError),
623 ),
624 );
625
626 const rest = (input: GitHubRest.GitHubRestInput, notFoundDetail?: string) =>
627 api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(error, notFoundDetail)));
628
629 // Batch by host/credential; isolate missing repositories and interactive/background reserves.
630 const headResolver = GraphQLResolver.aliased(client.PullRequestsByHead, {
631 batchKey: GitHubGraphQlClient.batchKey,
632 }).pipe(RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT));
633 const interactiveHeadResolver = headResolver.pipe(
634 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
635 );
636 const backgroundHeadResolver = headResolver.pipe(
637 RequestResolver.batchN(BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT),
638 RequestResolver.setDelay(BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW),
639 );
640
641 const listByHead = Effect.fn("GitHubSourceControlProvider.listByHead")(function* (input: {
642 readonly cwd: string;
643 readonly headSelector: string;
644 readonly state: PullRequestListState;
645 readonly limit: number;
646 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
647 readonly host?: string | undefined;
648 readonly allowReserve: boolean;
649 }) {
650 const locator = yield* resolveRepository(input);
651 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
652 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
653 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
654 if (ownerMatch) {
655 // GraphQL cannot filter heads by owner, and names like a fork's `main` match thousands.
656 const query = new URLSearchParams({
657 head: `${ownerMatch[1]}:${headRefName}`,
658 state: input.state === "all" || input.state === "open" ? input.state : "closed",
659 sort: "created",
660 direction: "desc",
661 per_page: String(OWNER_HEAD_SCAN_LIMIT),
662 });
663 const response = yield* rest({
664 host: locator.host,
665 operation: "listPullRequestsByHead",
666 allowReserve: input.allowReserve,
667 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls?${query}`,
668 });
669 const decoded = decodeRestPullRequests(response.body);
670 if (Result.isFailure(decoded)) {
671 return yield* failure("GitHub returned an invalid change request list.", decoded.failure);
672 }
673 return decoded.success
674 .flatMap((entry) => {
675 const node = Option.getOrNull(decodePullRequestNode(restPullRequestNode(entry)));
676 const record = node === null ? null : toPullRequestRecord(node);
677 return record === null ? [] : [record];
678 })
679 .filter((row) => input.state === "all" || row.state === input.state)
680 .slice(0, limit);
681 }
682 const result = yield* graphqlRead(
683 {
684 host: locator.host,
685 operation: "listPullRequestsByHead",
686 allowReserve: input.allowReserve,
687 // 50 default-branch lookups can each match 100 fork PRs and exceed the usual cap.
688 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
689 },
690 "GitHub returned an invalid change request list.",
691 GraphQLResolver.request(
692 {
693 owner: locator.owner,
694 name: locator.name,
695 head: headRefName,
696 states: GRAPHQL_STATES[input.state],
697 first: limit,
698 },
699 input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
700 ),
701 );
702 if (result.repository === null) return yield* notFound("The repository could not be read.");
703 return (result.repository.pullRequests.nodes ?? []).flatMap((entry) => {
704 const node = Option.getOrNull(decodePullRequestNode(entry));
705 const record = node === null ? null : toPullRequestRecord(node);
706 return record === null ? [] : [record];
707 });
708 });
709
710 const readPullRequest = Effect.fn("GitHubSourceControlProvider.readPullRequest")(
711 function* (input: {
712 readonly cwd: string;
713 readonly reference: string;
714 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
715 readonly host?: string | undefined;
716 }) {
717 const parsed = parsePullRequestReference(input.reference);
718 if (parsed.kind === "branch") {
719 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
720 const lookup = (state: PullRequestListState) =>
721 listByHead({
722 cwd: input.cwd,
723 headSelector: parsed.headSelector,
724 state,
725 limit: 1,
726 host: input.host,
727 context: input.context,
728 allowReserve: true,
729 });
730 const [open] = yield* lookup("open");
731 const found = open ?? (yield* lookup("all"))[0];
732 if (found === undefined) return yield* notFound("No pull request has this head branch.");
733 return found;
734 }
735 const locator = parsed.kind === "url" ? parsed.locator : yield* resolveRepository(input);
736 const decodeDetail = "GitHub returned an invalid pull request.";
737 const result = yield* graphqlRead(
738 { host: locator.host, operation: "getPullRequest", allowReserve: true },
739 decodeDetail,
740 client.PullRequestByNumber({
741 owner: locator.owner,
742 name: locator.name,
743 number: parsed.number,
744 }),
745 );
746 const node = result.repository?.pullRequest;
747 if (node == null) return yield* notFound("The pull request does not exist.");
748 const record = toPullRequestRecord(node);
749 if (record === null)
750 return yield* failure(decodeDetail, new Error("Malformed pull request."));
751 return record;
752 },
753 );
754
755 const readRepository = Effect.fn("GitHubSourceControlProvider.readRepository")(function* (
756 locator: GitHubRepositoryLocator,
757 ) {
758 const response = yield* rest(
759 {
760 host: locator.host,
761 operation: "getRepository",
762 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
763 allowReserve: true,
764 },
765 REPOSITORY_NOT_FOUND,
766 );
767 const decoded = decodeRawRepository(response.body);
768 if (Result.isFailure(decoded)) {
769 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
770 }
771 return decoded.success;
772 });
773
774 const readViewerLogin = Effect.fn("GitHubSourceControlProvider.readViewerLogin")(function* (
775 host: string,
776 ) {
777 const response = yield* rest({
778 host,
779 operation: "getViewer",
780 path: "user",
781 allowReserve: true,
782 });
783 const decoded = decodeViewerLogin(response.body);
784 if (Result.isFailure(decoded)) {
785 return yield* failure("GitHub request failed.", decoded.failure);
786 }
787 return decoded.success.login;
788 });
789
790 // Keep paths, argv and stderr in cause; expose only a fixed checkout error to clients.
791 const gitFailure = (cause: unknown) =>
792 failure("The pull request could not be checked out with git.", cause);
793
794 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
795 git.execute({
796 operation: `GitHubSourceControlProvider.checkoutPullRequest.${operation}`,
797 cwd,
798 args,
799 });
800
801 const checkoutPullRequest = Effect.fn("GitHubSourceControlProvider.checkoutPullRequest")(
802 function* (input: {
803 readonly cwd: string;
804 readonly reference: string;
805 readonly force?: boolean;
806 readonly context?: SourceControlProvider.SourceControlProviderContext;
807 }) {
808 const reference = parsePullRequestReference(input.reference);
809 const pullRequest = yield* readPullRequest(input);
810 const base = reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
811 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
812 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
813 const isCrossRepository =
814 pullRequest.isCrossRepository ??
815 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
816 const headOwner =
817 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
818
819 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
820 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
821 Effect.mapError(gitFailure),
822 );
823 const remoteFor = (nameWithOwner: string) =>
824 parseFetchRemotes(remotes).find(
825 (remote) =>
826 (gitHubApiHostForRemote(remote.url) ??
827 normalizeGitRemoteUrl(remote.url).split("/")[0]) === base.host &&
828 normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
829 nameWithOwner.toLowerCase(),
830 )?.name ?? null;
831 const baseRemote = Effect.suspend(() => {
832 const known = remoteFor(baseNameWithOwner);
833 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
834 });
835 // Avoid resetting the default branch; prefix colliding forks and fail if it is unknown.
836 const defaultBranch = isCrossRepository
837 ? yield* readRepository(base).pipe(
838 Effect.map((repository) => repository.default_branch ?? null),
839 )
840 : null;
841 const localBranch = pullRequestCheckoutBranchName({
842 headRefName: pullRequest.headRefName,
843 headOwner,
844 isCrossRepository,
845 defaultBranch,
846 });
847
848 const headRemote = Effect.gen(function* () {
849 if (!isCrossRepository) return yield* baseRemote;
850 if (headNameWithOwner === null) return yield* failure("The fork is gone.");
851 const known = remoteFor(headNameWithOwner);
852 if (known !== null) return known;
853 const [owner, name] = headNameWithOwner.split("/");
854 const fork = yield* readRepository({ host: base.host, owner: owner!, name: name! });
855 // Git fetches from a remote's first URL; `config --get` returns the last of several, and
856 // `git remote -v` applies `insteadOf` rewrites.
857 const originUrl = yield* runGit(input.cwd, "readOriginUrl", [
858 "config",
859 "--get-all",
860 "remote.origin.url",
861 ]).pipe(
862 Effect.map((result) => result.stdout.split("\n", 1)[0]?.trim() || null),
863 Effect.orElseSucceed(() => null),
864 );
865 return yield* git.ensureRemote({
866 cwd: input.cwd,
867 preferredName: headOwner ?? "fork",
868 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
869 });
870 });
871
872 const exists = (yield* git
873 .listLocalBranchNames(input.cwd)
874 .pipe(Effect.mapError(gitFailure))).includes(localBranch);
875
876 const target = yield* Effect.gen(function* () {
877 const remoteName = yield* headRemote;
878 yield* git.fetchRemoteTrackingBranch({
879 cwd: input.cwd,
880 remoteName,
881 remoteBranch: pullRequest.headRefName,
882 });
883 return {
884 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
885 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
886 };
887 }).pipe(
888 Effect.catch(() =>
889 Effect.gen(function* () {
890 yield* runGit(input.cwd, "fetchPullRef", [
891 "fetch",
892 "--quiet",
893 "--no-tags",
894 "--",
895 yield* baseRemote,
896 `refs/pull/${pullRequest.number}/head`,
897 ]);
898 const { commitSha } = yield* git.resolveCommit({
899 cwd: input.cwd,
900 revision: "FETCH_HEAD",
901 });
902 return { ref: commitSha, upstream: null };
903 }),
904 ),
905 Effect.mapError(gitFailure),
906 );
907
908 yield* Effect.gen(function* () {
909 if (!exists) {
910 yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: target.ref });
911 }
912 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
913 if (exists) {
914 yield* runGit(
915 input.cwd,
916 "sync",
917 input.force === true
918 ? ["reset", "--hard", "--quiet", target.ref]
919 : ["merge", "--ff-only", "--quiet", target.ref],
920 );
921 }
922 // Set tracking after sync succeeds so a failed checkout preserves the existing upstream.
923 if (target.upstream !== null) {
924 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
925 }
926 }).pipe(Effect.mapError(gitFailure));
927 },
928 );
929
930 const providerError =
931 (
932 operation: string,
933 cwd: string,
934 context?: { readonly reference?: string; readonly repository?: string },
935 ) =>
936 (error: GitHubFailure) =>
937 new SourceControlProviderError({
938 provider: SourceControlProviderKind.make("github"),
939 operation,
940 cwd,
941 ...(context?.reference === undefined
942 ? {}
943 : {
944 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
945 context.reference,
946 ),
947 }),
948 ...(context?.repository === undefined
949 ? {}
950 : {
951 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
952 context.repository,
953 ),
954 }),
955 detail: error.detail,
956 cause: error.cause,
957 });
958
959 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
960 input: { readonly cwd: string; readonly url: URL },
961 endpoint: string,
962 ) {
963 const result = yield* api
964 .rest({
965 host: input.url.host,
966 operation: "resolveLink",
967 path: endpoint,
968 maxResponseBytes: 1_000_000,
969 })
970 .pipe(
971 Effect.timeout("3 seconds"),
972 Effect.mapError(
973 (cause) =>
974 new SourceControlProviderError({
975 provider: SourceControlProviderKind.make("github"),
976 operation: "resolveLink",
977 cwd: input.cwd,
978 detail: "The linked subject could not be read.",
979 cause,
980 }),
981 ),
982 );
983 const subject = yield* decodeLinkSubject(result.body).pipe(
984 Effect.mapError(
985 (cause) =>
986 new SourceControlProviderError({
987 provider: SourceControlProviderKind.make("github"),
988 operation: "resolveLink.decode",
989 cwd: input.cwd,
990 detail: "The linked subject could not be read.",
991 cause,
992 }),
993 ),
994 );
995 return { title: subject.title, body: subject.body ?? null };
996 });
997
998 return SourceControlProvider.SourceControlProvider.of({
999 kind: SourceControlProviderKind.make("github"),
1000 refineRepositoryIdentity,
1001 resolveRemoteWebHost: Effect.fn("GitHubSourceControlProvider.resolveRemoteWebHost")(
1002 ({ context }) => Effect.succeed(gitHubApiHostForRemote(context.remoteUrl)),
1003 ),
1004 // GitHub matches bare heads; read a full page to disambiguate forks by owner. A default branch
1005 // collides with most forks, so its owner-qualified lookup has GitHub filter by owner instead.
1006 headBranchProbe: ({ headSelectors, ownerHeadSelector }) => ({
1007 headSelectors: ownerHeadSelector
1008 ? [ownerHeadSelector]
1009 : headSelectors.filter((selector) => !selector.includes(":")),
1010 limit: 100,
1011 }),
1012 readChangeRequestTemplate: Effect.fn("GitHubSourceControlProvider.readChangeRequestTemplate")(
1013 function ({ cwd, treeish }) {
1014 return GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
1015 },
1016 ),
1017 // `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
1018 // gh's pick among the checkout's remotes, led by the one `gh repo set-default` marked
1019 // (`gh-resolved`). An HTTPS remote keeps a non-default port in the context's host, and the
1020 // mark is then ignored.
1021 createsChangeRequestsIn: Effect.fn("GitHubSourceControlProvider.createsChangeRequestsIn")(
1022 function* ({ cwd, context, repository }) {
1023 const host = URL.canParse(context.provider.baseUrl)
1024 ? new URL(context.provider.baseUrl).host
1025 : null;
1026 const target = repository?.toLowerCase();
1027 const fromEnvironment = parseGitHubRepositorySelector(
1028 environment.GH_REPO ?? "",
1029 host ?? "",
1030 );
1031 if (fromEnvironment !== null) {
1032 const { host: targetHost, owner, name } = fromEnvironment;
1033 return (
1034 host !== null &&
1035 URL.canParse(`https://${targetHost}`) &&
1036 new URL(`https://${targetHost}`).host === host &&
1037 `${owner}/${name}`.toLowerCase() === target
1038 );
1039 }
1040 const { locator } = resolveGitHubRepository({
1041 ...(yield* readRemotes(cwd)),
1042 hostHint: host ?? undefined,
1043 defaultHost: host ?? "github.com",
1044 });
1045 return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === target;
1046 },
1047 ),
1048 // `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
1049 // from this key.
1050 recordBranchBase: Effect.fn("GitHubSourceControlProvider.recordBranchBase")(function ({
1051 cwd,
1052 branch,
1053 baseBranch,
1054 }) {
1055 return git
1056 .writeConfigValue({ cwd, key: `branch.${branch}.gh-merge-base`, value: baseBranch })
1057 .pipe(
1058 Effect.catch((cause) =>
1059 Effect.logWarning("Could not record the branch base for gh", { cause }),
1060 ),
1061 );
1062 }),
1063 resolveLink: (input) => {
1064 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
1065 if (input.url.host !== "github.com") return undefined;
1066 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
1067 input.url.pathname,
1068 );
1069 if (!match) return undefined;
1070 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
1071 },
1072 listChangeRequests: Effect.fn("GitHubSourceControlProvider.listChangeRequests")(
1073 function (input) {
1074 return (
1075 input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive
1076 ).pipe(
1077 Effect.flatMap((allowReserve) =>
1078 listByHead({
1079 cwd: input.cwd,
1080 headSelector: input.headSelector,
1081 state: input.state,
1082 limit: input.limit ?? (input.state === "open" ? 1 : 20),
1083 host: contextHost(input.context),
1084 context: input.context,
1085 allowReserve,
1086 }),
1087 ),
1088 Effect.map((records) => records.map(toChangeRequest)),
1089 Effect.mapError(
1090 providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
1091 ),
1092 );
1093 },
1094 ),
1095 getChangeRequest: Effect.fn("GitHubSourceControlProvider.getChangeRequest")(function (input) {
1096 return readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
1097 Effect.map(toChangeRequest),
1098 Effect.mapError(
1099 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
1100 ),
1101 );
1102 }),
1103 createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(
1104 function* (input) {
1105 const locator = yield* resolveRepository(input);
1106 const body = yield* fileSystem
1107 .readFileString(input.bodyFile)
1108 .pipe(
1109 Effect.mapError((cause) =>
1110 failure("The pull request description could not be read.", cause),
1111 ),
1112 );
1113 yield* rest({
1114 host: locator.host,
1115 operation: "createPullRequest",
1116 method: "POST",
1117 allowReserve: true,
1118 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
1119 // Explicitly allow maintainer edits to match gh; the API default is undocumented.
1120 body: {
1121 base: input.baseRefName,
1122 head: input.headSelector,
1123 title: input.title,
1124 body,
1125 maintainer_can_modify: true,
1126 },
1127 });
1128 },
1129 (effect, input) =>
1130 effect.pipe(
1131 Effect.mapError(
1132 providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
1133 ),
1134 ),
1135 ),
1136 getRepositoryCloneUrls: Effect.fn("GitHubSourceControlProvider.getRepositoryCloneUrls")(
1137 function* (input) {
1138 const fallbackHost = (
1139 input.host ??
1140 (yield* resolveRepository(input).pipe(
1141 Effect.map((locator) => locator.host),
1142 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
1143 ))
1144 ).toLowerCase();
1145 const bareName = input.repository.trim().replace(/\.git$/i, "");
1146 const locator =
1147 parseGitHubRepositorySelector(input.repository, fallbackHost) ??
1148 (/^[^/\s]+$/.test(bareName)
1149 ? {
1150 host: fallbackHost,
1151 owner: yield* readViewerLogin(fallbackHost),
1152 name: bareName,
1153 }
1154 : null);
1155 if (locator === null) return yield* failure("Repositories are named owner/name.");
1156 return repositoryCloneUrls(yield* readRepository(locator));
1157 },
1158 (effect, input) =>
1159 effect.pipe(
1160 Effect.mapError(
1161 providerError("getRepositoryCloneUrls", input.cwd, {
1162 repository: input.repository,
1163 }),
1164 ),
1165 ),
1166 ),
1167 createRepository: Effect.fn("GitHubSourceControlProvider.createRepository")(
1168 function* (input) {
1169 const locator = parseGitHubRepositorySelector(
1170 input.repository,
1171 (environment.GH_HOST ?? "github.com").toLowerCase(),
1172 );
1173 const viewer = locator === null ? null : yield* readViewerLogin(locator.host);
1174 const owner = locator?.owner ?? viewer;
1175 const name = locator?.name ?? input.repository.trim();
1176 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
1177 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
1178 const response = yield* rest(
1179 {
1180 host,
1181 operation: "createRepository",
1182 method: "POST",
1183 allowReserve: true,
1184 path:
1185 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1186 body: { name, private: input.visibility === "private" },
1187 },
1188 `No organization named ${owner ?? "that"} that this account can create repositories in.`,
1189 );
1190 const decoded = decodeRawRepository(response.body);
1191 if (Result.isFailure(decoded)) {
1192 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1193 }
1194 return repositoryCloneUrls(decoded.success);
1195 },
1196 (effect, input) =>
1197 effect.pipe(
1198 Effect.mapError(
1199 providerError("createRepository", input.cwd, { repository: input.repository }),
1200 ),
1201 ),
1202 ),
1203 getDefaultBranch: Effect.fn("GitHubSourceControlProvider.getDefaultBranch")(
1204 function* (input) {
1205 const locator = yield* resolveRepository({
1206 cwd: input.cwd,
1207 host: contextHost(input.context),
1208 context: input.context,
1209 });
1210 const repository = yield* readRepository(locator);
1211 const branch = repository.default_branch?.trim() ?? "";
1212 return branch.length > 0 ? branch : null;
1213 },
1214 (effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1215 ),
1216 checkoutChangeRequest: Effect.fn("GitHubSourceControlProvider.checkoutChangeRequest")(
1217 function (input) {
1218 return checkoutPullRequest(input).pipe(
1219 Effect.mapError(
1220 providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1221 ),
1222 );
1223 },
1224 ),
1225 });
1226});