Open History to see the last commit
1import type {
2 ClaudeSettings,
3 ClaudeModelSelection,
4 ModelCapabilities,
5 ServerProvider,
6 ServerProviderModel,
7 ServerProviderAuth,
8 ServerProviderSlashCommand,
9 ServerProviderState,
10} from "@t3tools/contracts";
11import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
12import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
13import { decodeJsonResult } from "@t3tools/shared/schemaJson";
14import {
15 createModelCapabilities,
16 getModelSelectionStringOptionValue,
17 getProviderOptionCurrentValue,
18 getProviderOptionDescriptors,
19} from "@t3tools/shared/model";
20import {
21 query as claudeQuery,
22 type SlashCommand as ClaudeSlashCommand,
23 type SDKUserMessage,
24} from "@anthropic-ai/claude-agent-sdk";
25
26import {
27 buildBooleanOptionDescriptor,
28 buildSelectOptionDescriptor,
29 buildServerProvider,
30 AUTH_PROBE_TIMEOUT_MS,
31 DEFAULT_TIMEOUT_MS,
32 detailFromResult,
33 extractAuthBoolean,
34 isCommandMissingCause,
35 parseGenericCliVersion,
36 providerModelsFromSettings,
37 spawnAndCollect,
38 type CommandResult,
39} from "../providerSnapshot.ts";
40import { compareCliVersions } from "../cliVersion.ts";
41import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
42import { ClaudeProvider } from "../Services/ClaudeProvider.ts";
43import { ServerSettingsService } from "../../serverSettings.ts";
44import { ServerSettingsError } from "@t3tools/contracts";
45
46const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
47 optionDescriptors: [],
48});
49
50const PROVIDER = "claudeAgent" as const;
51const CLAUDE_PRESENTATION = {
52 displayName: "Claude",
53 showInteractionModeToggle: true,
54} as const;
55const MINIMUM_CLAUDE_OPUS_4_7_VERSION = "2.1.111";
56const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
57 {
58 slug: "claude-opus-4-7",
59 name: "Claude Opus 4.7",
60 isCustom: false,
61 capabilities: createModelCapabilities({
62 optionDescriptors: [
63 buildSelectOptionDescriptor({
64 id: "effort",
65 label: "Reasoning",
66 options: [
67 { value: "low", label: "Low" },
68 { value: "medium", label: "Medium" },
69 { value: "high", label: "High" },
70 { value: "xhigh", label: "Extra High", isDefault: true },
71 { value: "max", label: "Max" },
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-6",
89 name: "Claude Opus 4.6",
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: "max", label: "Max" },
101 { value: "ultrathink", label: "Ultrathink" },
102 ],
103 promptInjectedValues: ["ultrathink"],
104 }),
105 buildBooleanOptionDescriptor({
106 id: "fastMode",
107 label: "Fast Mode",
108 }),
109 buildSelectOptionDescriptor({
110 id: "contextWindow",
111 label: "Context Window",
112 options: [
113 { value: "200k", label: "200k", isDefault: true },
114 { value: "1m", label: "1M" },
115 ],
116 }),
117 ],
118 }),
119 },
120 {
121 slug: "claude-opus-4-5",
122 name: "Claude Opus 4.5",
123 isCustom: false,
124 capabilities: createModelCapabilities({
125 optionDescriptors: [
126 buildSelectOptionDescriptor({
127 id: "effort",
128 label: "Reasoning",
129 options: [
130 { value: "low", label: "Low" },
131 { value: "medium", label: "Medium" },
132 { value: "high", label: "High", isDefault: true },
133 { value: "max", label: "Max" },
134 ],
135 }),
136 buildBooleanOptionDescriptor({
137 id: "fastMode",
138 label: "Fast Mode",
139 }),
140 ],
141 }),
142 },
143 {
144 slug: "claude-sonnet-4-6",
145 name: "Claude Sonnet 4.6",
146 isCustom: false,
147 capabilities: createModelCapabilities({
148 optionDescriptors: [
149 buildSelectOptionDescriptor({
150 id: "effort",
151 label: "Reasoning",
152 options: [
153 { value: "low", label: "Low" },
154 { value: "medium", label: "Medium" },
155 { value: "high", label: "High", isDefault: true },
156 { value: "ultrathink", label: "Ultrathink" },
157 ],
158 promptInjectedValues: ["ultrathink"],
159 }),
160 buildSelectOptionDescriptor({
161 id: "contextWindow",
162 label: "Context Window",
163 options: [
164 { value: "200k", label: "200k", isDefault: true },
165 { value: "1m", label: "1M" },
166 ],
167 }),
168 ],
169 }),
170 },
171 {
172 slug: "claude-haiku-4-5",
173 name: "Claude Haiku 4.5",
174 isCustom: false,
175 capabilities: createModelCapabilities({
176 optionDescriptors: [
177 buildBooleanOptionDescriptor({
178 id: "thinking",
179 label: "Thinking",
180 }),
181 ],
182 }),
183 },
184];
185
186function supportsClaudeOpus47(version: string | null | undefined): boolean {
187 return version ? compareCliVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
188}
189
190function getBuiltInClaudeModelsForVersion(
191 version: string | null | undefined,
192): ReadonlyArray<ServerProviderModel> {
193 if (supportsClaudeOpus47(version)) {
194 return BUILT_IN_MODELS;
195 }
196 return BUILT_IN_MODELS.filter((model) => model.slug !== "claude-opus-4-7");
197}
198
199function formatClaudeOpus47UpgradeMessage(version: string | null): string {
200 const versionLabel = version ? `v${version}` : "the installed version";
201 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.`;
202}
203
204export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {
205 const slug = model?.trim();
206 return (
207 BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ??
208 DEFAULT_CLAUDE_MODEL_CAPABILITIES
209 );
210}
211
212export function resolveClaudeEffort(
213 caps: ModelCapabilities,
214 raw: string | null | undefined,
215): string | undefined {
216 const descriptors = getProviderOptionDescriptors({
217 caps,
218 ...(raw ? { selections: [{ id: "effort", value: raw }] } : {}),
219 });
220 const effortDescriptor = descriptors.find((descriptor) => descriptor.id === "effort");
221 const value = getProviderOptionCurrentValue(effortDescriptor);
222 return typeof value === "string" ? value : undefined;
223}
224
225/**
226 * Normalize a resolved Claude effort value into one suitable for the Claude
227 * CLI's `--effort` flag.
228 *
229 * Mirrors the mapping used when invoking the Claude Agent SDK
230 * ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): the Opus 4.7
231 * capability `"xhigh"` is rewritten to the accepted CLI value `"max"`, and
232 * `"ultrathink"` is filtered out because it is a prompt-prefix mode rather
233 * than a CLI-effort value. Returns `undefined` when no flag should be passed.
234 */
235export function normalizeClaudeCliEffort(effort: string | null | undefined): string | undefined {
236 if (!effort || effort === "ultrathink") {
237 return undefined;
238 }
239 if (effort === "xhigh") {
240 return "max";
241 }
242 return effort;
243}
244
245export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
246 switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
247 case "1m":
248 return `${modelSelection.model}[1m]`;
249 default:
250 return modelSelection.model;
251 }
252}
253export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
254 readonly status: Exclude<ServerProviderState, "disabled">;
255 readonly auth: Pick<ServerProviderAuth, "status">;
256 readonly message?: string;
257} {
258 const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
259
260 if (
261 lowerOutput.includes("unknown command") ||
262 lowerOutput.includes("unrecognized command") ||
263 lowerOutput.includes("unexpected argument")
264 ) {
265 return {
266 status: "warning",
267 auth: { status: "unknown" },
268 message:
269 "Claude Agent authentication status command is unavailable in this version of Claude.",
270 };
271 }
272
273 if (
274 lowerOutput.includes("not logged in") ||
275 lowerOutput.includes("login required") ||
276 lowerOutput.includes("authentication required") ||
277 lowerOutput.includes("run `claude login`") ||
278 lowerOutput.includes("run claude login")
279 ) {
280 return {
281 status: "error",
282 auth: { status: "unauthenticated" },
283 message: "Claude is not authenticated. Run `claude auth login` and try again.",
284 };
285 }
286
287 const parsedAuth = (() => {
288 const trimmed = result.stdout.trim();
289 if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
290 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
291 }
292 try {
293 return {
294 attemptedJsonParse: true as const,
295 auth: extractAuthBoolean(JSON.parse(trimmed)),
296 };
297 } catch {
298 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
299 }
300 })();
301
302 if (parsedAuth.auth === true) {
303 return { status: "ready", auth: { status: "authenticated" } };
304 }
305 if (parsedAuth.auth === false) {
306 return {
307 status: "error",
308 auth: { status: "unauthenticated" },
309 message: "Claude is not authenticated. Run `claude auth login` and try again.",
310 };
311 }
312 if (parsedAuth.attemptedJsonParse) {
313 return {
314 status: "warning",
315 auth: { status: "unknown" },
316 message:
317 "Could not verify Claude authentication status from JSON output (missing auth marker).",
318 };
319 }
320 if (result.code === 0) {
321 return { status: "ready", auth: { status: "authenticated" } };
322 }
323
324 const detail = detailFromResult(result);
325 return {
326 status: "warning",
327 auth: { status: "unknown" },
328 message: detail
329 ? `Could not verify Claude authentication status. ${detail}`
330 : "Could not verify Claude authentication status.",
331 };
332}
333
334// ── Subscription type detection ─────────────────────────────────────
335//
336// The SDK probe returns typed `AccountInfo.subscriptionType` directly.
337// This walker is a best-effort fallback for the `claude auth status`
338// JSON output whose shape is not guaranteed.
339
340/** Keys that directly hold a subscription/plan identifier. */
341const SUBSCRIPTION_TYPE_KEYS = [
342 "subscriptionType",
343 "subscription_type",
344 "plan",
345 "tier",
346 "planType",
347 "plan_type",
348] as const;
349
350/** Keys whose value may be a nested object containing subscription info. */
351const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const;
352const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const;
353const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const;
354
355/** Lift an unknown value into `Option<string>` if it is a non-empty string. */
356const asNonEmptyString = (v: unknown): Option.Option<string> =>
357 typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none();
358
359/** Lift an unknown value into `Option<Record>` if it is a plain object. */
360const asRecord = (v: unknown): Option.Option<Record<string, unknown>> =>
361 typeof v === "object" && v !== null && !globalThis.Array.isArray(v)
362 ? Option.some(v as Record<string, unknown>)
363 : Option.none();
364
365/**
366 * Walk an unknown parsed JSON value looking for a subscription/plan
367 * identifier, returning the first match as an `Option`.
368 */
369function findSubscriptionType(value: unknown): Option.Option<string> {
370 if (globalThis.Array.isArray(value)) {
371 return Option.firstSomeOf(value.map(findSubscriptionType));
372 }
373
374 return asRecord(value).pipe(
375 Option.flatMap((record) => {
376 const direct = Option.firstSomeOf(
377 SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])),
378 );
379 if (Option.isSome(direct)) return direct;
380
381 return Option.firstSomeOf(
382 SUBSCRIPTION_CONTAINER_KEYS.map((key) =>
383 asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)),
384 ),
385 );
386 }),
387 );
388}
389
390function findAuthMethod(value: unknown): Option.Option<string> {
391 if (globalThis.Array.isArray(value)) {
392 return Option.firstSomeOf(value.map(findAuthMethod));
393 }
394
395 return asRecord(value).pipe(
396 Option.flatMap((record) => {
397 const direct = Option.firstSomeOf(
398 AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])),
399 );
400 if (Option.isSome(direct)) return direct;
401
402 return Option.firstSomeOf(
403 AUTH_METHOD_CONTAINER_KEYS.map((key) =>
404 asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)),
405 ),
406 );
407 }),
408 );
409}
410
411/**
412 * Try to extract a subscription type from the `claude auth status` JSON
413 * output. This is a zero-cost operation on data we already have.
414 */
415const decodeUnknownJson = decodeJsonResult(Schema.Unknown);
416
417function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined {
418 const parsed = decodeUnknownJson(result.stdout.trim());
419 if (Result.isFailure(parsed)) return undefined;
420 return Option.getOrUndefined(findSubscriptionType(parsed.success));
421}
422
423function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {
424 const parsed = decodeUnknownJson(result.stdout.trim());
425 if (Result.isFailure(parsed)) return undefined;
426 return Option.getOrUndefined(findAuthMethod(parsed.success));
427}
428
429function toTitleCaseWords(value: string): string {
430 return value
431 .split(/[\s_-]+/g)
432 .filter(Boolean)
433 .map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase())
434 .join(" ");
435}
436
437function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
438 const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
439 if (!normalized) return undefined;
440
441 switch (normalized) {
442 case "max":
443 case "maxplan":
444 case "max5":
445 case "max20":
446 return "Max";
447 case "enterprise":
448 return "Enterprise";
449 case "team":
450 return "Team";
451 case "pro":
452 return "Pro";
453 case "free":
454 return "Free";
455 default:
456 return toTitleCaseWords(subscriptionType!);
457 }
458}
459
460function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {
461 const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, "");
462 if (!normalized) return undefined;
463 if (normalized === "apikey") return "apiKey";
464 return undefined;
465}
466
467function claudeAuthMetadata(input: {
468 readonly subscriptionType: string | undefined;
469 readonly authMethod: string | undefined;
470}): { readonly type: string; readonly label: string } | undefined {
471 if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") {
472 return {
473 type: "apiKey",
474 label: "Claude API Key",
475 };
476 }
477
478 if (input.subscriptionType) {
479 const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType);
480 return {
481 type: input.subscriptionType,
482 label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`,
483 };
484 }
485
486 return undefined;
487}
488
489// ── SDK capability probe ────────────────────────────────────────────
490
491const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
492
493function nonEmptyProbeString(value: string): string | undefined {
494 const candidate = value.trim();
495 return candidate ? candidate : undefined;
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 = (binaryPath: string) => {
584 const abort = new AbortController();
585 return Effect.tryPromise(async () => {
586 const q = claudeQuery({
587 // Never yield — we only need initialization data, not a conversation.
588 // This prevents any prompt from reaching the Anthropic API.
589 // oxlint-disable-next-line require-yield
590 prompt: (async function* (): AsyncGenerator<SDKUserMessage> {
591 await waitForAbortSignal(abort.signal);
592 })(),
593 options: {
594 persistSession: false,
595 pathToClaudeCodeExecutable: binaryPath,
596 abortController: abort,
597 settingSources: ["user", "project", "local"],
598 allowedTools: [],
599 stderr: () => {},
600 },
601 });
602 const init = await q.initializationResult();
603 return {
604 subscriptionType: init.account?.subscriptionType,
605 slashCommands: parseClaudeInitializationCommands(init.commands),
606 };
607 }).pipe(
608 Effect.ensuring(
609 Effect.sync(() => {
610 if (!abort.signal.aborted) abort.abort();
611 }),
612 ),
613 Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
614 Effect.result,
615 Effect.map((result) => {
616 if (Result.isFailure(result)) return undefined;
617 return Option.isSome(result.success) ? result.success.value : undefined;
618 }),
619 );
620};
621
622const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: ReadonlyArray<string>) {
623 const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
624 Effect.flatMap((service) => service.getSettings),
625 Effect.map((settings) => settings.providers.claudeAgent),
626 );
627 const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
628 shell: process.platform === "win32",
629 });
630 return yield* spawnAndCollect(claudeSettings.binaryPath, command);
631});
632
633export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
634 resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
635 resolveSlashCommands?: (
636 binaryPath: string,
637 ) => Effect.Effect<ReadonlyArray<ServerProviderSlashCommand> | undefined>,
638): Effect.fn.Return<
639 ServerProvider,
640 ServerSettingsError,
641 ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
642> {
643 const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
644 Effect.flatMap((service) => service.getSettings),
645 Effect.map((settings) => settings.providers.claudeAgent),
646 );
647 const checkedAt = new Date().toISOString();
648 const allModels = providerModelsFromSettings(
649 BUILT_IN_MODELS,
650 PROVIDER,
651 claudeSettings.customModels,
652 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
653 );
654
655 if (!claudeSettings.enabled) {
656 return buildServerProvider({
657 provider: PROVIDER,
658 presentation: CLAUDE_PRESENTATION,
659 enabled: false,
660 checkedAt,
661 models: allModels,
662 probe: {
663 installed: false,
664 version: null,
665 status: "warning",
666 auth: { status: "unknown" },
667 message: "Claude is disabled in T3 Code settings.",
668 },
669 });
670 }
671
672 const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
673 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
674 Effect.result,
675 );
676
677 if (Result.isFailure(versionProbe)) {
678 const error = versionProbe.failure;
679 return buildServerProvider({
680 provider: PROVIDER,
681 presentation: CLAUDE_PRESENTATION,
682 enabled: claudeSettings.enabled,
683 checkedAt,
684 models: allModels,
685 probe: {
686 installed: !isCommandMissingCause(error),
687 version: null,
688 status: "error",
689 auth: { status: "unknown" },
690 message: isCommandMissingCause(error)
691 ? "Claude Agent CLI (`claude`) is not installed or not on PATH."
692 : `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
693 },
694 });
695 }
696
697 if (Option.isNone(versionProbe.success)) {
698 return buildServerProvider({
699 provider: PROVIDER,
700 presentation: CLAUDE_PRESENTATION,
701 enabled: claudeSettings.enabled,
702 checkedAt,
703 models: allModels,
704 probe: {
705 installed: true,
706 version: null,
707 status: "error",
708 auth: { status: "unknown" },
709 message:
710 "Claude Agent CLI is installed but failed to run. Timed out while running command.",
711 },
712 });
713 }
714
715 const version = versionProbe.success.value;
716 const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
717 if (version.code !== 0) {
718 const detail = detailFromResult(version);
719 return buildServerProvider({
720 provider: PROVIDER,
721 presentation: CLAUDE_PRESENTATION,
722 enabled: claudeSettings.enabled,
723 checkedAt,
724 models: allModels,
725 probe: {
726 installed: true,
727 version: parsedVersion,
728 status: "error",
729 auth: { status: "unknown" },
730 message: detail
731 ? `Claude Agent CLI is installed but failed to run. ${detail}`
732 : "Claude Agent CLI is installed but failed to run.",
733 },
734 });
735 }
736
737 const models = providerModelsFromSettings(
738 getBuiltInClaudeModelsForVersion(parsedVersion),
739 PROVIDER,
740 claudeSettings.customModels,
741 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
742 );
743 const opus47UpgradeMessage = supportsClaudeOpus47(parsedVersion)
744 ? undefined
745 : formatClaudeOpus47UpgradeMessage(parsedVersion);
746
747 const slashCommands =
748 (resolveSlashCommands
749 ? yield* resolveSlashCommands(claudeSettings.binaryPath).pipe(
750 Effect.orElseSucceed(() => undefined),
751 )
752 : undefined) ?? [];
753 const dedupedSlashCommands = dedupeSlashCommands(slashCommands);
754
755 // ── Auth check + subscription detection ────────────────────────────
756
757 const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
758 Effect.timeoutOption(AUTH_PROBE_TIMEOUT_MS),
759 Effect.result,
760 );
761
762 // Determine subscription type from multiple sources (cheapest first):
763 // 1. `claude auth status` JSON output (may or may not contain it)
764 // 2. Cached SDK probe (spawns a Claude process on miss, reads
765 // `initializationResult()` for account metadata, then aborts
766 // immediately — no API tokens are consumed)
767
768 let subscriptionType: string | undefined;
769 let authMethod: string | undefined;
770
771 if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {
772 subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value);
773 authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value);
774 }
775
776 if (!subscriptionType && resolveSubscriptionType) {
777 subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
778 }
779
780 // ── Handle auth results (same logic as before, adjusted models) ──
781
782 if (Result.isFailure(authProbe)) {
783 const error = authProbe.failure;
784 return buildServerProvider({
785 provider: PROVIDER,
786 presentation: CLAUDE_PRESENTATION,
787 enabled: claudeSettings.enabled,
788 checkedAt,
789 models,
790 slashCommands: dedupedSlashCommands,
791 probe: {
792 installed: true,
793 version: parsedVersion,
794 status: "warning",
795 auth: { status: "unknown" },
796 message:
797 error instanceof Error
798 ? `Could not verify Claude authentication status: ${error.message}.`
799 : "Could not verify Claude authentication status.",
800 },
801 });
802 }
803
804 if (Option.isNone(authProbe.success)) {
805 return buildServerProvider({
806 provider: PROVIDER,
807 presentation: CLAUDE_PRESENTATION,
808 enabled: claudeSettings.enabled,
809 checkedAt,
810 models,
811 slashCommands: dedupedSlashCommands,
812 probe: {
813 installed: true,
814 version: parsedVersion,
815 status: "warning",
816 auth: { status: "unknown" },
817 message: "Could not verify Claude authentication status. Timed out while running command.",
818 },
819 });
820 }
821
822 const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
823 const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
824 return buildServerProvider({
825 provider: PROVIDER,
826 presentation: CLAUDE_PRESENTATION,
827 enabled: claudeSettings.enabled,
828 checkedAt,
829 models,
830 slashCommands: dedupedSlashCommands,
831 probe: {
832 installed: true,
833 version: parsedVersion,
834 status: parsed.status,
835 auth: {
836 ...parsed.auth,
837 ...(authMetadata ? authMetadata : {}),
838 },
839 ...(parsed.message
840 ? { message: parsed.message }
841 : opus47UpgradeMessage
842 ? { message: opus47UpgradeMessage }
843 : {}),
844 },
845 });
846});
847
848const makePendingClaudeProvider = (claudeSettings: ClaudeSettings): ServerProvider => {
849 const checkedAt = new Date().toISOString();
850 const models = providerModelsFromSettings(
851 BUILT_IN_MODELS,
852 PROVIDER,
853 claudeSettings.customModels,
854 DEFAULT_CLAUDE_MODEL_CAPABILITIES,
855 );
856
857 if (!claudeSettings.enabled) {
858 return buildServerProvider({
859 provider: PROVIDER,
860 presentation: CLAUDE_PRESENTATION,
861 enabled: false,
862 checkedAt,
863 models,
864 probe: {
865 installed: false,
866 version: null,
867 status: "warning",
868 auth: { status: "unknown" },
869 message: "Claude is disabled in T3 Code settings.",
870 },
871 });
872 }
873
874 return buildServerProvider({
875 provider: PROVIDER,
876 presentation: CLAUDE_PRESENTATION,
877 enabled: true,
878 checkedAt,
879 models,
880 probe: {
881 installed: false,
882 version: null,
883 status: "warning",
884 auth: { status: "unknown" },
885 message: "Claude provider status has not been checked in this session yet.",
886 },
887 });
888};
889
890export const ClaudeProviderLive = Layer.effect(
891 ClaudeProvider,
892 Effect.gen(function* () {
893 const serverSettings = yield* ServerSettingsService;
894 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
895
896 const subscriptionProbeCache = yield* Cache.make({
897 capacity: 1,
898 timeToLive: Duration.minutes(5),
899 lookup: (binaryPath: string) => probeClaudeCapabilities(binaryPath),
900 });
901
902 const checkProvider = checkClaudeProviderStatus(
903 (binaryPath) =>
904 Cache.get(subscriptionProbeCache, binaryPath).pipe(
905 Effect.map((probe) => probe?.subscriptionType),
906 ),
907 (binaryPath) =>
908 Cache.get(subscriptionProbeCache, binaryPath).pipe(
909 Effect.map((probe) => probe?.slashCommands),
910 ),
911 ).pipe(
912 Effect.provideService(ServerSettingsService, serverSettings),
913 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
914 );
915
916 return yield* makeManagedServerProvider<ClaudeSettings>({
917 getSettings: serverSettings.getSettings.pipe(
918 Effect.map((settings) => settings.providers.claudeAgent),
919 Effect.orDie,
920 ),
921 streamSettings: serverSettings.streamChanges.pipe(
922 Stream.map((settings) => settings.providers.claudeAgent),
923 ),
924 haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
925 initialSnapshot: makePendingClaudeProvider,
926 checkProvider,
927 });
928 }),
929);