Open History to see the last commit
1/**
2 * ClaudeDriver — `ProviderDriver` for the Claude Agent SDK runtime.
3 *
4 * Mirrors `CodexDriver`: a plain value whose `create()` returns one
5 * `ProviderInstance` bundling `snapshot` / `adapter` / `textGeneration`
6 * closures captured over the per-instance `ClaudeSettings`.
7 *
8 * Unlike Codex, the Claude snapshot probe may invoke a secondary probe
9 * (`probeClaudeCapabilities`) to read Anthropic account + slash-command
10 * metadata. That probe is per-instance and keyed by binary + resolved HOME so
11 * two concurrent Claude instances don't cross-contaminate account metadata.
12 *
13 * @module provider/Drivers/ClaudeDriver
14 */
15import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
16import { Cache, Duration, Effect, FileSystem, Path, Schema, Stream } from "effect";
17import { HttpClient } from "effect/unstable/http";
18import { ChildProcessSpawner } from "effect/unstable/process";
19
20import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
21import { ServerConfig } from "../../config.ts";
22import { ProviderDriverError } from "../Errors.ts";
23import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
24import {
25 checkClaudeProviderStatus,
26 makePendingClaudeProvider,
27 probeClaudeCapabilities,
28} from "../Layers/ClaudeProvider.ts";
29import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
30import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
31import {
32 defaultProviderContinuationIdentity,
33 type ProviderDriver,
34 type ProviderInstance,
35} from "../ProviderDriver.ts";
36import type { ServerProviderDraft } from "../providerSnapshot.ts";
37import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
38import {
39 enrichProviderSnapshotWithVersionAdvisory,
40 makePackageManagedProviderMaintenanceResolver,
41 normalizeCommandPath,
42 resolveProviderMaintenanceCapabilitiesEffect,
43} from "../providerMaintenance.ts";
44import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
45
46const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
47const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
48const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
49
50function isClaudeNativeCommandPath(commandPath: string): boolean {
51 const normalized = normalizeCommandPath(commandPath);
52 return (
53 normalized.endsWith("/.local/bin/claude") ||
54 normalized.endsWith("/.local/bin/claude.exe") ||
55 normalized.includes("/.local/share/claude/")
56 );
57}
58
59const UPDATE = makePackageManagedProviderMaintenanceResolver({
60 provider: DRIVER_KIND,
61 npmPackageName: "@anthropic-ai/claude-code",
62 homebrewFormula: "claude-code",
63 nativeUpdate: {
64 executable: "claude",
65 args: ["update"],
66 lockKey: "claude-native",
67 isCommandPath: isClaudeNativeCommandPath,
68 },
69});
70
71export type ClaudeDriverEnv =
72 | ChildProcessSpawner.ChildProcessSpawner
73 | FileSystem.FileSystem
74 | HttpClient.HttpClient
75 | Path.Path
76 | ProviderEventLoggers
77 | ServerConfig;
78
79const withInstanceIdentity =
80 (input: {
81 readonly instanceId: ProviderInstance["instanceId"];
82 readonly displayName: string | undefined;
83 readonly accentColor: string | undefined;
84 readonly continuationGroupKey: string;
85 }) =>
86 (snapshot: ServerProviderDraft): ServerProvider => ({
87 ...snapshot,
88 instanceId: input.instanceId,
89 driver: DRIVER_KIND,
90 ...(input.displayName ? { displayName: input.displayName } : {}),
91 ...(input.accentColor ? { accentColor: input.accentColor } : {}),
92 continuation: { groupKey: input.continuationGroupKey },
93 });
94
95export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
96 driverKind: DRIVER_KIND,
97 metadata: {
98 displayName: "Claude",
99 supportsMultipleInstances: true,
100 },
101 configSchema: ClaudeSettings,
102 defaultConfig: (): ClaudeSettings => Schema.decodeSync(ClaudeSettings)({}),
103 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
104 Effect.gen(function* () {
105 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
106 const path = yield* Path.Path;
107 const httpClient = yield* HttpClient.HttpClient;
108 const eventLoggers = yield* ProviderEventLoggers;
109 const processEnv = mergeProviderInstanceEnvironment(environment);
110 const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
111 driverKind: DRIVER_KIND,
112 instanceId,
113 });
114 const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;
115 const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
116 binaryPath: effectiveConfig.binaryPath,
117 env: processEnv,
118 });
119 const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);
120 const stampIdentity = withInstanceIdentity({
121 instanceId,
122 displayName,
123 accentColor,
124 continuationGroupKey,
125 });
126
127 const adapterOptions = {
128 instanceId,
129 environment: processEnv,
130 ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
131 };
132 const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions);
133 const textGeneration = yield* makeClaudeTextGeneration(effectiveConfig, processEnv);
134
135 // Per-instance capabilities cache: keyed on binary + resolved HOME so
136 // account-specific probes never share auth metadata across instances.
137 const capabilitiesProbeCache = yield* Cache.make({
138 capacity: 1,
139 timeToLive: CAPABILITIES_PROBE_TTL,
140 lookup: () =>
141 probeClaudeCapabilities(effectiveConfig, processEnv).pipe(
142 Effect.provideService(Path.Path, path),
143 ),
144 });
145 const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig);
146
147 const checkProvider = checkClaudeProviderStatus(
148 effectiveConfig,
149 () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
150 processEnv,
151 ).pipe(
152 Effect.map(stampIdentity),
153 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
154 Effect.provideService(Path.Path, path),
155 );
156
157 const snapshot = yield* makeManagedServerProvider<ClaudeSettings>({
158 maintenanceCapabilities,
159 getSettings: Effect.succeed(effectiveConfig),
160 streamSettings: Stream.never,
161 haveSettingsChanged: () => false,
162 initialSnapshot: (settings) => stampIdentity(makePendingClaudeProvider(settings)),
163 checkProvider,
164 enrichSnapshot: ({ snapshot, publishSnapshot }) =>
165 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities).pipe(
166 Effect.provideService(HttpClient.HttpClient, httpClient),
167 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
168 ),
169 refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
170 }).pipe(
171 Effect.mapError(
172 (cause) =>
173 new ProviderDriverError({
174 driver: DRIVER_KIND,
175 instanceId,
176 detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
177 cause,
178 }),
179 ),
180 );
181
182 return {
183 instanceId,
184 driverKind: DRIVER_KIND,
185 continuationIdentity: {
186 ...fallbackContinuationIdentity,
187 continuationKey: continuationGroupKey,
188 },
189 displayName,
190 accentColor,
191 enabled,
192 snapshot,
193 adapter,
194 textGeneration,
195 } satisfies ProviderInstance;
196 }),
197};