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