Open History to see the last commit
1import {
2 type ClaudeSettings,
3 type ModelCapabilities,
4 type ModelSelection,
5 type ServerProviderModel,
6 type ServerProviderSlashCommand,
7} from "@t3tools/contracts";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Result from "effect/Result";
14import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
15import {
16 createModelCapabilities,
17 getModelSelectionStringOptionValue,
18 getProviderOptionCurrentValue,
19 getProviderOptionDescriptors,
20} from "@t3tools/shared/model";
21import { resolveSpawnCommand } from "@t3tools/shared/shell";
22import { compareSemverVersions } from "@t3tools/shared/semver";
23import {
24 query as claudeQuery,
25 type Options as ClaudeQueryOptions,
26 type SlashCommand as ClaudeSlashCommand,
27 type SDKUserMessage,
28 type SettingSource,
29} from "@anthropic-ai/claude-agent-sdk";
30
31import {
32 buildBooleanOptionDescriptor,
33 buildSelectOptionDescriptor,
34 buildServerProvider,
35 DEFAULT_TIMEOUT_MS,
36 isCommandMissingCause,
37 parseGenericCliVersion,
38 providerModelsFromSettings,
39 spawnAndCollect,
40 type ServerProviderDraft,
41} from "../providerSnapshot.ts";
42import { resolveClaudeSdkExecutablePath } from "../Drivers/ClaudeExecutable.ts";
43import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
44import { discoverClaudeSkills } from "../Drivers/ClaudeSkills.ts";
45
46const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
47 optionDescriptors: [],
48});
49
50const CLAUDE_PRESENTATION = {
51 displayName: "Claude",
52 showInteractionModeToggle: true,
53} as const;
54const MINIMUM_CLAUDE_OPUS_5_VERSION = "2.1.219";
55const MINIMUM_CLAUDE_FABLE_5_VERSION = "2.1.169";
56const MINIMUM_CLAUDE_OPUS_4_8_VERSION = "2.1.154";
57const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
58
59const CURRENT_CLAUDE_MODELS = new Set(["claude-fable-5", "claude-opus-5", "claude-sonnet-5"]);
60
61export function isLegacyClaudeModel(model: string): boolean {
62 return !CURRENT_CLAUDE_MODELS.has(model);
63}
64
65const CLAUDE_MODEL_CATALOG: ReadonlyArray<ServerProviderModel> = [
66 {
67 slug: "claude-fable-5",
68 name: "Claude Fable 5",
69 isCustom: false,
70 capabilities: createModelCapabilities({
71 optionDescriptors: [
72 buildSelectOptionDescriptor({
73 id: "effort",
74 label: "Reasoning",
75 options: [
76 { value: "low", label: "Low" },
77 { value: "medium", label: "Medium" },
78 { value: "high", label: "High", isDefault: true },
79 { value: "xhigh", label: "Extra High" },
80 { value: "max", label: "Max" },
81 { value: "ultracode", label: "Ultracode" },
82 { value: "ultrathink", label: "Ultrathink" },
83 ],
84 promptInjectedValues: ["ultrathink"],
85 }),
86 buildSelectOptionDescriptor({
87 id: "contextWindow",
88 label: "Context Window",
89 options: [
90 { value: "200k", label: "200k" },
91 { value: "1m", label: "1M", isDefault: true },
92 ],
93 }),
94 ],
95 }),
96 },
97 {
98 slug: "claude-opus-5",
99 name: "Claude Opus 5",
100 isCustom: false,
101 capabilities: createModelCapabilities({
102 optionDescriptors: [
103 buildSelectOptionDescriptor({
104 id: "effort",
105 label: "Reasoning",
106 options: [
107 { value: "low", label: "Low" },
108 { value: "medium", label: "Medium" },
109 { value: "high", label: "High", isDefault: true },
110 { value: "xhigh", label: "Extra High" },
111 { value: "max", label: "Max" },
112 { value: "ultracode", label: "Ultracode" },
113 { value: "ultrathink", label: "Ultrathink" },
114 ],
115 promptInjectedValues: ["ultrathink"],
116 }),
117 buildBooleanOptionDescriptor({
118 id: "fastMode",
119 label: "Fast Mode",
120 }),
121 buildSelectOptionDescriptor({
122 id: "contextWindow",
123 label: "Context Window",
124 // Claude Code selects the 1M variant explicitly (`claude-opus-5[1m]`).
125 options: [
126 { value: "200k", label: "200k" },
127 { value: "1m", label: "1M", isDefault: true },
128 ],
129 }),
130 ],
131 }),
132 },
133 {
134 slug: "claude-opus-4-8",
135 name: "Claude Opus 4.8",
136 isCustom: false,
137 capabilities: createModelCapabilities({
138 optionDescriptors: [
139 buildSelectOptionDescriptor({
140 id: "effort",
141 label: "Reasoning",
142 options: [
143 { value: "low", label: "Low" },
144 { value: "medium", label: "Medium" },
145 { value: "high", label: "High", isDefault: true },
146 { value: "xhigh", label: "Extra High" },
147 { value: "max", label: "Max" },
148 { value: "ultracode", label: "Ultracode" },
149 { value: "ultrathink", label: "Ultrathink" },
150 ],
151 promptInjectedValues: ["ultrathink"],
152 }),
153 buildBooleanOptionDescriptor({
154 id: "fastMode",
155 label: "Fast Mode",
156 }),
157 ],
158 }),
159 },
160 {
161 slug: "claude-opus-4-7",
162 name: "Claude Opus 4.7",
163 isCustom: false,
164 capabilities: createModelCapabilities({
165 optionDescriptors: [
166 buildSelectOptionDescriptor({
167 id: "effort",
168 label: "Reasoning",
169 options: [
170 { value: "low", label: "Low" },
171 { value: "medium", label: "Medium" },
172 { value: "high", label: "High" },
173 { value: "xhigh", label: "Extra High", isDefault: true },
174 { value: "max", label: "Max" },
175 { value: "ultrathink", label: "Ultrathink" },
176 ],
177 promptInjectedValues: ["ultrathink"],
178 }),
179 buildBooleanOptionDescriptor({
180 id: "fastMode",
181 label: "Fast Mode",
182 }),
183 ],
184 }),
185 },
186 {
187 slug: "claude-opus-4-6",
188 name: "Claude Opus 4.6",
189 isCustom: false,
190 capabilities: createModelCapabilities({
191 optionDescriptors: [
192 buildSelectOptionDescriptor({
193 id: "effort",
194 label: "Reasoning",
195 options: [
196 { value: "low", label: "Low" },
197 { value: "medium", label: "Medium" },
198 { value: "high", label: "High", isDefault: true },
199 { value: "max", label: "Max" },
200 { value: "ultrathink", label: "Ultrathink" },
201 ],
202 promptInjectedValues: ["ultrathink"],
203 }),
204 buildBooleanOptionDescriptor({
205 id: "fastMode",
206 label: "Fast Mode",
207 }),
208 buildSelectOptionDescriptor({
209 id: "contextWindow",
210 label: "Context Window",
211 options: [
212 { value: "200k", label: "200k" },
213 { value: "1m", label: "1M", isDefault: true },
214 ],
215 }),
216 ],
217 }),
218 },
219 {
220 slug: "claude-opus-4-5",
221 name: "Claude Opus 4.5",
222 isCustom: false,
223 capabilities: createModelCapabilities({
224 optionDescriptors: [
225 buildSelectOptionDescriptor({
226 id: "effort",
227 label: "Reasoning",
228 options: [
229 { value: "low", label: "Low" },
230 { value: "medium", label: "Medium" },
231 { value: "high", label: "High", isDefault: true },
232 { value: "max", label: "Max" },
233 ],
234 }),
235 buildBooleanOptionDescriptor({
236 id: "fastMode",
237 label: "Fast Mode",
238 }),
239 ],
240 }),
241 },
242 {
243 slug: "claude-sonnet-5",
244 name: "Claude Sonnet 5",
245 isCustom: false,
246 capabilities: createModelCapabilities({
247 optionDescriptors: [
248 buildSelectOptionDescriptor({
249 id: "effort",
250 label: "Reasoning",
251 options: [
252 { value: "low", label: "Low" },
253 { value: "medium", label: "Medium" },
254 { value: "high", label: "High", isDefault: true },
255 { value: "xhigh", label: "Extra High" },
256 { value: "max", label: "Max" },
257 { value: "ultrathink", label: "Ultrathink" },
258 ],
259 promptInjectedValues: ["ultrathink"],
260 }),
261 buildSelectOptionDescriptor({
262 id: "contextWindow",
263 label: "Context Window",
264 // Sonnet is 200k-default in Claude Code (1M is opt-in there too).
265 options: [
266 { value: "200k", label: "200k", isDefault: true },
267 { value: "1m", label: "1M" },
268 ],
269 }),
270 ],
271 }),
272 },
273 {
274 slug: "claude-sonnet-4-6",
275 name: "Claude Sonnet 4.6",
276 isCustom: false,
277 capabilities: createModelCapabilities({
278 optionDescriptors: [
279 buildSelectOptionDescriptor({
280 id: "effort",
281 label: "Reasoning",
282 options: [
283 { value: "low", label: "Low" },
284 { value: "medium", label: "Medium" },
285 { value: "high", label: "High", isDefault: true },
286 { value: "max", label: "Max" },
287 { value: "ultrathink", label: "Ultrathink" },
288 ],
289 promptInjectedValues: ["ultrathink"],
290 }),
291 buildSelectOptionDescriptor({
292 id: "contextWindow",
293 label: "Context Window",
294 // Sonnet is 200k-default in Claude Code (1M is opt-in there too).
295 options: [
296 { value: "200k", label: "200k", isDefault: true },
297 { value: "1m", label: "1M" },
298 ],
299 }),
300 ],
301 }),
302 },
303 {
304 slug: "claude-haiku-4-5",
305 name: "Claude Haiku 4.5",
306 isCustom: false,
307 capabilities: createModelCapabilities({
308 optionDescriptors: [
309 buildBooleanOptionDescriptor({
310 id: "thinking",
311 label: "Thinking",
312 }),
313 ],
314 }),
315 },
316];
317
318const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = CLAUDE_MODEL_CATALOG.map((model) =>
319 isLegacyClaudeModel(model.slug) ? { ...model, isLegacy: true } : model,
320);
321
322function supportsClaudeOpus5(version: string | null | undefined): boolean {
323 return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_5_VERSION) >= 0 : false;
324}
325
326function supportsClaudeFable5(version: string | null | undefined): boolean {
327 return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;
328}
329
330function supportsClaudeOpus48(version: string | null | undefined): boolean {
331 return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_8_VERSION) >= 0 : false;
332}
333
334function supportsClaudeOpus47(version: string | null | undefined): boolean {
335 return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
336}
337
338function getBuiltInClaudeModelsForVersion(
339 version: string | null | undefined,
340): ReadonlyArray<ServerProviderModel> {
341 return BUILT_IN_MODELS.filter((model) => {
342 if (model.slug === "claude-opus-5") {
343 return supportsClaudeOpus5(version);
344 }
345 if (model.slug === "claude-fable-5") {
346 return supportsClaudeFable5(version);
347 }
348 if (model.slug === "claude-opus-4-8") {
349 return supportsClaudeOpus48(version);
350 }
351 if (model.slug === "claude-opus-4-7") {
352 return supportsClaudeOpus47(version);
353 }
354 return true;
355 });
356}
357
358function formatClaudeOpus5UpgradeMessage(version: string | null): string {
359 const versionLabel = version ? `v${version}` : "the installed version";
360 return `Claude Code ${versionLabel} is too old for Claude Opus 5. Upgrade to v${MINIMUM_CLAUDE_OPUS_5_VERSION} or newer to access it.`;
361}
362
363function formatClaudeFable5UpgradeMessage(version: string | null): string {
364 const versionLabel = version ? `v${version}` : "the installed version";
365 return `Claude Code ${versionLabel} is too old for Claude Fable 5. Upgrade to v${MINIMUM_CLAUDE_FABLE_5_VERSION} or newer to access it.`;
366}
367
368function formatClaudeOpus48UpgradeMessage(version: string | null): string {
369 const versionLabel = version ? `v${version}` : "the installed version";
370 return `Claude Code ${versionLabel} is too old for Claude Opus 4.8. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_8_VERSION} or newer to access it.`;
371}
372
373function formatClaudeOpus47UpgradeMessage(version: string | null): string {
374 const versionLabel = version ? `v${version}` : "the installed version";
375 return `Claude Code ${versionLabel} is too old for Claude Opus 4.7. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_7_VERSION} or newer to access it.`;
376}
377
378export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {
379 const slug = model?.trim();
380 return (
381 BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ??
382 DEFAULT_CLAUDE_MODEL_CAPABILITIES
383 );
384}
385
386export function resolveClaudeEffort(
387 caps: ModelCapabilities,
388 raw: string | null | undefined,
389): string | undefined {
390 const descriptors = getProviderOptionDescriptors({
391 caps,
392 ...(raw ? { selections: [{ id: "effort", value: raw }] } : {}),
393 });
394 const effortDescriptor = descriptors.find((descriptor) => descriptor.id === "effort");
395 const value = getProviderOptionCurrentValue(effortDescriptor);
396 return typeof value === "string" ? value : undefined;
397}
398
399/**
400 * Normalize a resolved Claude effort value into one suitable for the Claude
401 * CLI's `--effort` flag.
402 *
403 * Mirrors the mapping used when invoking the Claude Agent SDK
404 * ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): `ultracode` is a
405 * Claude Code setting that pairs with `xhigh`, `ultrathink` is filtered out
406 * because it is a prompt-prefix mode, and older model compatibility mappings
407 * are preserved for current Claude Code behavior.
408 */
409export function normalizeClaudeCliEffort(
410 effort: string | null | undefined,
411 model: string | null | undefined,
412): string | undefined {
413 if (!effort || effort === "ultrathink") {
414 return undefined;
415 }
416 if (effort === "ultracode") {
417 return "xhigh";
418 }
419 if (
420 effort === "xhigh" &&
421 model !== "claude-fable-5" &&
422 model !== "claude-opus-5" &&
423 model !== "claude-opus-4-8" &&
424 model !== "claude-sonnet-5"
425 ) {
426 return "max";
427 }
428 if (effort === "max" && model === "claude-sonnet-4-6") {
429 return "high";
430 }
431 return effort;
432}
433
434export function isClaudeUltracodeEffort(effort: string | null | undefined): boolean {
435 return effort === "ultracode";
436}
437
438export function resolveClaudeContextWindow(
439 modelSelection: ModelSelection | undefined,
440): string | undefined {
441 const caps = getClaudeModelCapabilities(modelSelection?.model);
442 const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
443 const descriptors = getProviderOptionDescriptors({
444 caps,
445 ...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
446 });
447 const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
448 const value = getProviderOptionCurrentValue(descriptor);
449 return typeof value === "string" ? value : undefined;
450}
451
452export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
453 switch (resolveClaudeContextWindow(modelSelection)) {
454 case "1m":
455 return `${modelSelection.model}[1m]`;
456 default:
457 return modelSelection.model;
458 }
459}
460
461function toTitleCaseWords(value: string): string {
462 const parts: Array<string> = [];
463 for (const part of value.split(/[\s_-]+/g)) {
464 if (part.length > 0) {
465 parts.push(part[0]!.toUpperCase() + part.slice(1).toLowerCase());
466 }
467 }
468 return parts.join(" ");
469}
470
471function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
472 const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
473 if (!normalized) return undefined;
474
475 switch (normalized) {
476 case "claudemaxsubscription":
477 return "Max";
478 case "claudemax5xsubscription":
479 return "Max 5x";
480 case "claudemax20xsubscription":
481 return "Max 20x";
482 case "claudeenterprisesubscription":
483 return "Enterprise";
484 case "claudeteamsubscription":
485 return "Team";
486 case "claudeprosubscription":
487 return "Pro";
488 case "claudefreesubscription":
489 return "Free";
490 case "max":
491 case "maxplan":
492 return "Max";
493 case "max5":
494 return "Max 5x";
495 case "max20":
496 return "Max 20x";
497 case "enterprise":
498 return "Enterprise";
499 case "team":
500 return "Team";
501 case "pro":
502 return "Pro";
503 case "free":
504 return "Free";
505 default:
506 return toTitleCaseWords(subscriptionType!);
507 }
508}
509
510function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {
511 const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, "");
512 if (!normalized) return undefined;
513 if (
514 normalized === "apikey" ||
515 normalized === "anthropicapikey" ||
516 normalized === "anthropicauthtoken"
517 ) {
518 return "apiKey";
519 }
520 return undefined;
521}
522
523function formatClaudeSubscriptionAuthLabel(subscriptionType: string): string {
524 const subscriptionLabel =
525 claudeSubscriptionLabel(subscriptionType) ?? toTitleCaseWords(subscriptionType);
526 const normalized = subscriptionLabel.toLowerCase().replace(/[\s_-]+/g, "");
527
528 if (normalized.startsWith("claude") && normalized.endsWith("subscription")) {
529 return subscriptionLabel;
530 }
531 if (normalized.startsWith("claude")) {
532 return `${subscriptionLabel} Subscription`;
533 }
534 if (normalized.endsWith("subscription")) {
535 return `Claude ${subscriptionLabel}`;
536 }
537 return `Claude ${subscriptionLabel} Subscription`;
538}
539
540function claudeAuthMetadata(input: {
541 readonly subscriptionType: string | undefined;
542 readonly authMethod: string | undefined;
543}): { readonly type: string; readonly label: string } | undefined {
544 if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") {
545 return {
546 type: "apiKey",
547 label: "Claude API Key",
548 };
549 }
550
551 if (input.subscriptionType) {
552 return {
553 type: input.subscriptionType,
554 label: formatClaudeSubscriptionAuthLabel(input.subscriptionType),
555 };
556 }
557
558 return undefined;
559}
560
561function apiProviderAuthMetadata(
562 apiProvider: string | undefined,
563): { readonly type: string; readonly label: string } | undefined {
564 return apiProvider === "bedrock" ? { type: "bedrock", label: "Amazon Bedrock" } : undefined;
565}
566
567// ── SDK capability probe ────────────────────────────────────────────
568
569// Amazon Bedrock initializes far slower than first-party auth: the SDK boots the
570// Bedrock backend and runs the `awsAuthRefresh` credential hook before returning
571// account info. The previous 8s budget expired mid-init, so the probe returned
572// `undefined` and left the provider unverified and unselectable in the picker.
573const CAPABILITIES_PROBE_TIMEOUT_MS = 25_000;
574
575/**
576 * Keep workspace-scoped command discovery intact while isolating the periodic
577 * health check from configured MCP servers.
578 */
579export const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [
580 "user",
581 "project",
582 "local",
583] as const satisfies ReadonlyArray<SettingSource>;
584
585/** Build the exact SDK options used by the periodic Claude capability probe. */
586export function buildClaudeCapabilitiesProbeQueryOptions(input: {
587 readonly executablePath: string;
588 readonly abortController: AbortController;
589 readonly environment: NodeJS.ProcessEnv;
590 readonly cwd: string | undefined;
591}): ClaudeQueryOptions {
592 return {
593 persistSession: false,
594 pathToClaudeCodeExecutable: input.executablePath,
595 abortController: input.abortController,
596 settingSources: [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES],
597 allowedTools: [],
598 // Ignore MCP definitions from every filesystem setting source above. The
599 // SDK combines this empty explicit map with --strict-mcp-config.
600 mcpServers: {},
601 strictMcpConfig: true,
602 env: {
603 ...input.environment,
604 // Connected claude.ai MCP servers are discovered outside filesystem
605 // config; disable them independently for this health check.
606 ENABLE_CLAUDEAI_MCP_SERVERS: "false",
607 },
608 ...(input.cwd ? { cwd: input.cwd } : {}),
609 stderr: () => {},
610 };
611}
612
613function nonEmptyProbeString(value: string): string | undefined {
614 const candidate = value.trim();
615 return candidate ? candidate : undefined;
616}
617
618type ClaudeCapabilitiesProbe = {
619 readonly email: string | undefined;
620 readonly subscriptionType: string | undefined;
621 readonly tokenSource: string | undefined;
622 /**
623 * Active API backend reported by the SDK's `AccountInfo`. Anthropic OAuth
624 * login only applies when `"firstParty"`; for Amazon Bedrock (`"bedrock"`)
625 * the subscription/token fields are absent and auth is external AWS creds.
626 */
627 readonly apiProvider: string | undefined;
628 readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
629};
630
631function parseClaudeInitializationCommands(
632 commands: ReadonlyArray<ClaudeSlashCommand> | undefined,
633): ReadonlyArray<ServerProviderSlashCommand> {
634 return dedupeSlashCommands(
635 (commands ?? []).flatMap((command) => {
636 const name = nonEmptyProbeString(command.name);
637 if (!name) {
638 return [];
639 }
640
641 const description = nonEmptyProbeString(command.description);
642 const argumentHint = nonEmptyProbeString(command.argumentHint);
643
644 return [
645 {
646 name,
647 ...(description ? { description } : {}),
648 ...(argumentHint ? { input: { hint: argumentHint } } : {}),
649 } satisfies ServerProviderSlashCommand,
650 ];
651 }),
652 );
653}
654
655function dedupeSlashCommands(
656 commands: ReadonlyArray<ServerProviderSlashCommand>,
657): ReadonlyArray<ServerProviderSlashCommand> {
658 const commandsByName = new Map<string, ServerProviderSlashCommand>();
659
660 for (const command of commands) {
661 const name = nonEmptyProbeString(command.name);
662 if (!name) {
663 continue;
664 }
665
666 const key = name.toLowerCase();
667 const existing = commandsByName.get(key);
668 if (!existing) {
669 commandsByName.set(key, {
670 ...command,
671 name,
672 });
673 continue;
674 }
675
676 commandsByName.set(key, {
677 ...existing,
678 ...(existing.description
679 ? {}
680 : command.description
681 ? { description: command.description }
682 : {}),
683 ...(existing.input?.hint
684 ? {}
685 : command.input?.hint
686 ? { input: { hint: command.input.hint } }
687 : {}),
688 });
689 }
690
691 return [...commandsByName.values()];
692}
693
694function waitForAbortSignal(signal: AbortSignal): Promise<void> {
695 if (signal.aborted) {
696 return Promise.resolve();
697 }
698 return new Promise((resolve) => {
699 signal.addEventListener("abort", () => resolve(), { once: true });
700 });
701}
702
703/**
704 * Probe account information by spawning a lightweight Claude Agent SDK
705 * session and reading the initialization result.
706 *
707 * We pass a never-yielding AsyncIterable as the prompt so that no user
708 * message is ever written to the subprocess stdin. This means the Claude
709 * Code subprocess completes its local initialization IPC (returning
710 * account info and slash commands) but never starts an API request to
711 * Anthropic. We read the init data and then abort the subprocess.
712 *
713 * This is used as a fallback when `claude auth status` does not include
714 * subscription type information.
715 */
716const probeClaudeCapabilities = (
717 claudeSettings: ClaudeSettings,
718 environment?: NodeJS.ProcessEnv,
719 cwd?: string,
720) => {
721 const abort = new AbortController();
722 return Effect.gen(function* () {
723 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
724 const executablePath = yield* resolveClaudeSdkExecutablePath(
725 claudeSettings.binaryPath,
726 claudeEnvironment,
727 );
728 return yield* Effect.tryPromise(async () => {
729 const q = claudeQuery({
730 // Never yield — we only need initialization data, not a conversation.
731 // This prevents any prompt from reaching the Anthropic API.
732 // oxlint-disable-next-line require-yield
733 prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
734 await waitForAbortSignal(abort.signal);
735 })(),
736 options: buildClaudeCapabilitiesProbeQueryOptions({
737 executablePath,
738 abortController: abort,
739 environment: claudeEnvironment,
740 cwd,
741 }),
742 });
743 const init = await q.initializationResult();
744 const account = init.account as
745 | {
746 readonly email?: string;
747 readonly subscriptionType?: string;
748 readonly tokenSource?: string;
749 readonly apiProvider?: string;
750 }
751 | undefined;
752 return {
753 email: account?.email,
754 subscriptionType: account?.subscriptionType,
755 tokenSource: account?.tokenSource,
756 apiProvider: account?.apiProvider,
757 slashCommands: parseClaudeInitializationCommands(init.commands),
758 } satisfies ClaudeCapabilitiesProbe;
759 });
760 }).pipe(
761 Effect.ensuring(
762 Effect.sync(() => {
763 if (!abort.signal.aborted) abort.abort();
764 }),
765 ),
766 Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
767 Effect.result,
768 Effect.map((result) => {
769 if (Result.isFailure(result)) return undefined;
770 return Option.isSome(result.success) ? result.success.value : undefined;
771 }),
772 );
773};
774
775const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (
776 claudeSettings: ClaudeSettings,
777 args: ReadonlyArray<string>,
778 environment?: NodeJS.ProcessEnv,
779) {
780 const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
781 const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, {
782 env: claudeEnvironment,
783 });
784 const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {
785 env: claudeEnvironment,
786 shell: spawnCommand.shell,
787 });
788 return yield* spawnAndCollect(claudeSettings.binaryPath, command);
789});
790
791export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
792 claudeSettings: ClaudeSettings,
793 resolveCapabilities?: (
794 claudeSettings: ClaudeSettings,
795 ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,
796 environment?: NodeJS.ProcessEnv,
797 cwd?: string,
798): Effect.fn.Return<
799 ServerProviderDraft,
800 never,
801 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
802> {
803 const resolvedEnvironment = environment ?? process.env;
804 const checkedAt = DateTime.formatIso(yield* DateTime.now);
805 const allModels = providerModelsFromSettings(
806 BUILT_IN_MODELS,
807 claudeSettings.customModels,
808 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
809 );
810
811 if (!claudeSettings.enabled) {
812 return buildServerProvider({
813 presentation: CLAUDE_PRESENTATION,
814 enabled: false,
815 checkedAt,
816 models: allModels,
817 probe: {
818 installed: false,
819 version: null,
820 status: "warning",
821 auth: { status: "unknown" },
822 message: "Claude is disabled in T3 Code settings.",
823 },
824 });
825 }
826
827 const versionProbe = yield* runClaudeCommand(
828 claudeSettings,
829 ["--version"],
830 resolvedEnvironment,
831 ).pipe(Effect.timeoutOption(DEFAULT_TIMEOUT_MS), Effect.result);
832
833 if (Result.isFailure(versionProbe)) {
834 const error = versionProbe.failure;
835 yield* Effect.logWarning("Claude Agent CLI health check failed.", {
836 errorTag: error._tag,
837 });
838 return buildServerProvider({
839 presentation: CLAUDE_PRESENTATION,
840 enabled: claudeSettings.enabled,
841 checkedAt,
842 models: allModels,
843 probe: {
844 installed: !isCommandMissingCause(error),
845 version: null,
846 status: "error",
847 auth: { status: "unknown" },
848 message: isCommandMissingCause(error)
849 ? "Claude Agent CLI (`claude`) is not installed or not on PATH."
850 : "Failed to execute Claude Agent CLI health check.",
851 },
852 });
853 }
854
855 if (Option.isNone(versionProbe.success)) {
856 return buildServerProvider({
857 presentation: CLAUDE_PRESENTATION,
858 enabled: claudeSettings.enabled,
859 checkedAt,
860 models: allModels,
861 probe: {
862 installed: true,
863 version: null,
864 status: "error",
865 auth: { status: "unknown" },
866 message:
867 "Claude Agent CLI is installed but failed to run. Timed out while running command.",
868 },
869 });
870 }
871
872 const version = versionProbe.success.value;
873 const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
874 if (version.code !== 0) {
875 yield* Effect.logWarning("Claude Agent CLI version probe exited with a non-zero status.", {
876 exitCode: version.code,
877 stdoutLength: version.stdout.length,
878 stderrLength: version.stderr.length,
879 });
880 return buildServerProvider({
881 presentation: CLAUDE_PRESENTATION,
882 enabled: claudeSettings.enabled,
883 checkedAt,
884 models: allModels,
885 probe: {
886 installed: true,
887 version: parsedVersion,
888 status: "error",
889 auth: { status: "unknown" },
890 message: "Claude Agent CLI is installed but failed to run.",
891 },
892 });
893 }
894
895 const models = providerModelsFromSettings(
896 getBuiltInClaudeModelsForVersion(parsedVersion),
897 claudeSettings.customModels,
898 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
899 );
900 const versionUpgradeMessage = supportsClaudeOpus5(parsedVersion)
901 ? undefined
902 : supportsClaudeFable5(parsedVersion)
903 ? formatClaudeOpus5UpgradeMessage(parsedVersion)
904 : supportsClaudeOpus48(parsedVersion)
905 ? formatClaudeFable5UpgradeMessage(parsedVersion)
906 : supportsClaudeOpus47(parsedVersion)
907 ? formatClaudeOpus48UpgradeMessage(parsedVersion)
908 : formatClaudeOpus47UpgradeMessage(parsedVersion);
909
910 const capabilities = resolveCapabilities
911 ? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))
912 : undefined;
913 const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);
914 const slashCommands = capabilities?.slashCommands ?? [];
915 const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
916
917 if (!capabilities) {
918 return buildServerProvider({
919 presentation: CLAUDE_PRESENTATION,
920 enabled: claudeSettings.enabled,
921 checkedAt,
922 models,
923 slashCommands: dedupedSlashCommands,
924 skills,
925 probe: {
926 installed: true,
927 version: parsedVersion,
928 status: "warning",
929 auth: { status: "unknown" },
930 message: "Could not verify Claude authentication status from initialization result.",
931 },
932 });
933 }
934
935 const authMetadata =
936 claudeAuthMetadata({
937 subscriptionType: capabilities.subscriptionType,
938 authMethod: capabilities.tokenSource,
939 }) ?? apiProviderAuthMetadata(capabilities.apiProvider);
940 return buildServerProvider({
941 presentation: CLAUDE_PRESENTATION,
942 enabled: claudeSettings.enabled,
943 checkedAt,
944 models,
945 slashCommands: dedupedSlashCommands,
946 skills,
947 probe: {
948 installed: true,
949 version: parsedVersion,
950 status: "ready",
951 auth: {
952 status: "authenticated",
953 ...(capabilities.email ? { email: capabilities.email } : {}),
954 ...(authMetadata ? authMetadata : {}),
955 },
956 ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),
957 },
958 });
959});
960
961const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
962
963export const makePendingClaudeProvider = (
964 claudeSettings: ClaudeSettings,
965): Effect.Effect<ServerProviderDraft> =>
966 Effect.gen(function* () {
967 const checkedAt = yield* nowIso;
968 const models = providerModelsFromSettings(
969 BUILT_IN_MODELS,
970 claudeSettings.customModels,
971 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
972 );
973
974 if (!claudeSettings.enabled) {
975 return buildServerProvider({
976 presentation: CLAUDE_PRESENTATION,
977 enabled: false,
978 checkedAt,
979 models,
980 probe: {
981 installed: false,
982 version: null,
983 status: "warning",
984 auth: { status: "unknown" },
985 message: "Claude is disabled in T3 Code settings.",
986 },
987 });
988 }
989
990 return buildServerProvider({
991 presentation: CLAUDE_PRESENTATION,
992 enabled: true,
993 checkedAt,
994 models,
995 probe: {
996 installed: false,
997 version: null,
998 status: "warning",
999 auth: { status: "unknown" },
1000 message: "Claude provider status has not been checked in this session yet.",
1001 },
1002 });
1003 });
1004
1005export { probeClaudeCapabilities };