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(
142 effectiveConfig,
143 processEnv,
144 );
145 const stampIdentity = withInstanceIdentity({
146 instanceId,
147 driverKind: DRIVER_KIND,
148 displayName,
149 accentColor,
150 continuationGroupKey,
151 });
152
153 const scopedLimitNames = yield* makeClaudeScopedLimitNames;
154 const orchestrationAdapter = yield* createClaudeAdapterV2(
155 {
156 instanceId,
157 displayName,
158 accentColor,
159 environment,
160 enabled,
161 config,
162 },
163 { scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) },
164 ).pipe(
165 Effect.mapError(
166 (cause) =>
167 new ProviderDriverError({
168 driver: DRIVER_KIND,
169 instanceId,
170 detail: "Failed to build Claude orchestration adapter.",
171 cause,
172 }),
173 ),
174 );
175 const textGeneration = yield* makeClaudeTextGeneration(
176 effectiveConfig,
177 processEnv,
178 modelCatalog,
179 );
180
181 // Per-instance capabilities cache: keyed on binary + resolved HOME so
182 // account-specific probes never share auth metadata across instances.
183 const capabilitiesProbeCache = yield* Cache.make({
184 capacity: 1,
185 timeToLive: CAPABILITIES_PROBE_TTL,
186 lookup: () =>
187 probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(
188 Effect.provideService(Path.Path, path),
189 ),
190 });
191 const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(
192 effectiveConfig,
193 cwd,
194 processEnv,
195 );
196
197 // Start the TTL-gated refresh without delaying provider readiness. The
198 // next check observes a remote manifest after the background fetch lands.
199 const checkProvider = modelManifest.refreshInBackground.pipe(
200 Effect.andThen(
201 modelManifest.current.pipe(
202 Effect.flatMap((manifest) =>
203 checkClaudeProviderStatus(
204 effectiveConfig,
205 () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
206 processEnv,
207 cwd,
208 resolveClaudeModelCatalog(manifest),
209 scopedLimitNames,
210 ),
211 ),
212 Effect.map(stampIdentity),
213 ),
214 ),
215 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
216 Effect.provideService(FileSystem.FileSystem, fileSystem),
217 Effect.provideService(Path.Path, path),
218 );
219
220 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
221 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
222 resolveMaintenance,
223 getSettings: snapshotSettings.getSettings,
224 streamSettings: snapshotSettings.streamSettings,
225 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
226 initialSnapshot: (settings) =>
227 modelManifest.current.pipe(
228 Effect.flatMap((manifest) =>
229 makePendingClaudeProvider(settings.provider, resolveClaudeModelCatalog(manifest)),
230 ),
231 Effect.map(stampIdentity),
232 ),
233 checkProvider,
234 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
235 resolveMaintenance().pipe(
236 Effect.flatMap((maintenanceCapabilities) =>
237 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
238 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
239 }),
240 ),
241 Effect.provideService(HttpClient.HttpClient, httpClient),
242 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
243 ),
244 }).pipe(
245 Effect.mapError(
246 (cause) =>
247 new ProviderDriverError({
248 driver: DRIVER_KIND,
249 instanceId,
250 detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
251 cause,
252 }),
253 ),
254 );
255
256 return {
257 instanceId,
258 driverKind: DRIVER_KIND,
259 continuationIdentity: {
260 ...fallbackContinuationIdentity,
261 continuationKey: continuationGroupKey,
262 },
263 displayName,
264 accentColor,
265 enabled,
266 snapshot,
267 snapshotForCwd: (cwd: string) =>
268 !effectiveConfig.enabled
269 ? snapshot.getSnapshot
270 : Effect.all([
271 snapshot.getSnapshot,
272 discoverClaudeSkills(effectiveConfig, cwd, processEnv),
273 ]).pipe(
274 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
275 Effect.provideService(FileSystem.FileSystem, fileSystem),
276 Effect.provideService(Path.Path, path),
277 ),
278 orchestrationAdapter,
279 textGeneration,
280 } satisfies ProviderInstance;
281 }),
282};