@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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