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

ClaudeDriver.ts

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