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