@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 436 lines 16.7 KB
Raw
1 import { ClaudeSettings, ProviderDriverKind } from "@t3tools/contracts";
2 import * as Cache from "effect/Cache";
3 import type * as Cause from "effect/Cause";
4 import * as Duration from "effect/Duration";
5 import * as SecureRandom from "effect/crypto/SecureRandom";
6 import * as Effect from "effect/Effect";
7 import * as Exit from "effect/Exit";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Path from "effect/Path";
10 import * as Queue from "effect/Queue";
11 import * as Ref from "effect/Ref";
12 import * as Schema from "effect/Schema";
13 import * as Stream from "effect/Stream";
14 import { HttpClient } from "effect/http";
15 import { ChildProcessSpawner } from "effect/process";
16
17 import { makeClaudeTextGeneration } from "../../textGeneration/ClaudeTextGeneration.ts";
18 import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
19 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
20 import * as ServerConfig from "../../config.ts";
21 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
22 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
23 import {
24 createClaudeAdapterV2,
25 type ClaudeAdapterV2DriverEnv,
26 } from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
27 import { ProviderDriverError } from "../Errors.ts";
28 import { claudeUsageReader } from "./claudeUsage.ts";
29 import { makeClaudeScopedLimitNames } from "../claudeUsageLimits.ts";
30 import * as ClaudeResetCredits from "../claudeResetCredits.ts";
31 import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts";
32 import {
33 checkClaudeProviderStatus,
34 makePendingClaudeProvider,
35 probeClaudeCapabilities,
36 probeClaudeWorkspaceSnapshot,
37 type ClaudeCapabilitiesProbe,
38 } from "../ClaudeProvider.ts";
39 import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
40 import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
41 import { resolveClaudeModelCatalog } from "../ClaudeModelCatalog.ts";
42 import {
43 makeClaudeCodeModelRoutes,
44 resolveClaudeModelSettingsKey,
45 } from "../ClaudeCodeModelRoutes.ts";
46 import {
47 defaultProviderContinuationIdentity,
48 type ProviderDriver,
49 type ProviderInstance,
50 } from "@t3tools/provider-core/server/driver";
51 import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
52 import { enrichProviderSnapshotWithVersionAdvisory } from "@t3tools/provider-core/server/maintenanceResolver";
53 import {
54 haveProviderSnapshotSettingsChanged,
55 makeProviderSnapshotSettingsSource,
56 type ProviderSnapshotSettings,
57 } from "@t3tools/provider-core/server/snapshotSettings";
58 import {
59 makeClaudeCapabilitiesCacheKey,
60 makeClaudeContinuationGroupKey,
61 mergeClaudeProcessEnvironment,
62 resolveClaudeHomePath,
63 } from "./ClaudeHome.ts";
64 import * as HostProcess from "@t3tools/shared/HostProcess";
65 import { makeClaudeMaintenanceResolution } from "./ClaudeMaintenance.ts";
66 const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);
67
68 const DRIVER_KIND = ProviderDriverKind.make("claudeAgent");
69 const CAPABILITIES_PROBE_TTL = Duration.minutes(5);
70
71 const withoutUsage = (capabilities: ClaudeCapabilitiesProbe): ClaudeCapabilitiesProbe => {
72 const result = { ...capabilities };
73 delete result.usage;
74 return result;
75 };
76
77 export type ClaudeDriverEnv =
78 | ClaudeAdapterV2DriverEnv
79 | ProviderHost.ProviderHost
80 | ChildProcessSpawner.ChildProcessSpawner
81 | ResetCreditCoordinator.ResetCreditCoordinator
82 | SecureRandom.SecureRandom
83 | FileSystem.FileSystem
84 | HttpClient.HttpClient
85 | ProviderLatestVersions.ProviderLatestVersions
86 | ModelCatalog.ModelCatalog
87 | Path.Path
88 | ProviderEventLoggers.ProviderEventLoggers
89 | ServerConfig.ServerConfig;
90
91 export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.Path> = {
92 driverKind: DRIVER_KIND,
93 metadata: {
94 displayName: "Claude",
95 supportsMultipleInstances: true,
96 },
97 configSchema: ClaudeSettings,
98 defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),
99 usage: claudeUsageReader,
100 create: Effect.fn("ClaudeDriver.create")(function* ({
101 instanceId,
102 displayName,
103 accentColor,
104 environment,
105 enabled,
106 config,
107 }) {
108 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
109 const fileSystem = yield* FileSystem.FileSystem;
110 const path = yield* Path.Path;
111 // The server cwd is $HOME in packaged desktop builds, and `claude`
112 // wrappers that scope themselves to their cwd refuse to run there.
113 const { stateDir } = yield* ServerConfig.ServerConfig;
114 const httpClient = yield* HttpClient.HttpClient;
115 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
116 const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator;
117 const catalogService = yield* ModelCatalog.ModelCatalog;
118 const modelCatalog = catalogService
119 .current(DRIVER_KIND)
120 .pipe(Effect.map(resolveClaudeModelCatalog));
121 const processEnv = yield* mergeClaudeProcessEnvironment(config, environment, process.env);
122 const fallbackContinuationIdentity = defaultProviderContinuationIdentity({
123 driverKind: DRIVER_KIND,
124 instanceId,
125 });
126 const effectiveConfig = {
127 ...config,
128 enabled,
129 binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory),
130 } satisfies ClaudeSettings;
131 const resolveMaintenance = yield* makeClaudeMaintenanceResolution({
132 binaryPath: effectiveConfig.binaryPath,
133 env: processEnv,
134 }).pipe(
135 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
136 Effect.provideService(FileSystem.FileSystem, fileSystem),
137 Effect.provideService(Path.Path, path),
138 Effect.provideService(HttpClient.HttpClient, httpClient),
139 );
140 const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig, processEnv);
141 const configDir = yield* resolveClaudeHomePath(effectiveConfig, processEnv);
142 const accountConfigPath = yield* ClaudeResetCredits.claudeAccountConfigPath(
143 effectiveConfig.homePath.trim() || processEnv.CLAUDE_CONFIG_DIR?.trim()
144 ? configDir
145 : undefined,
146 );
147 const stampIdentity = withInstanceIdentity({
148 instanceId,
149 driverKind: DRIVER_KIND,
150 displayName,
151 accentColor,
152 continuationGroupKey,
153 });
154
155 const scopedLimitNames = yield* makeClaudeScopedLimitNames;
156 // The SDK's user source is the host's home, not a custom one; same rule as the adapter.
157 const customHome =
158 effectiveConfig.homePath.trim().length > 0 ||
159 processEnv.CLAUDE_CONFIG_DIR !== (yield* HostProcess.Environment).CLAUDE_CONFIG_DIR;
160 // Only a successful probe records routes, so a failed one never sends turns back to slugs
161 // the backend rejects.
162 const modelRoutes = yield* makeClaudeCodeModelRoutes(
163 (cwd) =>
164 resolveClaudeModelSettingsKey(
165 customHome ? ["project", "local"] : ["user", "project", "local"],
166 cwd,
167 ).pipe(
168 Effect.provideService(FileSystem.FileSystem, fileSystem),
169 Effect.provideService(Path.Path, path),
170 ),
171 stateDir,
172 );
173 // Retain reports until the registry subscribes; end its listener on teardown.
174 const workspaceRescans = yield* Queue.unbounded<string, Cause.Done>();
175 yield* Effect.addFinalizer(() => Queue.end(workspaceRescans));
176 const orchestrationAdapter = yield* createClaudeAdapterV2(
177 {
178 instanceId,
179 displayName,
180 accentColor,
181 environment,
182 enabled,
183 config,
184 },
185 {
186 scopedLimitNames,
187 onUsageLimits: (update) => snapshot.applyUsageLimits(update),
188 onSessionInit: (cwd) => Queue.offer(workspaceRescans, cwd).pipe(Effect.asVoid),
189 modelCatalog,
190 routeModelCatalog: modelRoutes.route,
191 },
192 ).pipe(
193 Effect.mapError(
194 (cause) =>
195 new ProviderDriverError({
196 driver: DRIVER_KIND,
197 instanceId,
198 detail: "Failed to build Claude orchestration adapter.",
199 cause,
200 }),
201 ),
202 );
203 const textGeneration = yield* makeClaudeTextGeneration(
204 effectiveConfig,
205 processEnv,
206 modelCatalog,
207 modelRoutes.route,
208 );
209
210 // Per-instance capabilities cache: keyed on binary + resolved HOME so
211 // account-specific probes never share auth metadata across instances.
212 // A transient miss may reuse the last account once, but its usage windows keep their age.
213 const lastGoodCapabilities = yield* Ref.make<ClaudeCapabilitiesProbe | undefined>(undefined);
214 const capabilitiesProbeCache = yield* Cache.makeWith(
215 () =>
216 probeClaudeCapabilities(effectiveConfig, processEnv, stateDir).pipe(
217 Effect.flatMap((capabilities) =>
218 ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(
219 Effect.map((workspaceId) => ({
220 _tag: "fresh" as const,
221 capabilities:
222 workspaceId === undefined ? capabilities : { ...capabilities, workspaceId },
223 })),
224 ),
225 ),
226 Effect.tap(({ capabilities }) =>
227 Ref.set(lastGoodCapabilities, capabilities).pipe(
228 Effect.andThen(modelRoutes.record(capabilities.models ?? [])),
229 ),
230 ),
231 Effect.ensuring(modelRoutes.settle),
232 Effect.catch((error) =>
233 Ref.getAndSet(lastGoodCapabilities, undefined).pipe(
234 Effect.flatMap((capabilities) =>
235 capabilities === undefined
236 ? Effect.fail(error)
237 : ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe(
238 Effect.flatMap((workspaceId) =>
239 workspaceId === capabilities.workspaceId
240 ? Effect.succeed({
241 _tag: "fallback" as const,
242 capabilities: withoutUsage(capabilities),
243 })
244 : Effect.fail(error),
245 ),
246 ),
247 ),
248 ),
249 ),
250 Effect.provideService(FileSystem.FileSystem, fileSystem),
251 Effect.provideService(Path.Path, path),
252 ),
253 {
254 capacity: 1,
255 timeToLive: (exit) =>
256 // Only fresh usage earns the TTL; failures, fallbacks and usage-less probes retry.
257 Exit.isSuccess(exit) &&
258 exit.value._tag === "fresh" &&
259 exit.value.capabilities.usage !== undefined
260 ? CAPABILITIES_PROBE_TTL
261 : Duration.zero,
262 },
263 );
264 const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(
265 effectiveConfig,
266 stateDir,
267 processEnv,
268 );
269 const resolveCapabilities = Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe(
270 Effect.map((result) => result.capabilities),
271 );
272
273 const checkProvider = catalogService.refreshInBackground.pipe(
274 Effect.andThen(
275 modelCatalog.pipe(
276 Effect.flatMap((catalog) =>
277 checkClaudeProviderStatus(
278 effectiveConfig,
279 () => resolveCapabilities,
280 processEnv,
281 stateDir,
282 catalog,
283 scopedLimitNames,
284 (version) =>
285 ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe(
286 Effect.provideService(HttpClient.HttpClient, httpClient),
287 Effect.provideService(FileSystem.FileSystem, fileSystem),
288 Effect.provideService(Path.Path, path),
289 ),
290 ),
291 ),
292 Effect.tap((provider) =>
293 provider.auth.status === "unauthenticated"
294 ? Cache.invalidateAll(capabilitiesProbeCache)
295 : Effect.void,
296 ),
297 Effect.map(stampIdentity),
298 ),
299 ),
300 // Disabled, failed version checks and interruption never reach the probe.
301 Effect.ensuring(modelRoutes.settle),
302 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
303 Effect.provideService(FileSystem.FileSystem, fileSystem),
304 Effect.provideService(Path.Path, path),
305 );
306
307 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
308 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({
309 resolveMaintenance,
310 getSettings: snapshotSettings.getSettings,
311 streamSettings: snapshotSettings.streamSettings,
312 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
313 initialSnapshot: (settings) =>
314 modelCatalog.pipe(
315 Effect.flatMap((catalog) => makePendingClaudeProvider(settings.provider, catalog)),
316 Effect.map(stampIdentity),
317 ),
318 checkProvider,
319 invalidateUsageCache: Cache.invalidateAll(capabilitiesProbeCache),
320 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
321 resolveMaintenance().pipe(
322 Effect.flatMap((maintenanceCapabilities) =>
323 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
324 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
325 }),
326 ),
327 Effect.provideService(HttpClient.HttpClient, httpClient),
328 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
329 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
330 ),
331 }).pipe(
332 Effect.mapError(
333 (cause) =>
334 new ProviderDriverError({
335 driver: DRIVER_KIND,
336 instanceId,
337 detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,
338 cause,
339 }),
340 ),
341 );
342
343 // Same rules as Codex: serialised on the config directory that holds the
344 // login, one request id kept until Claude answers (a cooldown or rate
345 // limit is an answer), then a re-probe.
346 const consumeResetCredit: NonNullable<ProviderInstance["consumeResetCredit"]> = Effect.fn(
347 "ClaudeDriver.consumeResetCredit",
348 )(
349 function* (creditId) {
350 const current = yield* snapshot.getSnapshot;
351 const credits = current.usageLimits?.resetCredits;
352 const grantId =
353 creditId === undefined
354 ? credits?.nextCreditId
355 : credits?.options?.some((option) => option.creditId === creditId)
356 ? creditId
357 : undefined;
358 if (!grantId || !current.version) return "noCredit" as const;
359 const version = current.version;
360 return yield* resetCreditCoordinator.redeem(
361 configDir,
362 (requestId) =>
363 ClaudeResetCredits.consumeClaudeResetCredit({
364 configDir,
365 accountConfigPath,
366 version,
367 grantId,
368 requestId,
369 }),
370 ClaudeResetCredits.isSettledClaudeResetCreditFailure,
371 );
372 },
373 Effect.provideService(HttpClient.HttpClient, httpClient),
374 Effect.provideService(FileSystem.FileSystem, fileSystem),
375 Effect.provideService(Path.Path, path),
376 Effect.mapError(
377 (cause) =>
378 new ProviderDriverError({
379 driver: DRIVER_KIND,
380 instanceId,
381 detail:
382 cause._tag === "ClaudeResetCreditError"
383 ? cause.message
384 : "Claude could not redeem the reset.",
385 cause,
386 }),
387 ),
388 Effect.tap((outcome) =>
389 ResetCreditCoordinator.refreshAfterRedemption({
390 outcome,
391 getSnapshot: snapshot.getSnapshot,
392 refresh: Cache.invalidateAll(capabilitiesProbeCache).pipe(
393 Effect.andThen(snapshot.refresh),
394 ),
395 }).pipe(
396 Effect.filterOrFail(
397 (confirmed) => confirmed,
398 () =>
399 new ProviderDriverError({
400 driver: DRIVER_KIND,
401 instanceId,
402 detail:
403 "The reset was applied, but Claude could not confirm the new limits. Refresh to check.",
404 }),
405 ),
406 ),
407 ),
408 );
409
410 return {
411 instanceId,
412 driverKind: DRIVER_KIND,
413 continuationIdentity: {
414 ...fallbackContinuationIdentity,
415 continuationKey: continuationGroupKey,
416 },
417 displayName,
418 accentColor,
419 enabled,
420 snapshot,
421 invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),
422 workspaceRescans: Stream.fromQueue(workspaceRescans),
423 snapshotForCwd: (cwd: string) =>
424 snapshot.getSnapshot.pipe(
425 Effect.flatMap((machineSnapshot) =>
426 probeClaudeWorkspaceSnapshot(effectiveConfig, machineSnapshot, cwd, processEnv),
427 ),
428 Effect.provideService(FileSystem.FileSystem, fileSystem),
429 Effect.provideService(Path.Path, path),
430 ),
431 orchestrationAdapter,
432 textGeneration,
433 consumeResetCredit,
434 } satisfies ProviderInstance;
435 }),
436 };