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