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