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
| 1 | import { |
| 2 | ProviderSetupError, |
| 3 | type ProviderAuthMethod, |
| 4 | type ProviderInstanceId, |
| 5 | } from "@t3tools/contracts"; |
| 6 | import type { AcpRegistrySettings } from "../settings.ts"; |
| 7 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 8 | import * as NodeUtil from "node:util"; |
| 9 | import * as Cause from "effect/Cause"; |
| 10 | import * as Deferred from "effect/Deferred"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as Exit from "effect/Exit"; |
| 13 | import * as Layer from "effect/Layer"; |
| 14 | import * as Option from "effect/Option"; |
| 15 | import * as Queue from "effect/Queue"; |
| 16 | import * as Scope from "effect/Scope"; |
| 17 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 18 | import * as Schema from "effect/Schema"; |
| 19 | import type * as AcpSchema from "effect-acp/compat"; |
| 20 | import * as EffectAcpErrors from "effect-acp/errors"; |
| 21 | |
| 22 | import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; |
| 23 | import * as ProviderAuthFlow from "@t3tools/provider-core/server/providerAuthFlow"; |
| 24 | import { normalizeAcpRegistryAuthMethods, normalizeAcpRegistryWebUrl } from "./probe.ts"; |
| 25 | import * as AcpRegistrySupport from "./AcpRegistrySupport.ts"; |
| 26 | import * as AcpRegistryRuntimeCoordinator from "./AcpRegistryRuntimeCoordinator.ts"; |
| 27 | import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; |
| 28 | |
| 29 | const isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError); |
| 30 | |
| 31 | const MAX_ERROR_MESSAGE_LENGTH = 500; |
| 32 | |
| 33 | const appendDetail = (detail: string, reason: string): string => { |
| 34 | let message = reason.trim(); |
| 35 | if (message.length > MAX_ERROR_MESSAGE_LENGTH) { |
| 36 | message = `${message.slice(0, MAX_ERROR_MESSAGE_LENGTH).trimEnd()}…`; |
| 37 | } |
| 38 | if (message.length === 0) return detail; |
| 39 | const trimmed = detail.trimEnd(); |
| 40 | const prefix = trimmed.endsWith(".") ? `${trimmed} ` : `${trimmed}. `; |
| 41 | return `${prefix}${message}`; |
| 42 | }; |
| 43 | |
| 44 | export const formatFailureDetail = (detail: string, cause?: unknown): string => { |
| 45 | const unwrapped = Cause.isCause(cause) ? Cause.squash(cause) : cause; |
| 46 | return isAcpRequestError(unwrapped) ? appendDetail(detail, unwrapped.errorMessage) : detail; |
| 47 | }; |
| 48 | |
| 49 | const MAX_LOGIN_OUTPUT_LINES = 5; |
| 50 | |
| 51 | const lastPrintedLines = (output: string): string => { |
| 52 | const lines = NodeUtil.stripVTControlCharacters(output) |
| 53 | .split("\n") |
| 54 | .map((line) => line.trimEnd()) |
| 55 | // A carriage return inside a line redraws it, so only the text after the last one is visible. |
| 56 | .map((line) => line.slice(line.lastIndexOf("\r") + 1).trim()) |
| 57 | .filter((line) => line.length > 0) |
| 58 | .slice(-MAX_LOGIN_OUTPUT_LINES) |
| 59 | .join(" "); |
| 60 | return lines.length > MAX_ERROR_MESSAGE_LENGTH |
| 61 | ? `…${lines.slice(-MAX_ERROR_MESSAGE_LENGTH).trimStart()}` |
| 62 | : lines; |
| 63 | }; |
| 64 | |
| 65 | type Runtime = Pick< |
| 66 | AcpSessionRuntime.AcpSessionRuntime["Service"], |
| 67 | "initialize" | "authenticate" | "start" | "handleElicitation" | "logout" |
| 68 | >; |
| 69 | |
| 70 | export const makeAcpRegistryAuth = Effect.fn("makeAcpRegistryAuth")(function* (options: { |
| 71 | readonly instanceId: ProviderInstanceId; |
| 72 | readonly settings: AcpRegistrySettings; |
| 73 | readonly cwd: string; |
| 74 | readonly environment: NodeJS.ProcessEnv; |
| 75 | readonly onChanged: (authenticated: boolean) => Effect.Effect<void>; |
| 76 | readonly makeRuntime?: ( |
| 77 | spawn: AcpSessionRuntime.AcpSpawnInput, |
| 78 | ) => Effect.Effect<Runtime, ProviderSetupError, Scope.Scope>; |
| 79 | }) { |
| 80 | const catalog = yield* AcpRegistrySupport.AcpRegistryCatalog; |
| 81 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 82 | const random = yield* SecureRandom.SecureRandom; |
| 83 | const pty = yield* Effect.serviceOption(PtyAdapter.PtyAdapter); |
| 84 | const coordinator = yield* Effect.serviceOption( |
| 85 | AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator, |
| 86 | ); |
| 87 | const agentKey = |
| 88 | options.settings.source === "local" ? `local:${options.instanceId}` : options.settings.agentId; |
| 89 | const failure = (operation: string, detail: string, cause?: unknown) => |
| 90 | new ProviderSetupError({ |
| 91 | instanceId: options.instanceId, |
| 92 | operation, |
| 93 | detail: formatFailureDetail(detail, cause), |
| 94 | cause, |
| 95 | }); |
| 96 | const resolve = catalog |
| 97 | .resolve(options.settings, options.cwd, options.environment) |
| 98 | .pipe( |
| 99 | Effect.mapError((cause) => |
| 100 | failure("start", "Could not prepare the selected ACP agent.", cause), |
| 101 | ), |
| 102 | ); |
| 103 | const makeRuntime = |
| 104 | options.makeRuntime ?? |
| 105 | ((spawn) => |
| 106 | Effect.gen(function* () { |
| 107 | const context = yield* Layer.build( |
| 108 | AcpSessionRuntime.layer({ |
| 109 | spawn, |
| 110 | cwd: options.cwd, |
| 111 | authenticateOnAuthRequired: false, |
| 112 | clientCapabilities: { |
| 113 | auth: { terminal: Option.isSome(pty) }, |
| 114 | elicitation: { url: {} }, |
| 115 | fs: { readTextFile: false, writeTextFile: false }, |
| 116 | terminal: false, |
| 117 | }, |
| 118 | clientInfo: { name: "t3-code-provider-auth", version: "0.0.0" }, |
| 119 | }).pipe( |
| 120 | Layer.provide( |
| 121 | Layer.mergeAll( |
| 122 | Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), |
| 123 | Layer.succeed(SecureRandom.SecureRandom, random), |
| 124 | ), |
| 125 | ), |
| 126 | ), |
| 127 | ); |
| 128 | return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( |
| 129 | Effect.provide(context), |
| 130 | ); |
| 131 | }).pipe( |
| 132 | Effect.mapError((cause) => |
| 133 | failure("start", "Could not start the selected ACP agent.", cause), |
| 134 | ), |
| 135 | )); |
| 136 | |
| 137 | let knownMethods: |
| 138 | | { readonly version: string | null; readonly methods: ReadonlyArray<ProviderAuthMethod> } |
| 139 | | undefined; |
| 140 | const discoverMethods = Effect.scoped( |
| 141 | Effect.gen(function* () { |
| 142 | const inspected = yield* catalog |
| 143 | .inspect(options.settings, options.environment) |
| 144 | .pipe( |
| 145 | Effect.mapError((cause) => |
| 146 | failure("methods", "Could not inspect the selected ACP agent.", cause), |
| 147 | ), |
| 148 | ); |
| 149 | if (inspected.status !== "ready") |
| 150 | return yield* failure("methods", "Prepare this ACP agent before signing in."); |
| 151 | // Path overrides can change in place; cache discovery only for registry versions. |
| 152 | if (inspected.version !== null && knownMethods?.version === inspected.version) |
| 153 | return knownMethods.methods; |
| 154 | const resolved = yield* resolve; |
| 155 | const runtime = yield* makeRuntime(resolved.spawn); |
| 156 | const initialized = yield* runtime |
| 157 | .initialize() |
| 158 | .pipe( |
| 159 | Effect.mapError((cause) => |
| 160 | failure("methods", "Could not discover this agent's sign-in methods.", cause), |
| 161 | ), |
| 162 | ); |
| 163 | const advertised = normalizeAcpRegistryAuthMethods(initialized.authMethods) |
| 164 | .filter( |
| 165 | (method) => method.id.length <= 128 && (method.type !== "terminal" || Option.isSome(pty)), |
| 166 | ) |
| 167 | .slice(0, 32) |
| 168 | .map((method) => ({ |
| 169 | id: method.id, |
| 170 | name: method.name, |
| 171 | description: method.description, |
| 172 | type: method.type === "env_var" ? ("credentials" as const) : method.type, |
| 173 | })); |
| 174 | knownMethods = { version: inspected.version, methods: advertised }; |
| 175 | return advertised; |
| 176 | }), |
| 177 | ).pipe( |
| 178 | Effect.timeoutOrElse({ |
| 179 | duration: "30 seconds", |
| 180 | orElse: () => |
| 181 | Effect.fail(failure("methods", "The ACP agent did not advertise sign-in methods in time.")), |
| 182 | }), |
| 183 | ); |
| 184 | |
| 185 | const methods = Option.isSome(coordinator) |
| 186 | ? coordinator.value |
| 187 | .runBackgroundProbe(agentKey, discoverMethods) |
| 188 | .pipe( |
| 189 | Effect.flatMap((result) => |
| 190 | Effect.fromOption(result, () => |
| 191 | failure( |
| 192 | "methods", |
| 193 | "Sign-in discovery was interrupted by an active provider session. Try again.", |
| 194 | ), |
| 195 | ), |
| 196 | ), |
| 197 | ) |
| 198 | : discoverMethods; |
| 199 | |
| 200 | const runTerminal = Effect.fnUntraced(function* ( |
| 201 | resolved: AcpRegistrySupport.ResolvedAcpRegistryAgent, |
| 202 | method: Extract<AcpSchema.AuthMethod, { readonly type: "terminal" }>, |
| 203 | context: ProviderAuthFlow.ProviderAuthFlowContext, |
| 204 | ) { |
| 205 | if (Option.isNone(pty)) |
| 206 | return yield* failure( |
| 207 | "start", |
| 208 | "Interactive provider login is unavailable on this environment.", |
| 209 | ); |
| 210 | const exited = yield* Deferred.make<number>(); |
| 211 | const output = yield* Queue.sliding<string>(64); |
| 212 | const process = yield* pty.value |
| 213 | .spawn({ |
| 214 | shell: resolved.spawn.command, |
| 215 | args: [...resolved.spawn.args, ...(method.args ?? [])], |
| 216 | cwd: options.cwd, |
| 217 | cols: 80, |
| 218 | rows: 24, |
| 219 | env: { ...options.environment, ...resolved.spawn.env, ...method.env }, |
| 220 | }) |
| 221 | .pipe( |
| 222 | Effect.mapError((cause) => |
| 223 | failure("start", "Could not open the provider sign-in terminal.", cause), |
| 224 | ), |
| 225 | ); |
| 226 | // Kept in the callback so output that arrives just before exit is not lost to the reader. |
| 227 | let printed = ""; |
| 228 | const detachData = process.onData((data) => { |
| 229 | printed = (printed + data).slice(-4_096); |
| 230 | Queue.offerUnsafe(output, data.slice(-16_384)); |
| 231 | }); |
| 232 | const detachExit = process.onExit(({ exitCode }) => { |
| 233 | Deferred.doneUnsafe(exited, Effect.succeed(exitCode)); |
| 234 | }); |
| 235 | yield* Effect.addFinalizer(() => |
| 236 | Effect.sync(() => { |
| 237 | detachData(); |
| 238 | detachExit(); |
| 239 | try { |
| 240 | process.kill(); |
| 241 | } catch {} |
| 242 | }), |
| 243 | ); |
| 244 | let transcript = ""; |
| 245 | let outputOffset = 0; |
| 246 | const update = () => |
| 247 | context.setInteraction( |
| 248 | { type: "terminal", id: "terminal", output: transcript, outputOffset }, |
| 249 | (response) => |
| 250 | response.type === "terminal" |
| 251 | ? Effect.try({ |
| 252 | try: () => { |
| 253 | if (response.size) process.resize(response.size.cols, response.size.rows); |
| 254 | if (response.data) |
| 255 | process.write(PtyAdapter.ptyInput(response.data, response.binary)); |
| 256 | }, |
| 257 | catch: () => |
| 258 | failure("respond", "The provider sign-in terminal is no longer available."), |
| 259 | }) |
| 260 | : Effect.void, |
| 261 | ); |
| 262 | yield* update(); |
| 263 | yield* Queue.take(output).pipe( |
| 264 | Effect.flatMap((data) => { |
| 265 | outputOffset += data.length; |
| 266 | transcript = (transcript + data).slice(-16_384); |
| 267 | return update(); |
| 268 | }), |
| 269 | Effect.forever, |
| 270 | Effect.forkScoped, |
| 271 | ); |
| 272 | if ((yield* Deferred.await(exited)) !== 0) |
| 273 | return yield* new ProviderSetupError({ |
| 274 | instanceId: options.instanceId, |
| 275 | operation: "start", |
| 276 | detail: appendDetail( |
| 277 | "The provider login command did not finish successfully.", |
| 278 | lastPrintedLines(printed), |
| 279 | ), |
| 280 | }); |
| 281 | }); |
| 282 | |
| 283 | const authenticate = Effect.fn("AcpRegistryAuth.authenticate")(function* ( |
| 284 | methodId: string, |
| 285 | context: ProviderAuthFlow.ProviderAuthFlowContext, |
| 286 | ) { |
| 287 | if (!options.settings.enabled) |
| 288 | return yield* failure("start", "Enable this provider before signing in."); |
| 289 | const login = Effect.scoped( |
| 290 | Effect.gen(function* () { |
| 291 | const resolved = yield* resolve; |
| 292 | const runtimeScope = yield* Scope.make(); |
| 293 | yield* Effect.addFinalizer(() => Scope.close(runtimeScope, Exit.void)); |
| 294 | const runtime = yield* makeRuntime(resolved.spawn).pipe( |
| 295 | Effect.provideService(Scope.Scope, runtimeScope), |
| 296 | ); |
| 297 | yield* runtime.handleElicitation((request) => |
| 298 | Effect.gen(function* () { |
| 299 | if ( |
| 300 | request.mode !== "url" || |
| 301 | !("url" in request) || |
| 302 | !("elicitationId" in request) || |
| 303 | typeof request.url !== "string" || |
| 304 | typeof request.elicitationId !== "string" |
| 305 | ) |
| 306 | return { action: "decline" } as const; |
| 307 | const url = normalizeAcpRegistryWebUrl(request.url); |
| 308 | const id = request.elicitationId.trim(); |
| 309 | if (!url || !id || id.length > 128) return { action: "decline" } as const; |
| 310 | const consent = yield* Deferred.make<boolean>(); |
| 311 | yield* context.setInteraction( |
| 312 | { type: "browser", id, url, requiresConsent: true }, |
| 313 | (response) => |
| 314 | response.type === "browser" |
| 315 | ? Deferred.succeed(consent, response.action === "accept").pipe(Effect.asVoid) |
| 316 | : Effect.void, |
| 317 | ); |
| 318 | return (yield* Deferred.await(consent)) |
| 319 | ? ({ action: "accept" } as const) |
| 320 | : ({ action: "decline" } as const); |
| 321 | }), |
| 322 | ); |
| 323 | const initialized = yield* runtime |
| 324 | .initialize() |
| 325 | .pipe( |
| 326 | Effect.mapError((cause) => |
| 327 | failure("start", "Could not initialize the selected ACP agent.", cause), |
| 328 | ), |
| 329 | ); |
| 330 | const method = initialized.authMethods?.find((method) => method.id === methodId); |
| 331 | if (!method) |
| 332 | return yield* failure("start", "The agent no longer advertises this sign-in method."); |
| 333 | if (method.type === "terminal") { |
| 334 | yield* Scope.close(runtimeScope, Exit.void); |
| 335 | yield* runTerminal(resolved, method, context).pipe(Effect.scoped); |
| 336 | // Terminal login is a separate invocation. Reconnect after it exits so |
| 337 | // the ACP process reads the credentials its login command persisted. |
| 338 | const verifiedRuntime = yield* makeRuntime(resolved.spawn); |
| 339 | yield* context.verifying; |
| 340 | yield* verifiedRuntime |
| 341 | .start() |
| 342 | .pipe( |
| 343 | Effect.mapError((cause) => |
| 344 | failure( |
| 345 | "verify", |
| 346 | "The provider could not create a session after terminal sign-in.", |
| 347 | cause, |
| 348 | ), |
| 349 | ), |
| 350 | ); |
| 351 | } else { |
| 352 | if (method.type === undefined || method.type === "agent") { |
| 353 | if (!runtime.authenticate) |
| 354 | return yield* failure("start", "This runtime does not support explicit ACP sign-in."); |
| 355 | yield* runtime |
| 356 | .authenticate(methodId) |
| 357 | .pipe( |
| 358 | Effect.mapError((cause) => |
| 359 | failure("start", "The ACP agent could not complete sign-in.", cause), |
| 360 | ), |
| 361 | ); |
| 362 | } |
| 363 | // Legacy env_var methods use the secret-backed environment fields in |
| 364 | // provider settings. Never send their ID to authenticate. |
| 365 | yield* context.verifying; |
| 366 | yield* runtime |
| 367 | .start() |
| 368 | .pipe( |
| 369 | Effect.mapError((cause) => |
| 370 | failure("verify", "The provider could not create a session after sign-in.", cause), |
| 371 | ), |
| 372 | ); |
| 373 | } |
| 374 | }), |
| 375 | ); |
| 376 | yield* Option.isSome(coordinator) |
| 377 | ? coordinator.value.withForegroundStartup(agentKey, login) |
| 378 | : login; |
| 379 | yield* options.onChanged(true); |
| 380 | }); |
| 381 | const logout = Effect.scoped( |
| 382 | Effect.gen(function* () { |
| 383 | const resolved = yield* resolve; |
| 384 | const runtime = yield* makeRuntime(resolved.spawn); |
| 385 | yield* runtime.logout.pipe( |
| 386 | Effect.mapError((cause) => |
| 387 | failure( |
| 388 | "logout", |
| 389 | "This ACP agent could not sign out. It may not advertise logout support.", |
| 390 | cause, |
| 391 | ), |
| 392 | ), |
| 393 | ); |
| 394 | }), |
| 395 | ).pipe( |
| 396 | Effect.timeoutOrElse({ |
| 397 | duration: "60 seconds", |
| 398 | orElse: () => |
| 399 | Effect.fail(failure("logout", "The ACP agent did not finish signing out in time.")), |
| 400 | }), |
| 401 | ); |
| 402 | const signOut = ( |
| 403 | Option.isSome(coordinator) ? coordinator.value.withForegroundStartup(agentKey, logout) : logout |
| 404 | ).pipe(Effect.andThen(options.onChanged(false))); |
| 405 | return yield* ProviderAuthFlow.make({ |
| 406 | instanceId: options.instanceId, |
| 407 | // ACP omits credential scope; assume an agent's instances share credentials in this environment. |
| 408 | credentialBinding: { owner: "provider", key: `acp:${agentKey}` }, |
| 409 | methods, |
| 410 | ...(options.settings.authMethodId ? { defaultMethodId: options.settings.authMethodId } : {}), |
| 411 | authenticate, |
| 412 | logout: signOut, |
| 413 | }); |
| 414 | }); |