Open History to see the last commit
1import type {
2 ClaudeSettings,
3 ModelCapabilities,
4 ServerProvider,
5 ServerProviderModel,
6 ServerProviderAuth,
7 ServerProviderState,
8} from "@t3tools/contracts";
9import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
10import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
11import { decodeJsonResult } from "@t3tools/shared/schemaJson";
12import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
13
14import {
15 buildServerProvider,
16 DEFAULT_TIMEOUT_MS,
17 detailFromResult,
18 extractAuthBoolean,
19 isCommandMissingCause,
20 parseGenericCliVersion,
21 providerModelsFromSettings,
22 spawnAndCollect,
23 type CommandResult,
24} from "../providerSnapshot";
25import { makeManagedServerProvider } from "../makeManagedServerProvider";
26import { ClaudeProvider } from "../Services/ClaudeProvider";
27import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
28
29const PROVIDER = "claudeAgent" as const;
30const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
31 {
32 slug: "claude-opus-4-6",
33 name: "Claude Opus 4.6",
34 isCustom: false,
35 capabilities: {
36 reasoningEffortLevels: [
37 { value: "low", label: "Low" },
38 { value: "medium", label: "Medium" },
39 { value: "high", label: "High", isDefault: true },
40 { value: "max", label: "Max" },
41 { value: "ultrathink", label: "Ultrathink" },
42 ],
43 supportsFastMode: true,
44 supportsThinkingToggle: false,
45 contextWindowOptions: [
46 { value: "200k", label: "200k", isDefault: true },
47 { value: "1m", label: "1M" },
48 ],
49 promptInjectedEffortLevels: ["ultrathink"],
50 } satisfies ModelCapabilities,
51 },
52 {
53 slug: "claude-sonnet-4-6",
54 name: "Claude Sonnet 4.6",
55 isCustom: false,
56 capabilities: {
57 reasoningEffortLevels: [
58 { value: "low", label: "Low" },
59 { value: "medium", label: "Medium" },
60 { value: "high", label: "High", isDefault: true },
61 { value: "ultrathink", label: "Ultrathink" },
62 ],
63 supportsFastMode: false,
64 supportsThinkingToggle: false,
65 contextWindowOptions: [
66 { value: "200k", label: "200k", isDefault: true },
67 { value: "1m", label: "1M" },
68 ],
69 promptInjectedEffortLevels: ["ultrathink"],
70 } satisfies ModelCapabilities,
71 },
72 {
73 slug: "claude-haiku-4-5",
74 name: "Claude Haiku 4.5",
75 isCustom: false,
76 capabilities: {
77 reasoningEffortLevels: [],
78 supportsFastMode: false,
79 supportsThinkingToggle: true,
80 contextWindowOptions: [],
81 promptInjectedEffortLevels: [],
82 } satisfies ModelCapabilities,
83 },
84];
85
86export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {
87 const slug = model?.trim();
88 return (
89 BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
90 reasoningEffortLevels: [],
91 supportsFastMode: false,
92 supportsThinkingToggle: false,
93 contextWindowOptions: [],
94 promptInjectedEffortLevels: [],
95 }
96 );
97}
98
99export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
100 readonly status: Exclude<ServerProviderState, "disabled">;
101 readonly auth: Pick<ServerProviderAuth, "status">;
102 readonly message?: string;
103} {
104 const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
105
106 if (
107 lowerOutput.includes("unknown command") ||
108 lowerOutput.includes("unrecognized command") ||
109 lowerOutput.includes("unexpected argument")
110 ) {
111 return {
112 status: "warning",
113 auth: { status: "unknown" },
114 message:
115 "Claude Agent authentication status command is unavailable in this version of Claude.",
116 };
117 }
118
119 if (
120 lowerOutput.includes("not logged in") ||
121 lowerOutput.includes("login required") ||
122 lowerOutput.includes("authentication required") ||
123 lowerOutput.includes("run `claude login`") ||
124 lowerOutput.includes("run claude login")
125 ) {
126 return {
127 status: "error",
128 auth: { status: "unauthenticated" },
129 message: "Claude is not authenticated. Run `claude auth login` and try again.",
130 };
131 }
132
133 const parsedAuth = (() => {
134 const trimmed = result.stdout.trim();
135 if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
136 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
137 }
138 try {
139 return {
140 attemptedJsonParse: true as const,
141 auth: extractAuthBoolean(JSON.parse(trimmed)),
142 };
143 } catch {
144 return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
145 }
146 })();
147
148 if (parsedAuth.auth === true) {
149 return { status: "ready", auth: { status: "authenticated" } };
150 }
151 if (parsedAuth.auth === false) {
152 return {
153 status: "error",
154 auth: { status: "unauthenticated" },
155 message: "Claude is not authenticated. Run `claude auth login` and try again.",
156 };
157 }
158 if (parsedAuth.attemptedJsonParse) {
159 return {
160 status: "warning",
161 auth: { status: "unknown" },
162 message:
163 "Could not verify Claude authentication status from JSON output (missing auth marker).",
164 };
165 }
166 if (result.code === 0) {
167 return { status: "ready", auth: { status: "authenticated" } };
168 }
169
170 const detail = detailFromResult(result);
171 return {
172 status: "warning",
173 auth: { status: "unknown" },
174 message: detail
175 ? `Could not verify Claude authentication status. ${detail}`
176 : "Could not verify Claude authentication status.",
177 };
178}
179
180// ── Subscription type detection ─────────────────────────────────────
181//
182// The SDK probe returns typed `AccountInfo.subscriptionType` directly.
183// This walker is a best-effort fallback for the `claude auth status`
184// JSON output whose shape is not guaranteed.
185
186/** Keys that directly hold a subscription/plan identifier. */
187const SUBSCRIPTION_TYPE_KEYS = [
188 "subscriptionType",
189 "subscription_type",
190 "plan",
191 "tier",
192 "planType",
193 "plan_type",
194] as const;
195
196/** Keys whose value may be a nested object containing subscription info. */
197const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const;
198const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const;
199const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const;
200
201/** Lift an unknown value into `Option<string>` if it is a non-empty string. */
202const asNonEmptyString = (v: unknown): Option.Option<string> =>
203 typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none();
204
205/** Lift an unknown value into `Option<Record>` if it is a plain object. */
206const asRecord = (v: unknown): Option.Option<Record<string, unknown>> =>
207 typeof v === "object" && v !== null && !globalThis.Array.isArray(v)
208 ? Option.some(v as Record<string, unknown>)
209 : Option.none();
210
211/**
212 * Walk an unknown parsed JSON value looking for a subscription/plan
213 * identifier, returning the first match as an `Option`.
214 */
215function findSubscriptionType(value: unknown): Option.Option<string> {
216 if (globalThis.Array.isArray(value)) {
217 return Option.firstSomeOf(value.map(findSubscriptionType));
218 }
219
220 return asRecord(value).pipe(
221 Option.flatMap((record) => {
222 const direct = Option.firstSomeOf(
223 SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])),
224 );
225 if (Option.isSome(direct)) return direct;
226
227 return Option.firstSomeOf(
228 SUBSCRIPTION_CONTAINER_KEYS.map((key) =>
229 asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)),
230 ),
231 );
232 }),
233 );
234}
235
236function findAuthMethod(value: unknown): Option.Option<string> {
237 if (globalThis.Array.isArray(value)) {
238 return Option.firstSomeOf(value.map(findAuthMethod));
239 }
240
241 return asRecord(value).pipe(
242 Option.flatMap((record) => {
243 const direct = Option.firstSomeOf(
244 AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])),
245 );
246 if (Option.isSome(direct)) return direct;
247
248 return Option.firstSomeOf(
249 AUTH_METHOD_CONTAINER_KEYS.map((key) =>
250 asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)),
251 ),
252 );
253 }),
254 );
255}
256
257/**
258 * Try to extract a subscription type from the `claude auth status` JSON
259 * output. This is a zero-cost operation on data we already have.
260 */
261const decodeUnknownJson = decodeJsonResult(Schema.Unknown);
262
263function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined {
264 const parsed = decodeUnknownJson(result.stdout.trim());
265 if (Result.isFailure(parsed)) return undefined;
266 return Option.getOrUndefined(findSubscriptionType(parsed.success));
267}
268
269function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {
270 const parsed = decodeUnknownJson(result.stdout.trim());
271 if (Result.isFailure(parsed)) return undefined;
272 return Option.getOrUndefined(findAuthMethod(parsed.success));
273}
274
275// ── Dynamic model capability adjustment ─────────────────────────────
276
277/** Subscription types where the 1M context window is included in the plan. */
278const PREMIUM_SUBSCRIPTION_TYPES = new Set([
279 "max",
280 "maxplan",
281 "max5",
282 "max20",
283 "enterprise",
284 "team",
285]);
286
287function toTitleCaseWords(value: string): string {
288 return value
289 .split(/[\s_-]+/g)
290 .filter(Boolean)
291 .map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase())
292 .join(" ");
293}
294
295function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
296 const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
297 if (!normalized) return undefined;
298
299 switch (normalized) {
300 case "max":
301 case "maxplan":
302 case "max5":
303 case "max20":
304 return "Max";
305 case "enterprise":
306 return "Enterprise";
307 case "team":
308 return "Team";
309 case "pro":
310 return "Pro";
311 case "free":
312 return "Free";
313 default:
314 return toTitleCaseWords(subscriptionType!);
315 }
316}
317
318function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {
319 const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, "");
320 if (!normalized) return undefined;
321 if (normalized === "apikey") return "apiKey";
322 return undefined;
323}
324
325function claudeAuthMetadata(input: {
326 readonly subscriptionType: string | undefined;
327 readonly authMethod: string | undefined;
328}): { readonly type: string; readonly label: string } | undefined {
329 if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") {
330 return {
331 type: "apiKey",
332 label: "Claude API Key",
333 };
334 }
335
336 if (input.subscriptionType) {
337 const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType);
338 return {
339 type: input.subscriptionType,
340 label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`,
341 };
342 }
343
344 return undefined;
345}
346
347/**
348 * Adjust the built-in model list based on the user's detected subscription.
349 *
350 * - Premium tiers (Max, Enterprise, Team): 1M context becomes the default.
351 * - Other tiers (Pro, free, unknown): 200k context stays the default;
352 * 1M remains available as a manual option so users can still enable it.
353 */
354export function adjustModelsForSubscription(
355 baseModels: ReadonlyArray<ServerProviderModel>,
356 subscriptionType: string | undefined,
357): ReadonlyArray<ServerProviderModel> {
358 const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
359 if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) {
360 return baseModels;
361 }
362
363 // Flip 1M to be the default for premium users
364 return baseModels.map((model) => {
365 const caps = model.capabilities;
366 if (!caps || caps.contextWindowOptions.length === 0) return model;
367
368 return {
369 ...model,
370 capabilities: {
371 ...caps,
372 contextWindowOptions: caps.contextWindowOptions.map((opt) =>
373 opt.value === "1m"
374 ? { value: opt.value, label: opt.label, isDefault: true as const }
375 : { value: opt.value, label: opt.label },
376 ),
377 },
378 };
379 });
380}
381
382// ── SDK capability probe ────────────────────────────────────────────
383
384const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
385
386/**
387 * Probe account information by spawning a lightweight Claude Agent SDK
388 * session and reading the initialization result.
389 *
390 * The prompt is never sent to the Anthropic API — we abort immediately
391 * after the local initialization phase completes. This gives us the
392 * user's subscription type without incurring any token cost.
393 *
394 * This is used as a fallback when `claude auth status` does not include
395 * subscription type information.
396 */
397const probeClaudeCapabilities = (binaryPath: string) => {
398 const abort = new AbortController();
399 return Effect.tryPromise(async () => {
400 const q = claudeQuery({
401 prompt: ".",
402 options: {
403 persistSession: false,
404 pathToClaudeCodeExecutable: binaryPath,
405 abortController: abort,
406 maxTurns: 0,
407 settingSources: [],
408 allowedTools: [],
409 stderr: () => {},
410 },
411 });
412 const init = await q.initializationResult();
413 return { subscriptionType: init.account?.subscriptionType };
414 }).pipe(
415 Effect.ensuring(
416 Effect.sync(() => {
417 if (!abort.signal.aborted) abort.abort();
418 }),
419 ),
420 Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
421 Effect.result,
422 Effect.map((result) => {
423 if (Result.isFailure(result)) return undefined;
424 return Option.isSome(result.success) ? result.success.value : undefined;
425 }),
426 );
427};
428
429const runClaudeCommand = (args: ReadonlyArray<string>) =>
430 Effect.gen(function* () {
431 const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
432 Effect.flatMap((service) => service.getSettings),
433 Effect.map((settings) => settings.providers.claudeAgent),
434 );
435 const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
436 shell: process.platform === "win32",
437 });
438 return yield* spawnAndCollect(claudeSettings.binaryPath, command);
439 });
440
441export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
442 resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
443): Effect.fn.Return<
444 ServerProvider,
445 ServerSettingsError,
446 ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
447> {
448 const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
449 Effect.flatMap((service) => service.getSettings),
450 Effect.map((settings) => settings.providers.claudeAgent),
451 );
452 const checkedAt = new Date().toISOString();
453 const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, claudeSettings.customModels);
454
455 if (!claudeSettings.enabled) {
456 return buildServerProvider({
457 provider: PROVIDER,
458 enabled: false,
459 checkedAt,
460 models,
461 probe: {
462 installed: false,
463 version: null,
464 status: "warning",
465 auth: { status: "unknown" },
466 message: "Claude is disabled in T3 Code settings.",
467 },
468 });
469 }
470
471 const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
472 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
473 Effect.result,
474 );
475
476 if (Result.isFailure(versionProbe)) {
477 const error = versionProbe.failure;
478 return buildServerProvider({
479 provider: PROVIDER,
480 enabled: claudeSettings.enabled,
481 checkedAt,
482 models,
483 probe: {
484 installed: !isCommandMissingCause(error),
485 version: null,
486 status: "error",
487 auth: { status: "unknown" },
488 message: isCommandMissingCause(error)
489 ? "Claude Agent CLI (`claude`) is not installed or not on PATH."
490 : `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
491 },
492 });
493 }
494
495 if (Option.isNone(versionProbe.success)) {
496 return buildServerProvider({
497 provider: PROVIDER,
498 enabled: claudeSettings.enabled,
499 checkedAt,
500 models,
501 probe: {
502 installed: true,
503 version: null,
504 status: "error",
505 auth: { status: "unknown" },
506 message:
507 "Claude Agent CLI is installed but failed to run. Timed out while running command.",
508 },
509 });
510 }
511
512 const version = versionProbe.success.value;
513 const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
514 if (version.code !== 0) {
515 const detail = detailFromResult(version);
516 return buildServerProvider({
517 provider: PROVIDER,
518 enabled: claudeSettings.enabled,
519 checkedAt,
520 models,
521 probe: {
522 installed: true,
523 version: parsedVersion,
524 status: "error",
525 auth: { status: "unknown" },
526 message: detail
527 ? `Claude Agent CLI is installed but failed to run. ${detail}`
528 : "Claude Agent CLI is installed but failed to run.",
529 },
530 });
531 }
532
533 // ── Auth check + subscription detection ────────────────────────────
534
535 const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
536 Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
537 Effect.result,
538 );
539
540 // Determine subscription type from multiple sources (cheapest first):
541 // 1. `claude auth status` JSON output (may or may not contain it)
542 // 2. Cached SDK probe (spawns a Claude process on miss, reads
543 // `initializationResult()` for account metadata, then aborts
544 // immediately — no API tokens are consumed)
545
546 let subscriptionType: string | undefined;
547 let authMethod: string | undefined;
548
549 if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {
550 subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value);
551 authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value);
552 }
553
554 if (!subscriptionType && resolveSubscriptionType) {
555 subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
556 }
557
558 const resolvedModels = adjustModelsForSubscription(models, subscriptionType);
559
560 // ── Handle auth results (same logic as before, adjusted models) ──
561
562 if (Result.isFailure(authProbe)) {
563 const error = authProbe.failure;
564 return buildServerProvider({
565 provider: PROVIDER,
566 enabled: claudeSettings.enabled,
567 checkedAt,
568 models: resolvedModels,
569 probe: {
570 installed: true,
571 version: parsedVersion,
572 status: "warning",
573 auth: { status: "unknown" },
574 message:
575 error instanceof Error
576 ? `Could not verify Claude authentication status: ${error.message}.`
577 : "Could not verify Claude authentication status.",
578 },
579 });
580 }
581
582 if (Option.isNone(authProbe.success)) {
583 return buildServerProvider({
584 provider: PROVIDER,
585 enabled: claudeSettings.enabled,
586 checkedAt,
587 models: resolvedModels,
588 probe: {
589 installed: true,
590 version: parsedVersion,
591 status: "warning",
592 auth: { status: "unknown" },
593 message: "Could not verify Claude authentication status. Timed out while running command.",
594 },
595 });
596 }
597
598 const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
599 const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
600 return buildServerProvider({
601 provider: PROVIDER,
602 enabled: claudeSettings.enabled,
603 checkedAt,
604 models: resolvedModels,
605 probe: {
606 installed: true,
607 version: parsedVersion,
608 status: parsed.status,
609 auth: {
610 ...parsed.auth,
611 ...(authMetadata ? authMetadata : {}),
612 },
613 ...(parsed.message ? { message: parsed.message } : {}),
614 },
615 });
616});
617
618export const ClaudeProviderLive = Layer.effect(
619 ClaudeProvider,
620 Effect.gen(function* () {
621 const serverSettings = yield* ServerSettingsService;
622 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
623
624 const subscriptionProbeCache = yield* Cache.make({
625 capacity: 1,
626 timeToLive: Duration.minutes(5),
627 lookup: (binaryPath: string) =>
628 probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)),
629 });
630
631 const checkProvider = checkClaudeProviderStatus((binaryPath) =>
632 Cache.get(subscriptionProbeCache, binaryPath),
633 ).pipe(
634 Effect.provideService(ServerSettingsService, serverSettings),
635 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
636 );
637
638 return yield* makeManagedServerProvider<ClaudeSettings>({
639 getSettings: serverSettings.getSettings.pipe(
640 Effect.map((settings) => settings.providers.claudeAgent),
641 Effect.orDie,
642 ),
643 streamSettings: serverSettings.streamChanges.pipe(
644 Stream.map((settings) => settings.providers.claudeAgent),
645 ),
646 haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
647 checkProvider,
648 });
649 }),
650);