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 ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
28import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
29import * as ServerConfig from "../../config.ts";
30import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
31import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
32import {
33 createClaudeAdapterV2,
34 type ClaudeAdapterV2DriverEnv,
35} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.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 "@t3tools/provider-core/server/managedProvider";
47import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
48import { resolveClaudeModelCatalog } from "../ClaudeModelCatalog.ts";
49import {
50 defaultProviderContinuationIdentity,
51 type ProviderDriver,
52 type ProviderInstance,
53} from "@t3tools/provider-core/server/driver";
54import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
55import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
56import {
57 enrichProviderSnapshotWithVersionAdvisory,
58 makeCachedProviderMaintenanceResolution,
59 makePackageManagedProviderMaintenanceResolver,
60 normalizeCommandPath,
61 resolveProviderMaintenanceCapabilitiesEffect,
62} from "@t3tools/provider-core/server/maintenanceResolver";
63import {
64 haveProviderSnapshotSettingsChanged,
65 makeProviderSnapshotSettingsSource,
66 type ProviderSnapshotSettings,
67} from "@t3tools/provider-core/server/snapshotSettings";
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 | ProviderHost.ProviderHost
99 | ChildProcessSpawner.ChildProcessSpawner
100 | ResetCreditCoordinator.ResetCreditCoordinator
101 | Crypto.Crypto
102 | FileSystem.FileSystem
103 | HttpClient.HttpClient
104 | ProviderLatestVersions.ProviderLatestVersions
105 | ModelCatalog.ModelCatalog
106 | Path.Path
107 | ProviderEventLoggers.ProviderEventLoggers
108 | ServerConfig.ServerConfig;
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 latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
126 const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
127 const catalogService = yield* ModelCatalog.ModelCatalog;
128 const modelCatalog = catalogService
129 .current(DRIVER_KIND)
130 .pipe(Effect.map(resolveClaudeModelCatalog));
131 const processEnv = mergeProviderInstanceEnvironment(environment);
132 const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
133 driverKind: DRIVER_KIND,
134 instanceId,
135 });
136 const effectiveConfig = {
137 ...config,
138 enabled,
139 binaryPath: expandHomePath(config.binaryPath),
140 } satisfies ClaudeSettings;
141 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
142 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
143 binaryPath: effectiveConfig.binaryPath,
144 env: processEnv,
145 }).pipe(
146 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
147 Effect.provideService(FileSystem.FileSystem, fileSystem),
148 Effect.provideService(Path.Path, path),
149 ),
150 );
151 const continuationGroupKey = yield* makeClaudeContinuationGroupKey(
152 effectiveConfig,
153 processEnv,
154 );
155 const configDir = yield* resolveClaudeHomePath(effectiveConfig, processEnv);
156 const accountConfigPath = yield* ClaudeResetCredits.claudeAccountConfigPath(
157 effectiveConfig.homePath.trim() || processEnv.CLAUDE_CONFIG_DIR?.trim()
158 ? configDir
159 : undefined,
160 );
161 const stampIdentity = withInstanceIdentity({
162 instanceId,
163 driverKind: DRIVER_KIND,
164 displayName,
165 accentColor,
166 continuationGroupKey,
167 });
168
169 const scopedLimitNames = yield* makeClaudeScopedLimitNames;
170 const orchestrationAdapter = yield* createClaudeAdapterV2(
171 {
172 instanceId,
173 displayName,
174 accentColor,
175 environment,
176 enabled,
177 config,
178 },
179 { scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) },
180 ).pipe(
181 Effect.mapError(
182 (cause) =>
183 new ProviderDriverError({
184 driver: DRIVER_KIND,
185 instanceId,
186 detail: "Failed to build Claude orchestration adapter.",
187 cause,
188 }),
189 ),
190 );
191 const textGeneration = yield* makeClaudeTextGeneration(
192 effectiveConfig,
193 processEnv,
194 modelCatalog,
195 );
196
197 // Per-instance capabilities cache: keyed on binary + resolved HOME so
198 // account-specific probes never share auth metadata across instances.
199 const capabilitiesProbeCache = yield* Cache.make({
200 capacity: 1,
201 timeToLive: CAPABILITIES_PROBE_TTL,
202 lookup: () =>
203 probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(
204 Effect.provideService(Path.Path, path),
205 ),
206 });
207 const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(
208 effectiveConfig,
209 cwd,
210 processEnv,
211 );
212
213 // Start the TTL-gated refresh without delaying provider readiness. The
214 // next check observes a remote manifest after the background fetch lands.
215 const checkProvider = catalogService.refreshInBackground.pipe(
216 Effect.andThen(
217 modelCatalog.pipe(
218 Effect.flatMap((catalog) =>
219 checkClaudeProviderStatus(
220 effectiveConfig,
221 () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
222 processEnv,
223 cwd,
224 catalog,
225 scopedLimitNames,
226 (version) =>
227 ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe(
228 Effect.provideService(HttpClient.HttpClient, httpClient),
229 Effect.provideService(FileSystem.FileSystem, fileSystem),
230 Effect.provideService(Path.Path, path),
231 ),
232 ),
233 ),
234 Effect.map(stampIdentity),
235 ),
236 ),
237 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
238 Effect.provideService(FileSystem.FileSystem, fileSystem),
239 Effect.provideService(Path.Path, path),
240 );
241
242 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
243 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
244 resolveMaintenance,
245 getSettings: snapshotSettings.getSettings,
246 streamSettings: snapshotSettings.streamSettings,
247 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
248 initialSnapshot: (settings) =>
249 modelCatalog.pipe(
250 Effect.flatMap((catalog) => makePendingClaudeProvider(settings.provider, catalog)),
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.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
263 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
264 ),
265 }).pipe(
266 Effect.mapError(
267 (cause) =>
268 new ProviderDriverError({
269 driver: DRIVER_KIND,
270 instanceId,
271 detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
272 cause,
273 }),
274 ),
275 );
276
277 // Same rules as Codex: serialised on the config directory that holds the
278 // login, one request id kept until Claude answers (a cooldown or rate
279 // limit is an answer), then a re-probe.
280 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
281 Effect.gen(function* () {
282 const current = yield* snapshot.getSnapshot;
283 const grantId = current.usageLimits?.resetCredits?.nextCreditId;
284 if (!grantId || !current.version) return "noCredit" as const;
285 const version = current.version;
286 return yield* resetCreditCoordinator.redeem(
287 configDir,
288 (requestId) =>
289 ClaudeResetCredits.consumeClaudeResetCredit({
290 configDir,
291 accountConfigPath,
292 version,
293 grantId,
294 requestId,
295 }),
296 ClaudeResetCredits.isSettledClaudeResetCreditFailure,
297 );
298 }).pipe(
299 Effect.provideService(HttpClient.HttpClient, httpClient),
300 Effect.provideService(FileSystem.FileSystem, fileSystem),
301 Effect.provideService(Path.Path, path),
302 Effect.mapError(
303 (cause) =>
304 new ProviderDriverError({
305 driver: DRIVER_KIND,
306 instanceId,
307 detail:
308 cause._tag === "ClaudeResetCreditError"
309 ? cause.message
310 : "Claude could not redeem the reset.",
311 cause,
312 }),
313 ),
314 // Re-probe after any answer, but only a reset claims the limits
315 // changed, so only a reset reports an unconfirmed refresh.
316 Effect.tap((outcome) =>
317 Effect.gen(function* () {
318 const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
319 yield* Cache.invalidateAll(capabilitiesProbeCache);
320 const refreshed = yield* snapshot.refresh;
321 const after = refreshed.usageLimits?.checkedAt;
322 if (
323 outcome === "reset" &&
324 (after === undefined ||
325 after === before ||
326 refreshed.usageLimits?.unavailable?.reason === "probeFailed")
327 ) {
328 return yield* new ProviderDriverError({
329 driver: DRIVER_KIND,
330 instanceId,
331 detail:
332 "The reset was applied, but Claude could not confirm the new limits. Refresh to check.",
333 });
334 }
335 }),
336 ),
337 );
338
339 return {
340 instanceId,
341 driverKind: DRIVER_KIND,
342 continuationIdentity: {
343 ...fallbackContinuationIdentity,
344 continuationKey: continuationGroupKey,
345 },
346 displayName,
347 accentColor,
348 enabled,
349 snapshot,
350 invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),
351 snapshotForCwd: (cwd: string) =>
352 snapshot.getSnapshot.pipe(
353 Effect.flatMap((machineSnapshot) =>
354 probeClaudeWorkspaceSnapshot(effectiveConfig, machineSnapshot, cwd, processEnv),
355 ),
356 Effect.provideService(FileSystem.FileSystem, fileSystem),
357 Effect.provideService(Path.Path, path),
358 ),
359 orchestrationAdapter,
360 textGeneration,
361 consumeResetCredit,
362 } satisfies ProviderInstance;
363 }),
364};