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