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

ClaudeProvider.ts

801 lines24.8 KB

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