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

ClaudeDriver.ts

413 lines15.6 KB

1import { ClaudeSettings, ProviderDriverKind } from "@t3tools/contracts";
2import * as Cache from "effect/Cache";
3import * as Duration from "effect/Duration";
4import * as Crypto from "effect/Crypto";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as Ref from "effect/Ref";
10import * as Schema from "effect/Schema";
11import { HttpClient } from "effect/http";
12import { ChildProcessSpawner } from "effect/process";
13​
14import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
15import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
16import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
17import * as ServerConfig from "../../config.ts";
18import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
19import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
20import {
21 createClaudeAdapterV2,
22 type ClaudeAdapterV2DriverEnv,
23} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
24import { ProviderDriverError } from "../Errors.ts";
25import { claudeUsageReader } from "./claudeUsage.ts";
26import { makeClaudeScopedLimitNames } from "../claudeUsageLimits.ts";
27import * as ClaudeResetCredits from "../claudeResetCredits.ts";
28import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts";
29import {
30 checkClaudeProviderStatus,
31 makePendingClaudeProvider,
32 probeClaudeCapabilities,
33 probeClaudeWorkspaceSnapshot,
34 type ClaudeCapabilitiesProbe,
35} from "../ClaudeProvider.ts";
36import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
37import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
38import { resolveClaudeModelCatalog } from "../ClaudeModelCatalog.ts";
39import {
40 defaultProviderContinuationIdentity,
41 type ProviderDriver,
42 type ProviderInstance,
43} from "@t3tools/provider-core/server/driver";
44import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
45import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
46import {
47 enrichProviderSnapshotWithVersionAdvisory,
48 makeCachedProviderMaintenanceResolution,
49 makePackageManagedProviderMaintenanceResolver,
50 normalizeCommandPath,
51 resolveProviderMaintenanceCapabilitiesEffect,
52} from "@t3tools/provider-core/server/maintenanceResolver";
53import {
54 haveProviderSnapshotSettingsChanged,
55 makeProviderSnapshotSettingsSource,
56 type ProviderSnapshotSettings,
57} from "@t3tools/provider-core/server/snapshotSettings";
58import {
59 makeClaudeCapabilitiesCacheKey,
60 makeClaudeContinuationGroupKey,
61 resolveClaudeHomePath,
62} from "./ClaudeHome.ts";
63import * as HostProcess from "@t3tools/shared/HostProcess";
64const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
65​
66const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
67const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
68​
69const withoutUsage = (capabilities: ClaudeCapabilitiesProbe): ClaudeCapabilitiesProbe => {
70 const result = { ...capabilities };
71 delete result.usage;
72 return result;
73};
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 );
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 | ClaudeAdapterV2DriverEnv
95 | ProviderHost.ProviderHost
96 | ChildProcessSpawner.ChildProcessSpawner
97 | ResetCreditCoordinator.ResetCreditCoordinator
98 | Crypto.Crypto
99 | FileSystem.FileSystem
100 | HttpClient.HttpClient
101 | ProviderLatestVersions.ProviderLatestVersions
102 | ModelCatalog.ModelCatalog
103 | Path.Path
104 | ProviderEventLoggers.ProviderEventLoggers
105 | ServerConfig.ServerConfig;
106​
107export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.Path> = {
108 driverKind: DRIVER_KIND,
109 metadata: {
110 displayName: "Claude",
111 supportsMultipleInstances: true,
112 },
113 configSchema: ClaudeSettings,
114 defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),
115 usage: claudeUsageReader,
116 create: Effect.fn("ClaudeDriver.create")(function* ({
117 instanceId,
118 displayName,
119 accentColor,
120 environment,
121 enabled,
122 config,
123 }) {
124 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
125 const fileSystem = yield* FileSystem.FileSystem;
126 const path = yield* Path.Path;
127 // The server cwd is $HOME in packaged desktop builds, and `claude`
128 // wrappers that scope themselves to their cwd refuse to run there.
129 const { stateDir } = yield* ServerConfig.ServerConfig;
130 const httpClient = yield* HttpClient.HttpClient;
131 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
132 const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
133 const catalogService = yield* ModelCatalog.ModelCatalog;
134 const modelCatalog = catalogService
135 .current(DRIVER_KIND)
136 .pipe(Effect.map(resolveClaudeModelCatalog));
137 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
138 const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
139 driverKind: DRIVER_KIND,
140 instanceId,
141 });
142 const effectiveConfig = {
143 ...config,
144 enabled,
145 binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
146 } satisfies ClaudeSettings;
147 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
148 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
149 binaryPath: effectiveConfig.binaryPath,
150 env: processEnv,
151 }).pipe(
152 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
153 Effect.provideService(FileSystem.FileSystem, fileSystem),
154 Effect.provideService(Path.Path, path),
155 ),
156 );
157 const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig, processEnv);
158 const configDir = yield* resolveClaudeHomePath(effectiveConfig, processEnv);
159 const accountConfigPath = yield* ClaudeResetCredits.claudeAccountConfigPath(
160 effectiveConfig.homePath.trim() || processEnv.CLAUDE_CONFIG_DIR?.trim()
161 ? configDir
162 : undefined,
163 );
164 const stampIdentity = withInstanceIdentity({
165 instanceId,
166 driverKind: DRIVER_KIND,
167 displayName,
168 accentColor,
169 continuationGroupKey,
170 });
171​
172 const scopedLimitNames = yield* makeClaudeScopedLimitNames;
173 const orchestrationAdapter = yield* createClaudeAdapterV2(
174 {
175 instanceId,
176 displayName,
177 accentColor,
178 environment,
179 enabled,
180 config,
181 },
182 { scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) },
183 ).pipe(
184 Effect.mapError(
185 (cause) =>
186 new ProviderDriverError({
187 driver: DRIVER_KIND,
188 instanceId,
189 detail: "Failed to build Claude orchestration adapter.",
190 cause,
191 }),
192 ),
193 );
194 const textGeneration = yield* makeClaudeTextGeneration(
195 effectiveConfig,
196 processEnv,
197 modelCatalog,
198 );
199​
200 // Per-instance capabilities cache: keyed on binary + resolved HOME so
201 // account-specific probes never share auth metadata across instances.
202 // A transient miss may reuse the last account once, but its usage windows keep their age.
203 const lastGoodCapabilities = yield* Ref.make<ClaudeCapabilitiesProbe | undefined>(undefined);
204 const capabilitiesProbeCache = yield* Cache.makeWith(
205 () =>
206 probeClaudeCapabilities(effectiveConfig, processEnv, stateDir).pipe(
207 Effect.flatMap((capabilities) =>
208 ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(
209 Effect.map((workspaceId) => ({
210 _tag: "fresh" as const,
211 capabilities:
212 workspaceId === undefined ? capabilities : { ...capabilities, workspaceId },
213 })),
214 ),
215 ),
216 Effect.tap(({ capabilities }) => Ref.set(lastGoodCapabilities, capabilities)),
217 Effect.catch((error) =>
218 Ref.getAndSet(lastGoodCapabilities, undefined).pipe(
219 Effect.flatMap((capabilities) =>
220 capabilities === undefined
221 ? Effect.fail(error)
222 : ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(
223 Effect.flatMap((workspaceId) =>
224 workspaceId === capabilities.workspaceId
225 ? Effect.succeed({
226 _tag: "fallback" as const,
227 capabilities: withoutUsage(capabilities),
228 })
229 : Effect.fail(error),
230 ),
231 ),
232 ),
233 ),
234 ),
235 Effect.provideService(FileSystem.FileSystem, fileSystem),
236 Effect.provideService(Path.Path, path),
237 ),
238 {
239 capacity: 1,
240 timeToLive: (exit) =>
241 // Only fresh usage earns the TTL; failures, fallbacks and usage-less probes retry.
242 Exit.isSuccess(exit) &&
243 exit.value._tag === "fresh" &&
244 exit.value.capabilities.usage !== undefined
245 ? CAPABILITIES_PROBE_TTL
246 : Duration.zero,
247 },
248 );
249 const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(
250 effectiveConfig,
251 stateDir,
252 processEnv,
253 );
254 const resolveCapabilities = Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe(
255 Effect.map((result) => result.capabilities),
256 );
257​
258 const checkProvider = catalogService.refreshInBackground.pipe(
259 Effect.andThen(
260 modelCatalog.pipe(
261 Effect.flatMap((catalog) =>
262 checkClaudeProviderStatus(
263 effectiveConfig,
264 () => resolveCapabilities,
265 processEnv,
266 stateDir,
267 catalog,
268 scopedLimitNames,
269 (version) =>
270 ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe(
271 Effect.provideService(HttpClient.HttpClient, httpClient),
272 Effect.provideService(FileSystem.FileSystem, fileSystem),
273 Effect.provideService(Path.Path, path),
274 ),
275 ),
276 ),
277 Effect.tap((provider) =>
278 provider.auth.status === "unauthenticated"
279 ? Cache.invalidateAll(capabilitiesProbeCache)
280 : Effect.void,
281 ),
282 Effect.map(stampIdentity),
283 ),
284 ),
285 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
286 Effect.provideService(FileSystem.FileSystem, fileSystem),
287 Effect.provideService(Path.Path, path),
288 );
289​
290 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
291 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
292 resolveMaintenance,
293 getSettings: snapshotSettings.getSettings,
294 streamSettings: snapshotSettings.streamSettings,
295 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
296 initialSnapshot: (settings) =>
297 modelCatalog.pipe(
298 Effect.flatMap((catalog) => makePendingClaudeProvider(settings.provider, catalog)),
299 Effect.map(stampIdentity),
300 ),
301 checkProvider,
302 invalidateUsageCache: Cache.invalidateAll(capabilitiesProbeCache),
303 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
304 resolveMaintenance().pipe(
305 Effect.flatMap((maintenanceCapabilities) =>
306 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
307 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
308 }),
309 ),
310 Effect.provideService(HttpClient.HttpClient, httpClient),
311 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
312 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
313 ),
314 }).pipe(
315 Effect.mapError(
316 (cause) =>
317 new ProviderDriverError({
318 driver: DRIVER_KIND,
319 instanceId,
320 detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
321 cause,
322 }),
323 ),
324 );
325​
326 // Same rules as Codex: serialised on the config directory that holds the
327 // login, one request id kept until Claude answers (a cooldown or rate
328 // limit is an answer), then a re-probe.
329 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = Effect.fn(
330 "ClaudeDriver.consumeResetCredit",
331 )(
332 function* () {
333 const current = yield* snapshot.getSnapshot;
334 const grantId = current.usageLimits?.resetCredits?.nextCreditId;
335 if (!grantId || !current.version) return "noCredit" as const;
336 const version = current.version;
337 return yield* resetCreditCoordinator.redeem(
338 configDir,
339 (requestId) =>
340 ClaudeResetCredits.consumeClaudeResetCredit({
341 configDir,
342 accountConfigPath,
343 version,
344 grantId,
345 requestId,
346 }),
347 ClaudeResetCredits.isSettledClaudeResetCreditFailure,
348 );
349 },
350 Effect.provideService(HttpClient.HttpClient, httpClient),
351 Effect.provideService(FileSystem.FileSystem, fileSystem),
352 Effect.provideService(Path.Path, path),
353 Effect.mapError(
354 (cause) =>
355 new ProviderDriverError({
356 driver: DRIVER_KIND,
357 instanceId,
358 detail:
359 cause._tag === "ClaudeResetCreditError"
360 ? cause.message
361 : "Claude could not redeem the reset.",
362 cause,
363 }),
364 ),
365 Effect.tap((outcome) =>
366 Effect.gen(function* () {
367 const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
368 yield* Cache.invalidateAll(capabilitiesProbeCache);
369 const refreshed = yield* snapshot.refresh;
370 const after = refreshed.usageLimits?.checkedAt;
371 if (
372 outcome === "reset" &&
373 (after === undefined ||
374 after === before ||
375 refreshed.usageLimits?.unavailable?.reason === "probeFailed")
376 ) {
377 return yield* new ProviderDriverError({
378 driver: DRIVER_KIND,
379 instanceId,
380 detail:
381 "The reset was applied, but Claude could not confirm the new limits. Refresh to check.",
382 });
383 }
384 }),
385 ),
386 );
387​
388 return {
389 instanceId,
390 driverKind: DRIVER_KIND,
391 continuationIdentity: {
392 ...fallbackContinuationIdentity,
393 continuationKey: continuationGroupKey,
394 },
395 displayName,
396 accentColor,
397 enabled,
398 snapshot,
399 invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),
400 snapshotForCwd: (cwd: string) =>
401 snapshot.getSnapshot.pipe(
402 Effect.flatMap((machineSnapshot) =>
403 probeClaudeWorkspaceSnapshot(effectiveConfig, machineSnapshot, cwd, processEnv),
404 ),
405 Effect.provideService(FileSystem.FileSystem, fileSystem),
406 Effect.provideService(Path.Path, path),
407 ),
408 orchestrationAdapter,
409 textGeneration,
410 consumeResetCredit,
411 } satisfies ProviderInstance;
412 }),
413};