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

ClaudeProvider.ts

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