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