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