Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeProvider.ts

744 lines25.2 KB

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(" ");
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 }
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;
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`;
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;
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;
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";
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 };
257​
258function nonEmptyProbeString(value: string): string | undefined {
259 const candidate = value.trim();
260 return candidate ? candidate : undefined;
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 );
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()];
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 });
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 cwd?: string,
459) {
460 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
461 const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, {
462 env: claudeEnvironment,
463 });
464 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
465 env: claudeEnvironment,
466 shell: spawnCommand.shell,
467 ...(cwd ? { cwd } : {}),
468 });
469 return yield* spawnAndCollect(claudeSettings.binaryPath, command);
470});
471​
472/** Read commands from the same cwd Claude uses for a workspace session. */
473export const probeClaudeWorkspaceSnapshot = Effect.fn("probeClaudeWorkspaceSnapshot")(function* (
474 claudeSettings: ClaudeSettings,
475 machineSnapshot: ServerProvider,
476 cwd: string,
477 environment?: NodeJS.ProcessEnv,
478): Effect.fn.Return<ProviderWorkspaceSnapshot, never, FileSystem.FileSystem | Path.Path> {
479 if (!claudeSettings.enabled) return machineSnapshot;
480 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, environment);
481 const capabilities = yield* probeClaudeCapabilities(claudeSettings, environment, cwd, false);
482 return {
483 ...machineSnapshot,
484 skills,
485 slashCommands: dedupeSlashCommands([
486 COMPACT_SLASH_COMMAND,
487 ...(capabilities?.slashCommands ?? []),
488 ]),
489 slashCommandsPending: !capabilities,
490 };
491});
492​
493export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
494 claudeSettings: ClaudeSettings,
495 resolveCapabilities?: (
496 claudeSettings: ClaudeSettings,
497 ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
498 environment?: NodeJS.ProcessEnv,
499 cwd?: string,
500 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
501 /** Shared with the adapter so turn events reuse the scoped-bucket names this probe saw. */
502 scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>,
503 /** Banked resets for a subscription login, given the CLI version for the user agent. */
504 resolveResetCredits?: (version: string) => Effect.Effect<ServerProviderResetCredits | undefined>,
505): Effect.fn.Return<
506 ServerProviderDraft,
507 never,
508 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
509> {
510 const resolvedEnvironment = environment ?? process.env;
511 const checkedAt = DateTime.formatIso(yield* DateTime.now);
512 const allModels = providerModelsFromSettings(
513 modelCatalog.models.map((entry) => entry.model),
514 claudeSettings.customModels,
515 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
516 );
517​
518 if (!claudeSettings.enabled) {
519 return buildServerProvider({
520 presentation: CLAUDE_PRESENTATION,
521 enabled: false,
522 checkedAt,
523 models: allModels,
524 probe: {
525 installed: false,
526 version: null,
527 status: "warning",
528 auth: { status: "unknown" },
529 message: "Claude is disabled in T3 Code settings.",
530 },
531 });
532 }
533​
534 const versionProbe = yield* runClaudeCommand(
535 claudeSettings,
536 ["--version"],
537 resolvedEnvironment,
538 cwd,
539 ).pipe(Effect.timeoutOption(DEFAULT_TIMEOUT_MS), Effect.result);
540​
541 if (Result.isFailure(versionProbe)) {
542 const error = versionProbe.failure;
543 yield* Effect.logWarning("Claude Agent CLI health check failed.", {
544 errorTag: error._tag,
545 });
546 return buildServerProvider({
547 presentation: CLAUDE_PRESENTATION,
548 enabled: claudeSettings.enabled,
549 checkedAt,
550 models: allModels,
551 probe: {
552 installed: !isCommandMissingCause(error),
553 version: null,
554 status: "error",
555 auth: { status: "unknown" },
556 message: isCommandMissingCause(error)
557 ? "Claude Agent CLI (`claude`) was not found on PATH."
558 : "Failed to execute Claude Agent CLI health check.",
559 },
560 });
561 }
562​
563 if (Option.isNone(versionProbe.success)) {
564 return buildServerProvider({
565 presentation: CLAUDE_PRESENTATION,
566 enabled: claudeSettings.enabled,
567 checkedAt,
568 models: allModels,
569 probe: {
570 installed: true,
571 version: null,
572 status: "error",
573 auth: { status: "unknown" },
574 message:
575 "Claude Agent CLI is installed but failed to run. Timed out while running command.",
576 },
577 });
578 }
579​
580 const version = versionProbe.success.value;
581 const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
582 if (version.code !== 0) {
583 yield* Effect.logWarning("Claude Agent CLI version probe exited with a non-zero status.", {
584 exitCode: version.code,
585 stdoutLength: version.stdout.length,
586 stderrLength: version.stderr.length,
587 });
588 return buildServerProvider({
589 presentation: CLAUDE_PRESENTATION,
590 enabled: claudeSettings.enabled,
591 checkedAt,
592 models: allModels,
593 probe: {
594 installed: true,
595 version: parsedVersion,
596 status: "error",
597 auth: { status: "unknown" },
598 message: "Claude Agent CLI is installed but failed to run.",
599 },
600 });
601 }
602​
603 const models = providerModelsFromSettings(
604 resolveClaudeModelsForVersion(modelCatalog, parsedVersion),
605 claudeSettings.customModels,
606 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
607 );
608 const updateRequiredModels = resolveClaudeUpdateRequiredModels(modelCatalog, parsedVersion);
609 const versionUpgradeMessage = formatClaudeVersionUpgradeMessage(modelCatalog, parsedVersion);
610​
611 const capabilities = resolveCapabilities
612 ? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
613 : undefined;
614 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
615 const slashCommands = [COMPACT_SLASH_COMMAND, ...(capabilities?.slashCommands ?? [])];
616 const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
617​
618 if (!capabilities) {
619 return buildServerProvider({
620 presentation: CLAUDE_PRESENTATION,
621 enabled: claudeSettings.enabled,
622 checkedAt,
623 models,
624 updateRequiredModels,
625 slashCommands: dedupedSlashCommands,
626 skills,
627 probe: {
628 installed: true,
629 version: parsedVersion,
630 status: "warning",
631 auth: { status: "unknown" },
632 message: "Could not verify Claude authentication status from initialization result.",
633 },
634 });
635 }
636​
637 if (claudeAuthStatus(capabilities) === "unauthenticated") {
638 return buildServerProvider({
639 presentation: CLAUDE_PRESENTATION,
640 enabled: claudeSettings.enabled,
641 checkedAt,
642 models,
643 slashCommands: dedupedSlashCommands,
644 skills,
645 probe: {
646 installed: true,
647 version: parsedVersion,
648 status: "error",
649 auth: { status: "unauthenticated" },
650 message: "Claude Code is not authenticated. Run `claude auth login` and try again.",
651 },
652 });
653 }
654​
655 const authMetadata =
656 claudeAuthMetadata({
657 subscriptionType: capabilities.subscriptionType,
658 authMethod: capabilities.tokenSource,
659 }) ?? apiProviderAuthMetadata(capabilities.apiProvider);
660 const usageLimits = !capabilities.usage
661 ? makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed" })
662 : scopedLimitNames
663 ? yield* recordClaudeUsageResponse(scopedLimitNames, {
664 response: capabilities.usage,
665 checkedAt,
666 })
667 : claudeUsageResponseToLimits({ response: capabilities.usage, checkedAt }).limits;
668 const resetCredits =
669 resolveResetCredits &&
670 capabilities.subscriptionType &&
671 !usageLimits.unavailable &&
672 parsedVersion
673 ? yield* resolveResetCredits(parsedVersion)
674 : undefined;
675 return buildServerProvider({
676 presentation: CLAUDE_PRESENTATION,
677 enabled: claudeSettings.enabled,
678 checkedAt,
679 models,
680 updateRequiredModels,
681 slashCommands: dedupedSlashCommands,
682 skills,
683 probe: {
684 installed: true,
685 version: parsedVersion,
686 status: "ready",
687 auth: {
688 status: "authenticated",
689 ...(capabilities.email ? { email: capabilities.email } : {}),
690 ...(capabilities.workspaceId ? { workspaceId: capabilities.workspaceId } : {}),
691 ...(authMetadata ? authMetadata : {}),
692 },
693 ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),
694 usageLimits: resetCredits ? { ...usageLimits, resetCredits } : usageLimits,
695 },
696 });
697});
698​
699const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
700​
701export const makePendingClaudeProvider = (
702 claudeSettings: ClaudeSettings,
703 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
704): Effect.Effect<ServerProviderDraft> =>
705 Effect.gen(function* () {
706 const checkedAt = yield* nowIso;
707 const models = providerModelsFromSettings(
708 modelCatalog.models.map((entry) => entry.model),
709 claudeSettings.customModels,
710 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
711 );
712​
713 if (!claudeSettings.enabled) {
714 return buildServerProvider({
715 presentation: CLAUDE_PRESENTATION,
716 enabled: false,
717 checkedAt,
718 models,
719 probe: {
720 installed: false,
721 version: null,
722 status: "warning",
723 auth: { status: "unknown" },
724 message: "Claude is disabled in T3 Code settings.",
725 },
726 });
727 }
728​
729 return buildServerProvider({
730 presentation: CLAUDE_PRESENTATION,
731 enabled: true,
732 checkedAt,
733 models,
734 probe: {
735 installed: false,
736 version: null,
737 status: "warning",
738 auth: { status: "unknown" },
739 message: "Claude provider status has not been checked in this session yet.",
740 },
741 });
742 });
743​
744export { probeClaudeCapabilities };