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

ClaudeDriver.ts

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