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

ClaudeDriver.ts

400 lines15.8 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: ({ 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 // The server cwd is $HOME in packaged desktop builds, and `claude`
122 // wrappers that scope themselves to their cwd refuse to run there.
123 const { stateDir } = 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 = yield* 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, yield* HostProcess.HomeDirectory),
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 // A transient miss may reuse the last account once, but its usage windows keep their age.
200 const lastGoodCapabilities = yield* Ref.make<ClaudeCapabilitiesProbe | undefined>(undefined);
201 const capabilitiesProbeCache = yield* Cache.makeWith(
202 () =>
203 probeClaudeCapabilities(effectiveConfig, processEnv, stateDir).pipe(
204 Effect.flatMap((capabilities) =>
205 ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(
206 Effect.map((workspaceId) => ({
207 _tag: "fresh" as const,
208 capabilities:
209 workspaceId === undefined ? capabilities : { ...capabilities, workspaceId },
210 })),
211 ),
212 ),
213 Effect.tap(({ capabilities }) => Ref.set(lastGoodCapabilities, capabilities)),
214 Effect.catch((error) =>
215 Ref.getAndSet(lastGoodCapabilities, undefined).pipe(
216 Effect.flatMap((capabilities) =>
217 capabilities === undefined
218 ? Effect.fail(error)
219 : ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(
220 Effect.flatMap((workspaceId) =>
221 workspaceId === capabilities.workspaceId
222 ? Effect.succeed({
223 _tag: "fallback" as const,
224 capabilities: withoutUsage(capabilities),
225 })
226 : Effect.fail(error),
227 ),
228 ),
229 ),
230 ),
231 ),
232 Effect.provideService(FileSystem.FileSystem, fileSystem),
233 Effect.provideService(Path.Path, path),
234 ),
235 {
236 capacity: 1,
237 timeToLive: (exit) =>
238 // Only a fresh probe earns the TTL; a failure or its fallback retries on the next check.
239 Exit.isSuccess(exit) && exit.value._tag === "fresh"
240 ? CAPABILITIES_PROBE_TTL
241 : Duration.zero,
242 },
243 );
244 const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(
245 effectiveConfig,
246 stateDir,
247 processEnv,
248 );
249 const resolveCapabilities = Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe(
250 Effect.map((result) => result.capabilities),
251 );
252​
253 const checkProvider = catalogService.refreshInBackground.pipe(
254 Effect.andThen(
255 modelCatalog.pipe(
256 Effect.flatMap((catalog) =>
257 checkClaudeProviderStatus(
258 effectiveConfig,
259 () => resolveCapabilities,
260 processEnv,
261 stateDir,
262 catalog,
263 scopedLimitNames,
264 (version) =>
265 ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe(
266 Effect.provideService(HttpClient.HttpClient, httpClient),
267 Effect.provideService(FileSystem.FileSystem, fileSystem),
268 Effect.provideService(Path.Path, path),
269 ),
270 ),
271 ),
272 Effect.map(stampIdentity),
273 ),
274 ),
275 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
276 Effect.provideService(FileSystem.FileSystem, fileSystem),
277 Effect.provideService(Path.Path, path),
278 );
279​
280 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
281 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
282 resolveMaintenance,
283 getSettings: snapshotSettings.getSettings,
284 streamSettings: snapshotSettings.streamSettings,
285 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
286 initialSnapshot: (settings) =>
287 modelCatalog.pipe(
288 Effect.flatMap((catalog) => makePendingClaudeProvider(settings.provider, catalog)),
289 Effect.map(stampIdentity),
290 ),
291 checkProvider,
292 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
293 resolveMaintenance().pipe(
294 Effect.flatMap((maintenanceCapabilities) =>
295 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
296 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
297 }),
298 ),
299 Effect.provideService(HttpClient.HttpClient, httpClient),
300 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
301 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
302 ),
303 }).pipe(
304 Effect.mapError(
305 (cause) =>
306 new ProviderDriverError({
307 driver: DRIVER_KIND,
308 instanceId,
309 detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
310 cause,
311 }),
312 ),
313 );
314​
315 // Same rules as Codex: serialised on the config directory that holds the
316 // login, one request id kept until Claude answers (a cooldown or rate
317 // limit is an answer), then a re-probe.
318 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = () =>
319 Effect.gen(function* () {
320 const current = yield* snapshot.getSnapshot;
321 const grantId = current.usageLimits?.resetCredits?.nextCreditId;
322 if (!grantId || !current.version) return "noCredit" as const;
323 const version = current.version;
324 return yield* resetCreditCoordinator.redeem(
325 configDir,
326 (requestId) =>
327 ClaudeResetCredits.consumeClaudeResetCredit({
328 configDir,
329 accountConfigPath,
330 version,
331 grantId,
332 requestId,
333 }),
334 ClaudeResetCredits.isSettledClaudeResetCreditFailure,
335 );
336 }).pipe(
337 Effect.provideService(HttpClient.HttpClient, httpClient),
338 Effect.provideService(FileSystem.FileSystem, fileSystem),
339 Effect.provideService(Path.Path, path),
340 Effect.mapError(
341 (cause) =>
342 new ProviderDriverError({
343 driver: DRIVER_KIND,
344 instanceId,
345 detail:
346 cause._tag === "ClaudeResetCreditError"
347 ? cause.message
348 : "Claude could not redeem the reset.",
349 cause,
350 }),
351 ),
352 Effect.tap((outcome) =>
353 Effect.gen(function* () {
354 const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt;
355 yield* Cache.invalidateAll(capabilitiesProbeCache);
356 const refreshed = yield* snapshot.refresh;
357 const after = refreshed.usageLimits?.checkedAt;
358 if (
359 outcome === "reset" &&
360 (after === undefined ||
361 after === before ||
362 refreshed.usageLimits?.unavailable?.reason === "probeFailed")
363 ) {
364 return yield* new ProviderDriverError({
365 driver: DRIVER_KIND,
366 instanceId,
367 detail:
368 "The reset was applied, but Claude could not confirm the new limits. Refresh to check.",
369 });
370 }
371 }),
372 ),
373 );
374​
375 return {
376 instanceId,
377 driverKind: DRIVER_KIND,
378 continuationIdentity: {
379 ...fallbackContinuationIdentity,
380 continuationKey: continuationGroupKey,
381 },
382 displayName,
383 accentColor,
384 enabled,
385 snapshot,
386 invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),
387 snapshotForCwd: (cwd: string) =>
388 snapshot.getSnapshot.pipe(
389 Effect.flatMap((machineSnapshot) =>
390 probeClaudeWorkspaceSnapshot(effectiveConfig, machineSnapshot, cwd, processEnv),
391 ),
392 Effect.provideService(FileSystem.FileSystem, fileSystem),
393 Effect.provideService(Path.Path, path),
394 ),
395 orchestrationAdapter,
396 textGeneration,
397 consumeResetCredit,
398 } satisfies ProviderInstance;
399 }),
400};