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

ClaudeDriver.ts

361 lines14.0 KB

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