Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeDriver.ts

269 lines10.3 KB

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