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