Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeProvider.ts

1,027 lines32.6 KB

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;
331​
332function supportsClaudeFable5(version: string | null | undefined): boolean {
333 return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;
335​
336function supportsClaudeOpus48(version: string | null | undefined): boolean {
337 return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_8_VERSION) >= 0 : false;
339​
340function supportsClaudeOpus47(version: string | null | undefined): boolean {
341 return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
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 });
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.`;
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.`;
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.`;
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.`;
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 );
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;
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;
439​
440export function isClaudeUltracodeEffort(effort: string | null | undefined): boolean {
441 return effort === "ultracode";
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;
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 }
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(" ");
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 }
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;
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`;
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;
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;
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 // This is a noninteractive health check, so IDE discovery cannot add any
618 // useful capability data. Skipping it also avoids Claude spawning a
619 // Windows `tasklist | findstr` process tree on every periodic refresh.
620 FORCE_CODE_TERMINAL: undefined,
621 CLAUDE_CODE_AUTO_CONNECT_IDE: "0",
622 CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL: "1",
623 },
624 ...(input.cwd ? { cwd: input.cwd } : {}),
625 stderr: () => {},
626 };
628​
629function nonEmptyProbeString(value: string): string | undefined {
630 const candidate = value.trim();
631 return candidate ? candidate : undefined;
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 );
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()];
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 });
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`) was not found 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 = [
931 {
932 name: "compact",
933 description: "Summarize the conversation and reduce context usage",
934 },
935 ...(capabilities?.slashCommands ?? []),
936 ];
937 const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
938​
939 if (!capabilities) {
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: "warning",
951 auth: { status: "unknown" },
952 message: "Could not verify Claude authentication status from initialization result.",
953 },
954 });
955 }
956​
957 const authMetadata =
958 claudeAuthMetadata({
959 subscriptionType: capabilities.subscriptionType,
960 authMethod: capabilities.tokenSource,
961 }) ?? apiProviderAuthMetadata(capabilities.apiProvider);
962 return buildServerProvider({
963 presentation: CLAUDE_PRESENTATION,
964 enabled: claudeSettings.enabled,
965 checkedAt,
966 models,
967 slashCommands: dedupedSlashCommands,
968 skills,
969 probe: {
970 installed: true,
971 version: parsedVersion,
972 status: "ready",
973 auth: {
974 status: "authenticated",
975 ...(capabilities.email ? { email: capabilities.email } : {}),
976 ...(authMetadata ? authMetadata : {}),
977 },
978 ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),
979 },
980 });
981});
982​
983const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
984​
985export const makePendingClaudeProvider = (
986 claudeSettings: ClaudeSettings,
987): Effect.Effect<ServerProviderDraft> =>
988 Effect.gen(function* () {
989 const checkedAt = yield* nowIso;
990 const models = providerModelsFromSettings(
991 BUILT_IN_MODELS,
992 claudeSettings.customModels,
993 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
994 );
995​
996 if (!claudeSettings.enabled) {
997 return buildServerProvider({
998 presentation: CLAUDE_PRESENTATION,
999 enabled: false,
1000 checkedAt,
1001 models,
1002 probe: {
1003 installed: false,
1004 version: null,
1005 status: "warning",
1006 auth: { status: "unknown" },
1007 message: "Claude is disabled in T3 Code settings.",
1008 },
1009 });
1011​
1012 return buildServerProvider({
1013 presentation: CLAUDE_PRESENTATION,
1014 enabled: true,
1015 checkedAt,
1016 models,
1017 probe: {
1018 installed: false,
1019 version: null,
1020 status: "warning",
1021 auth: { status: "unknown" },
1022 message: "Claude provider status has not been checked in this session yet.",
1023 },
1024 });
1025 });
1026​
1027export { probeClaudeCapabilities };