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 { ServerSettingsService } from "../../serverSettings.ts";
31import { ProviderDriverError } from "../Errors.ts";
32import { makeClaudeAdapter } from "../Layers/ClaudeAdapter.ts";
33import { makeClaudeScopedLimitNames } from "../Layers/claudeUsageLimits.ts";
34import {
35 checkClaudeProviderStatus,
36 makePendingClaudeProvider,
37 probeClaudeCapabilities,
38} from "../Layers/ClaudeProvider.ts";
39import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
40import { resolveClaudeModelCatalog } from "../ClaudeModelCatalog.ts";
41import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
42import * as ModelManifest from "../ModelManifest.ts";
43import {
44 defaultProviderContinuationIdentity,
45 type ProviderDriver,
46 type ProviderInstance,
47} from "../ProviderDriver.ts";
48import { withInstanceIdentity } from "./instanceIdentity.ts";
49import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
50import {
51 enrichProviderSnapshotWithVersionAdvisory,
52 makeCachedProviderMaintenanceResolution,
53 makePackageManagedProviderMaintenanceResolver,
54 normalizeCommandPath,
55 resolveProviderMaintenanceCapabilitiesEffect,
56} from "../providerMaintenance.ts";
57import {
58 haveProviderSnapshotSettingsChanged,
59 makeProviderSnapshotSettingsSource,
60 type ProviderSnapshotSettings,
61} from "../providerUpdateSettings.ts";
62import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from "./ClaudeHome.ts";
63import { discoverClaudeSkills } from "./ClaudeSkills.ts";
64const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
65
66const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
67const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
68
69function isClaudeNativeCommandPath(commandPath: string): boolean {
70 const normalized = normalizeCommandPath(commandPath);
71 return (
72 normalized.endsWith("/.local/bin/claude") ||
73 normalized.endsWith("/.local/bin/claude.exe") ||
74 normalized.includes("/.local/share/claude/")
75 );
76}
77
78const UPDATE = makePackageManagedProviderMaintenanceResolver({
79 provider: DRIVER_KIND,
80 npmPackageName: "@anthropic-ai/claude-code",
81 nativeUpdate: {
82 args: ["update"],
83 isCommandPath: isClaudeNativeCommandPath,
84 },
85});
86
87export type ClaudeDriverEnv =
88 | BackgroundPolicy.BackgroundPolicy
89 | ChildProcessSpawner.ChildProcessSpawner
90 | Crypto.Crypto
91 | FileSystem.FileSystem
92 | HttpClient.HttpClient
93 | ModelManifest.ModelManifest
94 | Path.Path
95 | ProviderEventLoggers
96 | ServerConfig
97 | ServerSettingsService;
98
99export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
100 driverKind: DRIVER_KIND,
101 metadata: {
102 displayName: "Claude",
103 supportsMultipleInstances: true,
104 },
105 configSchema: ClaudeSettings,
106 defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),
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 const { cwd } = yield* ServerConfig;
113 const httpClient = yield* HttpClient.HttpClient;
114 const serverSettings = yield* ServerSettingsService;
115 const eventLoggers = yield* ProviderEventLoggers;
116 const modelManifest = yield* ModelManifest.ModelManifest;
117 const modelCatalog = modelManifest.current.pipe(Effect.map(resolveClaudeModelCatalog));
118 const processEnv = mergeProviderInstanceEnvironment(environment);
119 const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
120 driverKind: DRIVER_KIND,
121 instanceId,
122 });
123 const effectiveConfig = {
124 ...config,
125 enabled,
126 binaryPath: expandHomePath(config.binaryPath),
127 } satisfies ClaudeSettings;
128 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
129 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
130 binaryPath: effectiveConfig.binaryPath,
131 env: processEnv,
132 }).pipe(
133 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
134 Effect.provideService(FileSystem.FileSystem, fileSystem),
135 Effect.provideService(Path.Path, path),
136 ),
137 );
138 const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);
139 const stampIdentity = withInstanceIdentity({
140 instanceId,
141 driverKind: DRIVER_KIND,
142 displayName,
143 accentColor,
144 continuationGroupKey,
145 });
146
147 // One per instance: the status probe writes the model-scoped bucket
148 // names it saw, the adapter reads them to place turn-driven events.
149 const scopedLimitNames = yield* makeClaudeScopedLimitNames;
150 const adapterOptions = {
151 instanceId,
152 environment: processEnv,
153 modelCatalog,
154 scopedLimitNames,
155 ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
156 };
157 const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions);
158 const textGeneration = yield* makeClaudeTextGeneration(
159 effectiveConfig,
160 processEnv,
161 modelCatalog,
162 );
163
164 // Per-instance capabilities cache: keyed on binary + resolved HOME so
165 // account-specific probes never share auth metadata across instances.
166 const capabilitiesProbeCache = yield* Cache.make({
167 capacity: 1,
168 timeToLive: CAPABILITIES_PROBE_TTL,
169 lookup: () =>
170 probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(
171 Effect.provideService(Path.Path, path),
172 ),
173 });
174 const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig, cwd);
175
176 // Start the TTL-gated refresh without delaying provider readiness. The
177 // next check observes a remote manifest after the background fetch lands.
178 const checkProvider = modelManifest.refreshInBackground.pipe(
179 Effect.andThen(
180 modelManifest.current.pipe(
181 Effect.flatMap((manifest) =>
182 checkClaudeProviderStatus(
183 effectiveConfig,
184 () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),
185 processEnv,
186 cwd,
187 resolveClaudeModelCatalog(manifest),
188 scopedLimitNames,
189 ),
190 ),
191 Effect.map(stampIdentity),
192 ),
193 ),
194 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
195 Effect.provideService(FileSystem.FileSystem, fileSystem),
196 Effect.provideService(Path.Path, path),
197 );
198
199 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
200 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
201 resolveMaintenance,
202 getSettings: snapshotSettings.getSettings,
203 streamSettings: snapshotSettings.streamSettings,
204 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
205 initialSnapshot: (settings) =>
206 modelManifest.current.pipe(
207 Effect.flatMap((manifest) =>
208 makePendingClaudeProvider(settings.provider, resolveClaudeModelCatalog(manifest)),
209 ),
210 Effect.map(stampIdentity),
211 ),
212 checkProvider,
213 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
214 resolveMaintenance().pipe(
215 Effect.flatMap((maintenanceCapabilities) =>
216 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
217 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
218 }),
219 ),
220 Effect.provideService(HttpClient.HttpClient, httpClient),
221 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
222 ),
223 }).pipe(
224 Effect.mapError(
225 (cause) =>
226 new ProviderDriverError({
227 driver: DRIVER_KIND,
228 instanceId,
229 detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
230 cause,
231 }),
232 ),
233 );
234 const snapshotForCwd = (cwd: string) =>
235 !effectiveConfig.enabled
236 ? snapshot.getSnapshot
237 : Effect.all([
238 snapshot.getSnapshot,
239 discoverClaudeSkills(effectiveConfig, cwd, processEnv),
240 ]).pipe(
241 Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })),
242 Effect.provideService(FileSystem.FileSystem, fileSystem),
243 Effect.provideService(Path.Path, path),
244 );
245
246 return {
247 instanceId,
248 driverKind: DRIVER_KIND,
249 continuationIdentity: {
250 ...fallbackContinuationIdentity,
251 continuationKey: continuationGroupKey,
252 },
253 displayName,
254 accentColor,
255 enabled,
256 snapshot,
257 snapshotForCwd,
258 adapter,
259 textGeneration,
260 } satisfies ProviderInstance;
261 }),
262};