Open History to see the last commit
1import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
2import * as CodexInstallation from "../CodexInstallation.ts";
3import * as ServerEnvironment from "../../environment/ServerEnvironment.ts";
4/**
5 * Multi-instance validation slices for `ProviderInstanceRegistryLive`.
6 *
7 * Two axes of the driver/registry refactor are exercised here:
8 *
9 * 1. **Same driver, many instances** — the "multi-instance codex slice"
10 * describe block below configures two independent `codex` instances and
11 * asserts each gets its own closures and identity. This is the
12 * multi-codex capability the refactor exists to unlock.
13 *
14 * 2. **Many drivers, one registry** — the "all drivers slice" describe
15 * block below configures one instance of every shipped driver
16 * (`codex`, `claudeAgent`, `cursor`, `grok`, `opencode`) in a single
17 * `ProviderInstanceConfigMap` and asserts the registry boots them all
18 * without cross-contamination. This proves the driver SPI is uniform
19 * across every provider — any driver plugs into the registry through
20 * the same `ProviderDriver` value contract.
21 *
22 * Every instance in these tests is configured with `enabled: false` so the
23 * provider-status checks short-circuit to pending/disabled snapshots
24 * without trying to spawn real `codex` / `claude` / `agent` / `grok` / `opencode`
25 * binaries. That keeps the assertions focused on registry routing
26 * behaviour rather than the runtime details of each provider.
27 */
28import { describe, expect, it } from "@effect/vitest";
29import * as NodeServices from "@effect/platform-node/NodeServices";
30import {
31 EnvironmentId,
32 type ClaudeSettings,
33 type CodexSettings,
34 type CursorSettings,
35 type GrokSettings,
36 type OpenCodeSettings,
37 ProviderDriverKind,
38 type ProviderInstanceConfigMap,
39 ProviderInstanceId,
40} from "@t3tools/contracts";
41import { HostProcessPlatform, isHostWindows } from "@t3tools/shared/hostProcess";
42import * as DateTime from "effect/DateTime";
43import * as Effect from "effect/Effect";
44import * as FileSystem from "effect/FileSystem";
45import * as Layer from "effect/Layer";
46import * as Path from "effect/Path";
47import * as Stream from "effect/Stream";
48import { HttpClient, HttpClientResponse } from "effect/unstable/http";
49
50import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
51import * as AntigravityInstallation from "../AntigravityInstallation.ts";
52import * as ServerConfig from "../../config.ts";
53import { expandHomePath } from "../../pathExpansion.ts";
54import * as ServerSettings from "../../serverSettings.ts";
55import { ClaudeDriver, type ClaudeDriverEnv } from "../Drivers/ClaudeDriver.ts";
56import { CodexDriver, type CodexDriverEnv } from "../Drivers/CodexDriver.ts";
57import { CursorDriver, type CursorDriverEnv } from "../Drivers/CursorDriver.ts";
58import { GrokDriver, type GrokDriverEnv } from "../Drivers/GrokDriver.ts";
59import { OpenCodeDriver, type OpenCodeDriverEnv } from "../Drivers/OpenCodeDriver.ts";
60import * as ModelManifest from "../ModelManifest.ts";
61import * as OpenCodeRuntime from "../opencodeRuntime.ts";
62import * as OpenCodeServerLedger from "../OpenCodeServerLedger.ts";
63import * as ResetCreditCoordinator from "./resetCreditCoordinator.ts";
64import * as ProviderEventLoggers from "./ProviderEventLoggers.ts";
65import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistryLive.ts";
66import { ProviderOrchestrationAdapterInfrastructureLive } from "./ProviderOrchestrationAdapterInfrastructure.ts";
67
68const TestHttpClientLive = Layer.succeed(
69 HttpClient.HttpClient,
70 HttpClient.make((request) =>
71 Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
72 ),
73);
74
75const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
76
77const BackgroundPolicyAlwaysRunLayer = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
78 reportClientActivity: () => Effect.void,
79 removeRpcClient: () => Effect.void,
80 reportHostPowerState: () => Effect.void,
81 snapshot: Effect.succeed({
82 hostPower: {
83 source: "unknown",
84 idle: "unknown",
85 idleSeconds: null,
86 locked: "unknown",
87 suspended: false,
88 onBattery: "unknown",
89 lowPowerMode: "unknown",
90 thermalState: "unknown",
91 stale: true,
92 updatedAt: TEST_EPOCH,
93 },
94 leases: [],
95 activeForegroundLeaseCount: 0,
96 activeScopeKeys: [],
97 shouldRunOpportunisticWork: true,
98 updatedAt: TEST_EPOCH,
99 }),
100 streamChanges: Stream.empty,
101 hasDemand: () => Effect.succeed(true),
102 shouldRunScopeWork: () => Effect.succeed(true),
103 shouldRunOpportunisticWork: Effect.succeed(true),
104});
105
106const makeCodexConfig = (overrides: Partial<CodexSettings>): CodexSettings => ({
107 enabled: false,
108 binaryPath: "codex",
109 homePath: "",
110 shadowHomePath: "",
111 launchArgs: "",
112 customModels: [],
113 ...overrides,
114});
115
116const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings => ({
117 enabled: false,
118 binaryPath: "claude",
119 homePath: "",
120 customModels: [],
121 launchArgs: "",
122 autoCompactWindow: "",
123 ...overrides,
124});
125
126const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings => ({
127 enabled: false,
128 customModels: [],
129 ...overrides,
130});
131
132const makeGrokConfig = (overrides: Partial<GrokSettings>): GrokSettings => ({
133 enabled: false,
134 binaryPath: "grok",
135 customModels: [],
136 ...overrides,
137});
138
139const makeOpenCodeConfig = (overrides: Partial<OpenCodeSettings>): OpenCodeSettings => ({
140 enabled: false,
141 binaryPath: "opencode",
142 serverUrl: "",
143 serverPassword: "",
144 customModels: [],
145 ...overrides,
146});
147
148const makeTildeProviderFixtures = Effect.fn(
149 "ProviderInstanceRegistryLive.test.makeTildeProviderFixtures",
150)(function* () {
151 const fileSystem = yield* FileSystem.FileSystem;
152 const path = yield* Path.Path;
153 const homePath = expandHomePath("~");
154 const fixtureDir = yield* fileSystem.makeTempDirectoryScoped({
155 directory: homePath,
156 prefix: ".t3-provider-path-test-",
157 });
158 const codexPath = path.join(fixtureDir, "codex");
159 const claudePath = path.join(fixtureDir, "claude");
160 const claudeHomePath = path.join(fixtureDir, "claude-home");
161 const codexScriptPath = path.join(fixtureDir, "codex-script.json");
162 const codexFixtureDir = path.join(import.meta.dirname, "../testFixtures");
163
164 yield* fileSystem.copyFile(path.join(codexFixtureDir, "codexCollabMockPeer.sh"), codexPath);
165 yield* fileSystem.copyFile(
166 path.join(codexFixtureDir, "codexCollabMockPeer.mjs"),
167 path.join(fixtureDir, "codexCollabMockPeer.mjs"),
168 );
169 yield* fileSystem.copyFile(
170 path.join(codexFixtureDir, "codexMultiAgentWire.json"),
171 path.join(fixtureDir, "codexMultiAgentWire.json"),
172 );
173 yield* fileSystem.writeFileString(
174 codexScriptPath,
175 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed script document read by the external Codex mock peer.
176 JSON.stringify({ rootThreadId: "probe-thread", notifications: [] }),
177 );
178 yield* fileSystem.chmod(codexPath, 0o755);
179
180 yield* fileSystem.writeFileString(
181 claudePath,
182 [
183 "#!/usr/bin/env node",
184 'import { existsSync } from "node:fs";',
185 'import * as NodeReadline from "node:readline";',
186 'if (process.argv.includes("--version")) {',
187 ' process.stdout.write("claude 2.1.219\\n");',
188 " process.exit(0);",
189 "}",
190 "const lines = NodeReadline.createInterface({ input: process.stdin });",
191 'lines.on("line", (line) => {',
192 " const message = JSON.parse(line);",
193 ' if (message.type !== "control_request") return;',
194 ' if (message.request?.subtype === "get_usage") {',
195 " const marker = process.env.T3_CLAUDE_RESET_MARKER;",
196 " if (process.env.T3_CLAUDE_USAGE_FAILS_AFTER_CLAIM && marker && existsSync(marker)) {",
197 " process.stdout.write(JSON.stringify({",
198 ' type: "control_response",',
199 ' response: { subtype: "error", request_id: message.request_id, error: "usage failed" },',
200 ' }) + "\\n");',
201 " return;",
202 " }",
203 " process.stdout.write(JSON.stringify({",
204 ' type: "control_response",',
205 ' response: { subtype: "success", request_id: message.request_id, response: {',
206 ' session: {}, subscription_type: "pro", rate_limits_available: true,',
207 " rate_limits: { five_hour: { utilization: marker && existsSync(marker) ? 0 : 100, resets_at: null } },",
208 " } },",
209 ' }) + "\\n");',
210 " return;",
211 " }",
212 ' if (message.request?.subtype !== "initialize") return;',
213 " process.stdout.write(JSON.stringify({",
214 ' type: "control_response",',
215 " response: {",
216 ' subtype: "success",',
217 " request_id: message.request_id,",
218 " response: {",
219 " commands: [], agents: [], models: [],",
220 ' output_style: "default", available_output_styles: ["default"],',
221 ' account: { email: "test@example.com", subscriptionType: "pro", tokenSource: "oauth" },',
222 " },",
223 " },",
224 ' }) + "\\n");',
225 "});",
226 "setInterval(() => {}, 1_000);",
227 "",
228 ].join("\n"),
229 );
230 yield* fileSystem.chmod(claudePath, 0o755);
231 yield* fileSystem.makeDirectory(claudeHomePath);
232
233 const asTildePath = (filePath: string) => `~/${path.relative(homePath, filePath)}`;
234 return {
235 codexBinaryPath: asTildePath(codexPath),
236 claudeBinaryPath: asTildePath(claudePath),
237 claudeHomePath,
238 codexScriptPath,
239 };
240});
241
242describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
243 // `ServerConfig.layerTest` needs `FileSystem` to materialize its scratch
244 // directory. `Layer.merge` just unions requirements, so we have to push
245 // `NodeServices.layer` through `Layer.provideMerge` to satisfy that
246 // dependency while still surfacing NodeServices to the test body (the
247 // codex driver's `create` yields `ChildProcessSpawner` directly).
248 const baseLayer = ServerConfig.layerTest(process.cwd(), {
249 prefix: "provider-instance-registry-test",
250 }).pipe(
251 Layer.provideMerge(NodeServices.layer),
252 Layer.provideMerge(
253 Layer.mock(CodexInstallation.CodexInstallation)({
254 managedDirectory: "unused-managed-installation",
255 }),
256 ),
257 Layer.provideMerge(Layer.mock(ServerSecretStore.ServerSecretStore)({})),
258 Layer.provideMerge(
259 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
260 getEnvironmentId: Effect.succeed(
261 EnvironmentId.make("00000000-0000-4000-8000-000000000001"),
262 ),
263 }),
264 ),
265 Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
266 Layer.provideMerge(ServerSettings.layerTest()),
267 Layer.provideMerge(TestHttpClientLive),
268 Layer.provideMerge(ServerSettings.layerTest()),
269 Layer.provideMerge(
270 Layer.succeed(
271 ProviderEventLoggers.ProviderEventLoggers,
272 ProviderEventLoggers.NoOpProviderEventLoggers,
273 ),
274 ),
275 Layer.provideMerge(ModelManifest.layerTest),
276 Layer.provideMerge(ResetCreditCoordinator.layerTest),
277 );
278 const testLayer = ProviderOrchestrationAdapterInfrastructureLive.pipe(
279 Layer.provideMerge(baseLayer),
280 );
281
282 it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () =>
283 Effect.gen(function* () {
284 const personalId = ProviderInstanceId.make("codex_personal");
285 const workId = ProviderInstanceId.make("codex_work");
286 const codexDriverKind = ProviderDriverKind.make("codex");
287
288 const configMap: ProviderInstanceConfigMap = {
289 [personalId]: {
290 driver: codexDriverKind,
291 displayName: "Codex (personal)",
292 enabled: false,
293 config: makeCodexConfig({
294 binaryPath: "/opt/codex-personal/bin/codex",
295 homePath: "/home/julius/.codex_personal",
296 customModels: ["personal-preview"],
297 }),
298 },
299 [workId]: {
300 driver: codexDriverKind,
301 displayName: "Codex (work)",
302 enabled: false,
303 config: makeCodexConfig({
304 binaryPath: "/opt/codex-work/bin/codex",
305 homePath: "/home/julius/.codex",
306 customModels: ["work-preview"],
307 }),
308 },
309 };
310
311 const { registry } = yield* makeProviderInstanceRegistry<CodexDriverEnv>({
312 drivers: [CodexDriver],
313 configMap,
314 });
315
316 const instances = yield* registry.listInstances;
317 expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
318 [personalId, workId].toSorted(),
319 );
320 expect(instances.every((instance) => instance.driverKind === codexDriverKind)).toBe(true);
321 expect(instances.map((instance) => instance.displayName).toSorted()).toEqual(
322 ["Codex (personal)", "Codex (work)"].toSorted(),
323 );
324
325 // Each instance must be retrievable by id and carry its *own* closures.
326 const personal = yield* registry.getInstance(personalId);
327 const work = yield* registry.getInstance(workId);
328 expect(personal).toBeDefined();
329 expect(work).toBeDefined();
330 expect(personal!.orchestrationAdapter).not.toBe(work!.orchestrationAdapter);
331 expect(personal!.textGeneration).not.toBe(work!.textGeneration);
332 expect(personal!.snapshot).not.toBe(work!.snapshot);
333
334 // Snapshots identify themselves by instanceId + driver — this is
335 // what makes per-instance routing distinguishable downstream.
336 const personalSnapshot = yield* personal!.snapshot.getSnapshot;
337 expect(personalSnapshot.instanceId).toBe(personalId);
338 expect(personalSnapshot.driver).toBe(codexDriverKind);
339 expect(personalSnapshot.enabled).toBe(false);
340 // The layout resolves the configured home through the host Path.
341 const path = yield* Path.Path;
342 expect(personalSnapshot.continuation?.groupKey).toBe(
343 `codex:home:${path.resolve("/home/julius/.codex_personal")}`,
344 );
345
346 const workSnapshot = yield* work!.snapshot.getSnapshot;
347 expect(workSnapshot.instanceId).toBe(workId);
348 expect(workSnapshot.driver).toBe(codexDriverKind);
349 expect(workSnapshot.enabled).toBe(false);
350 expect(workSnapshot.continuation?.groupKey).toBe(
351 `codex:home:${path.resolve("/home/julius/.codex")}`,
352 );
353
354 // Nothing goes to the unavailable bucket — both drivers are registered.
355 const unavailable = yield* registry.listUnavailable;
356 expect(unavailable).toEqual([]);
357 }).pipe(Effect.provide(testLayer)),
358 );
359
360 it.live("treats an explicit in-config enabled:false as disabling despite the envelope", () =>
361 Effect.gen(function* () {
362 // Old settings files can carry both flags with conflicting values.
363 // The explicit false must win so a user's disable is never undone.
364 const staleId = ProviderInstanceId.make("codex_stale");
365 const configMap: ProviderInstanceConfigMap = {
366 [staleId]: {
367 driver: ProviderDriverKind.make("codex"),
368 enabled: true,
369 config: makeCodexConfig({ enabled: false }),
370 },
371 };
372
373 const { registry } = yield* makeProviderInstanceRegistry({
374 drivers: [CodexDriver],
375 configMap,
376 });
377
378 const instance = yield* registry.getInstance(staleId);
379 expect(instance).toBeDefined();
380 expect(instance!.enabled).toBe(false);
381 const snapshot = yield* instance!.snapshot.getSnapshot;
382 expect(snapshot.enabled).toBe(false);
383 }).pipe(Effect.provide(testLayer)),
384 );
385
386 it.live("reports Codex's answer when a redemption changed nothing", () =>
387 Effect.gen(function* () {
388 if (yield* isHostWindows) return;
389 const fileSystem = yield* FileSystem.FileSystem;
390 const fixtures = yield* makeTildeProviderFixtures();
391 yield* fileSystem.writeFileString(
392 fixtures.codexScriptPath,
393 // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed script document read by the external Codex mock peer.
394 JSON.stringify({
395 rootThreadId: "probe-thread",
396 notifications: [],
397 account: { type: "chatgpt", email: "test@example.com", planType: "plus" },
398 failRateLimitsRead: true,
399 resetCreditOutcome: "alreadyRedeemed",
400 }),
401 );
402 const codexId = ProviderInstanceId.make("codex_reset");
403 const { registry } = yield* makeProviderInstanceRegistry({
404 drivers: [CodexDriver],
405 configMap: {
406 [codexId]: {
407 driver: ProviderDriverKind.make("codex"),
408 enabled: true,
409 environment: [
410 { name: "T3_CODEX_COLLAB_SCRIPT", value: fixtures.codexScriptPath, sensitive: false },
411 ],
412 config: makeCodexConfig({ enabled: true, binaryPath: fixtures.codexBinaryPath }),
413 },
414 },
415 });
416 const codex = yield* registry.getInstance(codexId);
417 expect(codex).toBeDefined();
418 // The usage read fails, so the re-probe cannot confirm new limits.
419 yield* codex!.snapshot.refresh;
420 expect(yield* codex!.consumeResetCredit!()).toBe("alreadyRedeemed");
421 }).pipe(Effect.provide(testLayer)),
422 );
423
424 it.live("runs Codex and Claude readiness probes from configured tilde paths", () =>
425 Effect.gen(function* () {
426 if (yield* isHostWindows) return;
427
428 const fixtures = yield* makeTildeProviderFixtures();
429
430 const codexId = ProviderInstanceId.make("codex_tilde");
431 const claudeId = ProviderInstanceId.make("claude_tilde");
432 const configMap: ProviderInstanceConfigMap = {
433 [codexId]: {
434 driver: ProviderDriverKind.make("codex"),
435 enabled: true,
436 environment: [
437 {
438 name: "T3_CODEX_COLLAB_SCRIPT",
439 value: fixtures.codexScriptPath,
440 sensitive: false,
441 },
442 ],
443 config: makeCodexConfig({ enabled: true, binaryPath: fixtures.codexBinaryPath }),
444 },
445 [claudeId]: {
446 driver: ProviderDriverKind.make("claudeAgent"),
447 enabled: true,
448 config: makeClaudeConfig({
449 enabled: true,
450 binaryPath: fixtures.claudeBinaryPath,
451 homePath: fixtures.claudeHomePath,
452 }),
453 },
454 };
455
456 const { registry } = yield* makeProviderInstanceRegistry<CodexDriverEnv | ClaudeDriverEnv>({
457 drivers: [CodexDriver, ClaudeDriver],
458 configMap,
459 });
460 const codex = yield* registry.getInstance(codexId);
461 const claude = yield* registry.getInstance(claudeId);
462 expect(codex).toBeDefined();
463 expect(claude).toBeDefined();
464
465 const [codexSnapshot, claudeSnapshot] = yield* Effect.all(
466 [codex!.snapshot.refresh, claude!.snapshot.refresh],
467 { concurrency: "unbounded" },
468 );
469 expect(codexSnapshot).toMatchObject({ status: "ready", installed: true, version: "0.0.0" });
470 expect(claudeSnapshot).toMatchObject({
471 status: "ready",
472 installed: true,
473 version: "2.1.219",
474 });
475 }).pipe(Effect.provide(testLayer)),
476 );
477
478 const redeemClaudeReset = (claim: { result: string; usageFailsAfterClaim: boolean }) =>
479 Effect.gen(function* () {
480 const fs = yield* FileSystem.FileSystem;
481 const path = yield* Path.Path;
482 const fixtures = yield* makeTildeProviderFixtures();
483 const marker = path.join(fixtures.claudeHomePath, "redeemed");
484 yield* fs.writeFileString(
485 path.join(fixtures.claudeHomePath, ".credentials.json"),
486 '{"claudeAiOauth":{"accessToken":"fake-token"}}',
487 );
488 yield* fs.writeFileString(
489 path.join(fixtures.claudeHomePath, ".claude.json"),
490 '{"oauthAccount":{"organizationUuid":"fake-org"}}',
491 );
492 const client = HttpClient.make((request) =>
493 Effect.gen(function* () {
494 if (request.url.endsWith("/api/oauth/usage")) {
495 return HttpClientResponse.fromWeb(
496 request,
497 Response.json({
498 cedar_ember: {
499 eligible: true,
500 next_grant_id: "grant_a",
501 grants: [{ id: "grant_a", resets_left: 1, usable_now: true }],
502 },
503 }),
504 );
505 }
506 if (request.url.endsWith("/reset_rate_limits")) {
507 yield* fs.writeFileString(marker, "redeemed").pipe(Effect.orDie);
508 return HttpClientResponse.fromWeb(request, Response.json({ result: claim.result }));
509 }
510 return HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }));
511 }),
512 );
513 const instanceId = ProviderInstanceId.make("claude_reset");
514 const { registry } = yield* makeProviderInstanceRegistry({
515 drivers: [ClaudeDriver],
516 configMap: {
517 [instanceId]: {
518 driver: ProviderDriverKind.make("claudeAgent"),
519 enabled: true,
520 environment: [
521 { name: "T3_CLAUDE_RESET_MARKER", value: marker, sensitive: false },
522 ...(claim.usageFailsAfterClaim
523 ? [{ name: "T3_CLAUDE_USAGE_FAILS_AFTER_CLAIM", value: "1", sensitive: false }]
524 : []),
525 ],
526 config: makeClaudeConfig({
527 enabled: true,
528 binaryPath: fixtures.claudeBinaryPath,
529 homePath: fixtures.claudeHomePath,
530 }),
531 },
532 },
533 }).pipe(Effect.provideService(HttpClient.HttpClient, client));
534 const instance = yield* registry.getInstance(instanceId);
535 expect(instance).toBeDefined();
536 const before = yield* instance!.snapshot.refresh;
537 expect(before.usageLimits?.windows[0]?.usedPercent).toBe(100);
538 expect(before.usageLimits?.resetCredits?.nextCreditId).toBe("grant_a");
539 const outcome = yield* instance!.consumeResetCredit!().pipe(Effect.result);
540 return { outcome, after: yield* instance!.snapshot.getSnapshot };
541 }).pipe(
542 // macOS logins live in the Keychain, where resets are never read.
543 Effect.provideService(HostProcessPlatform, "linux"),
544 Effect.provide(testLayer),
545 );
546
547 it.live("refreshes Claude usage after redeeming a reset", () =>
548 Effect.gen(function* () {
549 const { outcome, after } = yield* redeemClaudeReset({
550 result: "reset",
551 usageFailsAfterClaim: false,
552 });
553 expect(outcome).toMatchObject({ _tag: "Success", success: "reset" });
554 expect(after.usageLimits?.windows[0]?.usedPercent).toBe(0);
555 }),
556 );
557
558 it.live("reports Claude's answer when a claim changed nothing and the re-probe fails", () =>
559 Effect.gen(function* () {
560 const { outcome } = yield* redeemClaudeReset({
561 result: "already_used",
562 usageFailsAfterClaim: true,
563 });
564 expect(outcome).toMatchObject({ _tag: "Success", success: "alreadyRedeemed" });
565 }),
566 );
567
568 it.live(
569 "shadows instances whose driver is not registered in this build without failing boot",
570 () =>
571 Effect.gen(function* () {
572 const codexId = ProviderInstanceId.make("codex_main");
573 const ghostId = ProviderInstanceId.make("ghost_main");
574
575 const configMap: ProviderInstanceConfigMap = {
576 [codexId]: {
577 driver: ProviderDriverKind.make("codex"),
578 enabled: false,
579 config: makeCodexConfig({}),
580 },
581 [ghostId]: {
582 driver: ProviderDriverKind.make("ghostDriver"),
583 displayName: "A fork-only driver we don't ship",
584 enabled: false,
585 config: { arbitrary: "payload", preserved: true },
586 },
587 };
588
589 const { registry } = yield* makeProviderInstanceRegistry<CodexDriverEnv>({
590 drivers: [CodexDriver],
591 configMap,
592 });
593
594 const instances = yield* registry.listInstances;
595 expect(instances).toHaveLength(1);
596 expect(instances[0]!.instanceId).toBe(codexId);
597
598 const unavailable = yield* registry.listUnavailable;
599 expect(unavailable).toHaveLength(1);
600 const ghost = unavailable[0]!;
601 expect(ghost.instanceId).toBe(ghostId);
602 expect(ghost.driver).toBe("ghostDriver");
603 expect(ghost.availability).toBe("unavailable");
604 expect(ghost.unavailableReason).toMatch(/ghostDriver/);
605 }).pipe(Effect.provide(testLayer)),
606 );
607});
608
609describe("ProviderInstanceRegistryLive — all drivers slice", () => {
610 // All drivers need `NodeServices` (ChildProcessSpawner + FileSystem +
611 // Path). `OpenCodeDriver.create` additionally yields `OpenCodeRuntime`
612 // at construction time, so we wire `OpenCodeRuntimeLive` into the stack.
613 // `OpenCodeRuntimeLive` bundles its own `NetService.layer` via
614 // `Layer.provide`, so the only external requirement it still exposes is
615 // `ChildProcessSpawner` — resolved here by piping it through
616 // `provideMerge(NodeServices.layer)`.
617 //
618 // The nested `provideMerge`s read bottom-up: `NodeServices.layer`
619 // provides `OpenCodeRuntimeLive`'s deps while keeping its own outputs
620 // surfaced; that merged layer then provides `ServerConfig.layerTest`'s
621 // `FileSystem` dep while keeping everything else surfaced to the test.
622 const infraLayer = OpenCodeRuntime.OpenCodeRuntimeLive.pipe(
623 Layer.provide(OpenCodeServerLedger.layerTest),
624 Layer.provideMerge(NodeServices.layer),
625 Layer.provideMerge(
626 Layer.mock(CodexInstallation.CodexInstallation)({
627 managedDirectory: "unused-managed-installation",
628 }),
629 ),
630 Layer.provideMerge(
631 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
632 getEnvironmentId: Effect.succeed(
633 EnvironmentId.make("00000000-0000-4000-8000-000000000001"),
634 ),
635 }),
636 ),
637 );
638 const baseLayer = AntigravityInstallation.AntigravityInstallation.layer.pipe(
639 Layer.provideMerge(ServerSecretStore.layer),
640 Layer.provideMerge(
641 ServerConfig.layerTest(process.cwd(), {
642 prefix: "provider-instance-registry-all-drivers-test",
643 }),
644 ),
645 Layer.provideMerge(infraLayer),
646 Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
647 Layer.provideMerge(ServerSettings.layerTest()),
648 Layer.provideMerge(TestHttpClientLive),
649 Layer.provideMerge(ServerSettings.layerTest()),
650 Layer.provideMerge(
651 Layer.succeed(
652 ProviderEventLoggers.ProviderEventLoggers,
653 ProviderEventLoggers.NoOpProviderEventLoggers,
654 ),
655 ),
656 Layer.provideMerge(ModelManifest.layerTest),
657 Layer.provideMerge(ResetCreditCoordinator.layerTest),
658 );
659 const testLayer = ProviderOrchestrationAdapterInfrastructureLive.pipe(
660 Layer.provideMerge(baseLayer),
661 );
662
663 it.live("boots one instance of every shipped driver from a single config map", () =>
664 Effect.gen(function* () {
665 const codexId = ProviderInstanceId.make("codex_default");
666 const claudeId = ProviderInstanceId.make("claude_default");
667 const cursorId = ProviderInstanceId.make("cursor_default");
668 const grokId = ProviderInstanceId.make("grok_default");
669 const openCodeId = ProviderInstanceId.make("opencode_default");
670
671 const codexDriverKind = ProviderDriverKind.make("codex");
672 const claudeDriverKind = ProviderDriverKind.make("claudeAgent");
673 const cursorDriverKind = ProviderDriverKind.make("cursor");
674 const grokDriverKind = ProviderDriverKind.make("grok");
675 const openCodeDriverKind = ProviderDriverKind.make("opencode");
676
677 const configMap: ProviderInstanceConfigMap = {
678 [codexId]: {
679 driver: codexDriverKind,
680 displayName: "Codex",
681 enabled: false,
682 config: makeCodexConfig({ homePath: "/home/julius/.codex" }),
683 },
684 [claudeId]: {
685 driver: claudeDriverKind,
686 displayName: "Claude",
687 enabled: false,
688 config: makeClaudeConfig({
689 homePath: "/home/julius/.claude-work",
690 launchArgs: "--verbose",
691 }),
692 },
693 [cursorId]: {
694 driver: cursorDriverKind,
695 displayName: "Cursor",
696 enabled: false,
697 config: makeCursorConfig({}),
698 },
699 [grokId]: {
700 driver: grokDriverKind,
701 displayName: "Grok",
702 enabled: false,
703 config: makeGrokConfig({}),
704 },
705 [openCodeId]: {
706 driver: openCodeDriverKind,
707 displayName: "OpenCode",
708 enabled: false,
709 config: makeOpenCodeConfig({}),
710 },
711 };
712
713 const { registry } = yield* makeProviderInstanceRegistry<
714 CodexDriverEnv | ClaudeDriverEnv | CursorDriverEnv | GrokDriverEnv | OpenCodeDriverEnv
715 >({
716 drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver],
717 configMap,
718 });
719
720 // Every configured instance must materialize — none downgraded to a
721 // shadow snapshot, because every driver in the map is registered.
722 const unavailable = yield* registry.listUnavailable;
723 expect(unavailable).toEqual([]);
724
725 const instances = yield* registry.listInstances;
726 expect(instances).toHaveLength(5);
727 expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual(
728 [codexId, claudeId, cursorId, grokId, openCodeId].toSorted(),
729 );
730
731 // Instance lookup by id resolves each instance to its own bundle —
732 // this is how rest-of-server routes turn/session calls in the new
733 // model. Each driver's bundle carries its advertised `driverKind`.
734 const codex = yield* registry.getInstance(codexId);
735 const claude = yield* registry.getInstance(claudeId);
736 const cursor = yield* registry.getInstance(cursorId);
737 const grok = yield* registry.getInstance(grokId);
738 const openCode = yield* registry.getInstance(openCodeId);
739 expect(codex?.driverKind).toBe(codexDriverKind);
740 expect(claude?.driverKind).toBe(claudeDriverKind);
741 expect(cursor?.driverKind).toBe(cursorDriverKind);
742 expect(grok?.driverKind).toBe(grokDriverKind);
743 expect(openCode?.driverKind).toBe(openCodeDriverKind);
744 expect(codex?.displayName).toBe("Codex");
745 expect(claude?.displayName).toBe("Claude");
746 expect(cursor?.displayName).toBe("Cursor");
747 expect(grok?.displayName).toBe("Grok");
748 expect(openCode?.displayName).toBe("OpenCode");
749
750 // Every instance owns its own set of closures — no sharing across
751 // drivers. `orchestrationAdapter` / `textGeneration` / `snapshot` are all
752 // distinct references even when two instances happen to share a
753 // trait (e.g. Cursor + others all use a stub-or-real
754 // `textGeneration`; they must still be different object values).
755 const adapters = [
756 codex!.orchestrationAdapter,
757 claude!.orchestrationAdapter,
758 cursor!.orchestrationAdapter,
759 grok!.orchestrationAdapter,
760 openCode!.orchestrationAdapter,
761 ];
762 expect(new Set(adapters).size).toBe(adapters.length);
763 const textGenerations = [
764 codex!.textGeneration,
765 claude!.textGeneration,
766 cursor!.textGeneration,
767 grok!.textGeneration,
768 openCode!.textGeneration,
769 ];
770 expect(new Set(textGenerations).size).toBe(textGenerations.length);
771 const snapshots = [
772 codex!.snapshot,
773 claude!.snapshot,
774 cursor!.snapshot,
775 grok!.snapshot,
776 openCode!.snapshot,
777 ];
778 expect(new Set(snapshots).size).toBe(snapshots.length);
779
780 // Snapshots identify themselves by `instanceId` + `driver` so
781 // downstream aggregation in `ProviderRegistry` can tell instances
782 // apart even when two share a driver. With `enabled: false`, the
783 // check short-circuits and we get a disabled/pending snapshot back
784 // — that's enough signal to validate the stamping wrapper without
785 // spawning real binaries.
786 const codexSnapshot = yield* codex!.snapshot.getSnapshot;
787 expect(codexSnapshot.instanceId).toBe(codexId);
788 expect(codexSnapshot.driver).toBe(codexDriverKind);
789 expect(codexSnapshot.enabled).toBe(false);
790 expect(codexSnapshot.continuation?.groupKey).toBe(
791 `codex:home:${(yield* Path.Path).resolve("/home/julius/.codex")}`,
792 );
793
794 const claudeSnapshot = yield* claude!.snapshot.getSnapshot;
795 expect(claudeSnapshot.instanceId).toBe(claudeId);
796 expect(claudeSnapshot.driver).toBe(claudeDriverKind);
797 expect(claudeSnapshot.enabled).toBe(false);
798 expect(claudeSnapshot.continuation?.groupKey).toBe(
799 `claude:home:${(yield* Path.Path).resolve("/home/julius/.claude-work")}`,
800 );
801
802 const cursorSnapshot = yield* cursor!.snapshot.getSnapshot;
803 expect(cursorSnapshot.instanceId).toBe(cursorId);
804 expect(cursorSnapshot.driver).toBe(cursorDriverKind);
805 expect(cursorSnapshot.enabled).toBe(false);
806 expect(cursorSnapshot.continuation?.groupKey).toBe(
807 `${cursorDriverKind}:instance:${cursorId}`,
808 );
809
810 const grokSnapshot = yield* grok!.snapshot.getSnapshot;
811 expect(grokSnapshot.instanceId).toBe(grokId);
812 expect(grokSnapshot.driver).toBe(grokDriverKind);
813 expect(grokSnapshot.enabled).toBe(false);
814 expect(grokSnapshot.continuation?.groupKey).toBe(`${grokDriverKind}:instance:${grokId}`);
815
816 const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot;
817 expect(openCodeSnapshot.instanceId).toBe(openCodeId);
818 expect(openCodeSnapshot.driver).toBe(openCodeDriverKind);
819 expect(openCodeSnapshot.enabled).toBe(false);
820 expect(openCodeSnapshot.continuation?.groupKey).toBe(
821 `${openCodeDriverKind}:instance:${openCodeId}`,
822 );
823 }).pipe(Effect.provide(testLayer)),
824 );
825});