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

ClaudeProvider.ts

648 lines21.1 KB

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