Open History to see the last commit
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(" ");
67}
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 }
106}
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;
119}
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`;
136}
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;
157}
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;
163}
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 };
219}
220
221function nonEmptyProbeString(value: string): string | undefined {
222 const candidate = value.trim();
223 return candidate ? candidate : undefined;
224}
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 );
267}
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()];
306}
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 });
315}
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 return { q, init };
359 });
360 }).pipe(
361 Effect.timeout(CAPABILITIES_PROBE_TIMEOUT_MS),
362 Effect.flatMap(({ q, init }) =>
363 Effect.gen(function* () {
364 // Usage has its own deadline so a slow optional request cannot discard initialization.
365 const usageResult = yield* Effect.tryPromise(() =>
366 q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET(),
367 ).pipe(Effect.timeout(DEFAULT_TIMEOUT_MS), Effect.result);
368 const usage = Result.isSuccess(usageResult)
369 ? {
370 rate_limits_available: usageResult.success.rate_limits_available,
371 rate_limits: usageResult.success.rate_limits,
372 }
373 : undefined;
374 const account = init.account as
375 | {
376 readonly email?: string;
377 readonly subscriptionType?: string;
378 readonly tokenSource?: string;
379 readonly apiProvider?: string;
380 }
381 | undefined;
382 return {
383 email: account?.email,
384 subscriptionType: account?.subscriptionType,
385 tokenSource: account?.tokenSource,
386 apiProvider: account?.apiProvider,
387 slashCommands: parseClaudeInitializationCommands(init.commands),
388 ...(usage ? { usage } : {}),
389 } satisfies ClaudeCapabilitiesProbe;
390 }),
391 ),
392 Effect.ensuring(
393 Effect.sync(() => {
394 if (!abort.signal.aborted) abort.abort();
395 }),
396 ),
397 Effect.result,
398 Effect.map((result) => (Result.isSuccess(result) ? result.success : undefined)),
399 );
400};
401
402const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
403 claudeSettings: ClaudeSettings,
404 args: ReadonlyArray<string>,
405 environment?: NodeJS.ProcessEnv,
406) {
407 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
408 const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, {
409 env: claudeEnvironment,
410 });
411 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
412 env: claudeEnvironment,
413 shell: spawnCommand.shell,
414 });
415 return yield* spawnAndCollect(claudeSettings.binaryPath, command);
416});
417
418export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
419 claudeSettings: ClaudeSettings,
420 resolveCapabilities?: (
421 claudeSettings: ClaudeSettings,
422 ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
423 environment?: NodeJS.ProcessEnv,
424 cwd?: string,
425 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
426 /** Shared with the adapter so turn events reuse the scoped-bucket names this probe saw. */
427 scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>,
428): Effect.fn.Return<
429 ServerProviderDraft,
430 never,
431 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
432> {
433 const resolvedEnvironment = environment ?? process.env;
434 const checkedAt = DateTime.formatIso(yield* DateTime.now);
435 const allModels = providerModelsFromSettings(
436 modelCatalog.models.map((entry) => entry.model),
437 claudeSettings.customModels,
438 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
439 );
440
441 if (!claudeSettings.enabled) {
442 return buildServerProvider({
443 presentation: CLAUDE_PRESENTATION,
444 enabled: false,
445 checkedAt,
446 models: allModels,
447 probe: {
448 installed: false,
449 version: null,
450 status: "warning",
451 auth: { status: "unknown" },
452 message: "Claude is disabled in T3 Code settings.",
453 },
454 });
455 }
456
457 const versionProbe = yield* runClaudeCommand(
458 claudeSettings,
459 ["--version"],
460 resolvedEnvironment,
461 ).pipe(Effect.timeoutOption(DEFAULT_TIMEOUT_MS), Effect.result);
462
463 if (Result.isFailure(versionProbe)) {
464 const error = versionProbe.failure;
465 yield* Effect.logWarning("Claude Agent CLI health check failed.", {
466 errorTag: error._tag,
467 });
468 return buildServerProvider({
469 presentation: CLAUDE_PRESENTATION,
470 enabled: claudeSettings.enabled,
471 checkedAt,
472 models: allModels,
473 probe: {
474 installed: !isCommandMissingCause(error),
475 version: null,
476 status: "error",
477 auth: { status: "unknown" },
478 message: isCommandMissingCause(error)
479 ? "Claude Agent CLI (`claude`) was not found on PATH."
480 : "Failed to execute Claude Agent CLI health check.",
481 },
482 });
483 }
484
485 if (Option.isNone(versionProbe.success)) {
486 return buildServerProvider({
487 presentation: CLAUDE_PRESENTATION,
488 enabled: claudeSettings.enabled,
489 checkedAt,
490 models: allModels,
491 probe: {
492 installed: true,
493 version: null,
494 status: "error",
495 auth: { status: "unknown" },
496 message:
497 "Claude Agent CLI is installed but failed to run. Timed out while running command.",
498 },
499 });
500 }
501
502 const version = versionProbe.success.value;
503 const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
504 if (version.code !== 0) {
505 yield* Effect.logWarning("Claude Agent CLI version probe exited with a non-zero status.", {
506 exitCode: version.code,
507 stdoutLength: version.stdout.length,
508 stderrLength: version.stderr.length,
509 });
510 return buildServerProvider({
511 presentation: CLAUDE_PRESENTATION,
512 enabled: claudeSettings.enabled,
513 checkedAt,
514 models: allModels,
515 probe: {
516 installed: true,
517 version: parsedVersion,
518 status: "error",
519 auth: { status: "unknown" },
520 message: "Claude Agent CLI is installed but failed to run.",
521 },
522 });
523 }
524
525 const models = providerModelsFromSettings(
526 resolveClaudeModelsForVersion(modelCatalog, parsedVersion),
527 claudeSettings.customModels,
528 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
529 );
530 const versionUpgradeMessage = formatClaudeVersionUpgradeMessage(modelCatalog, parsedVersion);
531
532 const capabilities = resolveCapabilities
533 ? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
534 : undefined;
535 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
536 const slashCommands = [COMPACT_SLASH_COMMAND, ...(capabilities?.slashCommands ?? [])];
537 const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
538
539 if (!capabilities) {
540 return buildServerProvider({
541 presentation: CLAUDE_PRESENTATION,
542 enabled: claudeSettings.enabled,
543 checkedAt,
544 models,
545 slashCommands: dedupedSlashCommands,
546 skills,
547 probe: {
548 installed: true,
549 version: parsedVersion,
550 status: "warning",
551 auth: { status: "unknown" },
552 message: "Could not verify Claude authentication status from initialization result.",
553 },
554 });
555 }
556
557 const authMetadata =
558 claudeAuthMetadata({
559 subscriptionType: capabilities.subscriptionType,
560 authMethod: capabilities.tokenSource,
561 }) ?? apiProviderAuthMetadata(capabilities.apiProvider);
562 const usageLimits = !capabilities.usage
563 ? makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed" })
564 : scopedLimitNames
565 ? yield* recordClaudeUsageResponse(scopedLimitNames, {
566 response: capabilities.usage,
567 checkedAt,
568 })
569 : claudeUsageResponseToLimits({ response: capabilities.usage, checkedAt }).limits;
570 return buildServerProvider({
571 presentation: CLAUDE_PRESENTATION,
572 enabled: claudeSettings.enabled,
573 checkedAt,
574 models,
575 slashCommands: dedupedSlashCommands,
576 skills,
577 probe: {
578 installed: true,
579 version: parsedVersion,
580 status: "ready",
581 auth: {
582 status: "authenticated",
583 ...(capabilities.email ? { email: capabilities.email } : {}),
584 ...(authMetadata ? authMetadata : {}),
585 },
586 ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),
587 usageLimits,
588 },
589 });
590});
591
592const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
593
594export const makePendingClaudeProvider = (
595 claudeSettings: ClaudeSettings,
596 modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG,
597): Effect.Effect<ServerProviderDraft> =>
598 Effect.gen(function* () {
599 const checkedAt = yield* nowIso;
600 const models = providerModelsFromSettings(
601 modelCatalog.models.map((entry) => entry.model),
602 claudeSettings.customModels,
603 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
604 );
605
606 if (!claudeSettings.enabled) {
607 return buildServerProvider({
608 presentation: CLAUDE_PRESENTATION,
609 enabled: false,
610 checkedAt,
611 models,
612 probe: {
613 installed: false,
614 version: null,
615 status: "warning",
616 auth: { status: "unknown" },
617 message: "Claude is disabled in T3 Code settings.",
618 },
619 });
620 }
621
622 return buildServerProvider({
623 presentation: CLAUDE_PRESENTATION,
624 enabled: true,
625 checkedAt,
626 models,
627 probe: {
628 installed: false,
629 version: null,
630 status: "warning",
631 auth: { status: "unknown" },
632 message: "Claude provider status has not been checked in this session yet.",
633 },
634 });
635 });
636
637export { probeClaudeCapabilities };