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