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

ClaudeDriver.ts

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