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

ClaudeDriver.ts

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