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};
269
270function parseClaudeInitializationCommands(
271 commands: ReadonlyArray<ClaudeSlashCommand> | undefined,
272): ReadonlyArray<ServerProviderSlashCommand> {
273 return dedupeSlashCommands(
274 (commands ?? []).flatMap((command) => {
275 const name = nonEmptyProbeString(command.name);
276 if (!name) {
277 return [];
278 }
279
280 const description = nonEmptyProbeString(command.description);
281 const argumentHint = nonEmptyProbeString(command.argumentHint);
282
283 return [
284 {
285 name,
286 ...(description ? { description } : {}),
287 ...(argumentHint ? { input: { hint: argumentHint } } : {}),
288 } satisfies ServerProviderSlashCommand,
289 ];
290 }),
291 );
292}
293
294function dedupeSlashCommands(
295 commands: ReadonlyArray<ServerProviderSlashCommand>,
296): ReadonlyArray<ServerProviderSlashCommand> {
297 const commandsByName = new Map<string, ServerProviderSlashCommand>();
298
299 for (const command of commands) {
300 const name = nonEmptyProbeString(command.name);
301 if (!name) {
302 continue;
303 }
304
305 const key = name.toLowerCase();
306 const existing = commandsByName.get(key);
307 if (!existing) {
308 commandsByName.set(key, {
309 ...command,
310 name,
311 });
312 continue;
313 }
314
315 commandsByName.set(key, {
316 ...existing,
317 ...(existing.description
318 ? {}
319 : command.description
320 ? { description: command.description }
321 : {}),
322 ...(existing.input?.hint
323 ? {}
324 : command.input?.hint
325 ? { input: { hint: command.input.hint } }
326 : {}),
327 });
328 }
329
330 return [...commandsByName.values()];
331}
332
333function waitForAbortSignal(signal: AbortSignal): Promise<void> {
334 if (signal.aborted) {
335 return Promise.resolve();
336 }
337 return new Promise((resolve) => {
338 signal.addEventListener("abort", () => resolve(), { once: true });
339 });
340}
341
342/**
343 * We pass a never-yielding AsyncIterable as the prompt so that no user message is ever written
344 * to the subprocess stdin. This means the Claude Code subprocess completes its local
345 * initialization IPC (returning account info and slash commands) but never starts an API
346 * request to Anthropic.
347 */
348const probeClaudeCapabilities = (
349 claudeSettings: ClaudeSettings,
350 environment?: NodeJS.ProcessEnv,
351 cwd?: string,
352 includeUsage = true,
353) => {
354 const abort = new AbortController();
355 return Effect.gen(function* () {
356 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
357 const executablePath = yield* resolveClaudeSdkExecutablePath(
358 claudeSettings.binaryPath,
359 claudeEnvironment,
360 );
361 const managedMcpConfig = yield* hasClaudeManagedMcpConfig();
362 return yield* Effect.tryPromise(async () => {
363 const q = claudeQuery({
364 // Never yield — we only need initialization data, not a conversation.
365 // This prevents any prompt from reaching the Anthropic API.
366 // oxlint-disable-next-line require-yield
367 prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
368 await waitForAbortSignal(abort.signal);
369 })(),
370 options: buildClaudeCapabilitiesProbeQueryOptions({
371 executablePath,
372 abortController: abort,
373 environment: claudeEnvironment,
374 cwd,
375 managedMcpConfig,
376 }),
377 });
378 const init = await q.initializationResult();
379 return { q, init };
380 });
381 }).pipe(
382 Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS),
383 Effect.flatMap(({ q, init }) =>
384 Effect.gen(function* () {
385 // Usage has its own deadline so a slow optional request cannot discard initialization.
386 // Only the rate limits are read, so skip the local transcript scan that fills
387 // `behaviors`: with a few GB of transcripts it outlasts the deadline.
388 const usageResult = includeUsage
389 ? yield* Effect.tryPromise(() =>
390 q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true }),
391 ).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result)
392 : undefined;
393 const usage =
394 usageResult && Result.isSuccess(usageResult)
395 ? {
396 rate_limits_available: usageResult.success.rate_limits_available,
397 rate_limits: usageResult.success.rate_limits,
398 }
399 : undefined;
400 const account = init.account as
401 | {
402 readonly email?: string;
403 readonly subscriptionType?: string;
404 readonly tokenSource?: string;
405 readonly apiKeySource?: string;
406 readonly apiProvider?: string;
407 }
408 | undefined;
409 return {
410 email: account?.email,
411 subscriptionType: account?.subscriptionType,
412 tokenSource: account?.tokenSource,
413 apiKeySource: account?.apiKeySource,
414 apiProvider: account?.apiProvider,
415 slashCommands: parseClaudeInitializationCommands(init.commands),
416 ...(usage ? { usage } : {}),
417 } satisfies ClaudeCapabilitiesProbe;
418 }),
419 ),
420 Effect.ensuring(
421 Effect.sync(() => {
422 if (!abort.signal.aborted) abort.abort();
423 }),
424 ),
425 Effect.tapError((error) =>
426 Effect.logWarning("Claude capability probe failed.", { errorTag: error._tag }),
427 ),
428 );
429};
430
431type ClaudeCapabilitiesProbeError = Effect.Error<ReturnType<typeof probeClaudeCapabilities>>;
432
433const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
434 claudeSettings: ClaudeSettings,
435 args: ReadonlyArray<string>,
436 environment?: NodeJS.ProcessEnv,
437 cwd?: string,
438) {
439 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
440 const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, {
441 env: claudeEnvironment,
442 });
443 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
444 env: claudeEnvironment,
445 shell: spawnCommand.shell,
446 ...(cwd ? { cwd } : {}),
447 });
448 return yield* spawnAndCollect(claudeSettings.binaryPath, command);
449});
450
451export const probeClaudeWorkspaceSnapshot = Effect.fn("probeClaudeWorkspaceSnapshot")(function* (
452 claudeSettings: ClaudeSettings,
453 machineSnapshot: ServerProvider,
454 cwd: string,
455 environment?: NodeJS.ProcessEnv,
456): Effect.fn.Return<ProviderWorkspaceSnapshot, never, FileSystem.FileSystem | Path.Path> {
457 if (!claudeSettings.enabled) return machineSnapshot;
458 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, environment);
459 const probeResult = yield* probeClaudeCapabilities(claudeSettings, environment, cwd, false).pipe(
460 Effect.result,
461 );
462 const capabilities = Result.isSuccess(probeResult) ? probeResult.success : undefined;
463 return {
464 ...machineSnapshot,
465 skills,
466 slashCommands: dedupeSlashCommands([
467 COMPACT_SLASH_COMMAND,
468 ...(capabilities?.slashCommands ?? []),
469 ]),
470 slashCommandsPending: !capabilities,
471 };
472});
473
474export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
475 claudeSettings: ClaudeSettings,
476 resolveCapabilities?: (
477 claudeSettings: ClaudeSettings,
478 ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined, ClaudeCapabilitiesProbeError>,
479 environment?: NodeJS.ProcessEnv,
480 cwd?: string,
481 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
482 /** Shared with the adapter so turn events reuse the scoped-bucket names this probe saw. */
483 scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>,
484 resolveResetCredits?: (version: string) => Effect.Effect<ServerProviderResetCredits | undefined>,
485): Effect.fn.Return<
486 ServerProviderDraft,
487 never,
488 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
489> {
490 const resolvedEnvironment = environment ?? process.env;
491 const checkedAt = DateTime.formatIso(yield* DateTime.now);
492 const allModels = providerModelsFromSettings(
493 modelCatalog.models.map((entry) => entry.model),
494 claudeSettings.customModels,
495 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
496 );
497
498 if (!claudeSettings.enabled) {
499 return buildServerProvider({
500 presentation: CLAUDE_PRESENTATION,
501 enabled: false,
502 checkedAt,
503 models: allModels,
504 probe: {
505 installed: false,
506 version: null,
507 status: "warning",
508 auth: { status: "unknown" },
509 message: "Claude is disabled in T3 Code settings.",
510 },
511 });
512 }
513
514 const versionProbe = yield* runClaudeCommand(
515 claudeSettings,
516 ["--version"],
517 resolvedEnvironment,
518 cwd,
519 ).pipe(Effect.timeoutOption(CLAUDE_VERSION_CHECK_TIMEOUT_MS), Effect.result);
520
521 if (Result.isFailure(versionProbe)) {
522 const error = versionProbe.failure;
523 yield* Effect.logWarning("Claude Agent CLI health check failed.", {
524 errorTag: error._tag,
525 });
526 return buildServerProvider({
527 presentation: CLAUDE_PRESENTATION,
528 enabled: claudeSettings.enabled,
529 checkedAt,
530 models: allModels,
531 probe: {
532 installed: !isCommandMissingCause(error),
533 version: null,
534 status: "error",
535 auth: { status: "unknown" },
536 message: isCommandMissingCause(error)
537 ? "Claude Agent CLI (`claude`) was not found on PATH."
538 : "Failed to execute Claude Agent CLI health check.",
539 },
540 });
541 }
542
543 if (Option.isNone(versionProbe.success)) {
544 return buildServerProvider({
545 presentation: CLAUDE_PRESENTATION,
546 enabled: claudeSettings.enabled,
547 checkedAt,
548 models: allModels,
549 probe: {
550 installed: true,
551 version: null,
552 status: "error",
553 auth: { status: "unknown" },
554 message:
555 "Claude Agent CLI is installed but failed to run. Timed out while running command.",
556 },
557 });
558 }
559
560 const version = versionProbe.success.value;
561 const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
562 if (version.code !== 0) {
563 yield* Effect.logWarning("Claude Agent CLI version probe exited with a non-zero status.", {
564 exitCode: version.code,
565 stdoutLength: version.stdout.length,
566 stderrLength: version.stderr.length,
567 });
568 return buildServerProvider({
569 presentation: CLAUDE_PRESENTATION,
570 enabled: claudeSettings.enabled,
571 checkedAt,
572 models: allModels,
573 probe: {
574 installed: true,
575 version: parsedVersion,
576 status: "error",
577 auth: { status: "unknown" },
578 message: "Claude Agent CLI is installed but failed to run.",
579 },
580 });
581 }
582
583 const models = providerModelsFromSettings(
584 resolveClaudeModelsForVersion(modelCatalog, parsedVersion),
585 claudeSettings.customModels,
586 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
587 );
588 const updateRequiredModels = resolveClaudeUpdateRequiredModels(modelCatalog, parsedVersion);
589 const versionUpgradeMessage = formatClaudeVersionUpgradeMessage(modelCatalog, parsedVersion);
590
591 const probeResult = resolveCapabilities
592 ? yield* resolveCapabilities(claudeSettings).pipe(Effect.result)
593 : undefined;
594 const capabilities =
595 probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined;
596 const probeFailure =
597 probeResult && Result.isFailure(probeResult) ? probeResult.failure : undefined;
598 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
599 const slashCommands = [COMPACT_SLASH_COMMAND, ...(capabilities?.slashCommands ?? [])];
600 const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
601
602 if (!capabilities) {
603 return buildServerProvider({
604 presentation: CLAUDE_PRESENTATION,
605 enabled: claudeSettings.enabled,
606 checkedAt,
607 models,
608 updateRequiredModels,
609 slashCommands: dedupedSlashCommands,
610 skills,
611 probe: {
612 installed: true,
613 version: parsedVersion,
614 status: "warning",
615 auth: { status: "unknown" },
616 message: probeFailure
617 ? Cause.isTimeoutError(probeFailure)
618 ? `Timed out after ${CAPABILITIES_PROBE_TIMEOUT_MS / 1_000}s while checking Claude account status.`
619 : "Claude Agent CLI failed while checking account status."
620 : "Could not verify Claude authentication status from initialization result.",
621 },
622 });
623 }
624
625 if (claudeAuthStatus(capabilities) === "unauthenticated") {
626 return buildServerProvider({
627 presentation: CLAUDE_PRESENTATION,
628 enabled: claudeSettings.enabled,
629 checkedAt,
630 models,
631 slashCommands: dedupedSlashCommands,
632 skills,
633 probe: {
634 installed: true,
635 version: parsedVersion,
636 status: "error",
637 auth: { status: "unauthenticated" },
638 message: "Claude Code is not authenticated. Run `claude auth login` and try again.",
639 },
640 });
641 }
642
643 const authMetadata =
644 claudeAuthMetadata({
645 subscriptionType: capabilities.subscriptionType,
646 authMethod: capabilities.tokenSource,
647 }) ?? apiProviderAuthMetadata(capabilities.apiProvider);
648 const usageLimits = !capabilities.usage
649 ? makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed" })
650 : scopedLimitNames
651 ? yield* recordClaudeUsageResponse(scopedLimitNames, {
652 response: capabilities.usage,
653 checkedAt,
654 })
655 : claudeUsageResponseToLimits({ response: capabilities.usage, checkedAt }).limits;
656 const resetCredits =
657 resolveResetCredits &&
658 capabilities.subscriptionType &&
659 !usageLimits.unavailable &&
660 parsedVersion
661 ? yield* resolveResetCredits(parsedVersion)
662 : undefined;
663 return buildServerProvider({
664 presentation: CLAUDE_PRESENTATION,
665 enabled: claudeSettings.enabled,
666 checkedAt,
667 models,
668 updateRequiredModels,
669 slashCommands: dedupedSlashCommands,
670 skills,
671 probe: {
672 installed: true,
673 version: parsedVersion,
674 status: "ready",
675 auth: {
676 status: "authenticated",
677 ...(capabilities.email ? { email: capabilities.email } : {}),
678 ...(capabilities.workspaceId ? { workspaceId: capabilities.workspaceId } : {}),
679 ...(authMetadata ? authMetadata : {}),
680 },
681 ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),
682 usageLimits: resetCredits ? { ...usageLimits, resetCredits } : usageLimits,
683 },
684 });
685});
686
687const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
688
689export const makePendingClaudeProvider = Effect.fn("ClaudeProvider.makePendingClaudeProvider")(
690 function* (
691 claudeSettings: ClaudeSettings,
692 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
693 ): Effect.fn.Return<ServerProviderDraft> {
694 const checkedAt = yield* nowIso;
695 const models = providerModelsFromSettings(
696 modelCatalog.models.map((entry) => entry.model),
697 claudeSettings.customModels,
698 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
699 );
700
701 if (!claudeSettings.enabled) {
702 return buildServerProvider({
703 presentation: CLAUDE_PRESENTATION,
704 enabled: false,
705 checkedAt,
706 models,
707 probe: {
708 installed: false,
709 version: null,
710 status: "warning",
711 auth: { status: "unknown" },
712 message: "Claude is disabled in T3 Code settings.",
713 },
714 });
715 }
716
717 return buildServerProvider({
718 presentation: CLAUDE_PRESENTATION,
719 enabled: true,
720 checkedAt,
721 models,
722 probe: {
723 installed: false,
724 version: null,
725 status: "warning",
726 auth: { status: "unknown" },
727 message: "Claude provider status has not been checked in this session yet.",
728 },
729 });
730 },
731);
732
733export { probeClaudeCapabilities };