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