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

ClaudeProvider.ts

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