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