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