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