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
198export const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [
199 "user",
200 "project",
201 "local",
202] as const satisfies ReadonlyArray<SettingSource>;
203
204export function buildClaudeCapabilitiesProbeQueryOptions(input: {
205 readonly executablePath: string;
206 readonly abortController: AbortController;
207 readonly environment: NodeJS.ProcessEnv;
208 readonly cwd: string | undefined;
209 readonly managedMcpConfig: boolean;
210}): ClaudeQueryOptions {
211 return {
212 persistSession: false,
213 pathToClaudeCodeExecutable: input.executablePath,
214 abortController: input.abortController,
215 settingSources: [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES],
216 // The probe keeps filesystem setting sources for slash-command discovery,
217 // but must not run the user's hooks: it fires every few minutes, so
218 // SessionStart hooks would run on every health check.
219 settings: { disableAllHooks: true },
220 allowedTools: [],
221 // Ignore MCP definitions from every filesystem setting source above. The
222 // SDK combines this empty explicit map with --strict-mcp-config, which
223 // Claude refuses next to a managed-mcp.json that already excludes them.
224 mcpServers: {},
225 ...(input.managedMcpConfig ? {} : { strictMcpConfig: true }),
226 env: {
227 ...input.environment,
228 // Connected claude.ai MCP servers are discovered outside filesystem
229 // config; disable them independently for this health check.
230 ENABLE_CLAUDEAI_MCP_SERVERS: "false",
231 // Skipping it also avoids Claude spawning a Windows `tasklist | findstr` process tree on
232 // every periodic refresh.
233 FORCE_CODE_TERMINAL: undefined,
234 CLAUDE_CODE_AUTO_CONNECT_IDE: "0",
235 CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL: "1",
236 },
237 ...(input.cwd ? { cwd: input.cwd } : {}),
238 stderr: () => {},
239 };
240}
241
242function nonEmptyProbeString(value: string): string | undefined {
243 const candidate = value.trim();
244 return candidate ? candidate : undefined;
245}
246
247export type ClaudeCapabilitiesProbe = {
248 readonly email: string | undefined;
249 readonly workspaceId?: string | undefined;
250 readonly subscriptionType: string | undefined;
251 readonly tokenSource: string | undefined;
252 readonly apiKeySource: string | undefined;
253 /**
254 * Active API backend reported by the SDK's `AccountInfo`. Anthropic OAuth
255 * login only applies when `"firstParty"`; for Amazon Bedrock (`"bedrock"`)
256 * the subscription/token fields are absent and auth is external AWS creds.
257 */
258 readonly apiProvider: string | undefined;
259 readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
260 /**
261 * Subscription windows from the SDK's `get_usage` control request, or
262 * `undefined` when the request itself failed. Absent windows on an
263 * otherwise successful response mean the account has none (API key).
264 */
265 readonly usage?: Pick<SDKControlGetUsageResponse, "rate_limits_available" | "rate_limits">;
266};
267
268function parseClaudeInitializationCommands(
269 commands: ReadonlyArray<ClaudeSlashCommand> | undefined,
270): ReadonlyArray<ServerProviderSlashCommand> {
271 return dedupeSlashCommands(
272 (commands ?? []).flatMap((command) => {
273 const name = nonEmptyProbeString(command.name);
274 if (!name) {
275 return [];
276 }
277
278 const description = nonEmptyProbeString(command.description);
279 const argumentHint = nonEmptyProbeString(command.argumentHint);
280
281 return [
282 {
283 name,
284 ...(description ? { description } : {}),
285 ...(argumentHint ? { input: { hint: argumentHint } } : {}),
286 } satisfies ServerProviderSlashCommand,
287 ];
288 }),
289 );
290}
291
292function dedupeSlashCommands(
293 commands: ReadonlyArray<ServerProviderSlashCommand>,
294): ReadonlyArray<ServerProviderSlashCommand> {
295 const commandsByName = new Map<string, ServerProviderSlashCommand>();
296
297 for (const command of commands) {
298 const name = nonEmptyProbeString(command.name);
299 if (!name) {
300 continue;
301 }
302
303 const key = name.toLowerCase();
304 const existing = commandsByName.get(key);
305 if (!existing) {
306 commandsByName.set(key, {
307 ...command,
308 name,
309 });
310 continue;
311 }
312
313 commandsByName.set(key, {
314 ...existing,
315 ...(existing.description
316 ? {}
317 : command.description
318 ? { description: command.description }
319 : {}),
320 ...(existing.input?.hint
321 ? {}
322 : command.input?.hint
323 ? { input: { hint: command.input.hint } }
324 : {}),
325 });
326 }
327
328 return [...commandsByName.values()];
329}
330
331function waitForAbortSignal(signal: AbortSignal): Promise<void> {
332 if (signal.aborted) {
333 return Promise.resolve();
334 }
335 return new Promise((resolve) => {
336 signal.addEventListener("abort", () => resolve(), { once: true });
337 });
338}
339
340/**
341 * We pass a never-yielding AsyncIterable as the prompt so that no user message is ever written
342 * to the subprocess stdin. This means the Claude Code subprocess completes its local
343 * initialization IPC (returning account info and slash commands) but never starts an API
344 * request to Anthropic.
345 */
346const probeClaudeCapabilities = (
347 claudeSettings: ClaudeSettings,
348 environment?: NodeJS.ProcessEnv,
349 cwd?: string,
350 includeUsage = true,
351) => {
352 const abort = new AbortController();
353 return Effect.gen(function* () {
354 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
355 const executablePath = yield* resolveClaudeSdkExecutablePath(
356 claudeSettings.binaryPath,
357 claudeEnvironment,
358 );
359 const managedMcpConfig = yield* hasClaudeManagedMcpConfig();
360 return yield* Effect.tryPromise(async () => {
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 };