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