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