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 type {
20 Options as ClaudeQueryOptions,
21 SlashCommand as ClaudeSlashCommand,
22 SDKControlGetUsageResponse,
23 SDKUserMessage,
24 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 { hasClaudeManagedMcpConfig, 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 * The capability probe resolves for a logged-out CLI, so a completed probe only proves Claude
172 * Code started. `tokenSource: "none"` is the CLI reporting it found no token at all, and is the
173 * one shape that disproves authentication.
174 */
175function claudeAuthStatus(
176 capabilities: Pick<
177 ClaudeCapabilitiesProbe,
178 "email" | "subscriptionType" | "tokenSource" | "apiKeySource" | "apiProvider"
179 >,
180): "authenticated" | "unauthenticated" {
181 if (capabilities.apiProvider !== undefined && capabilities.apiProvider !== "firstParty") {
182 return "authenticated";
183 }
184 if (capabilities.tokenSource !== "none") return "authenticated";
185 // An `ANTHROPIC_API_KEY` install reports no token source but is authenticated
186 // all the same, so the key and account fields still get a say.
187 const hasApiKey = Boolean(capabilities.apiKeySource) && capabilities.apiKeySource !== "none";
188 return hasApiKey || capabilities.email || capabilities.subscriptionType
189 ? "authenticated"
190 : "unauthenticated";
191}
192
193// Amazon Bedrock initializes far slower than first-party auth: the SDK boots the Bedrock
194// backend and runs the `awsAuthRefresh` credential hook before returning account info.
195const CAPABILITIES_PROBE_TIMEOUT_MS = 25_000;
196
197export const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [
198 "user",
199 "project",
200 "local",
201] as const satisfies ReadonlyArray<SettingSource>;
202
203export function buildClaudeCapabilitiesProbeQueryOptions(input: {
204 readonly executablePath: string;
205 readonly abortController: AbortController;
206 readonly environment: NodeJS.ProcessEnv;
207 readonly cwd: string | undefined;
208 readonly managedMcpConfig: boolean;
209}): ClaudeQueryOptions {
210 return {
211 persistSession: false,
212 pathToClaudeCodeExecutable: input.executablePath,
213 abortController: input.abortController,
214 settingSources: [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES],
215 // The probe keeps filesystem setting sources for slash-command discovery,
216 // but must not run the user's hooks: it fires every few minutes, so
217 // SessionStart hooks would run on every health check.
218 settings: { disableAllHooks: true },
219 allowedTools: [],
220 // Ignore MCP definitions from every filesystem setting source above. The
221 // SDK combines this empty explicit map with --strict-mcp-config, which
222 // Claude refuses next to a managed-mcp.json that already excludes them.
223 mcpServers: {},
224 ...(input.managedMcpConfig ? {} : { strictMcpConfig: true }),
225 env: {
226 ...input.environment,
227 // Connected claude.ai MCP servers are discovered outside filesystem
228 // config; disable them independently for this health check.
229 ENABLE_CLAUDEAI_MCP_SERVERS: "false",
230 // Skipping it also avoids Claude spawning a Windows `tasklist | findstr` process tree on
231 // every periodic refresh.
232 FORCE_CODE_TERMINAL: undefined,
233 CLAUDE_CODE_AUTO_CONNECT_IDE: "0",
234 CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL: "1",
235 },
236 ...(input.cwd ? { cwd: input.cwd } : {}),
237 stderr: () => {},
238 };
239}
240
241function nonEmptyProbeString(value: string): string | undefined {
242 const candidate = value.trim();
243 return candidate ? candidate : undefined;
244}
245
246export type ClaudeCapabilitiesProbe = {
247 readonly email: string | undefined;
248 readonly workspaceId?: string | undefined;
249 readonly subscriptionType: string | undefined;
250 readonly tokenSource: string | undefined;
251 readonly apiKeySource: string | undefined;
252 /**
253 * Active API backend reported by the SDK's `AccountInfo`. Anthropic OAuth
254 * login only applies when `"firstParty"`; for Amazon Bedrock (`"bedrock"`)
255 * the subscription/token fields are absent and auth is external AWS creds.
256 */
257 readonly apiProvider: string | undefined;
258 readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
259 /**
260 * Subscription windows from the SDK's `get_usage` control request, or
261 * `undefined` when the request itself failed. Absent windows on an
262 * otherwise successful response mean the account has none (API key).
263 */
264 readonly usage?: Pick<SDKControlGetUsageResponse, "rate_limits_available" | "rate_limits">;
265};
266
267function parseClaudeInitializationCommands(
268 commands: ReadonlyArray<ClaudeSlashCommand> | undefined,
269): ReadonlyArray<ServerProviderSlashCommand> {
270 return dedupeSlashCommands(
271 (commands ?? []).flatMap((command) => {
272 const name = nonEmptyProbeString(command.name);
273 if (!name) {
274 return [];
275 }
276
277 const description = nonEmptyProbeString(command.description);
278 const argumentHint = nonEmptyProbeString(command.argumentHint);
279
280 return [
281 {
282 name,
283 ...(description ? { description } : {}),
284 ...(argumentHint ? { input: { hint: argumentHint } } : {}),
285 } satisfies ServerProviderSlashCommand,
286 ];
287 }),
288 );
289}
290
291function dedupeSlashCommands(
292 commands: ReadonlyArray<ServerProviderSlashCommand>,
293): ReadonlyArray<ServerProviderSlashCommand> {
294 const commandsByName = new Map<string, ServerProviderSlashCommand>();
295
296 for (const command of commands) {
297 const name = nonEmptyProbeString(command.name);
298 if (!name) {
299 continue;
300 }
301
302 const key = name.toLowerCase();
303 const existing = commandsByName.get(key);
304 if (!existing) {
305 commandsByName.set(key, {
306 ...command,
307 name,
308 });
309 continue;
310 }
311
312 commandsByName.set(key, {
313 ...existing,
314 ...(existing.description
315 ? {}
316 : command.description
317 ? { description: command.description }
318 : {}),
319 ...(existing.input?.hint
320 ? {}
321 : command.input?.hint
322 ? { input: { hint: command.input.hint } }
323 : {}),
324 });
325 }
326
327 return [...commandsByName.values()];
328}
329
330function waitForAbortSignal(signal: AbortSignal): Promise<void> {
331 if (signal.aborted) {
332 return Promise.resolve();
333 }
334 return new Promise((resolve) => {
335 signal.addEventListener("abort", () => resolve(), { once: true });
336 });
337}
338
339/**
340 * We pass a never-yielding AsyncIterable as the prompt so that no user message is ever written
341 * to the subprocess stdin. This means the Claude Code subprocess completes its local
342 * initialization IPC (returning account info and slash commands) but never starts an API
343 * request to Anthropic.
344 */
345const probeClaudeCapabilities = (
346 claudeSettings: ClaudeSettings,
347 environment?: NodeJS.ProcessEnv,
348 cwd?: string,
349 includeUsage = true,
350) => {
351 const abort = new AbortController();
352 return Effect.gen(function* () {
353 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
354 const executablePath = yield* resolveClaudeSdkExecutablePath(
355 claudeSettings.binaryPath,
356 claudeEnvironment,
357 );
358 const managedMcpConfig = yield* hasClaudeManagedMcpConfig();
359 return yield* Effect.tryPromise(async () => {
360 const { query: claudeQuery } = await import("@anthropic-ai/claude-agent-sdk");
361 const q = claudeQuery({
362 // Never yield — we only need initialization data, not a conversation.
363 // This prevents any prompt from reaching the Anthropic API.
364 // oxlint-disable-next-line require-yield
365 prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
366 await waitForAbortSignal(abort.signal);
367 })(),
368 options: buildClaudeCapabilitiesProbeQueryOptions({
369 executablePath,
370 abortController: abort,
371 environment: claudeEnvironment,
372 cwd,
373 managedMcpConfig,
374 }),
375 });
376 const init = await q.initializationResult();
377 return { q, init };
378 });
379 }).pipe(
380 Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS),
381 Effect.flatMap(({ q, init }) =>
382 Effect.gen(function* () {
383 // Usage has its own deadline so a slow optional request cannot discard initialization.
384 // Only the rate limits are read, so skip the local transcript scan that fills
385 // `behaviors`: with a few GB of transcripts it outlasts the deadline.
386 const usageResult = includeUsage
387 ? yield* Effect.tryPromise(() =>
388 q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true }),
389 ).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result)
390 : undefined;
391 const usage =
392 usageResult && Result.isSuccess(usageResult)
393 ? {
394 rate_limits_available: usageResult.success.rate_limits_available,
395 rate_limits: usageResult.success.rate_limits,
396 }
397 : undefined;
398 const account = init.account as
399 | {
400 readonly email?: string;
401 readonly subscriptionType?: string;
402 readonly tokenSource?: string;
403 readonly apiKeySource?: string;
404 readonly apiProvider?: string;
405 }
406 | undefined;
407 return {
408 email: account?.email,
409 subscriptionType: account?.subscriptionType,
410 tokenSource: account?.tokenSource,
411 apiKeySource: account?.apiKeySource,
412 apiProvider: account?.apiProvider,
413 slashCommands: parseClaudeInitializationCommands(init.commands),
414 ...(usage ? { usage } : {}),
415 } satisfies ClaudeCapabilitiesProbe;
416 }),
417 ),
418 Effect.ensuring(
419 Effect.sync(() => {
420 if (!abort.signal.aborted) abort.abort();
421 }),
422 ),
423 Effect.tapError((error) =>
424 Effect.logWarning("Claude capability probe failed.", { errorTag: error._tag }),
425 ),
426 );
427};
428
429type ClaudeCapabilitiesProbeError = Effect.Error<ReturnType<typeof probeClaudeCapabilities>>;
430
431const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
432 claudeSettings: ClaudeSettings,
433 args: ReadonlyArray<string>,
434 environment?: NodeJS.ProcessEnv,
435 cwd?: string,
436) {
437 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
438 const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, {
439 env: claudeEnvironment,
440 });
441 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
442 env: claudeEnvironment,
443 shell: spawnCommand.shell,
444 ...(cwd ? { cwd } : {}),
445 });
446 return yield* spawnAndCollect(claudeSettings.binaryPath, command);
447});
448
449export const probeClaudeWorkspaceSnapshot = Effect.fn("probeClaudeWorkspaceSnapshot")(function* (
450 claudeSettings: ClaudeSettings,
451 machineSnapshot: ServerProvider,
452 cwd: string,
453 environment?: NodeJS.ProcessEnv,
454): Effect.fn.Return<ProviderWorkspaceSnapshot, never, FileSystem.FileSystem | Path.Path> {
455 if (!claudeSettings.enabled) return machineSnapshot;
456 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, environment);
457 const probeResult = yield* probeClaudeCapabilities(claudeSettings, environment, cwd, false).pipe(
458 Effect.result,
459 );
460 const capabilities = Result.isSuccess(probeResult) ? probeResult.success : undefined;
461 return {
462 ...machineSnapshot,
463 skills,
464 slashCommands: dedupeSlashCommands([
465 COMPACT_SLASH_COMMAND,
466 ...(capabilities?.slashCommands ?? []),
467 ]),
468 slashCommandsPending: !capabilities,
469 };
470});
471
472export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
473 claudeSettings: ClaudeSettings,
474 resolveCapabilities?: (
475 claudeSettings: ClaudeSettings,
476 ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined, ClaudeCapabilitiesProbeError>,
477 environment?: NodeJS.ProcessEnv,
478 cwd?: string,
479 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
480 /** Shared with the adapter so turn events reuse the scoped-bucket names this probe saw. */
481 scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>,
482 resolveResetCredits?: (version: string) => Effect.Effect<ServerProviderResetCredits | undefined>,
483): Effect.fn.Return<
484 ServerProviderDraft,
485 never,
486 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
487> {
488 const resolvedEnvironment = environment ?? process.env;
489 const checkedAt = DateTime.formatIso(yield* DateTime.now);
490 const allModels = providerModelsFromSettings(
491 modelCatalog.models.map((entry) => entry.model),
492 claudeSettings.customModels,
493 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
494 );
495
496 if (!claudeSettings.enabled) {
497 return buildServerProvider({
498 presentation: CLAUDE_PRESENTATION,
499 enabled: false,
500 checkedAt,
501 models: allModels,
502 probe: {
503 installed: false,
504 version: null,
505 status: "warning",
506 auth: { status: "unknown" },
507 message: "Claude is disabled in T3 Code settings.",
508 },
509 });
510 }
511
512 const versionProbe = yield* runClaudeCommand(
513 claudeSettings,
514 ["--version"],
515 resolvedEnvironment,
516 cwd,
517 ).pipe(Effect.timeoutOption(DEFAULT_TIMEOUT_MS), Effect.result);
518
519 if (Result.isFailure(versionProbe)) {
520 const error = versionProbe.failure;
521 yield* Effect.logWarning("Claude Agent CLI health check failed.", {
522 errorTag: error._tag,
523 });
524 return buildServerProvider({
525 presentation: CLAUDE_PRESENTATION,
526 enabled: claudeSettings.enabled,
527 checkedAt,
528 models: allModels,
529 probe: {
530 installed: !isCommandMissingCause(error),
531 version: null,
532 status: "error",
533 auth: { status: "unknown" },
534 message: isCommandMissingCause(error)
535 ? "Claude Agent CLI (`claude`) was not found on PATH."
536 : "Failed to execute Claude Agent CLI health check.",
537 },
538 });
539 }
540
541 if (Option.isNone(versionProbe.success)) {
542 return buildServerProvider({
543 presentation: CLAUDE_PRESENTATION,
544 enabled: claudeSettings.enabled,
545 checkedAt,
546 models: allModels,
547 probe: {
548 installed: true,
549 version: null,
550 status: "error",
551 auth: { status: "unknown" },
552 message:
553 "Claude Agent CLI is installed but failed to run. Timed out while running command.",
554 },
555 });
556 }
557
558 const version = versionProbe.success.value;
559 const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
560 if (version.code !== 0) {
561 yield* Effect.logWarning("Claude Agent CLI version probe exited with a non-zero status.", {
562 exitCode: version.code,
563 stdoutLength: version.stdout.length,
564 stderrLength: version.stderr.length,
565 });
566 return buildServerProvider({
567 presentation: CLAUDE_PRESENTATION,
568 enabled: claudeSettings.enabled,
569 checkedAt,
570 models: allModels,
571 probe: {
572 installed: true,
573 version: parsedVersion,
574 status: "error",
575 auth: { status: "unknown" },
576 message: "Claude Agent CLI is installed but failed to run.",
577 },
578 });
579 }
580
581 const models = providerModelsFromSettings(
582 resolveClaudeModelsForVersion(modelCatalog, parsedVersion),
583 claudeSettings.customModels,
584 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
585 );
586 const updateRequiredModels = resolveClaudeUpdateRequiredModels(modelCatalog, parsedVersion);
587 const versionUpgradeMessage = formatClaudeVersionUpgradeMessage(modelCatalog, parsedVersion);
588
589 const probeResult = resolveCapabilities
590 ? yield* resolveCapabilities(claudeSettings).pipe(Effect.result)
591 : undefined;
592 const capabilities =
593 probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined;
594 const probeFailure =
595 probeResult && Result.isFailure(probeResult) ? probeResult.failure : undefined;
596 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
597 const slashCommands = [COMPACT_SLASH_COMMAND, ...(capabilities?.slashCommands ?? [])];
598 const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
599
600 if (!capabilities) {
601 return buildServerProvider({
602 presentation: CLAUDE_PRESENTATION,
603 enabled: claudeSettings.enabled,
604 checkedAt,
605 models,
606 updateRequiredModels,
607 slashCommands: dedupedSlashCommands,
608 skills,
609 probe: {
610 installed: true,
611 version: parsedVersion,
612 status: "warning",
613 auth: { status: "unknown" },
614 message: probeFailure
615 ? Cause.isTimeoutError(probeFailure)
616 ? `Timed out after ${CAPABILITIES_PROBE_TIMEOUT_MS / 1_000}s while checking Claude account status.`
617 : "Claude Agent CLI failed while checking account status."
618 : "Could not verify Claude authentication status from initialization result.",
619 },
620 });
621 }
622
623 if (claudeAuthStatus(capabilities) === "unauthenticated") {
624 return buildServerProvider({
625 presentation: CLAUDE_PRESENTATION,
626 enabled: claudeSettings.enabled,
627 checkedAt,
628 models,
629 slashCommands: dedupedSlashCommands,
630 skills,
631 probe: {
632 installed: true,
633 version: parsedVersion,
634 status: "error",
635 auth: { status: "unauthenticated" },
636 message: "Claude Code is not authenticated. Run `claude auth login` and try again.",
637 },
638 });
639 }
640
641 const authMetadata =
642 claudeAuthMetadata({
643 subscriptionType: capabilities.subscriptionType,
644 authMethod: capabilities.tokenSource,
645 }) ?? apiProviderAuthMetadata(capabilities.apiProvider);
646 const usageLimits = !capabilities.usage
647 ? makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed" })
648 : scopedLimitNames
649 ? yield* recordClaudeUsageResponse(scopedLimitNames, {
650 response: capabilities.usage,
651 checkedAt,
652 })
653 : claudeUsageResponseToLimits({ response: capabilities.usage, checkedAt }).limits;
654 const resetCredits =
655 resolveResetCredits &&
656 capabilities.subscriptionType &&
657 !usageLimits.unavailable &&
658 parsedVersion
659 ? yield* resolveResetCredits(parsedVersion)
660 : undefined;
661 return buildServerProvider({
662 presentation: CLAUDE_PRESENTATION,
663 enabled: claudeSettings.enabled,
664 checkedAt,
665 models,
666 updateRequiredModels,
667 slashCommands: dedupedSlashCommands,
668 skills,
669 probe: {
670 installed: true,
671 version: parsedVersion,
672 status: "ready",
673 auth: {
674 status: "authenticated",
675 ...(capabilities.email ? { email: capabilities.email } : {}),
676 ...(capabilities.workspaceId ? { workspaceId: capabilities.workspaceId } : {}),
677 ...(authMetadata ? authMetadata : {}),
678 },
679 ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),
680 usageLimits: resetCredits ? { ...usageLimits, resetCredits } : usageLimits,
681 },
682 });
683});
684
685const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
686
687export const makePendingClaudeProvider = (
688 claudeSettings: ClaudeSettings,
689 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
690): Effect.Effect<ServerProviderDraft> =>
691 Effect.gen(function* () {
692 const checkedAt = yield* nowIso;
693 const models = providerModelsFromSettings(
694 modelCatalog.models.map((entry) => entry.model),
695 claudeSettings.customModels,
696 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
697 );
698
699 if (!claudeSettings.enabled) {
700 return buildServerProvider({
701 presentation: CLAUDE_PRESENTATION,
702 enabled: false,
703 checkedAt,
704 models,
705 probe: {
706 installed: false,
707 version: null,
708 status: "warning",
709 auth: { status: "unknown" },
710 message: "Claude is disabled in T3 Code settings.",
711 },
712 });
713 }
714
715 return buildServerProvider({
716 presentation: CLAUDE_PRESENTATION,
717 enabled: true,
718 checkedAt,
719 models,
720 probe: {
721 installed: false,
722 version: null,
723 status: "warning",
724 auth: { status: "unknown" },
725 message: "Claude provider status has not been checked in this session yet.",
726 },
727 });
728 });
729
730export { probeClaudeCapabilities };