Open History to see the last commit
1/**
2 * ClaudeDriver — `ProviderDriver` for the Claude Agent SDK runtime.
3 *
4 * Mirrors `CodexDriver`: a plain value whose `create()` returns one
5 * `ProviderInstance` bundling `snapshot` / `adapter` / `textGeneration`
6 * closures captured over the per-instance `ClaudeSettings`.
7 *
8 * Unlike Codex, the Claude snapshot probe may invoke a secondary probe
9 * (`probeClaudeCapabilities`) to read Anthropic account + slash-command
10 * metadata. That probe is per-instance and keyed by binary + resolved HOME so
11 * two concurrent Claude instances don't cross-contaminate account metadata.
12 *
13 * @module provider/Drivers/ClaudeDriver
14 */
15import { ClaudeSettings, ProviderDriverKind } from "@t3tools/contracts";
16import * as Cache from "effect/Cache";
17import * as Duration from "effect/Duration";
18import * as Crypto from "effect/Crypto";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Path from "effect/Path";
22import * as Schema from "effect/Schema";
23import { HttpClient } from "effect/unstable/http";
24import { ChildProcessSpawner } from "effect/unstable/process";
25
26import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
27import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
28import { ServerConfig } from "../../config.ts";
29import { expandHomePath } from "../../pathExpansion.ts";
30import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
31import {
32 createClaudeAdapterV2,
33 type ClaudeAdapterV2DriverEnv,
34} from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
35import { ServerSettingsService } from "../../serverSettings.ts";
36import { ProviderDriverError } from "../Errors.ts";
37import { makeClaudeScopedLimitNames } from "../Layers/claudeUsageLimits.ts";
38import {
39 checkClaudeProviderStatus,
40 makePendingClaudeProvider,
41 probeClaudeCapabilities,
42} from "../Layers/ClaudeProvider.ts";
43import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
44import * as ModelManifest from "../ModelManifest.ts";
45import { resolveClaudeModelCatalog } from "../ClaudeModelCatalog.ts";
46import {
47 defaultProviderContinuationIdentity,
48 type ProviderDriver,
49 type ProviderInstance,
50} from "../ProviderDriver.ts";
51import { withInstanceIdentity } from "./instanceIdentity.ts";
52import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
53import {
54 enrichProviderSnapshotWithVersionAdvisory,
55 makeCachedProviderMaintenanceResolution,
56 makePackageManagedProviderMaintenanceResolver,
57 normalizeCommandPath,
58 resolveProviderMaintenanceCapabilitiesEffect,
59} from "../providerMaintenance.ts";
60import {
61 haveProviderSnapshotSettingsChanged,
62 makeProviderSnapshotSettingsSource,
63 type ProviderSnapshotSettings,
64} from "../providerUpdateSettings.ts";
65import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
66import { discoverClaudeSkills } from "./ClaudeSkills.ts";
67const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
68
69const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
70const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
71
72function isClaudeNativeCommandPath(commandPath: string): boolean {
73 const normalized = normalizeCommandPath(commandPath);
74 return (
75 normalized.endsWith("/.local/bin/claude") ||
76 normalized.endsWith("/.local/bin/claude.exe") ||
77 normalized.includes("/.local/share/claude/")
78 );
79}
80
81const UPDATE = makePackageManagedProviderMaintenanceResolver({
82 provider: DRIVER_KIND,
83 npmPackageName: "@anthropic-ai/claude-code",
84 nativeUpdate: {
85 args: ["update"],
86 isCommandPath: isClaudeNativeCommandPath,
87 },
88});
89
90export type ClaudeDriverEnv =
91 | ClaudeAdapterV2DriverEnv
92 | BackgroundPolicy.BackgroundPolicy
93 | ChildProcessSpawner.ChildProcessSpawner
94 | Crypto.Crypto
95 | FileSystem.FileSystem
96 | HttpClient.HttpClient
97 | ModelManifest.ModelManifest
98 | Path.Path
99 | ProviderEventLoggers
100 | ServerConfig
101 | ServerSettingsService;
102
103export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
104 driverKind: DRIVER_KIND,
105 metadata: {
106 displayName: "Claude",
107 supportsMultipleInstances: true,
108 },
109 configSchema: ClaudeSettings,
110 defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),
111 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
112 Effect.gen(function* () {
113 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
114 const fileSystem = yield* FileSystem.FileSystem;
115 const path = yield* Path.Path;
116 const { cwd } = yield* ServerConfig;
117 const httpClient = yield* HttpClient.HttpClient;
118 const serverSettings = yield* ServerSettingsService;
119 const modelManifest = yield* ModelManifest.ModelManifest;
120 const modelCatalog = modelManifest.current.pipe(Effect.map(resolveClaudeModelCatalog));
121 const processEnv = mergeProviderInstanceEnvironment(environment);
122 const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
123 driverKind: DRIVER_KIND,
124 instanceId,
125 });
126 const effectiveConfig = {
127 ...config,
128 enabled,
129 binaryPath: expandHomePath(config.binaryPath),
130 } satisfies ClaudeSettings;
131 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
132 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
133 binaryPath: effectiveConfig.binaryPath,
134 env: processEnv,
135 }).pipe(
136 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
137 Effect.provideService(FileSystem.FileSystem, fileSystem),
138 Effect.provideService(Path.Path, path),
139 ),
140 );
141 const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);
142 const stampIdentity = withInstanceIdentity({
143 instanceId,
144 driverKind: DRIVER_KIND,
145 displayName,
146 accentColor,
147 continuationGroupKey,
148 });
149
150 const scopedLimitNames = yield* makeClaudeScopedLimitNames;
151 const orchestrationAdapter = yield* createClaudeAdapterV2(
152 {
153 instanceId,
154 displayName,
155 accentColor,
156 environment,
157 enabled,
158 config,
159 },
160 { scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) },
161 ).pipe(
162 Effect.mapError(
163 (cause) =>
164 new ProviderDriverError({
165 driver: DRIVER_KIND,
166 instanceId,
167 detail: "Failed to build Claude orchestration adapter.",
168 cause,
169 }),
170 ),
171 );
172 const textGeneration = yield* makeClaudeTextGeneration(
173 effectiveConfig,
174 processEnv,
175 modelCatalog,
176 );
177
178 // Per-instance capabilities cache: keyed on binary + resolved HOME so
179 // account-specific probes never share auth metadata across instances.
180 const capabilitiesProbeCache = yield* Cache.make({
181 capacity: 1,
182 timeToLive: CAPABILITIES_PROBE_TTL,
183 lookup: () =>
184 probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(
185 Effect.provideService(Path.Path, path),
186 ),
187 });
188 const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig, cwd);
189
190 // Start the TTL-gated refresh without delaying provider readiness. The
191 // next check observes a remote manifest after the background fetch lands.
192 const checkProvider = modelManifest.refreshInBackground.pipe(
193 Effect.andThen(
194 modelManifest.current.pipe(
195 Effect.flatMap((manifest) =>
196 checkClaudeProviderStatus(
197 effectiveConfig,
198 () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
199 processEnv,
200 cwd,
201 resolveClaudeModelCatalog(manifest),
202 scopedLimitNames,
203 ),
204 ),
205 Effect.map(stampIdentity),
206 ),
207 ),
208 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
209 Effect.provideService(FileSystem.FileSystem, fileSystem),
210 Effect.provideService(Path.Path, path),
211 );
212
213 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
214 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
215 resolveMaintenance,
216 getSettings: snapshotSettings.getSettings,
217 streamSettings: snapshotSettings.streamSettings,
218 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
219 initialSnapshot: (settings) =>
220 modelManifest.current.pipe(
221 Effect.flatMap((manifest) =>
222 makePendingClaudeProvider(settings.provider, resolveClaudeModelCatalog(manifest)),
223 ),
224 Effect.map(stampIdentity),
225 ),
226 checkProvider,
227 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
228 resolveMaintenance().pipe(
229 Effect.flatMap((maintenanceCapabilities) =>
230 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
231 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
232 }),
233 ),
234 Effect.provideService(HttpClient.HttpClient, httpClient),
235 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
236 ),
237 }).pipe(
238 Effect.mapError(
239 (cause) =>
240 new ProviderDriverError({
241 driver: DRIVER_KIND,
242 instanceId,
243 detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
244 cause,
245 }),
246 ),
247 );
248
249 return {
250 instanceId,
251 driverKind: DRIVER_KIND,
252 continuationIdentity: {
253 ...fallbackContinuationIdentity,
254 continuationKey: continuationGroupKey,
255 },
256 displayName,
257 accentColor,
258 enabled,
259 snapshot,
260 snapshotForCwd: (cwd: string) =>
261 !effectiveConfig.enabled
262 ? snapshot.getSnapshot
263 : Effect.all([
264 snapshot.getSnapshot,
265 discoverClaudeSkills(effectiveConfig, cwd, processEnv),
266 ]).pipe(
267 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
268 Effect.provideService(FileSystem.FileSystem, fileSystem),
269 Effect.provideService(Path.Path, path),
270 ),
271 orchestrationAdapter,
272 textGeneration,
273 } satisfies ProviderInstance;
274 }),
275};