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