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