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 | // @effect-diagnostics-next-line nodeBuiltinImport:off -- the SDK's spawn hook returns a Node child process. |
| 2 | import * as NodeChildProcess from "node:child_process"; |
| 3 | |
| 4 | import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe"; |
| 5 | import { |
| 6 | type ClaudeSettings, |
| 7 | type ModelCapabilities, |
| 8 | type ServerProvider, |
| 9 | type ServerProviderModel, |
| 10 | type ServerProviderSlashCommand, |
| 11 | type ServerProviderResetCredits, |
| 12 | } from "@t3tools/contracts"; |
| 13 | import * as Cause from "effect/Cause"; |
| 14 | import * as DateTime from "effect/DateTime"; |
| 15 | import * as Effect from "effect/Effect"; |
| 16 | import * as FileSystem from "effect/FileSystem"; |
| 17 | import * as Option from "effect/Option"; |
| 18 | import * as Path from "effect/Path"; |
| 19 | import * as Ref from "effect/Ref"; |
| 20 | import * as Result from "effect/Result"; |
| 21 | import * as Schema from "effect/Schema"; |
| 22 | import { ChildProcess, ChildProcessSpawner } from "effect/process"; |
| 23 | import { createModelCapabilities } from "@t3tools/shared/model"; |
| 24 | import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline"; |
| 25 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 26 | import * as SpawnWorker from "../process/SpawnWorker.ts"; |
| 27 | import { resolveSpawnCommand } from "@t3tools/shared/shell"; |
| 28 | import { |
| 29 | query as claudeQuery, |
| 30 | type ModelInfo as ClaudeModelInfo, |
| 31 | type Options as ClaudeQueryOptions, |
| 32 | type SlashCommand as ClaudeSlashCommand, |
| 33 | type SDKControlGetUsageResponse, |
| 34 | type SDKUserMessage, |
| 35 | type SettingSource, |
| 36 | type SpawnOptions as ClaudeSpawnOptions, |
| 37 | } from "@anthropic-ai/claude-agent-sdk"; |
| 38 | |
| 39 | import { |
| 40 | buildServerProvider, |
| 41 | COMPACT_SLASH_COMMAND, |
| 42 | DEFAULT_TIMEOUT_MS, |
| 43 | isCommandMissingCause, |
| 44 | parseCliVersionResult, |
| 45 | providerModelsFromSettings, |
| 46 | providerProbeEnvironment, |
| 47 | spawnAndCollect, |
| 48 | type ServerProviderDraft, |
| 49 | } from "@t3tools/provider-core/server/snapshotProbe"; |
| 50 | import { resolveClaudeSdkExecutablePath } from "./Drivers/ClaudeExecutable.ts"; |
| 51 | import { |
| 52 | claudeSignedOutMessage, |
| 53 | hasClaudeManagedMcpConfig, |
| 54 | makeClaudeEnvironment, |
| 55 | } from "./Drivers/ClaudeHome.ts"; |
| 56 | import { |
| 57 | customClaudeApiEndpointHost, |
| 58 | discoverClaudeSkills, |
| 59 | readClaudeSettingsEnv, |
| 60 | } from "./Drivers/ClaudeSkills.ts"; |
| 61 | import type { ProviderWorkspaceSnapshot } from "@t3tools/provider-core/server/driver"; |
| 62 | import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits"; |
| 63 | import { |
| 64 | type ClaudeScopedLimitNames, |
| 65 | claudeUsageResponseToLimits, |
| 66 | recordClaudeUsageResponse, |
| 67 | } from "./claudeUsageLimits.ts"; |
| 68 | import { |
| 69 | BUNDLED_CLAUDE_MODEL_CATALOG, |
| 70 | CLAUDE_EFFORT_LEVELS, |
| 71 | capClaudeCatalogEffort, |
| 72 | type ClaudeEffortCapSource, |
| 73 | type ClaudeEffortLevel, |
| 74 | type ClaudeModelCatalog, |
| 75 | claudeReportedModels, |
| 76 | formatClaudeVersionUpgradeMessage, |
| 77 | resolveClaudeModelsForVersion, |
| 78 | resolveClaudeUpdateRequiredModels, |
| 79 | withUltracodeToggle, |
| 80 | } from "./ClaudeModelCatalog.ts"; |
| 81 | |
| 82 | const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({ |
| 83 | optionDescriptors: [], |
| 84 | }); |
| 85 | |
| 86 | function claudeProviderModels( |
| 87 | builtInModels: ReadonlyArray<ServerProviderModel>, |
| 88 | customModels: ClaudeSettings["customModels"], |
| 89 | ): ReadonlyArray<ServerProviderModel> { |
| 90 | return providerModelsFromSettings( |
| 91 | builtInModels, |
| 92 | customModels, |
| 93 | DEFAULT_CLAUDE_MODEL_CAPABILITIES, |
| 94 | ).map((model) => |
| 95 | model.isCustom ? { ...model, capabilities: withUltracodeToggle(model.capabilities) } : model, |
| 96 | ); |
| 97 | } |
| 98 | |
| 99 | const CLAUDE_PRESENTATION = { |
| 100 | displayName: "Claude", |
| 101 | showInteractionModeToggle: true, |
| 102 | reportsContextWindow: true, |
| 103 | } as const; |
| 104 | function toTitleCaseWords(value: string): string { |
| 105 | const parts: Array<string> = []; |
| 106 | for (const part of value.split(/[\s_-]+/g)) { |
| 107 | if (part.length > 0) { |
| 108 | parts.push(part[0]!.toUpperCase() + part.slice(1).toLowerCase()); |
| 109 | } |
| 110 | } |
| 111 | return parts.join(" "); |
| 112 | } |
| 113 | |
| 114 | function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined { |
| 115 | const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, ""); |
| 116 | if (!normalized) return undefined; |
| 117 | |
| 118 | switch (normalized) { |
| 119 | case "claudemaxsubscription": |
| 120 | case "claudemax5xsubscription": |
| 121 | return "Max"; |
| 122 | case "claudemax20xsubscription": |
| 123 | return "Ultra"; |
| 124 | case "claudeenterprisesubscription": |
| 125 | return "Enterprise"; |
| 126 | case "claudeteamsubscription": |
| 127 | return "Team"; |
| 128 | case "claudeprosubscription": |
| 129 | return "Pro"; |
| 130 | case "claudefreesubscription": |
| 131 | return "Free"; |
| 132 | case "max": |
| 133 | case "maxplan": |
| 134 | case "max5": |
| 135 | return "Max"; |
| 136 | case "max20": |
| 137 | return "Ultra"; |
| 138 | case "enterprise": |
| 139 | return "Enterprise"; |
| 140 | case "team": |
| 141 | return "Team"; |
| 142 | case "pro": |
| 143 | return "Pro"; |
| 144 | case "free": |
| 145 | return "Free"; |
| 146 | default: |
| 147 | return toTitleCaseWords(subscriptionType!); |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined { |
| 152 | const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, ""); |
| 153 | if (!normalized) return undefined; |
| 154 | if ( |
| 155 | normalized === "apikey" || |
| 156 | normalized === "anthropicapikey" || |
| 157 | normalized === "anthropicauthtoken" |
| 158 | ) { |
| 159 | return "apiKey"; |
| 160 | } |
| 161 | return undefined; |
| 162 | } |
| 163 | |
| 164 | function formatClaudeSubscriptionAuthLabel(subscriptionType: string): string { |
| 165 | const subscriptionLabel = |
| 166 | claudeSubscriptionLabel(subscriptionType) ?? toTitleCaseWords(subscriptionType); |
| 167 | const normalized = subscriptionLabel.toLowerCase().replace(/[\s_-]+/g, ""); |
| 168 | |
| 169 | if (normalized.startsWith("claude") && normalized.endsWith("subscription")) { |
| 170 | return subscriptionLabel; |
| 171 | } |
| 172 | if (normalized.startsWith("claude")) { |
| 173 | return `${subscriptionLabel} Subscription`; |
| 174 | } |
| 175 | if (normalized.endsWith("subscription")) { |
| 176 | return `Claude ${subscriptionLabel}`; |
| 177 | } |
| 178 | return `Claude ${subscriptionLabel} Subscription`; |
| 179 | } |
| 180 | |
| 181 | function hasApiKey(apiKeySource: string | undefined): boolean { |
| 182 | return Boolean(apiKeySource) && apiKeySource !== "none"; |
| 183 | } |
| 184 | |
| 185 | function claudeAuthMetadata(input: { |
| 186 | readonly subscriptionType: string | undefined; |
| 187 | readonly authMethod: string | undefined; |
| 188 | readonly apiKeySource: string | undefined; |
| 189 | }): { readonly type: string; readonly label: string } | undefined { |
| 190 | if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey" || hasApiKey(input.apiKeySource)) { |
| 191 | return { |
| 192 | type: "apiKey", |
| 193 | label: "Claude API Key", |
| 194 | }; |
| 195 | } |
| 196 | |
| 197 | if (input.subscriptionType) { |
| 198 | return { |
| 199 | type: input.subscriptionType, |
| 200 | label: formatClaudeSubscriptionAuthLabel(input.subscriptionType), |
| 201 | }; |
| 202 | } |
| 203 | |
| 204 | return undefined; |
| 205 | } |
| 206 | |
| 207 | function apiProviderAuthMetadata( |
| 208 | apiProvider: string | undefined, |
| 209 | ): { readonly type: string; readonly label: string } | undefined { |
| 210 | return apiProvider === "bedrock" ? { type: "bedrock", label: "Amazon Bedrock" } : undefined; |
| 211 | } |
| 212 | |
| 213 | /** Probe completion only proves Claude started. Only tokenSource: "none" disproves auth. */ |
| 214 | function claudeAuthStatus( |
| 215 | capabilities: Pick< |
| 216 | ClaudeCapabilitiesProbe, |
| 217 | "email" | "subscriptionType" | "tokenSource" | "apiKeySource" | "apiProvider" |
| 218 | >, |
| 219 | ): "authenticated" | "unauthenticated" { |
| 220 | if (capabilities.apiProvider !== undefined && capabilities.apiProvider !== "firstParty") { |
| 221 | return "authenticated"; |
| 222 | } |
| 223 | if (capabilities.tokenSource !== "none") return "authenticated"; |
| 224 | // API keys can authenticate with tokenSource: none; also check key and account fields. |
| 225 | return hasApiKey(capabilities.apiKeySource) || capabilities.email || capabilities.subscriptionType |
| 226 | ? "authenticated" |
| 227 | : "unauthenticated"; |
| 228 | } |
| 229 | |
| 230 | // Bedrock initialization includes backend startup and awsAuthRefresh, taking longer than first-party auth. |
| 231 | const CAPABILITIES_PROBE_TIMEOUT_MS = 25_000; |
| 232 | // Native CLI startup on Windows can exceed the shared probe deadline. |
| 233 | const CLAUDE_VERSION_CHECK_TIMEOUT_MS = 20_000; |
| 234 | |
| 235 | const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [ |
| 236 | "user", |
| 237 | "project", |
| 238 | "local", |
| 239 | ] as const satisfies ReadonlyArray<SettingSource>; |
| 240 | |
| 241 | /** |
| 242 | * The SDK's own spawn stats the executable and hands libuv the workspace as cwd, so a mount |
| 243 | * that stops answering freezes the server. `env` enters the cwd and finds the CLI in the child. |
| 244 | * A shell would not do: dash drops the exported Bash functions a launcher may call. |
| 245 | */ |
| 246 | export function spawnClaudeProbeThroughEnv({ |
| 247 | command, |
| 248 | args, |
| 249 | cwd, |
| 250 | env, |
| 251 | signal, |
| 252 | }: ClaudeSpawnOptions) { |
| 253 | const launch = envTrampoline(command, args, cwd) ?? { command, args, cwd }; |
| 254 | return NodeChildProcess.spawn(launch.command, launch.args, { |
| 255 | ...("cwd" in launch ? { cwd: launch.cwd } : {}), |
| 256 | env, |
| 257 | signal, |
| 258 | // The probe ignores stderr. |
| 259 | stdio: ["pipe", "pipe", "ignore"], |
| 260 | }); |
| 261 | } |
| 262 | |
| 263 | /** Windows runs CreateProcess on the calling thread, so the probe launches from a launcher thread. */ |
| 264 | function spawnClaudeProbeOffThread({ command, args, cwd, env, signal }: ClaudeSpawnOptions) { |
| 265 | const child = SpawnWorker.spawnPiped(command, args, { cwd, env, signal, windowsHide: true }); |
| 266 | // The probe ignores stderr; drain it so a full pipe cannot stall the CLI. |
| 267 | child.stderr.resume(); |
| 268 | return child; |
| 269 | } |
| 270 | |
| 271 | export function buildClaudeCapabilitiesProbeQueryOptions(input: { |
| 272 | readonly executablePath: string; |
| 273 | readonly abortController: AbortController; |
| 274 | readonly environment: NodeJS.ProcessEnv; |
| 275 | readonly cwd: string | undefined; |
| 276 | readonly managedMcpConfig: boolean; |
| 277 | readonly spawnVia: "env" | "launcher-thread" | undefined; |
| 278 | }): ClaudeQueryOptions { |
| 279 | return { |
| 280 | ...(input.spawnVia === "env" ? { spawnClaudeCodeProcess: spawnClaudeProbeThroughEnv } : {}), |
| 281 | ...(input.spawnVia === "launcher-thread" |
| 282 | ? { spawnClaudeCodeProcess: spawnClaudeProbeOffThread } |
| 283 | : {}), |
| 284 | persistSession: false, |
| 285 | pathToClaudeCodeExecutable: input.executablePath, |
| 286 | abortController: input.abortController, |
| 287 | settingSources: [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES], |
| 288 | // Keep settings for slash-command discovery, but disable hooks so health checks do not run SessionStart repeatedly. |
| 289 | settings: { disableAllHooks: true }, |
| 290 | allowedTools: [], |
| 291 | // Exclude filesystem MCP servers; omit strict mode when managed-mcp.json already excludes them and forbids the flag. |
| 292 | mcpServers: {}, |
| 293 | ...(input.managedMcpConfig ? {} : { strictMcpConfig: true }), |
| 294 | env: { |
| 295 | ...providerProbeEnvironment(input.environment), |
| 296 | // Disable claude.ai MCP separately; it is discovered outside filesystem config. |
| 297 | ENABLE_CLAUDEAI_MCP_SERVERS: "false", |
| 298 | // Skipping this avoids a Windows tasklist | findstr process tree on every refresh. |
| 299 | FORCE_CODE_TERMINAL: undefined, |
| 300 | CLAUDE_CODE_AUTO_CONNECT_IDE: "0", |
| 301 | CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL: "1", |
| 302 | }, |
| 303 | ...(input.cwd ? { cwd: input.cwd } : {}), |
| 304 | stderr: () => {}, |
| 305 | }; |
| 306 | } |
| 307 | |
| 308 | function nonEmptyProbeString(value: string): string | undefined { |
| 309 | const candidate = value.trim(); |
| 310 | return candidate ? candidate : undefined; |
| 311 | } |
| 312 | |
| 313 | export type ClaudeCapabilitiesProbe = { |
| 314 | readonly email: string | undefined; |
| 315 | readonly workspaceId?: string | undefined; |
| 316 | readonly subscriptionType: string | undefined; |
| 317 | readonly tokenSource: string | undefined; |
| 318 | readonly apiKeySource: string | undefined; |
| 319 | /** OAuth applies only to firstParty; Bedrock uses external AWS credentials and omits subscription/token fields. */ |
| 320 | readonly apiProvider: string | undefined; |
| 321 | readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>; |
| 322 | readonly models?: ReadonlyArray<ClaudeModelInfo>; |
| 323 | /** Undefined means get_usage failed; absent windows on success mean no subscription windows, as with API keys. */ |
| 324 | readonly usage?: Pick<SDKControlGetUsageResponse, "rate_limits_available" | "rate_limits">; |
| 325 | readonly usageCheckedAt?: string; |
| 326 | /** Each settings source's `maxEffortLevel` caps; Claude Code clamps every higher effort. */ |
| 327 | readonly effortCapSources?: ReadonlyArray<ClaudeEffortCapSource>; |
| 328 | }; |
| 329 | |
| 330 | // `getSettings` exists at runtime but is missing from the SDK's `Query` type, and older CLIs |
| 331 | // reject the control request. |
| 332 | type ClaudeSettingsQuery = { |
| 333 | readonly getSettings?: () => Promise<{ |
| 334 | readonly effective?: unknown; |
| 335 | readonly sources?: unknown; |
| 336 | }>; |
| 337 | }; |
| 338 | |
| 339 | function parseClaudeMaxEffortLevel(value: unknown): ClaudeEffortLevel | undefined { |
| 340 | return CLAUDE_EFFORT_LEVELS.find((level) => level === value); |
| 341 | } |
| 342 | |
| 343 | function parseClaudeModelMaxEffortLevels( |
| 344 | modelSettings: unknown, |
| 345 | ): ReadonlyMap<string, ClaudeEffortLevel> | undefined { |
| 346 | if (!modelSettings || typeof modelSettings !== "object") return undefined; |
| 347 | const levels = new Map<string, ClaudeEffortLevel>(); |
| 348 | for (const [model, settings] of Object.entries(modelSettings)) { |
| 349 | const level = parseClaudeMaxEffortLevel( |
| 350 | settings && typeof settings === "object" |
| 351 | ? (settings as { readonly maxEffortLevel?: unknown }).maxEffortLevel |
| 352 | : undefined, |
| 353 | ); |
| 354 | if (level) levels.set(model, level); |
| 355 | } |
| 356 | return levels.size > 0 ? levels : undefined; |
| 357 | } |
| 358 | |
| 359 | function parseClaudeEffortCapSource(settings: unknown): ClaudeEffortCapSource | undefined { |
| 360 | if (!settings || typeof settings !== "object") return undefined; |
| 361 | const { maxEffortLevel, modelSettings } = settings as { |
| 362 | readonly maxEffortLevel?: unknown; |
| 363 | readonly modelSettings?: unknown; |
| 364 | }; |
| 365 | const level = parseClaudeMaxEffortLevel(maxEffortLevel); |
| 366 | const modelMaxEffortLevels = parseClaudeModelMaxEffortLevels(modelSettings); |
| 367 | return level || modelMaxEffortLevels |
| 368 | ? { |
| 369 | ...(level ? { maxEffortLevel: level } : {}), |
| 370 | ...(modelMaxEffortLevels ? { modelMaxEffortLevels } : {}), |
| 371 | } |
| 372 | : undefined; |
| 373 | } |
| 374 | |
| 375 | // `sources` holds each settings file's raw settings. CLIs that report only the merged `effective` |
| 376 | // settings are read as a single source. |
| 377 | function parseClaudeEffortCapSources( |
| 378 | settings: { readonly effective?: unknown; readonly sources?: unknown } | undefined, |
| 379 | ): ReadonlyArray<ClaudeEffortCapSource> | undefined { |
| 380 | const sources = Array.isArray(settings?.sources) |
| 381 | ? settings.sources.flatMap((source) => { |
| 382 | const parsed = parseClaudeEffortCapSource( |
| 383 | source && typeof source === "object" |
| 384 | ? (source as { readonly settings?: unknown }).settings |
| 385 | : undefined, |
| 386 | ); |
| 387 | return parsed ? [parsed] : []; |
| 388 | }) |
| 389 | : [parseClaudeEffortCapSource(settings?.effective)].filter((source) => source !== undefined); |
| 390 | return sources.length > 0 ? sources : undefined; |
| 391 | } |
| 392 | |
| 393 | function parseClaudeInitializationCommands( |
| 394 | commands: ReadonlyArray<ClaudeSlashCommand> | undefined, |
| 395 | ): ReadonlyArray<ServerProviderSlashCommand> { |
| 396 | return dedupeSlashCommands( |
| 397 | (commands ?? []).flatMap((command) => { |
| 398 | const name = nonEmptyProbeString(command.name); |
| 399 | if (!name) { |
| 400 | return []; |
| 401 | } |
| 402 | |
| 403 | const description = nonEmptyProbeString(command.description); |
| 404 | const argumentHint = nonEmptyProbeString(command.argumentHint); |
| 405 | |
| 406 | return [ |
| 407 | { |
| 408 | name, |
| 409 | ...(description ? { description } : {}), |
| 410 | ...(argumentHint ? { input: { hint: argumentHint } } : {}), |
| 411 | } satisfies ServerProviderSlashCommand, |
| 412 | ]; |
| 413 | }), |
| 414 | ); |
| 415 | } |
| 416 | |
| 417 | function dedupeSlashCommands( |
| 418 | commands: ReadonlyArray<ServerProviderSlashCommand>, |
| 419 | ): ReadonlyArray<ServerProviderSlashCommand> { |
| 420 | const commandsByName = new Map<string, ServerProviderSlashCommand>(); |
| 421 | |
| 422 | for (const command of commands) { |
| 423 | const name = nonEmptyProbeString(command.name); |
| 424 | if (!name) { |
| 425 | continue; |
| 426 | } |
| 427 | |
| 428 | const key = name.toLowerCase(); |
| 429 | const existing = commandsByName.get(key); |
| 430 | if (!existing) { |
| 431 | commandsByName.set(key, { |
| 432 | ...command, |
| 433 | name, |
| 434 | }); |
| 435 | continue; |
| 436 | } |
| 437 | |
| 438 | commandsByName.set(key, { |
| 439 | ...existing, |
| 440 | ...(existing.description |
| 441 | ? {} |
| 442 | : command.description |
| 443 | ? { description: command.description } |
| 444 | : {}), |
| 445 | ...(existing.input?.hint |
| 446 | ? {} |
| 447 | : command.input?.hint |
| 448 | ? { input: { hint: command.input.hint } } |
| 449 | : {}), |
| 450 | }); |
| 451 | } |
| 452 | |
| 453 | return [...commandsByName.values()]; |
| 454 | } |
| 455 | |
| 456 | function waitForAbortSignal(signal: AbortSignal): Promise<void> { |
| 457 | if (signal.aborted) { |
| 458 | return Promise.resolve(); |
| 459 | } |
| 460 | return new Promise((resolve) => { |
| 461 | signal.addEventListener("abort", () => resolve(), { once: true }); |
| 462 | }); |
| 463 | } |
| 464 | |
| 465 | /** |
| 466 | * With gateway model discovery on, Claude Code refreshes its model cache in the background after |
| 467 | * initialization, so the probe subprocess outlives init by Claude Code's discovery timeout. |
| 468 | */ |
| 469 | function claudeGatewayDiscoveryGraceMs(environment: Readonly<Record<string, unknown>>): number { |
| 470 | const enabled = String(environment.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY ?? "") |
| 471 | .trim() |
| 472 | .toLowerCase(); |
| 473 | if (!enabled || enabled === "0" || enabled === "false") return 0; |
| 474 | if (!String(environment.ANTHROPIC_BASE_URL ?? "").trim()) return 0; |
| 475 | const configured = Number(environment.CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS); |
| 476 | return Number.isFinite(configured) && configured > 0 ? configured : 3_000; |
| 477 | } |
| 478 | |
| 479 | class ClaudeCapabilitiesProbeSdkError extends Schema.TaggedError<ClaudeCapabilitiesProbeSdkError>()( |
| 480 | "ClaudeCapabilitiesProbeSdkError", |
| 481 | { operation: Schema.Literals(["initialize", "usage", "settings"]), cause: Schema.Defect() }, |
| 482 | ) { |
| 483 | override get message(): string { |
| 484 | return `Claude capability probe ${this.operation} failed.`; |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | /** A never-yielding prompt allows local initialization IPC without sending an Anthropic request. */ |
| 489 | const probeClaudeCapabilities = ( |
| 490 | claudeSettings: ClaudeSettings, |
| 491 | environment?: NodeJS.ProcessEnv, |
| 492 | cwd?: string, |
| 493 | includeStatus = true, |
| 494 | ) => { |
| 495 | const abort = new AbortController(); |
| 496 | const abortProbe = Effect.sync(() => { |
| 497 | if (!abort.signal.aborted) abort.abort(); |
| 498 | }); |
| 499 | return Effect.gen(function* () { |
| 500 | const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment); |
| 501 | const executablePath = yield* resolveClaudeSdkExecutablePath( |
| 502 | claudeSettings.binaryPath, |
| 503 | claudeEnvironment, |
| 504 | ); |
| 505 | const managedMcpConfig = yield* hasClaudeManagedMcpConfig(); |
| 506 | // Workspace probes (no usage) discard models; the machine probe refreshes the shared cache. |
| 507 | const graceMs = includeStatus |
| 508 | ? claudeGatewayDiscoveryGraceMs({ |
| 509 | ...claudeEnvironment, |
| 510 | ...(yield* readClaudeSettingsEnv(claudeSettings, cwd, claudeEnvironment)), |
| 511 | }) |
| 512 | : 0; |
| 513 | const platform = yield* HostProcess.Platform; |
| 514 | const spawnVia = |
| 515 | platform === "win32" |
| 516 | ? "launcher-thread" |
| 517 | : platform === "linux" && (yield* Effect.promise(supportsEnvChdir)) |
| 518 | ? "env" |
| 519 | : undefined; |
| 520 | return yield* Effect.tryPromise({ |
| 521 | try: async () => { |
| 522 | const q = claudeQuery({ |
| 523 | // oxlint-disable-next-line require-yield -- never yields, so no prompt reaches the API |
| 524 | prompt: (async function* (): AsyncGenerator<SDKUserMessage> { |
| 525 | await waitForAbortSignal(abort.signal); |
| 526 | })(), |
| 527 | options: buildClaudeCapabilitiesProbeQueryOptions({ |
| 528 | executablePath, |
| 529 | abortController: abort, |
| 530 | environment: claudeEnvironment, |
| 531 | cwd, |
| 532 | managedMcpConfig, |
| 533 | spawnVia, |
| 534 | }), |
| 535 | }); |
| 536 | const init = await q.initializationResult(); |
| 537 | return { q, init, graceMs }; |
| 538 | }, |
| 539 | catch: (cause) => new ClaudeCapabilitiesProbeSdkError({ operation: "initialize", cause }), |
| 540 | }); |
| 541 | }).pipe( |
| 542 | Effect.timeout( |
| 543 | resolveProviderProbeTimeoutMs("claude", CAPABILITIES_PROBE_TIMEOUT_MS, environment), |
| 544 | ), |
| 545 | Effect.flatMap(({ q, init, graceMs }) => |
| 546 | Effect.gen(function* () { |
| 547 | // Usage has its own deadline so a slow optional request cannot discard initialization. |
| 548 | // Only the rate limits are read, so skip the local transcript scan that fills |
| 549 | // `behaviors`: with a few GB of transcripts it outlasts the deadline. |
| 550 | // The effort caps are read in parallel under the same deadline; workspace probes skip both. |
| 551 | const usageCheckedAt = DateTime.formatIso(yield* DateTime.now); |
| 552 | const { getSettings } = q as ClaudeSettingsQuery; |
| 553 | const [usageResult, settingsResult] = yield* Effect.all( |
| 554 | [ |
| 555 | includeStatus |
| 556 | ? Effect.tryPromise({ |
| 557 | try: () => |
| 558 | q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ |
| 559 | skipBehaviors: true, |
| 560 | }), |
| 561 | catch: (cause) => |
| 562 | new ClaudeCapabilitiesProbeSdkError({ operation: "usage", cause }), |
| 563 | }).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result) |
| 564 | : Effect.undefined, |
| 565 | includeStatus && getSettings |
| 566 | ? Effect.tryPromise({ |
| 567 | try: () => getSettings.call(q), |
| 568 | catch: (cause) => |
| 569 | new ClaudeCapabilitiesProbeSdkError({ operation: "settings", cause }), |
| 570 | }).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result) |
| 571 | : Effect.undefined, |
| 572 | ], |
| 573 | { concurrency: "unbounded" }, |
| 574 | ); |
| 575 | const usage = |
| 576 | usageResult && Result.isSuccess(usageResult) |
| 577 | ? { |
| 578 | rate_limits_available: usageResult.success.rate_limits_available, |
| 579 | rate_limits: usageResult.success.rate_limits, |
| 580 | } |
| 581 | : undefined; |
| 582 | const effortCapSources = parseClaudeEffortCapSources( |
| 583 | settingsResult && Result.isSuccess(settingsResult) ? settingsResult.success : undefined, |
| 584 | ); |
| 585 | const account = init.account as |
| 586 | | { |
| 587 | readonly email?: string; |
| 588 | readonly subscriptionType?: string; |
| 589 | readonly tokenSource?: string; |
| 590 | readonly apiKeySource?: string; |
| 591 | readonly apiProvider?: string; |
| 592 | } |
| 593 | | undefined; |
| 594 | return { |
| 595 | email: account?.email, |
| 596 | subscriptionType: account?.subscriptionType, |
| 597 | tokenSource: account?.tokenSource, |
| 598 | apiKeySource: account?.apiKeySource, |
| 599 | apiProvider: account?.apiProvider, |
| 600 | slashCommands: parseClaudeInitializationCommands(init.commands), |
| 601 | ...(init.models?.length ? { models: init.models } : {}), |
| 602 | ...(usage ? { usage, usageCheckedAt } : {}), |
| 603 | ...(effortCapSources ? { effortCapSources } : {}), |
| 604 | } satisfies ClaudeCapabilitiesProbe; |
| 605 | }).pipe( |
| 606 | Effect.tap(() => |
| 607 | graceMs > 0 |
| 608 | ? Effect.sleep(graceMs).pipe(Effect.andThen(abortProbe), Effect.forkDetach) |
| 609 | : abortProbe, |
| 610 | ), |
| 611 | ), |
| 612 | ), |
| 613 | Effect.onError(() => abortProbe), |
| 614 | Effect.tapError((error) => |
| 615 | Effect.logWarning("Claude capability probe failed.", { errorTag: error._tag }), |
| 616 | ), |
| 617 | ); |
| 618 | }; |
| 619 | |
| 620 | type ClaudeCapabilitiesProbeError = Effect.Error<ReturnType<typeof probeClaudeCapabilities>>; |
| 621 | |
| 622 | const runClaudeCommand = Effect.fn("runClaudeCommand")(function* ( |
| 623 | claudeSettings: ClaudeSettings, |
| 624 | args: ReadonlyArray<string>, |
| 625 | environment?: NodeJS.ProcessEnv, |
| 626 | cwd?: string, |
| 627 | ) { |
| 628 | const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment); |
| 629 | const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, { |
| 630 | env: claudeEnvironment, |
| 631 | }); |
| 632 | const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, { |
| 633 | env: claudeEnvironment, |
| 634 | shell: spawnCommand.shell, |
| 635 | ...(cwd ? { cwd } : {}), |
| 636 | }); |
| 637 | return yield* spawnAndCollect(claudeSettings.binaryPath, command); |
| 638 | }); |
| 639 | |
| 640 | export const probeClaudeWorkspaceSnapshot = Effect.fn("probeClaudeWorkspaceSnapshot")(function* ( |
| 641 | claudeSettings: ClaudeSettings, |
| 642 | machineSnapshot: ServerProvider, |
| 643 | cwd: string, |
| 644 | environment?: NodeJS.ProcessEnv, |
| 645 | ): Effect.fn.Return<ProviderWorkspaceSnapshot, never, FileSystem.FileSystem | Path.Path> { |
| 646 | if (!claudeSettings.enabled) return machineSnapshot; |
| 647 | const skills = yield* discoverClaudeSkills(claudeSettings, cwd, environment); |
| 648 | const fileSystem = yield* FileSystem.FileSystem; |
| 649 | // A deleted worktree can never answer the probe. Pending would make clients rescan it forever. |
| 650 | const cwdExists = yield* fileSystem.exists(cwd).pipe(Effect.orElseSucceed(() => true)); |
| 651 | const probeResult = cwdExists |
| 652 | ? yield* probeClaudeCapabilities(claudeSettings, environment, cwd, false).pipe(Effect.result) |
| 653 | : undefined; |
| 654 | const capabilities = |
| 655 | probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined; |
| 656 | return { |
| 657 | ...machineSnapshot, |
| 658 | skills, |
| 659 | slashCommands: dedupeSlashCommands([ |
| 660 | COMPACT_SLASH_COMMAND, |
| 661 | ...(capabilities?.slashCommands ?? []), |
| 662 | ]), |
| 663 | slashCommandsPending: cwdExists && !capabilities, |
| 664 | }; |
| 665 | }); |
| 666 | |
| 667 | export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* ( |
| 668 | claudeSettings: ClaudeSettings, |
| 669 | resolveCapabilities?: ( |
| 670 | claudeSettings: ClaudeSettings, |
| 671 | ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined, ClaudeCapabilitiesProbeError>, |
| 672 | environment?: NodeJS.ProcessEnv, |
| 673 | cwd?: string, |
| 674 | modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG, |
| 675 | /** Shared with the adapter so turn events reuse the scoped-bucket names this probe saw. */ |
| 676 | scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>, |
| 677 | resolveResetCredits?: (version: string) => Effect.Effect<ServerProviderResetCredits | undefined>, |
| 678 | ): Effect.fn.Return< |
| 679 | ServerProviderDraft, |
| 680 | never, |
| 681 | ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path |
| 682 | > { |
| 683 | const resolvedEnvironment = environment ?? process.env; |
| 684 | const checkedAt = DateTime.formatIso(yield* DateTime.now); |
| 685 | const allModels = claudeProviderModels( |
| 686 | modelCatalog.models.map((entry) => entry.model), |
| 687 | claudeSettings.customModels, |
| 688 | ); |
| 689 | |
| 690 | if (!claudeSettings.enabled) { |
| 691 | return buildServerProvider({ |
| 692 | presentation: CLAUDE_PRESENTATION, |
| 693 | enabled: false, |
| 694 | checkedAt, |
| 695 | models: allModels, |
| 696 | probe: { |
| 697 | installed: false, |
| 698 | version: null, |
| 699 | status: "warning", |
| 700 | auth: { status: "unknown" }, |
| 701 | message: "Claude is disabled in T3 Code settings.", |
| 702 | }, |
| 703 | }); |
| 704 | } |
| 705 | |
| 706 | const versionProbe = yield* runClaudeCommand( |
| 707 | claudeSettings, |
| 708 | ["--version"], |
| 709 | providerProbeEnvironment(resolvedEnvironment), |
| 710 | cwd, |
| 711 | ).pipe( |
| 712 | Effect.timeoutOption( |
| 713 | resolveProviderProbeTimeoutMs("claude", CLAUDE_VERSION_CHECK_TIMEOUT_MS, resolvedEnvironment), |
| 714 | ), |
| 715 | Effect.result, |
| 716 | ); |
| 717 | |
| 718 | if (Result.isFailure(versionProbe)) { |
| 719 | const error = versionProbe.failure; |
| 720 | yield* Effect.logWarning("Claude Agent CLI health check failed.", { |
| 721 | errorTag: error._tag, |
| 722 | }); |
| 723 | return buildServerProvider({ |
| 724 | presentation: CLAUDE_PRESENTATION, |
| 725 | enabled: claudeSettings.enabled, |
| 726 | checkedAt, |
| 727 | models: allModels, |
| 728 | probe: { |
| 729 | installed: !isCommandMissingCause(error), |
| 730 | version: null, |
| 731 | status: "error", |
| 732 | auth: { status: "unknown" }, |
| 733 | message: isCommandMissingCause(error) |
| 734 | ? "Claude Agent CLI (`claude`) was not found on PATH." |
| 735 | : "Failed to execute Claude Agent CLI health check.", |
| 736 | }, |
| 737 | }); |
| 738 | } |
| 739 | |
| 740 | if (Option.isNone(versionProbe.success)) { |
| 741 | return buildServerProvider({ |
| 742 | presentation: CLAUDE_PRESENTATION, |
| 743 | enabled: claudeSettings.enabled, |
| 744 | checkedAt, |
| 745 | models: allModels, |
| 746 | probe: { |
| 747 | installed: true, |
| 748 | version: null, |
| 749 | status: "error", |
| 750 | auth: { status: "unknown" }, |
| 751 | message: |
| 752 | "Claude Agent CLI is installed but failed to run. Timed out while running command.", |
| 753 | }, |
| 754 | }); |
| 755 | } |
| 756 | |
| 757 | const version = versionProbe.success.value; |
| 758 | const parsedVersion = parseCliVersionResult(version); |
| 759 | if (version.code !== 0) { |
| 760 | yield* Effect.logWarning("Claude Agent CLI version probe exited with a non-zero status.", { |
| 761 | exitCode: version.code, |
| 762 | stdoutLength: version.stdout.length, |
| 763 | stderrLength: version.stderr.length, |
| 764 | }); |
| 765 | return buildServerProvider({ |
| 766 | presentation: CLAUDE_PRESENTATION, |
| 767 | enabled: claudeSettings.enabled, |
| 768 | checkedAt, |
| 769 | models: allModels, |
| 770 | probe: { |
| 771 | installed: true, |
| 772 | version: parsedVersion, |
| 773 | status: "error", |
| 774 | auth: { status: "unknown" }, |
| 775 | message: "Claude Agent CLI is installed but failed to run.", |
| 776 | }, |
| 777 | }); |
| 778 | } |
| 779 | |
| 780 | const updateRequiredModels = resolveClaudeUpdateRequiredModels(modelCatalog, parsedVersion); |
| 781 | const versionUpgradeMessage = formatClaudeVersionUpgradeMessage(modelCatalog, parsedVersion); |
| 782 | |
| 783 | const probeResult = resolveCapabilities |
| 784 | ? yield* resolveCapabilities(claudeSettings).pipe(Effect.result) |
| 785 | : undefined; |
| 786 | const capabilities = |
| 787 | probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined; |
| 788 | const probeFailure = |
| 789 | probeResult && Result.isFailure(probeResult) ? probeResult.failure : undefined; |
| 790 | const models = capClaudeCatalogEffort( |
| 791 | modelCatalog, |
| 792 | claudeProviderModels( |
| 793 | [ |
| 794 | ...resolveClaudeModelsForVersion(modelCatalog, parsedVersion), |
| 795 | ...claudeReportedModels(modelCatalog, claudeSettings.customModels, capabilities?.models), |
| 796 | ], |
| 797 | claudeSettings.customModels, |
| 798 | ), |
| 799 | capabilities?.effortCapSources ?? [], |
| 800 | ); |
| 801 | const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment); |
| 802 | const slashCommands = [COMPACT_SLASH_COMMAND, ...(capabilities?.slashCommands ?? [])]; |
| 803 | const dedupedSlashCommands = dedupeSlashCommands(slashCommands); |
| 804 | |
| 805 | if (!capabilities) { |
| 806 | return buildServerProvider({ |
| 807 | presentation: CLAUDE_PRESENTATION, |
| 808 | enabled: claudeSettings.enabled, |
| 809 | checkedAt, |
| 810 | models, |
| 811 | updateRequiredModels, |
| 812 | slashCommands: dedupedSlashCommands, |
| 813 | skills, |
| 814 | probe: { |
| 815 | installed: true, |
| 816 | version: parsedVersion, |
| 817 | status: "warning", |
| 818 | auth: { status: "unknown" }, |
| 819 | message: probeFailure |
| 820 | ? Cause.isTimeoutError(probeFailure) |
| 821 | ? `Timed out after ${resolveProviderProbeTimeoutMs("claude", CAPABILITIES_PROBE_TIMEOUT_MS, resolvedEnvironment) / 1_000}s while checking Claude account status.` |
| 822 | : "Claude Agent CLI failed while checking account status." |
| 823 | : "Could not verify Claude authentication status from initialization result.", |
| 824 | }, |
| 825 | }); |
| 826 | } |
| 827 | |
| 828 | // First-party account fields cannot verify custom endpoint credentials. |
| 829 | const baseUrl = |
| 830 | (yield* readClaudeSettingsEnv(claudeSettings, cwd, resolvedEnvironment)).ANTHROPIC_BASE_URL ?? |
| 831 | resolvedEnvironment.ANTHROPIC_BASE_URL; |
| 832 | const customApiEndpoint = customClaudeApiEndpointHost(baseUrl) !== undefined; |
| 833 | const endpoint = customApiEndpoint ? URL.parse(baseUrl?.trim() ?? "")?.origin : undefined; |
| 834 | if (!customApiEndpoint && claudeAuthStatus(capabilities) === "unauthenticated") { |
| 835 | const path = yield* Path.Path; |
| 836 | const configDir = (yield* makeClaudeEnvironment(claudeSettings, resolvedEnvironment)) |
| 837 | .CLAUDE_CONFIG_DIR; |
| 838 | return buildServerProvider({ |
| 839 | presentation: CLAUDE_PRESENTATION, |
| 840 | enabled: claudeSettings.enabled, |
| 841 | checkedAt, |
| 842 | models, |
| 843 | updateRequiredModels, |
| 844 | slashCommands: dedupedSlashCommands, |
| 845 | skills, |
| 846 | probe: { |
| 847 | installed: true, |
| 848 | version: parsedVersion, |
| 849 | status: "error", |
| 850 | auth: { status: "unauthenticated" }, |
| 851 | message: |
| 852 | configDir === undefined |
| 853 | ? "Claude Code is not authenticated. Run `claude auth login` and try again." |
| 854 | : claudeSignedOutMessage({ configDir, cwd: path.resolve(cwd ?? ".") }), |
| 855 | }, |
| 856 | }); |
| 857 | } |
| 858 | |
| 859 | // A proxy's ANTHROPIC_AUTH_TOKEN reads as an API key; the endpoint is what the token is for. |
| 860 | const authMetadata = |
| 861 | apiProviderAuthMetadata(capabilities.apiProvider) ?? |
| 862 | (customApiEndpoint |
| 863 | ? { type: "customEndpoint", label: "Custom API endpoint", ...(endpoint ? { endpoint } : {}) } |
| 864 | : undefined) ?? |
| 865 | claudeAuthMetadata({ |
| 866 | subscriptionType: capabilities.subscriptionType, |
| 867 | authMethod: capabilities.tokenSource, |
| 868 | apiKeySource: capabilities.apiKeySource, |
| 869 | }); |
| 870 | const usageCheckedAt = capabilities.usageCheckedAt ?? checkedAt; |
| 871 | const usageLimits = !capabilities.usage |
| 872 | ? makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed" }) |
| 873 | : scopedLimitNames |
| 874 | ? yield* recordClaudeUsageResponse(scopedLimitNames, { |
| 875 | response: capabilities.usage, |
| 876 | checkedAt: usageCheckedAt, |
| 877 | }) |
| 878 | : claudeUsageResponseToLimits({ |
| 879 | response: capabilities.usage, |
| 880 | checkedAt: usageCheckedAt, |
| 881 | }).limits; |
| 882 | const resetCredits = |
| 883 | resolveResetCredits && |
| 884 | capabilities.subscriptionType && |
| 885 | !usageLimits.unavailable && |
| 886 | parsedVersion |
| 887 | ? yield* resolveResetCredits(parsedVersion) |
| 888 | : undefined; |
| 889 | return buildServerProvider({ |
| 890 | presentation: CLAUDE_PRESENTATION, |
| 891 | enabled: claudeSettings.enabled, |
| 892 | checkedAt, |
| 893 | models, |
| 894 | updateRequiredModels, |
| 895 | slashCommands: dedupedSlashCommands, |
| 896 | skills, |
| 897 | probe: { |
| 898 | installed: true, |
| 899 | version: parsedVersion, |
| 900 | status: "ready", |
| 901 | auth: { |
| 902 | status: "authenticated", |
| 903 | ...(capabilities.email ? { email: capabilities.email } : {}), |
| 904 | ...(capabilities.workspaceId ? { workspaceId: capabilities.workspaceId } : {}), |
| 905 | ...(authMetadata ? authMetadata : {}), |
| 906 | }, |
| 907 | ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}), |
| 908 | usageLimits: resetCredits ? { ...usageLimits, resetCredits } : usageLimits, |
| 909 | }, |
| 910 | }); |
| 911 | }); |
| 912 | |
| 913 | const nowIso = Effect.map(DateTime.now, DateTime.formatIso); |
| 914 | |
| 915 | export const makePendingClaudeProvider = Effect.fn("ClaudeProvider.makePendingClaudeProvider")( |
| 916 | function* ( |
| 917 | claudeSettings: ClaudeSettings, |
| 918 | modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG, |
| 919 | ): Effect.fn.Return<ServerProviderDraft> { |
| 920 | const checkedAt = yield* nowIso; |
| 921 | const models = claudeProviderModels( |
| 922 | modelCatalog.models.map((entry) => entry.model), |
| 923 | claudeSettings.customModels, |
| 924 | ); |
| 925 | |
| 926 | if (!claudeSettings.enabled) { |
| 927 | return buildServerProvider({ |
| 928 | presentation: CLAUDE_PRESENTATION, |
| 929 | enabled: false, |
| 930 | checkedAt, |
| 931 | models, |
| 932 | probe: { |
| 933 | installed: false, |
| 934 | version: null, |
| 935 | status: "warning", |
| 936 | auth: { status: "unknown" }, |
| 937 | message: "Claude is disabled in T3 Code settings.", |
| 938 | }, |
| 939 | }); |
| 940 | } |
| 941 | |
| 942 | return buildServerProvider({ |
| 943 | presentation: CLAUDE_PRESENTATION, |
| 944 | enabled: true, |
| 945 | checkedAt, |
| 946 | models, |
| 947 | probe: { |
| 948 | installed: false, |
| 949 | version: null, |
| 950 | status: "warning", |
| 951 | auth: { status: "unknown" }, |
| 952 | message: "Claude provider status has not been checked in this session yet.", |
| 953 | }, |
| 954 | }); |
| 955 | }, |
| 956 | ); |
| 957 | |
| 958 | export { probeClaudeCapabilities }; |