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 } from "@t3tools/contracts";
16import * as Cache from "effect/Cache";
17import * as Duration from "effect/Duration";
18import * as Crypto from "effect/Crypto";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Path from "effect/Path";
22import * as Schema from "effect/Schema";
23import { HttpClient } from "effect/http";
24import { ChildProcessSpawner } from "effect/process";
25
26import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
27import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
28import * as ServerConfig from "../../config.ts";
29import { expandHomePath } from "../../pathExpansion.ts";
30import * as ProviderEventLoggers from "../ProviderEventLoggers.ts";
31import {
32 createClaudeAdapterV2,
33 type ClaudeAdapterV2DriverEnv,
34} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
35import * as ServerSettings from "../../serverSettings.ts";
36import { ProviderDriverError } from "../Errors.ts";
37import { makeClaudeScopedLimitNames } from "../claudeUsageLimits.ts";
38import * as ClaudeResetCredits from "../claudeResetCredits.ts";
39import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts";
40import {
41 checkClaudeProviderStatus,
42 makePendingClaudeProvider,
43 probeClaudeCapabilities,
44 probeClaudeWorkspaceSnapshot,
45} from "../ClaudeProvider.ts";
46import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
47import * as ModelManifest from "../ModelManifest.ts";
48import { resolveClaudeModelCatalog } from "../ClaudeModelCatalog.ts";
49import {
50 defaultProviderContinuationIdentity,
51 type ProviderDriver,
52 type ProviderInstance,
53} from "../ProviderDriver.ts";
54import { withInstanceIdentity } from "./instanceIdentity.ts";
55import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
56import {
57 enrichProviderSnapshotWithVersionAdvisory,
58 makeCachedProviderMaintenanceResolution,
59 makePackageManagedProviderMaintenanceResolver,
60 normalizeCommandPath,
61 resolveProviderMaintenanceCapabilitiesEffect,
62} from "../providerMaintenance.ts";
63import {
64 haveProviderSnapshotSettingsChanged,
65 makeProviderSnapshotSettingsSource,
66 type ProviderSnapshotSettings,
67} from "../providerUpdateSettings.ts";
68import {
69 makeClaudeCapabilitiesCacheKey,
70 makeClaudeContinuationGroupKey,
71 resolveClaudeHomePath,
72} from "./ClaudeHome.ts";
73const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
74
75const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
76const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
77
78function isClaudeNativeCommandPath(commandPath: string): boolean {
79 const normalized = normalizeCommandPath(commandPath);
80 return (
81 normalized.endsWith("/.local/bin/claude") ||
82 normalized.endsWith("/.local/bin/claude.exe") ||
83 normalized.includes("/.local/share/claude/")
84 );
85}
86
87const UPDATE = makePackageManagedProviderMaintenanceResolver({
88 provider: DRIVER_KIND,
89 npmPackageName: "@anthropic-ai/claude-code",
90 nativeUpdate: {
91 args: ["update"],
92 isCommandPath: isClaudeNativeCommandPath,
93 },
94});
95
96export type ClaudeDriverEnv =
97 | ClaudeAdapterV2DriverEnv
98 | BackgroundPolicy.BackgroundPolicy
99 | ChildProcessSpawner.ChildProcessSpawner
100 | ResetCreditCoordinator.ResetCreditCoordinator
101 | Crypto.Crypto
102 | FileSystem.FileSystem
103 | HttpClient.HttpClient
104 | ModelManifest.ModelManifest
105 | Path.Path
106 | ProviderEventLoggers.ProviderEventLoggers
107 | ServerConfig.ServerConfig
108 | ServerSettings.ServerSettingsService;
109
110export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
111 driverKind: DRIVER_KIND,
112 metadata: {
113 displayName: "Claude",
114 supportsMultipleInstances: true,
115 },
116 configSchema: ClaudeSettings,
117 defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),
118 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
119 Effect.gen(function* () {
120 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
121 const fileSystem = yield* FileSystem.FileSystem;
122 const path = yield* Path.Path;
123 const { cwd } = yield* ServerConfig.ServerConfig;
124 const httpClient = yield* HttpClient.HttpClient;
125 const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
126 const serverSettings = yield* ServerSettings.ServerSettingsService;
127 const modelManifest = yield* ModelManifest.ModelManifest;
128 const modelCatalog = modelManifest.current.pipe(Effect.map(resolveClaudeModelCatalog));
129 const processEnv = mergeProviderInstanceEnvironment(environment);
130 const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
131 driverKind: DRIVER_KIND,
132 instanceId,
133 });
134 const effectiveConfig = {
135 ...config,
136 enabled,
137 binaryPath: expandHomePath(config.binaryPath),
138 } satisfies ClaudeSettings;
139 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
140 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
141 binaryPath: effectiveConfig.binaryPath,
142 env: processEnv,
143 }).pipe(
144 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
145 Effect.provideService(FileSystem.FileSystem, fileSystem),
146 Effect.provideService(Path.Path, path),
147 ),
148 );
149 const continuationGroupKey = yield* makeClaudeContinuationGroupKey(
150 effectiveConfig,
151 processEnv,
152 );
153 const configDir = yield* resolveClaudeHomePath(effectiveConfig, processEnv);
154 const accountConfigPath = yield* ClaudeResetCredits.claudeAccountConfigPath(
155 effectiveConfig.homePath.trim() || processEnv.CLAUDE_CONFIG_DIR?.trim()
156 ? configDir
157 : undefined,
158 );
159 const stampIdentity = withInstanceIdentity({
160 instanceId,
161 driverKind: DRIVER_KIND,
162 displayName,
163 accentColor,
164 continuationGroupKey,
165 });
166
167 const scopedLimitNames = yield* makeClaudeScopedLimitNames;
168 const orchestrationAdapter = yield* createClaudeAdapterV2(
169 {
170 instanceId,
171 displayName,
172 accentColor,
173 environment,
174 enabled,
175 config,
176 },
177 { scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) },
178 ).pipe(
179 Effect.mapError(
180 (cause) =>
181 new ProviderDriverError({
182 driver: DRIVER_KIND,
183 instanceId,
184 detail: "Failed to build Claude orchestration adapter.",
185 cause,
186 }),
187 ),
188 );
189 const textGeneration = yield* makeClaudeTextGeneration(
190 effectiveConfig,
191 processEnv,
192 modelCatalog,
193 );
194
195 // Per-instance capabilities cache: keyed on binary + resolved HOME so
196 // account-specific probes never share auth metadata across instances.
197 const capabilitiesProbeCache = yield* Cache.make({
198 capacity: 1,
199 timeToLive: CAPABILITIES_PROBE_TTL,
200 lookup: () =>
201 probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(
202 Effect.provideService(Path.Path, path),
203 ),
204 });
205 const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(
206 effectiveConfig,
207 cwd,
208 processEnv,
209 );
210
211 // Start the TTL-gated refresh without delaying provider readiness. The
212 // next check observes a remote manifest after the background fetch lands.
213 const checkProvider = modelManifest.refreshInBackground.pipe(
214 Effect.andThen(
215 modelManifest.current.pipe(
216 Effect.flatMap((manifest) =>
217 checkClaudeProviderStatus(
218 effectiveConfig,
219 () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
220 processEnv,
221 cwd,
222 resolveClaudeModelCatalog(manifest),
223 scopedLimitNames,
224 (version) =>
225 ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe(
226 Effect.provideService(HttpClient.HttpClient, httpClient),
227 Effect.provideService(FileSystem.FileSystem, fileSystem),
228 Effect.provideService(Path.Path, path),
229 ),
230 ),
231 ),
232 Effect.map(stampIdentity),
233 ),
234 ),
235 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
236 Effect.provideService(FileSystem.FileSystem, fileSystem),
237 Effect.provideService(Path.Path, path),
238 );
239
240 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
241 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
242 resolveMaintenance,
243 getSettings: snapshotSettings.getSettings,
244 streamSettings: snapshotSettings.streamSettings,
245 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
246 initialSnapshot: (settings) =>
247 modelManifest.current.pipe(
248 Effect.flatMap((manifest) =>
249 makePendingClaudeProvider(settings.provider, resolveClaudeModelCatalog(manifest)),
250 ),
251 Effect.map(stampIdentity),
252 ),
253 checkProvider,
254 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
255 resolveMaintenance().pipe(
256 Effect.flatMap((maintenanceCapabilities) =>
257 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
258 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
259 }),
260 ),
261 Effect.provideService(HttpClient.HttpClient, httpClient),
262 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
263 ),
264 }).pipe(
265 Effect.mapError(
266 (cause) =>
267 new ProviderDriverError({
268 driver: DRIVER_KIND,
269 instanceId,
270 detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
271 cause,
272 }),
273 ),
274 );
275
276 // Same rules as Codex: serialised on the config directory that holds the
277 // login, one request id kept until Claude answers (a cooldown or rate
278 // limit is an answer), then a re-probe.
279 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
280 Effect.gen(function* () {
281 const current = yield* snapshot.getSnapshot;
282 const grantId = current.usageLimits?.resetCredits?.nextCreditId;
283 if (!grantId || !current.version) return "noCredit" as const;
284 const version = current.version;
285 return yield* resetCreditCoordinator.redeem(
286 configDir,
287 (requestId) =>
288 ClaudeResetCredits.consumeClaudeResetCredit({
289 configDir,
290 accountConfigPath,
291 version,
292 grantId,
293 requestId,
294 }),
295 ClaudeResetCredits.isSettledClaudeResetCreditFailure,
296 );
297 }).pipe(
298 Effect.provideService(HttpClient.HttpClient, httpClient),
299 Effect.provideService(FileSystem.FileSystem, fileSystem),
300 Effect.provideService(Path.Path, path),
301 Effect.mapError(
302 (cause) =>
303 new ProviderDriverError({
304 driver: DRIVER_KIND,
305 instanceId,
306 detail:
307 cause._tag === "ClaudeResetCreditError"
308 ? cause.message
309 : "Claude could not redeem the reset.",
310 cause,
311 }),
312 ),
313 // Re-probe after any answer, but only a reset claims the limits
314 // changed, so only a reset reports an unconfirmed refresh.
315 Effect.tap((outcome) =>
316 Effect.gen(function* () {
317 const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
318 yield* Cache.invalidateAll(capabilitiesProbeCache);
319 const refreshed = yield* snapshot.refresh;
320 const after = refreshed.usageLimits?.checkedAt;
321 if (
322 outcome === "reset" &&
323 (after === undefined ||
324 after === before ||
325 refreshed.usageLimits?.unavailable?.reason === "probeFailed")
326 ) {
327 return yield* new ProviderDriverError({
328 driver: DRIVER_KIND,
329 instanceId,
330 detail:
331 "The reset was applied, but Claude could not confirm the new limits. Refresh to check.",
332 });
333 }
334 }),
335 ),
336 );
337
338 return {
339 instanceId,
340 driverKind: DRIVER_KIND,
341 continuationIdentity: {
342 ...fallbackContinuationIdentity,
343 continuationKey: continuationGroupKey,
344 },
345 displayName,
346 accentColor,
347 enabled,
348 snapshot,
349 invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),
350 snapshotForCwd: (cwd: string) =>
351 snapshot.getSnapshot.pipe(
352 Effect.flatMap((machineSnapshot) =>
353 probeClaudeWorkspaceSnapshot(effectiveConfig, machineSnapshot, cwd, processEnv),
354 ),
355 Effect.provideService(FileSystem.FileSystem, fileSystem),
356 Effect.provideService(Path.Path, path),
357 ),
358 orchestrationAdapter,
359 textGeneration,
360 consumeResetCredit,
361 } satisfies ProviderInstance;
362 }),
363};