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

ClaudeDriver.ts

358 lines14.0 KB

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