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

ClaudeDriver.ts

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