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