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

ClaudeProvider.ts

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