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

ClaudeProvider.ts

634 lines20.5 KB

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