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

ClaudeDriver.ts

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