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