Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeProvider.ts

962 lines34.2 KB

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