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

ClaudeProvider.ts

658 lines20.8 KB

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