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