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

ClaudeDriver.ts

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