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

ClaudeDriver.ts

446 lines17.0 KB

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