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

ClaudeDriver.ts

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