The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeUtil from "node:util"; |
| 2 | import { |
| 3 | VcsProcessExitError, |
| 4 | VcsProcessSpawnError, |
| 5 | VcsProcessTimeoutError, |
| 6 | type SourceControlProviderAuth, |
| 7 | type SourceControlProviderDiscoveryItem, |
| 8 | type SourceControlProviderInfo, |
| 9 | type SourceControlProviderKind, |
| 10 | } from "@t3tools/contracts"; |
| 11 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 12 | import { SpawnExecutableResolution } from "@t3tools/shared/shell"; |
| 13 | import type * as Cause from "effect/Cause"; |
| 14 | import * as Effect from "effect/Effect"; |
| 15 | import * as Option from "effect/Option"; |
| 16 | import * as PlatformError from "effect/PlatformError"; |
| 17 | import * as Result from "effect/Result"; |
| 18 | import * as Schema from "effect/Schema"; |
| 19 | |
| 20 | import type * as SourceControlProvider from "./SourceControlProvider.ts"; |
| 21 | import type * as SourceControlHost from "./SourceControlHost.ts"; |
| 22 | |
| 23 | export interface SourceControlAuthProbeInput { |
| 24 | readonly stdout: string; |
| 25 | readonly stderr: string; |
| 26 | readonly exitCode: SourceControlHost.SourceControlProcessOutput["exitCode"]; |
| 27 | } |
| 28 | |
| 29 | export interface SourceControlUnknownRemoteRefinementInput { |
| 30 | readonly cwd: string; |
| 31 | readonly context: SourceControlProvider.SourceControlProviderContext; |
| 32 | readonly auth: SourceControlAuthProbeInput; |
| 33 | } |
| 34 | |
| 35 | interface SourceControlDiscoverySpecBase { |
| 36 | readonly kind: SourceControlProviderKind; |
| 37 | readonly label: string; |
| 38 | readonly installHint: string; |
| 39 | } |
| 40 | |
| 41 | export type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & { |
| 42 | readonly type: "cli"; |
| 43 | readonly executable: string; |
| 44 | readonly versionArgs: ReadonlyArray<string>; |
| 45 | readonly authArgs: ReadonlyArray<string>; |
| 46 | /** Asked once when `authArgs` reports signed out; its answer counts only when it finds a sign-in. */ |
| 47 | readonly authRetryArgs?: ReadonlyArray<string>; |
| 48 | readonly remoteRefinementArgs?: ( |
| 49 | context: SourceControlProvider.SourceControlProviderContext, |
| 50 | ) => ReadonlyArray<string>; |
| 51 | readonly probeTimeoutMs?: number; |
| 52 | readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth; |
| 53 | /** `null` when the CLI holds nothing for the remote; `undefined` when its output cannot say. */ |
| 54 | readonly refineUnknownRemote?: ( |
| 55 | input: SourceControlUnknownRemoteRefinementInput, |
| 56 | ) => SourceControlProviderInfo | null | undefined; |
| 57 | }; |
| 58 | |
| 59 | export type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & { |
| 60 | readonly type: "api"; |
| 61 | readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>; |
| 62 | }; |
| 63 | |
| 64 | export type SourceControlManagedCliDiscoverySpec = SourceControlDiscoverySpecBase & { |
| 65 | readonly type: "managed-cli"; |
| 66 | readonly probe: (cwd: string) => Effect.Effect<SourceControlProviderDiscoveryItem>; |
| 67 | /** Null includes missing CLIs. Failure means unknown and must not be cached by the registry. */ |
| 68 | readonly refineUnknownRemote: (input: { |
| 69 | readonly cwd: string; |
| 70 | readonly context: SourceControlProvider.SourceControlProviderContext; |
| 71 | }) => Effect.Effect<SourceControlProviderInfo | null, Cause.YieldableError>; |
| 72 | }; |
| 73 | |
| 74 | export type SourceControlProviderDiscoverySpec = |
| 75 | | SourceControlCliDiscoverySpec |
| 76 | | SourceControlManagedCliDiscoverySpec |
| 77 | | SourceControlApiDiscoverySpec; |
| 78 | |
| 79 | type SourceControlCliRemoteRefinementSpec = SourceControlCliDiscoverySpec & { |
| 80 | readonly refineUnknownRemote: NonNullable<SourceControlCliDiscoverySpec["refineUnknownRemote"]>; |
| 81 | }; |
| 82 | |
| 83 | const DEFAULT_PROBE_TIMEOUT_MS = 5_000; |
| 84 | /** An API host that stalls must not hold the whole discovery answer behind it. */ |
| 85 | const API_PROBE_TIMEOUT = "3 seconds"; |
| 86 | |
| 87 | function probeTimeoutMs(spec: SourceControlCliDiscoverySpec): number { |
| 88 | return spec.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS; |
| 89 | } |
| 90 | |
| 91 | interface DiscoveryProbeResult { |
| 92 | readonly kind: SourceControlProviderKind; |
| 93 | readonly label: string; |
| 94 | readonly executable: string; |
| 95 | readonly status: "available" | "missing"; |
| 96 | readonly version: Option.Option<string>; |
| 97 | readonly installHint: string; |
| 98 | readonly detail: Option.Option<string>; |
| 99 | } |
| 100 | |
| 101 | export function firstNonEmptyLine(text: string): Option.Option<string> { |
| 102 | const line = NodeUtil.stripVTControlCharacters(text) |
| 103 | .split(/\r?\n/) |
| 104 | .map((entry) => entry.trim()) |
| 105 | .find((entry) => entry.length > 0); |
| 106 | return line === undefined ? Option.none() : Option.some(line); |
| 107 | } |
| 108 | |
| 109 | export function detailFromCause(cause: unknown): Option.Option<string> { |
| 110 | if (cause instanceof Error && cause.message.trim().length > 0) { |
| 111 | return Option.some(cause.message.trim()); |
| 112 | } |
| 113 | return Option.none(); |
| 114 | } |
| 115 | |
| 116 | function authAccount(account: string | undefined): Option.Option<string> { |
| 117 | const trimmed = account?.trim(); |
| 118 | return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed); |
| 119 | } |
| 120 | |
| 121 | function authHost(host: string | undefined): Option.Option<string> { |
| 122 | const trimmed = host?.trim(); |
| 123 | return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed); |
| 124 | } |
| 125 | |
| 126 | function authDetail(detail: string | undefined): Option.Option<string> { |
| 127 | const trimmed = detail?.trim(); |
| 128 | return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed); |
| 129 | } |
| 130 | |
| 131 | export function providerAuth(input: { |
| 132 | readonly status: SourceControlProviderAuth["status"]; |
| 133 | readonly account?: string | undefined; |
| 134 | readonly host?: string | undefined; |
| 135 | readonly detail?: string | undefined; |
| 136 | }): SourceControlProviderAuth { |
| 137 | return { |
| 138 | status: input.status, |
| 139 | account: authAccount(input.account), |
| 140 | host: authHost(input.host), |
| 141 | detail: authDetail(input.detail), |
| 142 | }; |
| 143 | } |
| 144 | |
| 145 | function unknownAuth(detail?: string): SourceControlProviderAuth { |
| 146 | return providerAuth({ status: "unknown", detail }); |
| 147 | } |
| 148 | |
| 149 | export function combinedAuthOutput(input: SourceControlAuthProbeInput): string { |
| 150 | const parts: string[] = []; |
| 151 | for (const entry of [input.stdout, input.stderr]) { |
| 152 | if (entry.trim().length > 0) { |
| 153 | parts.push(entry); |
| 154 | } |
| 155 | } |
| 156 | return parts.join("\n"); |
| 157 | } |
| 158 | |
| 159 | function sanitizedAuthLines(text: string): ReadonlyArray<string> { |
| 160 | const lines: string[] = []; |
| 161 | for (const entry of text.split(/\r?\n/)) { |
| 162 | const line = entry.trim(); |
| 163 | if (line.length === 0) continue; |
| 164 | if (/^[-\s]*token(?:\s+scopes?)?:/iu.test(line)) continue; |
| 165 | lines.push(line); |
| 166 | } |
| 167 | return lines; |
| 168 | } |
| 169 | |
| 170 | export function firstSafeAuthLine(text: string): string | undefined { |
| 171 | return sanitizedAuthLines(text)[0]; |
| 172 | } |
| 173 | |
| 174 | export function parseCliHost(text: string): string | undefined { |
| 175 | return sanitizedAuthLines(text) |
| 176 | .map((line) => line.replace(/^[^a-z0-9]+/iu, "")) |
| 177 | .find((line) => /^[a-z0-9][a-z0-9.-]*(?::\d+)?$/iu.test(line)); |
| 178 | } |
| 179 | |
| 180 | export function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): string | undefined { |
| 181 | for (const pattern of patterns) { |
| 182 | const match = pattern.exec(text); |
| 183 | const value = match?.[1]?.trim(); |
| 184 | if (value && value.length > 0) return value; |
| 185 | } |
| 186 | return undefined; |
| 187 | } |
| 188 | |
| 189 | function isCliRemoteRefinementSpec( |
| 190 | spec: SourceControlProviderDiscoverySpec, |
| 191 | ): spec is SourceControlCliRemoteRefinementSpec { |
| 192 | return spec.type === "cli" && spec.refineUnknownRemote !== undefined; |
| 193 | } |
| 194 | |
| 195 | const isVcsProcessTimeoutError = Schema.is(VcsProcessTimeoutError); |
| 196 | const isVcsProcessExitError = Schema.is(VcsProcessExitError); |
| 197 | |
| 198 | function probeCli(input: { |
| 199 | readonly spec: SourceControlCliDiscoverySpec; |
| 200 | readonly process: SourceControlHost.SourceControlHost["Service"]["process"]; |
| 201 | readonly cwd: string; |
| 202 | }): Effect.Effect<DiscoveryProbeResult> { |
| 203 | return input.process |
| 204 | .run({ |
| 205 | operation: "source-control.discovery.probe", |
| 206 | command: input.spec.executable, |
| 207 | args: input.spec.versionArgs, |
| 208 | cwd: input.cwd, |
| 209 | timeoutMs: probeTimeoutMs(input.spec), |
| 210 | maxOutputBytes: 8_000, |
| 211 | appendTruncationMarker: true, |
| 212 | }) |
| 213 | .pipe( |
| 214 | Effect.map( |
| 215 | (result) => |
| 216 | ({ |
| 217 | kind: input.spec.kind, |
| 218 | label: input.spec.label, |
| 219 | executable: input.spec.executable, |
| 220 | status: "available" as const, |
| 221 | version: Option.orElse(firstNonEmptyLine(result.stdout), () => |
| 222 | firstNonEmptyLine(result.stderr), |
| 223 | ), |
| 224 | installHint: input.spec.installHint, |
| 225 | detail: Option.none<string>(), |
| 226 | }) satisfies DiscoveryProbeResult, |
| 227 | ), |
| 228 | Effect.catch((cause) => |
| 229 | Effect.gen(function* () { |
| 230 | return { |
| 231 | kind: input.spec.kind, |
| 232 | label: input.spec.label, |
| 233 | executable: input.spec.executable, |
| 234 | status: "missing" as const, |
| 235 | version: Option.none<string>(), |
| 236 | installHint: yield* failedProbeHint(input.spec, cause), |
| 237 | detail: detailFromCause(cause), |
| 238 | } satisfies DiscoveryProbeResult; |
| 239 | }), |
| 240 | ), |
| 241 | ); |
| 242 | } |
| 243 | |
| 244 | export function probeSourceControlProvider(input: { |
| 245 | readonly spec: SourceControlProviderDiscoverySpec; |
| 246 | readonly process: SourceControlHost.SourceControlHost["Service"]["process"]; |
| 247 | readonly cwd: string; |
| 248 | }): Effect.Effect<SourceControlProviderDiscoveryItem> { |
| 249 | if (input.spec.type === "managed-cli") return input.spec.probe(input.cwd); |
| 250 | if (input.spec.type === "api") { |
| 251 | return input.spec.probeAuth.pipe( |
| 252 | Effect.timeoutOption(API_PROBE_TIMEOUT), |
| 253 | Effect.map( |
| 254 | Option.getOrElse(() => |
| 255 | unknownAuth("The hosting service did not answer in time. Refresh to try again."), |
| 256 | ), |
| 257 | ), |
| 258 | Effect.map( |
| 259 | (auth) => |
| 260 | ({ |
| 261 | kind: input.spec.kind, |
| 262 | label: input.spec.label, |
| 263 | status: "available" as const, |
| 264 | version: Option.none<string>(), |
| 265 | installHint: input.spec.installHint, |
| 266 | detail: Option.none<string>(), |
| 267 | auth, |
| 268 | }) satisfies SourceControlProviderDiscoveryItem, |
| 269 | ), |
| 270 | ); |
| 271 | } |
| 272 | |
| 273 | const spec = input.spec; |
| 274 | const runAuth = (args: ReadonlyArray<string>) => |
| 275 | input.process |
| 276 | .run({ |
| 277 | operation: "source-control.discovery.auth", |
| 278 | command: spec.executable, |
| 279 | args, |
| 280 | cwd: input.cwd, |
| 281 | allowNonZeroExit: true, |
| 282 | timeoutMs: probeTimeoutMs(spec), |
| 283 | maxOutputBytes: 8_000, |
| 284 | appendTruncationMarker: true, |
| 285 | }) |
| 286 | .pipe( |
| 287 | Effect.map(spec.parseAuth), |
| 288 | Effect.catch((cause) => |
| 289 | Effect.succeed(unknownAuth(Option.getOrUndefined(detailFromCause(cause)))), |
| 290 | ), |
| 291 | ); |
| 292 | const retryArgs = spec.authRetryArgs; |
| 293 | const auth = |
| 294 | retryArgs === undefined |
| 295 | ? runAuth(spec.authArgs) |
| 296 | : runAuth(spec.authArgs).pipe( |
| 297 | Effect.filterOrElse( |
| 298 | (result) => result.status !== "unauthenticated", |
| 299 | (signedOut) => |
| 300 | runAuth(retryArgs).pipe( |
| 301 | Effect.map((retry) => (retry.status === "authenticated" ? retry : signedOut)), |
| 302 | ), |
| 303 | ), |
| 304 | ); |
| 305 | |
| 306 | // The auth check does not depend on the version output, so both spawn at once. |
| 307 | return Effect.all( |
| 308 | [ |
| 309 | probeCli({ |
| 310 | spec, |
| 311 | process: input.process, |
| 312 | cwd: input.cwd, |
| 313 | }), |
| 314 | auth, |
| 315 | ], |
| 316 | { concurrency: "unbounded" }, |
| 317 | ).pipe( |
| 318 | Effect.map( |
| 319 | ([item, auth]) => |
| 320 | ({ |
| 321 | ...item, |
| 322 | auth: item.status === "available" ? auth : unknownAuth(item.installHint), |
| 323 | }) satisfies SourceControlProviderDiscoveryItem, |
| 324 | ), |
| 325 | ); |
| 326 | } |
| 327 | |
| 328 | const isVcsProcessSpawnError = Schema.is(VcsProcessSpawnError); |
| 329 | |
| 330 | /** The spawner checks cwd first, so ChildProcess NotFound identifies the executable. */ |
| 331 | export function isMissingExecutable(error: unknown): boolean { |
| 332 | return ( |
| 333 | isVcsProcessSpawnError(error) && |
| 334 | PlatformError.isPlatformError(error.cause) && |
| 335 | error.cause.reason._tag === "NotFound" && |
| 336 | error.cause.reason.module === "ChildProcess" |
| 337 | ); |
| 338 | } |
| 339 | |
| 340 | // macOS's EBADARCH, which Node has no name for: the binary is built for another CPU, such as an |
| 341 | // Intel-only `gh` on Apple Silicon without Rosetta. |
| 342 | const BAD_CPU_TYPE_ERRNO = -86; |
| 343 | |
| 344 | const unavailableInstallHint = Effect.fn("discovery.unavailableInstallHint")(function* ( |
| 345 | executable: string, |
| 346 | installHint: string, |
| 347 | cause: unknown, |
| 348 | ) { |
| 349 | const platform = yield* HostProcess.Platform; |
| 350 | if ( |
| 351 | platform !== "darwin" || |
| 352 | !isVcsProcessSpawnError(cause) || |
| 353 | !(cause.cause instanceof Error) || |
| 354 | !("errno" in cause.cause) || |
| 355 | cause.cause.errno !== BAD_CPU_TYPE_ERRNO |
| 356 | ) { |
| 357 | return installHint; |
| 358 | } |
| 359 | const resolveExecutable = yield* SpawnExecutableResolution; |
| 360 | const path = resolveExecutable(executable, platform, yield* HostProcess.Environment); |
| 361 | const architecture = yield* HostProcess.Architecture; |
| 362 | return `\`${path ?? executable}\` is built for another CPU architecture, so this ${architecture} machine cannot run it. Remove or replace it. ${installHint}`; |
| 363 | }); |
| 364 | |
| 365 | /** An installed CLI whose version probe failed needs a repair, not install advice. */ |
| 366 | function probeFailureHint( |
| 367 | probe: { readonly executable: string; readonly versionArgs: ReadonlyArray<string> }, |
| 368 | cause: unknown, |
| 369 | ): string { |
| 370 | const command = `\`${[probe.executable, ...probe.versionArgs].join(" ")}\``; |
| 371 | const outcome = isVcsProcessTimeoutError(cause) |
| 372 | ? `timed out after ${cause.timeoutMs}ms` |
| 373 | : isVcsProcessExitError(cause) |
| 374 | ? `exited with status ${cause.exitCode}` |
| 375 | : "failed"; |
| 376 | return `${command} ${outcome}. Check the \`${probe.executable}\` that the server's PATH resolves.`; |
| 377 | } |
| 378 | |
| 379 | export const failedProbeHint = Effect.fn("discovery.failedProbeHint")(function* ( |
| 380 | probe: { |
| 381 | readonly executable: string; |
| 382 | readonly versionArgs: ReadonlyArray<string>; |
| 383 | readonly installHint: string; |
| 384 | }, |
| 385 | cause: unknown, |
| 386 | ) { |
| 387 | const hint = yield* unavailableInstallHint(probe.executable, probe.installHint, cause); |
| 388 | // A wrong-CPU hint or an absent executable keeps its advice; other failures need repair. |
| 389 | return hint !== probe.installHint || isMissingExecutable(cause) |
| 390 | ? hint |
| 391 | : probeFailureHint(probe, cause); |
| 392 | }); |
| 393 | |
| 394 | class UnknownRemoteUnanswered extends Schema.TaggedError<UnknownRemoteUnanswered>()( |
| 395 | "UnknownRemoteUnanswered", |
| 396 | {}, |
| 397 | ) {} |
| 398 | |
| 399 | export interface UnknownRemoteVerdict { |
| 400 | readonly provider: SourceControlProviderInfo | null; |
| 401 | readonly settled: boolean; |
| 402 | } |
| 403 | |
| 404 | function refineWithSpec(input: { |
| 405 | readonly spec: SourceControlProviderDiscoverySpec; |
| 406 | readonly process: SourceControlHost.SourceControlHost["Service"]["process"]; |
| 407 | readonly cwd: string; |
| 408 | readonly context: SourceControlProvider.SourceControlProviderContext; |
| 409 | }): Effect.Effect<SourceControlProviderInfo | null, Cause.YieldableError> { |
| 410 | const { spec, context } = input; |
| 411 | if (spec.type === "managed-cli") { |
| 412 | return spec.refineUnknownRemote({ cwd: input.cwd, context }); |
| 413 | } |
| 414 | if (!isCliRemoteRefinementSpec(spec)) return Effect.succeed(null); |
| 415 | return input.process |
| 416 | .run({ |
| 417 | operation: "source-control.discovery.refine-unknown-remote", |
| 418 | command: spec.executable, |
| 419 | args: spec.remoteRefinementArgs?.(context) ?? spec.authArgs, |
| 420 | cwd: input.cwd, |
| 421 | allowNonZeroExit: true, |
| 422 | timeoutMs: probeTimeoutMs(spec), |
| 423 | maxOutputBytes: 8_000, |
| 424 | appendTruncationMarker: true, |
| 425 | }) |
| 426 | .pipe( |
| 427 | Effect.catchIf(isMissingExecutable, () => Effect.void), |
| 428 | Effect.flatMap((auth) => { |
| 429 | const provider = |
| 430 | auth === undefined ? null : spec.refineUnknownRemote({ cwd: input.cwd, context, auth }); |
| 431 | return provider === undefined |
| 432 | ? Effect.fail(new UnknownRemoteUnanswered()) |
| 433 | : Effect.succeed(provider); |
| 434 | }), |
| 435 | ); |
| 436 | } |
| 437 | |
| 438 | export const refineUnknownRemoteProvider = Effect.fn("refineUnknownRemoteProvider")( |
| 439 | function* (input: { |
| 440 | readonly specs: ReadonlyArray<SourceControlProviderDiscoverySpec>; |
| 441 | readonly process: SourceControlHost.SourceControlHost["Service"]["process"]; |
| 442 | readonly cwd: string; |
| 443 | readonly context: SourceControlProvider.SourceControlProviderContext; |
| 444 | }): Effect.fn.Return<UnknownRemoteVerdict> { |
| 445 | const results = yield* Effect.forEach(input.specs, (spec) => |
| 446 | refineWithSpec({ ...input, spec }).pipe(Effect.result), |
| 447 | ); |
| 448 | // An earlier integration that could not answer might have claimed this host. |
| 449 | let settled = true; |
| 450 | for (const result of results) { |
| 451 | if (Result.isFailure(result)) settled = false; |
| 452 | else if (result.success !== null) return { provider: result.success, settled }; |
| 453 | } |
| 454 | return { provider: null, settled }; |
| 455 | }, |
| 456 | ); |