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

ClaudeDriver.ts

398 lines15.0 KB

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