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