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

main
ts 4,867 lines 193 KB
Raw
1 import * as CodexErrors from "effect-codex-app-server/errors";
2 import { vi } from "vite-plus/test";
3 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
4 import * as CodexInstallation from "./CodexInstallation.ts";
5 import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts";
6 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
7 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
8 import * as NodeServices from "@effect/platform-node/NodeServices";
9 import type { ModelInfo } from "@anthropic-ai/claude-agent-sdk";
10 import { describe, it, assert, expect } from "@effect/vitest";
11 import * as DateTime from "effect/DateTime";
12 import * as Deferred from "effect/Deferred";
13 import * as Effect from "effect/Effect";
14 import * as Exit from "effect/Exit";
15 import * as Fiber from "effect/Fiber";
16 import * as FileSystem from "effect/FileSystem";
17 import * as Layer from "effect/Layer";
18 import * as Path from "effect/Path";
19 import * as PubSub from "effect/PubSub";
20 import * as Queue from "effect/Queue";
21 import * as Ref from "effect/Ref";
22 import * as Schema from "effect/Schema";
23 import * as Scope from "effect/Scope";
24 import * as Sink from "effect/Sink";
25 import * as Stream from "effect/Stream";
26 import * as TestClock from "effect/testing/TestClock";
27 import {
28 EnvironmentId,
29 ClaudeSettings,
30 CodexSettings,
31 DEFAULT_SERVER_SETTINGS,
32 PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS,
33 ProviderDriverKind,
34 ProviderInstanceId,
35 ServerSettings,
36 ServerSettingsError,
37 ServerProvider,
38 type ServerProviderSlashCommand,
39 type ServerProviderUpdateState,
40 type ServerProviderVersionAdvisoryStatus,
41 type ServerSettings as ContractServerSettings,
42 } from "@t3tools/contracts";
43 import { HttpClient, HttpClientResponse } from "effect/http";
44 import { ChildProcessSpawner } from "effect/process";
45 import * as HostProcess from "@t3tools/shared/HostProcess";
46 import { WindowsShellEnvironment } from "@t3tools/shared/shell";
47 import { deepMerge } from "@t3tools/shared/Struct";
48 import { createModelCapabilities } from "@t3tools/shared/model";
49 import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
50
51 import {
52 checkCodexProviderStatus,
53 mapCodexModelCapabilities,
54 type CodexAppServerProviderSnapshot,
55 } from "./CodexProvider.ts";
56 import { BUNDLED_CLAUDE_MODEL_CATALOG } from "./ClaudeModelCatalog.ts";
57 import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
58 import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
59 import * as AntigravityInstallation from "./AntigravityInstallation.ts";
60 import * as ModelManifest from "./ModelManifest.ts";
61 import { applyProviderCompatibility } from "./providerCompatibility.ts";
62 import * as ResetCreditCoordinator from "./resetCreditCoordinator.ts";
63 import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
64 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
65 import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime";
66 import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger";
67 import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
68 import * as ProviderInstallationGate from "./ProviderInstallationGate.ts";
69 import * as ProviderInstanceRegistryHydration from "./ProviderInstanceRegistryHydration.ts";
70 import * as PortScanner from "../preview/PortScanner.ts";
71 import * as ServerConfig from "../config.ts";
72 import * as ServerSettingsModule from "../serverSettings.ts";
73 import * as SqlitePersistence from "../persistence/Sqlite.ts";
74 import {
75 readProviderStatusCache,
76 resolveProviderStatusCachePath,
77 writeProviderStatusCache,
78 } from "./providerStatusCache.ts";
79 import { COMPACT_SLASH_COMMAND } from "@t3tools/provider-core/server/snapshotProbe";
80 import type {
81 ProviderInstance,
82 ProviderWorkspaceSnapshot,
83 } from "@t3tools/provider-core/server/driver";
84 import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts";
85 import * as ProviderInstanceRegistryMutator from "./ProviderInstanceRegistryMutator.ts";
86 import * as ProviderRegistry from "./ProviderRegistry.ts";
87 import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
88 import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
89 import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver";
90 vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
91
92 const decodeServerProvider = Schema.decodeSync(ServerProvider);
93 const encodeServerProvider = Schema.encodeSync(ServerProvider);
94 const decodeServerSettings = Schema.decodeSync(ServerSettings);
95 const encodeServerSettings = Schema.encodeSync(ServerSettings);
96 const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS);
97
98 const disabledDefaultSlots = (
99 ...drivers: ReadonlyArray<string>
100 ): ContractServerSettings["providerInstances"] =>
101 Object.fromEntries(
102 drivers.map((driver) => [
103 ProviderInstanceId.make(driver),
104 { driver: ProviderDriverKind.make(driver), enabled: false },
105 ]),
106 );
107
108 const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});
109 const decodeCodexSettings = Schema.decodeSync(CodexSettings);
110 const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});
111
112 process.env.T3CODE_CURSOR_ENABLED = "1";
113
114 const encoder = new TextEncoder();
115 const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
116 const withBundledCompatibility = (snapshot: ServerProvider) =>
117 applyProviderCompatibility(
118 snapshot,
119 undefined,
120 ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility,
121 );
122
123 const layerUnusedMutator = Layer.mock(
124 ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator,
125 )({});
126
127 const layerTestHttpClient = Layer.succeed(
128 HttpClient.HttpClient,
129 HttpClient.make((request) =>
130 Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))),
131 ),
132 ).pipe(Layer.provideMerge(ModelManifest.layerTest));
133
134 const layerBackgroundPolicyAlwaysRun = Layer.mock(BackgroundPolicy.BackgroundPolicy)({
135 reportClientActivity: () => Effect.void,
136 removeRpcClient: () => Effect.void,
137 snapshot: Effect.succeed({
138 hostPower: {
139 source: "unknown",
140 idle: "unknown",
141 idleSeconds: null,
142 locked: "unknown",
143 suspended: false,
144 onBattery: "unknown",
145 lowPowerMode: "unknown",
146 thermalState: "unknown",
147 stale: true,
148 updatedAt: TEST_EPOCH,
149 },
150 leases: [],
151 activeForegroundLeaseCount: 0,
152 activeScopeKeys: [],
153 shouldRunOpportunisticWork: true,
154 updatedAt: TEST_EPOCH,
155 }),
156 shouldRunScopeWork: () => Effect.succeed(true),
157 shouldRunOpportunisticWork: Effect.succeed(true),
158 });
159
160 const makeWorkspaceRescanHarness = Effect.gen(function* () {
161 const instanceId = ProviderInstanceId.make("claude");
162 const driver = ProviderDriverKind.make("claudeCode");
163 const provider = {
164 instanceId,
165 driver,
166 status: "ready",
167 enabled: true,
168 installed: true,
169 auth: { status: "authenticated" },
170 checkedAt: "1970-01-01T00:00:00.000Z",
171 version: "1.0.0",
172 models: [],
173 slashCommands: [],
174 skills: [],
175 } as const satisfies ServerProvider;
176 const scans = yield* Queue.unbounded<{
177 readonly cwd: string;
178 readonly result: Deferred.Deferred<ProviderWorkspaceSnapshot>;
179 }>();
180 const makeInstance = Effect.gen(function* () {
181 const rescans = yield* Queue.unbounded<string>();
182 const reports = yield* Queue.unbounded<string>();
183 const instance: ProviderInstance = {
184 instanceId,
185 driverKind: driver,
186 continuationIdentity: { driverKind: driver, continuationKey: "claude:rescan-test" },
187 displayName: undefined,
188 enabled: true,
189 snapshot: {
190 resolveMaintenance: () =>
191 Effect.succeed(
192 makeManualOnlyProviderMaintenanceCapabilities({
193 provider: driver,
194 packageName: null,
195 }),
196 ),
197 getSnapshot: Effect.succeed(provider),
198 refresh: Effect.succeed(provider),
199 streamChanges: Stream.empty,
200 applyUsageLimits: () => Effect.void,
201 },
202 // A pull-based stream pulls the next report only after the registry queued the last.
203 workspaceRescans: Stream.fromQueue(rescans).pipe(
204 Stream.tap((cwd) => Queue.offer(reports, cwd)),
205 ),
206 snapshotForCwd: (cwd) =>
207 Effect.gen(function* () {
208 const result = yield* Deferred.make<ProviderWorkspaceSnapshot>();
209 yield* Queue.offer(scans, { cwd, result });
210 return yield* Deferred.await(result);
211 }),
212 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
213 textGeneration: {} as ProviderInstance["textGeneration"],
214 };
215 return { instance, rescans, reports };
216 });
217 const first = yield* makeInstance;
218 const instances = yield* Ref.make([first.instance]);
219 const changes = yield* PubSub.unbounded<void>();
220 const scope = yield* Scope.make();
221 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
222 const services = yield* Layer.build(
223 ProviderRegistry.layer.pipe(
224 Layer.provide(layerUnusedMutator),
225 Layer.provideMerge(
226 Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, {
227 getInstance: (id) =>
228 Ref.get(instances).pipe(Effect.map((all) => all.find((i) => i.instanceId === id))),
229 listInstances: Ref.get(instances),
230 listUnavailable: Effect.succeed([]),
231 streamChanges: Stream.fromPubSub(changes),
232 subscribeChanges: PubSub.subscribe(changes),
233 }),
234 ),
235 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-workspace-rescan-" })),
236 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
237 ),
238 ).pipe(Scope.provide(scope));
239 const registry = yield* ProviderRegistry.ProviderRegistry.pipe(Effect.provide(services));
240 const snapshot = (name: string): ProviderWorkspaceSnapshot => ({
241 ...provider,
242 skills: [{ name, path: `/workspace/${name}/SKILL.md`, enabled: true }],
243 });
244 const nextScan = Effect.fnUntraced(function* (cwd: string) {
245 const scan = yield* Queue.take(scans);
246 assert.equal(scan.cwd, cwd);
247 return (name: string) => Deferred.succeed(scan.result, snapshot(name));
248 });
249 const refresh = (cwd: string, fresh = false) =>
250 registry.refreshWorkspaceSnapshot({ instanceId, cwd, fresh });
251 const seed = Effect.fnUntraced(function* (cwd: string) {
252 const pending = yield* refresh(cwd).pipe(Effect.forkChild);
253 const complete = yield* nextScan(cwd);
254 yield* complete("initial");
255 yield* Fiber.join(pending);
256 });
257 // A later requested cwd reaching the serial consumer proves the previous rescan settled,
258 // including when that rescan correctly publishes no change. Seed "/barrier" first; it rescans
259 // to the skills it was seeded with, so it never stamps workspaceRescannedAt.
260 const drainRescans = Effect.gen(function* () {
261 yield* Queue.offer(first.rescans, "/barrier");
262 const complete = yield* nextScan("/barrier");
263 yield* complete("initial");
264 });
265 const skillsOf = (cwd: string) =>
266 Effect.map(registry.getProviders, (providers) =>
267 providers[0]?.workspaceSnapshots?.find((s) => s.cwd === cwd)?.skills?.map((s) => s.name),
268 );
269 const rescannedAtOf = Effect.map(
270 registry.getProviders,
271 (providers) => providers[0]?.workspaceRescannedAt,
272 );
273 return {
274 first,
275 makeInstance,
276 instances,
277 changes,
278 registry,
279 scans,
280 nextScan,
281 refresh,
282 seed,
283 drainRescans,
284 skillsOf,
285 rescannedAtOf,
286 };
287 });
288
289 function selectDescriptor(
290 id: string,
291 label: string,
292 options: ReadonlyArray<{ id: string; label: string; isDefault?: boolean }>,
293 ) {
294 return {
295 id,
296 label,
297 type: "select" as const,
298 options: [...options],
299 ...(options.find((option) => option.isDefault)?.id
300 ? { currentValue: options.find((option) => option.isDefault)?.id }
301 : {}),
302 };
303 }
304
305 function booleanDescriptor(id: string, label: string) {
306 return {
307 id,
308 label,
309 type: "boolean" as const,
310 };
311 }
312
313 type TestClaudeCapabilities = {
314 readonly email: string | undefined;
315 readonly subscriptionType: string | undefined;
316 readonly tokenSource: string | undefined;
317 readonly apiKeySource: string | undefined;
318 readonly apiProvider: string | undefined;
319 readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;
320 readonly models?: ReadonlyArray<ModelInfo>;
321 };
322
323 function claudeCapabilities(overrides: Partial<TestClaudeCapabilities> = {}) {
324 return () =>
325 Effect.succeed({
326 email: undefined,
327 subscriptionType: undefined,
328 tokenSource: undefined,
329 apiKeySource: undefined,
330 apiProvider: undefined,
331 slashCommands: [],
332 ...overrides,
333 });
334 }
335
336 function mockHandle(result: { stdout: string; stderr: string; code: number }) {
337 return ChildProcessSpawner.makeHandle({
338 pid: ChildProcessSpawner.ProcessId(1),
339 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
340 isRunning: Effect.succeed(false),
341 kill: () => Effect.void,
342 unref: Effect.succeed(Effect.void),
343 stdin: Sink.drain,
344 stdout: Stream.make(encoder.encode(result.stdout)),
345 stderr: Stream.make(encoder.encode(result.stderr)),
346 all: Stream.empty,
347 getInputFd: () => Sink.drain,
348 getOutputFd: () => Stream.empty,
349 });
350 }
351
352 function layerMockSpawner(
353 handler: (args: ReadonlyArray<string>) => {
354 stdout: string;
355 stderr: string;
356 code: number;
357 },
358 ) {
359 return Layer.succeed(
360 ChildProcessSpawner.ChildProcessSpawner,
361 ChildProcessSpawner.make((command) => {
362 const cmd = command as unknown as { args: ReadonlyArray<string> };
363 return Effect.succeed(mockHandle(handler(cmd.args)));
364 }),
365 );
366 }
367
368 // A Codex CLI on disk whose `app-server` and `--version` behave as `script` says.
369 const writeFakeCodexCli = Effect.fn("writeFakeCodexCli")(function* (script: string) {
370 const fs = yield* FileSystem.FileSystem;
371 const path = yield* Path.Path;
372 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-fake-codex-" });
373 const binaryPath = path.join(directory, "codex");
374 yield* fs.writeFileString(binaryPath, `#!/bin/sh\n${script}\n`);
375 yield* fs.chmod(binaryPath, 0o755);
376 return { directory, binaryPath };
377 });
378
379 // The npm `@openai/codex` 0.1 CLI treats `app-server` as a prompt and exits 1.
380 const OBSOLETE_CODEX_APP_SERVER = `echo "Missing OpenAI API key." >&2; exit 1`;
381
382 const codexModelCapabilities = createModelCapabilities({
383 optionDescriptors: [
384 selectDescriptor("reasoningEffort", "Reasoning", [
385 { id: "high", label: "High", isDefault: true },
386 { id: "low", label: "Low" },
387 ]),
388 booleanDescriptor("fastMode", "Fast Mode"),
389 ],
390 }) satisfies NonNullable<ServerProvider["models"][number]["capabilities"]>;
391
392 function makeCodexProbeSnapshot(
393 input: Partial<CodexAppServerProviderSnapshot> = {},
394 ): CodexAppServerProviderSnapshot {
395 return {
396 version: "1.0.0",
397 account: {
398 account: {
399 type: "chatgpt",
400 email: "test@example.com",
401 planType: "pro",
402 },
403 requiresOpenaiAuth: false,
404 },
405 models: [
406 {
407 slug: "gpt-live-codex",
408 name: "GPT Live Codex",
409 isCustom: false,
410 capabilities: codexModelCapabilities,
411 },
412 ],
413 skills: [],
414 ...input,
415 };
416 }
417
418 function makeMutableServerSettingsService(
419 initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS,
420 ) {
421 return Effect.gen(function* () {
422 const settingsRef = yield* Ref.make(initial);
423 const changes = yield* PubSub.unbounded<ContractServerSettings>();
424
425 return {
426 start: Effect.void,
427 ready: Effect.void,
428 getSettings: Ref.get(settingsRef),
429 updateSettings: (patch) =>
430 Effect.gen(function* () {
431 const current = yield* Ref.get(settingsRef);
432 const next = applyServerSettingsPatch(current, patch);
433 encodeServerSettings(next);
434 yield* Ref.set(settingsRef, next);
435 yield* PubSub.publish(changes, next);
436 return next;
437 }),
438 updateProviderInstance: (mutation, patch = {}) =>
439 Effect.gen(function* () {
440 const current = yield* Ref.get(settingsRef);
441 const next = ServerSettingsModule.applyProviderInstanceMutation(
442 applyServerSettingsPatch(current, patch),
443 mutation,
444 );
445 encodeServerSettings(next);
446 yield* Ref.set(settingsRef, next);
447 yield* PubSub.publish(changes, next);
448 return next;
449 }),
450 withSettingsSnapshot: (use) => Ref.get(settingsRef).pipe(Effect.flatMap(use)),
451 get streamChanges() {
452 return Stream.fromPubSub(changes);
453 },
454 get subscribeChanges() {
455 return PubSub.subscribe(changes).pipe(
456 Effect.map((subscription) => Stream.fromSubscription(subscription)),
457 );
458 },
459 } satisfies ServerSettingsModule.ServerSettingsService["Service"];
460 });
461 }
462
463 const awaitPersistedProvider = (
464 registry: ProviderRegistry.ProviderRegistry["Service"],
465 checkedAt: string,
466 ) =>
467 registry.streamChanges.pipe(
468 Stream.filter((providers) => providers.some((provider) => provider.checkedAt === checkedAt)),
469 Stream.take(1),
470 Stream.runDrain,
471 Effect.forkScoped,
472 );
473
474 const codexUpdateSnapshot = (advisory: ServerProviderVersionAdvisoryStatus) =>
475 ({
476 instanceId: ProviderInstanceId.make("codex"),
477 driver: ProviderDriverKind.make("codex"),
478 status: "ready",
479 enabled: true,
480 installed: true,
481 auth: { status: "authenticated" },
482 checkedAt: "2026-06-10T00:00:00.000Z",
483 version: "1.0.0",
484 models: [],
485 slashCommands: [],
486 skills: [],
487 versionAdvisory: {
488 status: advisory,
489 currentVersion: "1.0.0",
490 latestVersion: advisory === "unknown" ? null : advisory === "current" ? "1.0.0" : "2.0.0",
491 updateCommand: null,
492 canUpdate: true,
493 checkedAt: "2026-06-10T00:00:00.000Z",
494 message: null,
495 },
496 }) as const satisfies ServerProvider;
497
498 const makeUpdateState = (status: ServerProviderUpdateState["status"]) =>
499 ({
500 status,
501 startedAt: "2026-06-10T00:00:00.000Z",
502 finishedAt: status === "queued" || status === "running" ? null : "2026-06-10T00:01:00.000Z",
503 message: `update ${status}`,
504 output: null,
505 }) satisfies ServerProviderUpdateState;
506
507 // One Codex instance whose probe returns whatever `snapshot` currently holds.
508 const buildRegistryOverSnapshot = Effect.fn("buildRegistryOverSnapshot")(function* (
509 snapshot: Ref.Ref<ServerProvider>,
510 ) {
511 const driver = ProviderDriverKind.make("codex");
512 const instance = {
513 instanceId: ProviderInstanceId.make("codex"),
514 driverKind: driver,
515 continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" },
516 displayName: undefined,
517 enabled: true,
518 snapshot: {
519 resolveMaintenance: () =>
520 Effect.succeed(
521 makeManualOnlyProviderMaintenanceCapabilities({ provider: driver, packageName: null }),
522 ),
523 getSnapshot: Ref.get(snapshot),
524 refresh: Ref.get(snapshot),
525 streamChanges: Stream.empty,
526 applyUsageLimits: () => Effect.void,
527 },
528 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
529 textGeneration: {} as ProviderInstance["textGeneration"],
530 } satisfies ProviderInstance;
531 const layerInstanceRegistry = Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, {
532 getInstance: (instanceId) =>
533 Effect.succeed(instanceId === instance.instanceId ? instance : undefined),
534 listInstances: Effect.succeed([instance]),
535 listUnavailable: Effect.succeed([]),
536 streamChanges: Stream.empty,
537 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
538 });
539 const scope = yield* Scope.make();
540 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
541 return yield* Layer.build(
542 ProviderRegistry.layer.pipe(
543 Layer.provide(layerUnusedMutator),
544 Layer.provideMerge(layerInstanceRegistry),
545 Layer.provideMerge(
546 ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-update-state-" }),
547 ),
548 Layer.provideMerge(layerBackgroundPolicyAlwaysRun),
549 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
550 ),
551 ).pipe(Scope.provide(scope));
552 });
553
554 const layerTestNodeServices = Layer.mergeAll(
555 ProviderLatestVersions.layer,
556 NodeServices.layer,
557 NodeCrypto.layer,
558 Layer.mock(CodexManagedTokenBroker.CodexManagedTokenBroker)({
559 endpoint: Effect.succeed("unused-private-pipe"),
560 }),
561 Layer.mock(CodexInstallation.CodexInstallation)({
562 managedDirectory: "unused-managed-installation",
563 }),
564 Layer.mock(ServerSecretStore.ServerSecretStore)({}),
565 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
566 getEnvironmentId: Effect.succeed(EnvironmentId.make("00000000-0000-4000-8000-000000000001")),
567 }),
568 // An empty home, so the developer's own Claude settings never reach provider probes.
569 Layer.effect(
570 HostProcess.HomeDirectory,
571 Effect.gen(function* () {
572 return yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped();
573 }),
574 ).pipe(Layer.provide(NodeServices.layer)),
575 );
576
577 it.layer(
578 Layer.mergeAll(layerTestNodeServices, ServerSettingsModule.layerTest(), layerTestHttpClient),
579 )("ProviderRegistry", (it) => {
580 describe("checkCodexProviderStatus", () => {
581 it.effect("uses the app-server account and model list for provider status", () =>
582 Effect.gen(function* () {
583 const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>
584 Effect.succeed(
585 makeCodexProbeSnapshot({
586 skills: [
587 {
588 name: "github:gh-fix-ci",
589 path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
590 enabled: true,
591 displayName: "CI Debug",
592 shortDescription: "Debug failing GitHub Actions checks",
593 },
594 ],
595 }),
596 ),
597 );
598 assert.strictEqual(status.status, "ready");
599 assert.strictEqual(status.installed, true);
600 assert.strictEqual(status.version, "1.0.0");
601 assert.strictEqual(status.auth.status, "authenticated");
602 assert.strictEqual(status.auth.type, "chatgpt");
603 assert.strictEqual(status.auth.label, "ChatGPT Pro 200 Subscription");
604 assert.strictEqual(status.auth.email, "test@example.com");
605 assert.deepStrictEqual(status.setup, { canAuthenticate: false, canInstall: false });
606 assert.deepStrictEqual(status.models, [
607 {
608 slug: "gpt-live-codex",
609 name: "GPT Live Codex",
610 isCustom: false,
611 capabilities: codexModelCapabilities,
612 },
613 ]);
614 assert.deepStrictEqual(status.skills, [
615 {
616 name: "github:gh-fix-ci",
617 path: "/Users/test/.codex/skills/gh-fix-ci/SKILL.md",
618 enabled: true,
619 displayName: "CI Debug",
620 shortDescription: "Debug failing GitHub Actions checks",
621 },
622 ]);
623 assert.deepStrictEqual(status.slashCommands.slice(1), [
624 {
625 name: "goal",
626 description: "Set a goal Codex keeps working toward until it is done",
627 input: { hint: "Objective, or pause, resume, clear" },
628 },
629 {
630 name: "feedback",
631 description: "Send this thread and Codex logs to OpenAI",
632 input: { hint: "Describe the issue (optional)" },
633 },
634 ]);
635 }),
636 );
637
638 it.effect("allows a slow successful Codex probe with a configured budget", () =>
639 Effect.gen(function* () {
640 const fiber = yield* checkCodexProviderStatus(
641 defaultCodexSettings,
642 () => Effect.sleep("22 seconds").pipe(Effect.as(makeCodexProbeSnapshot())),
643 { T3CODE_CODEX_PROBE_TIMEOUT_MS: "60000" },
644 ).pipe(Effect.forkChild);
645 yield* TestClock.adjust("22 seconds");
646 const status = yield* Fiber.join(fiber);
647 assert.strictEqual(status.status, "ready");
648 assert.strictEqual(status.auth.status, "authenticated");
649 }),
650 );
651
652 it.effect("labels the plan the usage read reports over the cached login plan", () =>
653 Effect.gen(function* () {
654 const statusWithUsagePlan = (planType: string | null) =>
655 checkCodexProviderStatus(defaultCodexSettings, () =>
656 Effect.succeed(
657 makeCodexProbeSnapshot({
658 rateLimits: { snapshot: { planType }, resetCredits: null },
659 }),
660 ),
661 );
662
663 const downgraded = yield* statusWithUsagePlan("free");
664 assert.strictEqual(downgraded.auth.label, "ChatGPT Free Subscription");
665
666 const unreported = yield* statusWithUsagePlan(null);
667 assert.strictEqual(unreported.auth.label, "ChatGPT Pro 200 Subscription");
668
669 const unknown = yield* statusWithUsagePlan("unknown");
670 assert.strictEqual(unknown.auth.label, "ChatGPT Pro 200 Subscription");
671 }),
672 );
673
674 it.effect("returns unauthenticated when app-server requires OpenAI auth", () =>
675 Effect.gen(function* () {
676 const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>
677 Effect.succeed(
678 makeCodexProbeSnapshot({
679 account: {
680 account: null,
681 requiresOpenaiAuth: true,
682 },
683 }),
684 ),
685 );
686
687 assert.strictEqual(status.status, "error");
688 assert.strictEqual(status.auth.status, "unauthenticated");
689 assert.strictEqual(
690 status.message,
691 "Codex CLI is not authenticated. Run `codex login` and try again.",
692 );
693 assert.deepStrictEqual(status.usageLimits?.unavailable, {
694 reason: "probeFailed",
695 message: "Codex CLI is not authenticated. Run `codex login` and try again.",
696 });
697 }),
698 );
699
700 it.effect("names the instance's CODEX_HOME in the sign-in hint for a custom home", () =>
701 Effect.gen(function* () {
702 const homePath = "/srv/codex-work-home";
703 const status = yield* checkCodexProviderStatus(
704 decodeCodexSettings({ binaryPath: "codex", homePath }),
705 () =>
706 Effect.succeed(
707 makeCodexProbeSnapshot({
708 account: { account: null, requiresOpenaiAuth: true },
709 }),
710 ),
711 );
712
713 assert.strictEqual(status.auth.status, "unauthenticated");
714 assert.include(status.message ?? "", "CODEX_HOME");
715 assert.include(status.message ?? "", homePath);
716 }),
717 );
718
719 it.effect("returns ready with unknown auth when app-server does not require OpenAI auth", () =>
720 Effect.gen(function* () {
721 const status = yield* checkCodexProviderStatus(defaultCodexSettings, () =>
722 Effect.succeed(
723 makeCodexProbeSnapshot({
724 account: {
725 account: null,
726 requiresOpenaiAuth: false,
727 },
728 }),
729 ),
730 );
731
732 assert.strictEqual(status.status, "ready");
733 assert.strictEqual(status.auth.status, "unknown");
734 }),
735 );
736
737 it.effect("offers cyber access only on catalog models that advertise it", () =>
738 Effect.gen(function* () {
739 const catalogModel = (slug: string, cyber?: Array<"standard" | "daybreakBlue">) => ({
740 slug,
741 name: slug,
742 isCustom: false,
743 capabilities: mapCodexModelCapabilities({
744 additionalSpeedTiers: [],
745 ...(cyber ? { availableAccessPrograms: { cyber } } : {}),
746 defaultReasoningEffort: "medium",
747 description: slug,
748 displayName: slug,
749 hidden: false,
750 id: slug,
751 isDefault: false,
752 model: slug,
753 supportedReasoningEfforts: [],
754 }),
755 });
756 const defaultPrograms = (snapshot: Partial<CodexAppServerProviderSnapshot>) =>
757 checkCodexProviderStatus(decodeCodexSettings({ customModels: ["my-model"] }), () =>
758 Effect.succeed(
759 makeCodexProbeSnapshot({
760 models: [
761 catalogModel("both", ["standard", "daybreakBlue"]),
762 catalogModel("daybreak-only", ["daybreakBlue"]),
763 catalogModel("plain"),
764 ],
765 ...snapshot,
766 }),
767 ),
768 ).pipe(
769 Effect.map((status) =>
770 Object.fromEntries(
771 status.models.map((model) => {
772 const descriptor = model.capabilities?.optionDescriptors?.find(
773 (option) => option.id === "cyberAccessProgram",
774 );
775 return [
776 model.slug,
777 descriptor?.type === "select"
778 ? (descriptor.currentValue ?? "no default")
779 : null,
780 ];
781 }),
782 ),
783 ),
784 );
785
786 assert.deepStrictEqual(yield* defaultPrograms({ daybreakEnabled: false }), {
787 both: "standard",
788 "daybreak-only": "daybreakBlue",
789 plain: null,
790 "my-model": null,
791 });
792 assert.deepStrictEqual(yield* defaultPrograms({ daybreakEnabled: true }), {
793 both: "daybreakBlue",
794 "daybreak-only": "daybreakBlue",
795 plain: null,
796 "my-model": null,
797 });
798 // An unread config keeps the choice but cannot know Codex's default.
799 assert.deepStrictEqual(yield* defaultPrograms({}), {
800 both: "no default",
801 "daybreak-only": "no default",
802 plain: null,
803 "my-model": null,
804 });
805 assert.deepStrictEqual(
806 yield* defaultPrograms({
807 account: { account: { type: "apiKey" }, requiresOpenaiAuth: false },
808 cyberAccessProgramsUnavailable: true,
809 }),
810 { both: null, "daybreak-only": null, plain: null, "my-model": null },
811 );
812 }),
813 );
814
815 it.effect("reads the version of a Codex CLI too old to run app-server (#20351)", () =>
816 Effect.gen(function* () {
817 if ((yield* HostProcess.Platform) === "win32") return;
818 const codexHome = yield* FileSystem.FileSystem.pipe(
819 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-codex-home-" })),
820 );
821 const { binaryPath } = yield* writeFakeCodexCli(
822 [
823 `if [ "$1" = "--version" ]; then`,
824 // The fallback runs with the provider's environment and CODEX_HOME.
825 ` [ "$CODEX_HOME" = "${codexHome}" ] && [ "$FAKE_CODEX_ENV" = "kept" ] || exit 2`,
826 ` echo 0.1.4161006; exit 0`,
827 `fi`,
828 OBSOLETE_CODEX_APP_SERVER,
829 ].join("\n"),
830 );
831 const settings = decodeCodexSettings({ binaryPath, homePath: codexHome });
832
833 const status = yield* checkCodexProviderStatus(settings, undefined, {
834 ...process.env,
835 FAKE_CODEX_ENV: "kept",
836 });
837
838 assert.strictEqual(status.status, "error");
839 assert.strictEqual(status.installed, true);
840 assert.strictEqual(status.version, "0.1.4161006");
841 assert.match(status.message ?? "", /^Codex app-server provider probe failed: /);
842 const classified = withBundledCompatibility({
843 ...status,
844 instanceId: ProviderInstanceId.make("codex"),
845 driver: ProviderDriverKind.make("codex"),
846 });
847 assert.strictEqual(classified.compatibilityAdvisory?.status, "broken");
848 }),
849 );
850
851 it.effect("keeps a prerelease --version unclassified instead of reading it as stable", () =>
852 Effect.gen(function* () {
853 if ((yield* HostProcess.Platform) === "win32") return;
854 const { binaryPath } = yield* writeFakeCodexCli(
855 [
856 `[ "$1" = "--version" ] && { echo "codex-cli 0.159.0-alpha.1"; exit 0; }`,
857 OBSOLETE_CODEX_APP_SERVER,
858 ].join("\n"),
859 );
860
861 const status = yield* checkCodexProviderStatus(decodeCodexSettings({ binaryPath }));
862
863 assert.strictEqual(status.version, "0.159.0-alpha.1");
864 const classified = withBundledCompatibility({
865 ...status,
866 instanceId: ProviderInstanceId.make("codex"),
867 driver: ProviderDriverKind.make("codex"),
868 });
869 assert.strictEqual(classified.compatibilityAdvisory?.status, "unknown");
870 }),
871 );
872
873 it.effect("keeps the probe failure without a version when --version also fails", () =>
874 Effect.gen(function* () {
875 if ((yield* HostProcess.Platform) === "win32") return;
876 const { binaryPath } = yield* writeFakeCodexCli(
877 [
878 `[ "$1" = "--version" ] && { echo "codex 0.1.0" >&2; exit 3; }`,
879 OBSOLETE_CODEX_APP_SERVER,
880 ].join("\n"),
881 );
882
883 const status = yield* checkCodexProviderStatus(decodeCodexSettings({ binaryPath }));
884
885 assert.strictEqual(status.status, "error");
886 assert.strictEqual(status.installed, true);
887 assert.strictEqual(status.version, null);
888 assert.match(status.message ?? "", /^Codex app-server provider probe failed: /);
889 }),
890 );
891
892 it.effect("bounds a hanging Codex --version fallback and releases its process scope", () =>
893 Effect.gen(function* () {
894 const started = yield* Deferred.make<void>();
895 const released = yield* Deferred.make<void>();
896 const spawner = ChildProcessSpawner.make(() =>
897 Effect.gen(function* () {
898 yield* Effect.addFinalizer(() => Deferred.succeed(released, undefined));
899 return ChildProcessSpawner.makeHandle({
900 ...mockHandle({ stdout: "", stderr: "", code: 0 }),
901 exitCode: Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)),
902 });
903 }),
904 );
905 const fiber = yield* checkCodexProviderStatus(defaultCodexSettings, () =>
906 Effect.fail(new CodexErrors.CodexAppServerProcessExitedError({ code: 1 })),
907 ).pipe(
908 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
909 Effect.forkChild,
910 );
911 yield* Deferred.await(started);
912 yield* TestClock.adjust("4 seconds");
913 const status = yield* Fiber.join(fiber);
914 assert.strictEqual(status.version, null);
915 assert.strictEqual(status.status, "error");
916 assert.strictEqual(status.installed, true);
917 assert.match(status.message ?? "", /^Codex app-server provider probe failed: /);
918 assert.isTrue(yield* Deferred.isDone(released));
919 }),
920 );
921
922 it.effect("shows Codex usage that answers after three seconds inside the probe budget", () =>
923 Effect.gen(function* () {
924 const usageRequested = yield* Deferred.make<void>();
925 const spawner = ChildProcessSpawner.make(() =>
926 Effect.gen(function* () {
927 const scope = yield* Effect.scope;
928 const output = yield* Queue.unbounded<Uint8Array>();
929 const send = (message: unknown) =>
930 Queue.offer(output, encoder.encode(`${JSON.stringify(message)}\n`));
931 const results: Record<string, unknown> = {
932 initialize: {
933 userAgent: "codex_cli_rs/0.167.0",
934 codexHome: "/nonexistent-codex-home",
935 platformFamily: "unix",
936 platformOs: "linux",
937 },
938 "account/read": {
939 account: { type: "chatgpt", email: "test@example.com", planType: "pro" },
940 requiresOpenaiAuth: true,
941 },
942 "config/read": { config: {}, origins: {} },
943 "skills/list": { data: [] },
944 "model/list": { data: [] },
945 };
946 const answer = (line: string) => {
947 const { id, method } = JSON.parse(line) as { id?: number; method?: string };
948 if (id === undefined || method === undefined) return Effect.void;
949 if (method !== "account/rateLimits/read") {
950 return send({ id, result: results[method] ?? {} });
951 }
952 return Deferred.succeed(usageRequested, undefined).pipe(
953 Effect.andThen(Effect.sleep("4 seconds")),
954 Effect.andThen(
955 send({
956 id,
957 result: {
958 rateLimits: {
959 limitId: "codex",
960 planType: "pro",
961 primary: { usedPercent: 42, windowDurationMins: 300, resetsAt: 2e9 },
962 },
963 rateLimitsByLimitId: null,
964 rateLimitResetCredits: null,
965 accountId: null,
966 },
967 }),
968 ),
969 Effect.forkIn(scope),
970 );
971 };
972 const decoder = new TextDecoder();
973 let buffered = "";
974 return ChildProcessSpawner.makeHandle({
975 ...mockHandle({ stdout: "", stderr: "", code: 0 }),
976 exitCode: Effect.never,
977 isRunning: Effect.succeed(true),
978 stdin: Sink.forEach((chunk: Uint8Array) => {
979 buffered += decoder.decode(chunk, { stream: true });
980 const lines = buffered.split("\n");
981 buffered = lines.pop() ?? "";
982 return Effect.forEach(lines.filter(Boolean), answer, { discard: true });
983 }),
984 stdout: Stream.fromQueue(output),
985 });
986 }),
987 );
988 const fiber = yield* checkCodexProviderStatus(defaultCodexSettings).pipe(
989 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
990 Effect.forkChild,
991 );
992 yield* Deferred.await(usageRequested);
993 yield* TestClock.adjust("25 seconds");
994 const status = yield* Fiber.join(fiber);
995
996 assert.strictEqual(status.auth.status, "authenticated");
997 assert.isUndefined(status.usageLimits?.unavailable);
998 assert.strictEqual(status.usageLimits?.windows[0]?.usedPercent, 42);
999 }),
1000 );
1001
1002 it.effect("does not run --version when the Codex executable cannot start", () =>
1003 Effect.gen(function* () {
1004 if ((yield* HostProcess.Platform) === "win32") return;
1005 const fs = yield* FileSystem.FileSystem;
1006 const path = yield* Path.Path;
1007 const { directory, binaryPath } = yield* writeFakeCodexCli(
1008 `touch "$(dirname "$0")/ran"; echo 0.1.4161006`,
1009 );
1010
1011 const status = yield* checkCodexProviderStatus(decodeCodexSettings({ binaryPath }), () =>
1012 Effect.fail(
1013 new CodexErrors.CodexAppServerSpawnError({
1014 command: `${binaryPath} app-server`,
1015 cause: new Error("spawn ENOENT"),
1016 }),
1017 ),
1018 );
1019
1020 assert.strictEqual(status.installed, false);
1021 assert.strictEqual(status.version, null);
1022 assert.isFalse(yield* fs.exists(path.join(directory, "ran")));
1023 }),
1024 );
1025 });
1026
1027 describe("ProviderRegistry.layer", () => {
1028 it("marks folder catalogs pending when a machine refresh changes the machine models", () => {
1029 const machineModel = {
1030 slug: "opencode/big-pickle",
1031 name: "Big Pickle",
1032 isCustom: false,
1033 capabilities: null,
1034 } satisfies ServerProvider["models"][number];
1035 const projectModel = { ...machineModel, slug: "uni/medium-gpt", name: "Medium GPT" };
1036 const addedModel = { ...machineModel, slug: "opencode/new", name: "New" };
1037 const provider = {
1038 instanceId: ProviderInstanceId.make("opencode"),
1039 driver: ProviderDriverKind.make("opencode"),
1040 status: "ready",
1041 enabled: true,
1042 installed: true,
1043 auth: { status: "authenticated" },
1044 checkedAt: "2026-03-25T00:00:00.000Z",
1045 version: "2.0.0",
1046 models: [machineModel],
1047 slashCommands: [],
1048 skills: [],
1049 } satisfies ServerProvider;
1050 const withCatalog = ProviderRegistry.upsertProviderWorkspaceSnapshot(
1051 ProviderRegistry.upsertProviderWorkspaceSnapshot(provider, "/project", {
1052 ...provider,
1053 workspaceModels: [machineModel, projectModel],
1054 }),
1055 "/plain",
1056 provider,
1057 );
1058
1059 const unchanged = ProviderRegistry.mergeProviderSnapshot(withCatalog, provider);
1060 assert.deepStrictEqual(
1061 unchanged.workspaceSnapshots?.map((snapshot) => snapshot.cwd),
1062 ["/project", "/plain"],
1063 );
1064 // A machine health refresh must not read as a rescan, nor erase the last one.
1065 const rescanned = { ...withCatalog, workspaceRescannedAt: "2026-03-25T00:01:00.000Z" };
1066 assert.equal(
1067 ProviderRegistry.mergeProviderSnapshot(rescanned, provider).workspaceRescannedAt,
1068 "2026-03-25T00:01:00.000Z",
1069 );
1070 assert.equal(
1071 ProviderRegistry.mergeProviderSnapshot(rescanned, {
1072 ...provider,
1073 workspaceRescannedAt: "2026-03-25T00:02:00.000Z",
1074 }).workspaceRescannedAt,
1075 "2026-03-25T00:02:00.000Z",
1076 );
1077 assert.equal(unchanged.workspaceRescannedAt, undefined);
1078 const changed = ProviderRegistry.mergeProviderSnapshot(withCatalog, {
1079 ...provider,
1080 models: [machineModel, addedModel],
1081 });
1082 assert.deepStrictEqual(
1083 changed.workspaceSnapshots?.map(({ cwd, models, modelsPending }) => ({
1084 cwd,
1085 models,
1086 modelsPending,
1087 })),
1088 [
1089 { cwd: "/project", models: [machineModel, projectModel], modelsPending: true },
1090 // Its folder may define a model the machine catalog just dropped.
1091 { cwd: "/plain", models: undefined, modelsPending: true },
1092 ],
1093 );
1094 });
1095
1096 it("stores workspace skills, commands and options without changing machine metadata", () => {
1097 const provider = {
1098 instanceId: ProviderInstanceId.make("codex"),
1099 driver: ProviderDriverKind.make("codex"),
1100 status: "ready",
1101 enabled: true,
1102 installed: true,
1103 auth: { status: "authenticated" },
1104 checkedAt: "2026-03-25T00:00:00.000Z",
1105 version: "1.0.0",
1106 models: [],
1107 slashCommands: [{ name: "global" }],
1108 skills: [{ name: "global", path: "/global/SKILL.md", enabled: true }],
1109 } satisfies ServerProvider;
1110 const projectModels = [
1111 { slug: "project-model", name: "Project Model", isCustom: false, capabilities: null },
1112 ] satisfies ServerProvider["models"];
1113 const scopedSnapshot = {
1114 ...provider,
1115 checkedAt: "2026-03-25T00:01:00.000Z",
1116 slashCommands: [{ name: "project" }],
1117 skills: [{ name: "project", path: "/project/SKILL.md", enabled: true }],
1118 workspaceModels: projectModels,
1119 optionDescriptors: [
1120 {
1121 id: "agent",
1122 label: "Agent",
1123 type: "select",
1124 options: [{ id: "readonly", label: "Readonly" }],
1125 },
1126 ],
1127 } satisfies ProviderWorkspaceSnapshot;
1128
1129 const result = ProviderRegistry.upsertProviderWorkspaceSnapshot(
1130 provider,
1131 "/project",
1132 scopedSnapshot,
1133 );
1134
1135 assert.deepStrictEqual(result.slashCommands, provider.slashCommands);
1136 assert.deepStrictEqual(result.skills, provider.skills);
1137 assert.strictEqual(result.models, provider.models);
1138 const decoded = decodeServerProvider(encodeServerProvider(result));
1139 assert.deepStrictEqual(decoded.workspaceSnapshots, [
1140 {
1141 cwd: "/project",
1142 checkedAt: scopedSnapshot.checkedAt,
1143 slashCommands: scopedSnapshot.slashCommands,
1144 skills: scopedSnapshot.skills,
1145 optionDescriptors: scopedSnapshot.optionDescriptors,
1146 models: projectModels,
1147 },
1148 ]);
1149
1150 const pendingSnapshot = {
1151 ...scopedSnapshot,
1152 slashCommands: [COMPACT_SLASH_COMMAND],
1153 slashCommandsPending: true,
1154 workspaceModelsPending: true,
1155 } satisfies ProviderWorkspaceSnapshot;
1156 const partial = ProviderRegistry.upsertProviderWorkspaceSnapshot(
1157 result,
1158 "/project",
1159 pendingSnapshot,
1160 );
1161 assert.deepStrictEqual(partial.workspaceSnapshots?.[0]?.slashCommands, [{ name: "project" }]);
1162 assert.strictEqual(partial.workspaceSnapshots?.[0]?.slashCommandsPending, true);
1163 assert.deepStrictEqual(partial.workspaceSnapshots?.[0]?.models, projectModels);
1164 assert.strictEqual(partial.workspaceSnapshots?.[0]?.modelsPending, true);
1165 const otherProject = ProviderRegistry.upsertProviderWorkspaceSnapshot(
1166 partial,
1167 "/other-project",
1168 pendingSnapshot,
1169 );
1170 assert.deepStrictEqual(otherProject.workspaceSnapshots?.[1]?.slashCommands, [
1171 COMPACT_SLASH_COMMAND,
1172 ]);
1173 const recovered = ProviderRegistry.upsertProviderWorkspaceSnapshot(partial, "/project", {
1174 ...scopedSnapshot,
1175 slashCommands: [COMPACT_SLASH_COMMAND, { name: "replacement" }],
1176 });
1177 assert.deepStrictEqual(recovered.workspaceSnapshots?.[0]?.slashCommands, [
1178 COMPACT_SLASH_COMMAND,
1179 { name: "replacement" },
1180 ]);
1181 assert.strictEqual(recovered.workspaceSnapshots?.[0]?.slashCommandsPending, undefined);
1182 assert.deepStrictEqual(recovered.workspaceSnapshots?.[0]?.models, projectModels);
1183 assert.strictEqual(recovered.workspaceSnapshots?.[0]?.modelsPending, undefined);
1184 const withoutModels = ProviderRegistry.upsertProviderWorkspaceSnapshot(
1185 recovered,
1186 "/project",
1187 { ...scopedSnapshot, workspaceModels: undefined },
1188 );
1189 assert.strictEqual(withoutModels.workspaceSnapshots?.[0]?.models, undefined);
1190
1191 const { optionDescriptors, ...failedSnapshot } = scopedSnapshot;
1192 const firstFailure = ProviderRegistry.upsertProviderWorkspaceSnapshot(
1193 provider,
1194 "/project",
1195 failedSnapshot,
1196 );
1197 assert.strictEqual(
1198 Object.hasOwn(firstFailure.workspaceSnapshots![0]!, "optionDescriptors"),
1199 false,
1200 );
1201 const failedOtherProject = ProviderRegistry.upsertProviderWorkspaceSnapshot(
1202 recovered,
1203 "/other-project",
1204 failedSnapshot,
1205 );
1206 assert.strictEqual(
1207 Object.hasOwn(failedOtherProject.workspaceSnapshots![1]!, "optionDescriptors"),
1208 false,
1209 );
1210
1211 for (const clearedDescriptors of [[], [{ ...optionDescriptors[0]!, options: [] }]]) {
1212 const cleared = ProviderRegistry.upsertProviderWorkspaceSnapshot(recovered, "/project", {
1213 ...scopedSnapshot,
1214 optionDescriptors: clearedDescriptors,
1215 });
1216 assert.deepStrictEqual(
1217 cleared.workspaceSnapshots?.[0]?.optionDescriptors,
1218 clearedDescriptors,
1219 );
1220 }
1221
1222 const failedRefresh = ProviderRegistry.upsertProviderWorkspaceSnapshot(
1223 failedOtherProject,
1224 "/project",
1225 failedSnapshot,
1226 );
1227 assert.deepStrictEqual(
1228 failedRefresh.workspaceSnapshots?.[1]?.optionDescriptors,
1229 optionDescriptors,
1230 );
1231 });
1232
1233 it("preserves previously discovered provider models when a refresh returns none", () => {
1234 const previousProvider = {
1235 instanceId: ProviderInstanceId.make("cursor"),
1236 driver: ProviderDriverKind.make("cursor"),
1237 status: "ready",
1238 enabled: true,
1239 installed: true,
1240 auth: { status: "authenticated" },
1241 checkedAt: "2026-04-14T00:00:00.000Z",
1242 version: "2026.04.09-f2b0fcd",
1243 models: [
1244 {
1245 slug: "claude-opus-4-6",
1246 name: "Opus 4.6",
1247 isCustom: false,
1248 capabilities: createModelCapabilities({
1249 optionDescriptors: [
1250 selectDescriptor("reasoning", "Reasoning", [
1251 { id: "high", label: "High", isDefault: true },
1252 ]),
1253 booleanDescriptor("fastMode", "Fast Mode"),
1254 booleanDescriptor("thinking", "Thinking"),
1255 ],
1256 }),
1257 },
1258 ],
1259 slashCommands: [{ name: "review", description: "Review changes" }],
1260 skills: [
1261 {
1262 name: "typescript",
1263 description: "TypeScript help",
1264 path: "/skills/typescript/SKILL.md",
1265 enabled: true,
1266 },
1267 ],
1268 } as const satisfies ServerProvider;
1269 const refreshedProvider = {
1270 ...previousProvider,
1271 status: "warning",
1272 checkedAt: "2026-04-14T00:01:00.000Z",
1273 models: [],
1274 slashCommands: [],
1275 skills: [],
1276 } satisfies ServerProvider;
1277
1278 assert.deepStrictEqual(
1279 ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
1280 [...previousProvider.models],
1281 );
1282 assert.deepStrictEqual(
1283 ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).slashCommands,
1284 [],
1285 );
1286 assert.deepStrictEqual(
1287 ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).skills,
1288 [],
1289 );
1290 });
1291
1292 it("does not bring back models the installed CLI is too old to run", () => {
1293 const pendingProvider = {
1294 instanceId: ProviderInstanceId.make("claudeAgent"),
1295 driver: ProviderDriverKind.make("claudeAgent"),
1296 status: "warning",
1297 enabled: true,
1298 installed: false,
1299 auth: { status: "unknown" },
1300 checkedAt: "2026-04-14T00:00:00.000Z",
1301 version: null,
1302 models: [
1303 { slug: "claude-old", name: "Old", isCustom: false, capabilities: null },
1304 { slug: "claude-next", name: "Next", isCustom: false, capabilities: null },
1305 ],
1306 slashCommands: [],
1307 skills: [],
1308 } as const satisfies ServerProvider;
1309 const probedProvider = {
1310 ...pendingProvider,
1311 status: "ready",
1312 installed: true,
1313 auth: { status: "authenticated" },
1314 version: "1.0.0",
1315 models: [pendingProvider.models[0]],
1316 updateRequiredModels: [{ slug: "claude-next", name: "Next", minVersion: "1.1.0" }],
1317 } satisfies ServerProvider;
1318
1319 assert.deepStrictEqual(
1320 ProviderRegistry.mergeProviderSnapshot(pendingProvider, probedProvider).models,
1321 [...probedProvider.models],
1322 );
1323 });
1324
1325 it("does not bring back models on a sub-provider that is now unavailable", () => {
1326 const subProviderModel = (slug: string, subProvider: string) => ({
1327 slug,
1328 name: slug,
1329 subProvider,
1330 isCustom: false,
1331 capabilities: null,
1332 });
1333 const previousProvider = {
1334 instanceId: ProviderInstanceId.make("fx"),
1335 driver: ProviderDriverKind.make("fx"),
1336 status: "ready",
1337 enabled: true,
1338 installed: true,
1339 auth: { status: "authenticated" },
1340 checkedAt: "2026-04-14T00:00:00.000Z",
1341 version: "0.0.17",
1342 models: [subProviderModel("gateway:a", "Gateway"), subProviderModel("codex:b", "Codex")],
1343 subProviders: [{ name: "Gateway" }, { name: "Codex" }],
1344 slashCommands: [],
1345 skills: [],
1346 } as const satisfies ServerProvider;
1347 const refreshedProvider = {
1348 ...previousProvider,
1349 status: "warning",
1350 models: [],
1351 subProviders: [{ name: "Gateway" }, { name: "Codex", unavailableReason: "Signed out." }],
1352 } satisfies ServerProvider;
1353
1354 assert.deepStrictEqual(
1355 ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
1356 [previousProvider.models[0]],
1357 );
1358 });
1359
1360 it("retains ACP Registry models while discovery has not completed", () => {
1361 const previousProvider = {
1362 instanceId: ProviderInstanceId.make("acpRegistry_codex"),
1363 driver: ProviderDriverKind.make("acpRegistry"),
1364 status: "ready",
1365 enabled: true,
1366 installed: true,
1367 auth: { status: "authenticated" },
1368 checkedAt: "2026-08-13T00:00:00.000Z",
1369 version: "1.2.0",
1370 models: [{ slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null }],
1371 slashCommands: [],
1372 skills: [],
1373 } as const satisfies ServerProvider;
1374 const checkingProvider = {
1375 ...previousProvider,
1376 checkedAt: "2026-08-13T00:01:00.000Z",
1377 auth: { status: "unknown" },
1378 message: "Checking ACP authentication, models, and commands in the background...",
1379 models: [{ slug: "default", name: "Default", isCustom: false, capabilities: null }],
1380 } satisfies ServerProvider;
1381 const confirmedCheckingProvider = {
1382 ...checkingProvider,
1383 auth: { status: "authenticated" },
1384 } satisfies ServerProvider;
1385 const failedProbeProvider = {
1386 ...checkingProvider,
1387 status: "warning",
1388 message: "ACP discovery failed.",
1389 } satisfies ServerProvider;
1390
1391 assert.deepStrictEqual(
1392 ProviderRegistry.mergeProviderSnapshot(previousProvider, checkingProvider).models,
1393 [
1394 { slug: "default", name: "Default", isCustom: false, capabilities: null },
1395 { slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null },
1396 ],
1397 );
1398 assert.deepStrictEqual(
1399 ProviderRegistry.mergeProviderSnapshot(previousProvider, confirmedCheckingProvider).models,
1400 [
1401 { slug: "default", name: "Default", isCustom: false, capabilities: null },
1402 { slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null },
1403 ],
1404 );
1405 assert.deepStrictEqual(
1406 ProviderRegistry.mergeProviderSnapshot(previousProvider, failedProbeProvider).models,
1407 [
1408 { slug: "default", name: "Default", isCustom: false, capabilities: null },
1409 { slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null },
1410 ],
1411 );
1412 });
1413
1414 it.each([
1415 ["grok", "warning"],
1416 ["cursor", "error"],
1417 ["muse", "error"],
1418 ["fx", "warning"],
1419 ] as const)("drops %s models a completed listing no longer returns", (driver, failedStatus) => {
1420 const previousProvider = {
1421 instanceId: ProviderInstanceId.make(driver),
1422 driver: ProviderDriverKind.make(driver),
1423 status: "ready",
1424 enabled: true,
1425 installed: true,
1426 auth: { status: "authenticated" },
1427 checkedAt: "2026-10-30T00:00:00.000Z",
1428 version: "1.0.0",
1429 models: [
1430 { slug: "current-model", name: "Current", isCustom: false, capabilities: null },
1431 { slug: "retired-model", name: "Retired", isCustom: false, capabilities: null },
1432 ],
1433 slashCommands: [],
1434 skills: [],
1435 } as const satisfies ServerProvider;
1436 const refreshedProvider = {
1437 ...previousProvider,
1438 checkedAt: "2026-10-30T00:01:00.000Z",
1439 models: [previousProvider.models[0]],
1440 } satisfies ServerProvider;
1441 const failedProvider = {
1442 ...refreshedProvider,
1443 status: failedStatus,
1444 } satisfies ServerProvider;
1445
1446 assert.deepStrictEqual(
1447 ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
1448 [previousProvider.models[0]],
1449 );
1450 assert.deepStrictEqual(
1451 ProviderRegistry.mergeProviderSnapshot(previousProvider, failedProvider).models,
1452 [...previousProvider.models],
1453 );
1454 });
1455
1456 it("marks a ready catalog retained for one failed check", () => {
1457 const readyProvider = {
1458 instanceId: ProviderInstanceId.make("codex"),
1459 driver: ProviderDriverKind.make("codex"),
1460 status: "ready",
1461 enabled: true,
1462 installed: true,
1463 auth: { status: "authenticated" },
1464 checkedAt: "2026-10-30T00:00:00.000Z",
1465 version: "1.0.0",
1466 models: [{ slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null }],
1467 slashCommands: [],
1468 skills: [],
1469 } as const satisfies ServerProvider;
1470 const failedProvider = {
1471 ...readyProvider,
1472 status: "error",
1473 auth: { status: "unknown" },
1474 checkedAt: "2026-10-30T00:01:00.000Z",
1475 models: [],
1476 } as const satisfies ServerProvider;
1477 const merge = ProviderRegistry.mergeProviderSnapshot;
1478
1479 const failedOnce = merge(readyProvider, failedProvider);
1480 assert.deepStrictEqual(failedOnce.models, [...readyProvider.models]);
1481 assert.strictEqual(failedOnce.modelsRetained, true);
1482 assert.strictEqual(merge(failedOnce, failedProvider).modelsRetained, true);
1483 assert.strictEqual(
1484 merge(failedOnce, { ...failedProvider, checkedAt: "2026-10-30T00:02:00.000Z" })
1485 .modelsRetained,
1486 undefined,
1487 );
1488 assert.strictEqual(merge(failedOnce, readyProvider).modelsRetained, undefined);
1489 const customOnly = {
1490 ...readyProvider,
1491 models: [{ slug: "bailian", name: "bailian", isCustom: true, capabilities: null }],
1492 } satisfies ServerProvider;
1493 assert.strictEqual(
1494 merge(customOnly, { ...failedProvider, models: customOnly.models }).modelsRetained,
1495 true,
1496 );
1497 assert.strictEqual(
1498 merge(readyProvider, { ...failedProvider, installed: false }).modelsRetained,
1499 undefined,
1500 );
1501 assert.strictEqual(
1502 merge(readyProvider, { ...failedProvider, auth: { status: "unauthenticated" } })
1503 .modelsRetained,
1504 undefined,
1505 );
1506 });
1507
1508 it.each(["kiro", "claudeAgent"] as const)(
1509 "keeps %s models a ready probe can omit",
1510 (driver) => {
1511 const previousProvider = {
1512 instanceId: ProviderInstanceId.make(driver),
1513 driver: ProviderDriverKind.make(driver),
1514 status: "ready",
1515 enabled: true,
1516 installed: true,
1517 auth: { status: "authenticated" },
1518 checkedAt: "2026-10-30T00:00:00.000Z",
1519 version: "1.0.0",
1520 models: [
1521 { slug: "built-in-model", name: "Built-in", isCustom: false, capabilities: null },
1522 { slug: "listed-model", name: "Listed", isCustom: false, capabilities: null },
1523 ],
1524 slashCommands: [],
1525 skills: [],
1526 } as const satisfies ServerProvider;
1527 const partialProvider = {
1528 ...previousProvider,
1529 checkedAt: "2026-10-30T00:01:00.000Z",
1530 models: [previousProvider.models[0]],
1531 } satisfies ServerProvider;
1532
1533 assert.deepStrictEqual(
1534 ProviderRegistry.mergeProviderSnapshot(previousProvider, partialProvider).models,
1535 [...previousProvider.models],
1536 );
1537 },
1538 );
1539
1540 it("retains stale OpenCode models when a refresh fails or lists none", () => {
1541 const previousProvider = {
1542 instanceId: ProviderInstanceId.make("opencode"),
1543 driver: ProviderDriverKind.make("opencode"),
1544 status: "ready",
1545 enabled: true,
1546 installed: true,
1547 auth: { status: "authenticated" },
1548 checkedAt: "2026-07-17T00:00:00.000Z",
1549 version: "1.0.0",
1550 models: [
1551 {
1552 slug: "github/gpt-5",
1553 name: "GPT-5",
1554 subProvider: "GitHub",
1555 isCustom: false,
1556 capabilities: null,
1557 },
1558 ],
1559 slashCommands: [{ name: "review", description: "Review changes" }],
1560 skills: [
1561 {
1562 name: "typescript",
1563 description: "TypeScript help",
1564 path: "/skills/typescript/SKILL.md",
1565 enabled: true,
1566 },
1567 ],
1568 } as const satisfies ServerProvider;
1569 const refreshedProvider = {
1570 ...previousProvider,
1571 status: "error",
1572 auth: { status: "unknown" },
1573 checkedAt: "2026-07-17T00:01:00.000Z",
1574 models: [],
1575 message: "Failed to refresh OpenCode models.",
1576 } satisfies ServerProvider;
1577
1578 assert.deepStrictEqual(
1579 ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
1580 [...previousProvider.models],
1581 );
1582 assert.deepStrictEqual(
1583 ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).slashCommands,
1584 previousProvider.slashCommands,
1585 );
1586 assert.deepStrictEqual(
1587 ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).skills,
1588 previousProvider.skills,
1589 );
1590
1591 const emptyCatalogProvider = {
1592 ...refreshedProvider,
1593 status: "warning",
1594 message: "OpenCode 2 is running, but it did not list any models yet.",
1595 slashCommands: [],
1596 skills: [],
1597 } satisfies ServerProvider;
1598 const mergedEmptyCatalog = ProviderRegistry.mergeProviderSnapshot(
1599 previousProvider,
1600 emptyCatalogProvider,
1601 );
1602 assert.deepStrictEqual(mergedEmptyCatalog.models, [...previousProvider.models]);
1603 assert.deepStrictEqual(mergedEmptyCatalog.slashCommands, previousProvider.slashCommands);
1604 assert.deepStrictEqual(mergedEmptyCatalog.skills, previousProvider.skills);
1605 });
1606
1607 describe("Pi model inventories", () => {
1608 const defaultModel = {
1609 slug: "default",
1610 name: "Pi default",
1611 isCustom: false,
1612 capabilities: null,
1613 } as const;
1614 const currentModel = {
1615 slug: "openai/gpt-6.1-sol",
1616 name: "GPT-6.1-Sol",
1617 isCustom: false,
1618 capabilities: null,
1619 } as const;
1620 const removedModel = {
1621 slug: "openrouter/google/gemini-2.5-pro",
1622 name: "Google: Gemini 2.5 Pro",
1623 isCustom: false,
1624 capabilities: null,
1625 } as const;
1626 const customModel = {
1627 slug: "custom-model",
1628 name: "Custom model",
1629 isCustom: true,
1630 capabilities: null,
1631 } as const;
1632 const cachedProvider = {
1633 instanceId: ProviderInstanceId.make("pi-personal"),
1634 driver: ProviderDriverKind.make("pi"),
1635 status: "ready",
1636 enabled: true,
1637 installed: true,
1638 auth: { status: "authenticated", type: "pi" },
1639 checkedAt: "2026-10-03T00:00:00.000Z",
1640 version: "1.0.0",
1641 models: [
1642 defaultModel,
1643 currentModel,
1644 removedModel,
1645 { ...customModel, slug: "removed-custom" },
1646 ],
1647 slashCommands: [],
1648 skills: [],
1649 } satisfies ServerProvider;
1650 const refreshedProvider = {
1651 ...cachedProvider,
1652 checkedAt: "2026-10-03T00:01:00.000Z",
1653 models: [defaultModel, currentModel, customModel],
1654 } satisfies ServerProvider;
1655 const pendingProvider = {
1656 ...cachedProvider,
1657 status: "warning",
1658 version: null,
1659 auth: { status: "unknown" },
1660 models: [defaultModel, customModel],
1661 } satisfies ServerProvider;
1662 const failedProvider = {
1663 ...pendingProvider,
1664 checkedAt: "2026-10-03T00:02:00.000Z",
1665 status: "ready",
1666 version: "1.0.0",
1667 message: "Pi is available, but T3 Code could not refresh its models and commands.",
1668 } satisfies ServerProvider;
1669
1670 it("retains Pi inventories during incomplete probes without restoring removed custom models", () => {
1671 const incompleteProviders = [
1672 pendingProvider,
1673 { ...pendingProvider, installed: false },
1674 failedProvider,
1675 { ...failedProvider, status: "error" },
1676 ] satisfies ReadonlyArray<ServerProvider>;
1677
1678 for (const provider of incompleteProviders) {
1679 assert.deepStrictEqual(
1680 ProviderRegistry.mergeProviderSnapshot(cachedProvider, provider).models,
1681 [defaultModel, customModel, currentModel, removedModel],
1682 );
1683 }
1684 });
1685
1686 it("does not restore disconnected Pi models after a later discovery failure", () => {
1687 const afterRemoval = ProviderRegistry.mergeProviderSnapshot(
1688 cachedProvider,
1689 refreshedProvider,
1690 );
1691 assert.deepStrictEqual(
1692 ProviderRegistry.mergeProviderSnapshot(afterRemoval, failedProvider).models,
1693 [defaultModel, customModel, currentModel],
1694 );
1695 });
1696
1697 it.effect(
1698 "persists Pi inventory removals across failed refreshes and registry restarts",
1699 () =>
1700 Effect.gen(function* () {
1701 const config = yield* ServerConfig.ServerConfig;
1702 const filePath = yield* resolveProviderStatusCachePath({
1703 cacheDir: config.providerStatusCacheDir,
1704 instanceId: cachedProvider.instanceId,
1705 });
1706 yield* writeProviderStatusCache({ filePath, provider: cachedProvider });
1707 const nextProvider = yield* Ref.make<ServerProvider>(refreshedProvider);
1708 const currentProvider = yield* Ref.make<ServerProvider>(pendingProvider);
1709 const instance = {
1710 instanceId: cachedProvider.instanceId,
1711 driverKind: cachedProvider.driver,
1712 continuationIdentity: {
1713 driverKind: cachedProvider.driver,
1714 continuationKey: "pi:instance:pi-personal",
1715 },
1716 displayName: undefined,
1717 enabled: true,
1718 snapshot: {
1719 resolveMaintenance: () =>
1720 Effect.succeed(
1721 makeManualOnlyProviderMaintenanceCapabilities({
1722 provider: cachedProvider.driver,
1723 packageName: null,
1724 }),
1725 ),
1726 getSnapshot: Ref.get(currentProvider),
1727 refresh: Ref.get(nextProvider).pipe(
1728 Effect.tap((provider) => Ref.set(currentProvider, provider)),
1729 ),
1730 streamChanges: Stream.empty,
1731 applyUsageLimits: () => Effect.void,
1732 },
1733 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
1734 textGeneration: {} as ProviderInstance["textGeneration"],
1735 } satisfies ProviderInstance;
1736 const layerInstanceRegistry = Layer.succeed(
1737 ProviderInstanceRegistry.ProviderInstanceRegistry,
1738 {
1739 getInstance: (id) =>
1740 Effect.succeed(id === instance.instanceId ? instance : undefined),
1741 listInstances: Effect.succeed([instance]),
1742 listUnavailable: Effect.succeed([]),
1743 streamChanges: Stream.empty,
1744 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
1745 },
1746 );
1747 const retainedModels = [defaultModel, customModel, currentModel];
1748
1749 for (const restarted of [false, true]) {
1750 yield* Ref.set(currentProvider, pendingProvider);
1751 yield* Effect.gen(function* () {
1752 const registry = yield* ProviderRegistry.ProviderRegistry;
1753 assert.deepStrictEqual(
1754 (yield* registry.getProviders)[0]?.models,
1755 restarted
1756 ? retainedModels
1757 : [defaultModel, customModel, currentModel, removedModel],
1758 );
1759
1760 yield* registry.refreshInstance(instance.instanceId);
1761 assert.deepStrictEqual(
1762 (yield* readProviderStatusCache(filePath))?.models,
1763 restarted ? retainedModels : refreshedProvider.models,
1764 );
1765
1766 yield* Ref.set(nextProvider, failedProvider);
1767 const afterFailure = yield* registry.refreshInstance(instance.instanceId);
1768 assert.deepStrictEqual(afterFailure[0]?.models, retainedModels);
1769 assert.deepStrictEqual(
1770 (yield* readProviderStatusCache(filePath))?.models,
1771 retainedModels,
1772 );
1773 }).pipe(
1774 Effect.provide(
1775 ProviderRegistry.layer.pipe(
1776 Layer.provide(layerInstanceRegistry),
1777 Layer.provide(layerUnusedMutator),
1778 ),
1779 ),
1780 Effect.scoped,
1781 );
1782 }
1783 }).pipe(
1784 Effect.provide(
1785 ServerConfig.layerTest(process.cwd(), {
1786 prefix: "t3-pi-model-cache-",
1787 }).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1788 ),
1789 ),
1790 );
1791 });
1792
1793 describe("Codex model inventories", () => {
1794 const cachedProvider = {
1795 instanceId: ProviderInstanceId.make("codex-personal"),
1796 driver: ProviderDriverKind.make("codex"),
1797 status: "ready",
1798 enabled: true,
1799 installed: true,
1800 auth: { status: "authenticated" },
1801 checkedAt: "2026-09-04T19:00:00.000Z",
1802 version: "0.153.3",
1803 models: ["vega-alpha", "joule-alpha", "kindle-alpha", "ultima-alpha", "solstice-alpha"].map(
1804 (slug) => ({ slug, name: slug, isCustom: false, capabilities: null }),
1805 ),
1806 slashCommands: [],
1807 skills: [],
1808 } satisfies ServerProvider;
1809 const customModel = {
1810 slug: "custom-model",
1811 name: "Custom model",
1812 isCustom: true,
1813 capabilities: null,
1814 } as const;
1815 const refreshedProvider = {
1816 ...cachedProvider,
1817 checkedAt: "2026-09-04T19:01:00.000Z",
1818 models: [
1819 { slug: "gpt-6-astra", name: "GPT 6 Astra", isCustom: false, capabilities: null },
1820 cachedProvider.models[0]!,
1821 customModel,
1822 ],
1823 } satisfies ServerProvider;
1824 const pendingProvider = {
1825 ...cachedProvider,
1826 status: "warning",
1827 installed: false,
1828 auth: { status: "unknown" },
1829 models: [customModel],
1830 } satisfies ServerProvider;
1831 const failedProvider = {
1832 ...pendingProvider,
1833 checkedAt: "2026-09-04T19:02:00.000Z",
1834 status: "error",
1835 installed: true,
1836 } satisfies ServerProvider;
1837
1838 it.effect("persists removals across failed refreshes and registry restarts", () =>
1839 Effect.gen(function* () {
1840 const config = yield* ServerConfig.ServerConfig;
1841 const filePath = yield* resolveProviderStatusCachePath({
1842 cacheDir: config.providerStatusCacheDir,
1843 instanceId: cachedProvider.instanceId,
1844 });
1845 yield* writeProviderStatusCache({ filePath, provider: cachedProvider });
1846 const nextProvider = yield* Ref.make<ServerProvider>(refreshedProvider);
1847 const currentProvider = yield* Ref.make<ServerProvider>(pendingProvider);
1848 const instance = {
1849 instanceId: cachedProvider.instanceId,
1850 driverKind: cachedProvider.driver,
1851 continuationIdentity: {
1852 driverKind: cachedProvider.driver,
1853 continuationKey: "codex:instance:codex-personal",
1854 },
1855 displayName: undefined,
1856 enabled: true,
1857 snapshot: {
1858 resolveMaintenance: () =>
1859 Effect.succeed(
1860 makeManualOnlyProviderMaintenanceCapabilities({
1861 provider: cachedProvider.driver,
1862 packageName: null,
1863 }),
1864 ),
1865 getSnapshot: Ref.get(currentProvider),
1866 isAwaitingFirstCheck: Ref.get(currentProvider).pipe(
1867 Effect.map((provider) => provider === pendingProvider),
1868 ),
1869 refresh: Ref.get(nextProvider).pipe(
1870 Effect.tap((provider) => Ref.set(currentProvider, provider)),
1871 ),
1872 streamChanges: Stream.empty,
1873 applyUsageLimits: () => Effect.void,
1874 },
1875 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
1876 textGeneration: {} as ProviderInstance["textGeneration"],
1877 } satisfies ProviderInstance;
1878 const layerInstanceRegistry = Layer.succeed(
1879 ProviderInstanceRegistry.ProviderInstanceRegistry,
1880 {
1881 getInstance: (id) =>
1882 Effect.succeed(id === instance.instanceId ? instance : undefined),
1883 listInstances: Effect.succeed([instance]),
1884 listUnavailable: Effect.succeed([]),
1885 streamChanges: Stream.empty,
1886 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
1887 },
1888 );
1889 const retainedModels = [
1890 customModel,
1891 ...refreshedProvider.models.filter((model) => !model.isCustom),
1892 ];
1893
1894 for (const restarted of [false, true]) {
1895 yield* Ref.set(currentProvider, pendingProvider);
1896 yield* Effect.gen(function* () {
1897 const registry = yield* ProviderRegistry.ProviderRegistry;
1898 const expectedModels = restarted
1899 ? retainedModels
1900 : [customModel, ...cachedProvider.models];
1901 assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, expectedModels);
1902 if (!restarted) {
1903 const probeFields = ({ status, installed, auth, version }: ServerProvider) => ({
1904 status,
1905 installed,
1906 auth,
1907 version,
1908 });
1909 // Boot reads the probe state from the cache, not the pending snapshot, and never persists the pending one.
1910 assert.deepStrictEqual(
1911 probeFields((yield* registry.getProviders)[0]!),
1912 probeFields(cachedProvider),
1913 );
1914 assert.deepStrictEqual(
1915 probeFields((yield* readProviderStatusCache(filePath))!),
1916 probeFields(cachedProvider),
1917 );
1918 }
1919
1920 yield* registry.refreshInstance(instance.instanceId);
1921 assert.deepStrictEqual(
1922 (yield* readProviderStatusCache(filePath))?.models,
1923 restarted ? retainedModels : refreshedProvider.models,
1924 );
1925
1926 yield* Ref.set(nextProvider, failedProvider);
1927 const afterFailure = yield* registry.refreshInstance(instance.instanceId);
1928 assert.deepStrictEqual(afterFailure[0]?.models, retainedModels);
1929 assert.deepStrictEqual(
1930 (yield* readProviderStatusCache(filePath))?.models,
1931 retainedModels,
1932 );
1933 }).pipe(
1934 Effect.provide(
1935 ProviderRegistry.layer.pipe(
1936 Layer.provide(layerInstanceRegistry),
1937 Layer.provide(layerUnusedMutator),
1938 ),
1939 ),
1940 Effect.scoped,
1941 );
1942 }
1943 }).pipe(
1944 Effect.provide(
1945 ServerConfig.layerTest(process.cwd(), {
1946 prefix: "t3-codex-retired-model-cache-",
1947 }).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1948 ),
1949 ),
1950 );
1951 it.effect("keeps a check that finished before boot over the cached status", () =>
1952 Effect.gen(function* () {
1953 const config = yield* ServerConfig.ServerConfig;
1954 const filePath = yield* resolveProviderStatusCachePath({
1955 cacheDir: config.providerStatusCacheDir,
1956 instanceId: cachedProvider.instanceId,
1957 });
1958 const instance = {
1959 instanceId: cachedProvider.instanceId,
1960 driverKind: cachedProvider.driver,
1961 continuationIdentity: {
1962 driverKind: cachedProvider.driver,
1963 continuationKey: "codex:instance:codex-personal",
1964 },
1965 displayName: undefined,
1966 enabled: true,
1967 snapshot: {
1968 resolveMaintenance: () =>
1969 Effect.succeed(
1970 makeManualOnlyProviderMaintenanceCapabilities({
1971 provider: cachedProvider.driver,
1972 packageName: null,
1973 }),
1974 ),
1975 getSnapshot: Effect.succeed(failedProvider),
1976 isAwaitingFirstCheck: Effect.succeed(false),
1977 refresh: Effect.succeed(failedProvider),
1978 streamChanges: Stream.empty,
1979 applyUsageLimits: () => Effect.void,
1980 },
1981 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
1982 textGeneration: {} as ProviderInstance["textGeneration"],
1983 } satisfies ProviderInstance;
1984 const layerInstanceRegistry = Layer.succeed(
1985 ProviderInstanceRegistry.ProviderInstanceRegistry,
1986 {
1987 getInstance: (id) =>
1988 Effect.succeed(id === instance.instanceId ? instance : undefined),
1989 listInstances: Effect.succeed([instance]),
1990 listUnavailable: Effect.succeed([]),
1991 streamChanges: Stream.empty,
1992 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
1993 },
1994 );
1995
1996 // First boot has no cache file; the second has a stale ready one.
1997 for (const hasCache of [false, true]) {
1998 if (hasCache) {
1999 yield* writeProviderStatusCache({
2000 filePath,
2001 provider: { ...cachedProvider, status: "ready" },
2002 });
2003 }
2004 yield* Effect.gen(function* () {
2005 const registry = yield* ProviderRegistry.ProviderRegistry;
2006 assert.strictEqual((yield* registry.getProviders)[0]?.status, failedProvider.status);
2007 assert.strictEqual(
2008 (yield* readProviderStatusCache(filePath))?.status,
2009 failedProvider.status,
2010 );
2011 }).pipe(
2012 Effect.provide(
2013 ProviderRegistry.layer.pipe(
2014 Layer.provide(layerInstanceRegistry),
2015 Layer.provide(layerUnusedMutator),
2016 ),
2017 ),
2018 Effect.scoped,
2019 );
2020 }
2021 }).pipe(
2022 Effect.provide(
2023 ServerConfig.layerTest(process.cwd(), {
2024 prefix: "t3-codex-probed-before-boot-",
2025 }).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
2026 ),
2027 ),
2028 );
2029 });
2030
2031 describe("Antigravity model inventories", () => {
2032 const previousProvider = {
2033 instanceId: ProviderInstanceId.make("antigravity-personal"),
2034 driver: ProviderDriverKind.make("antigravity"),
2035 status: "ready",
2036 enabled: true,
2037 installed: true,
2038 auth: { status: "authenticated" },
2039 checkedAt: "2026-09-02T00:00:00.000Z",
2040 version: "0.1.3",
2041 models: [
2042 {
2043 slug: "gemini-3.1-pro-high",
2044 name: "Gemini 3.1 Pro High",
2045 isCustom: false,
2046 capabilities: null,
2047 },
2048 {
2049 slug: "gemini-3-flash",
2050 name: "Gemini 3 Flash",
2051 isCustom: false,
2052 capabilities: null,
2053 },
2054 ],
2055 slashCommands: [],
2056 skills: [],
2057 } as const satisfies ServerProvider;
2058
2059 it("clears models after sign-out, disable, uninstall, or an empty successful refresh", () => {
2060 const emptyProvider = {
2061 ...previousProvider,
2062 checkedAt: "2026-09-02T00:01:00.000Z",
2063 models: [],
2064 } satisfies ServerProvider;
2065 const clearedProviders = [
2066 { ...emptyProvider, status: "warning", auth: { status: "unauthenticated" } },
2067 { ...emptyProvider, status: "error", auth: { status: "unauthenticated" } },
2068 { ...emptyProvider, status: "disabled", enabled: false },
2069 { ...emptyProvider, status: "error", enabled: false },
2070 { ...emptyProvider, status: "error", installed: false, auth: { status: "unknown" } },
2071 emptyProvider,
2072 ] satisfies ReadonlyArray<ServerProvider>;
2073
2074 for (const provider of clearedProviders) {
2075 const afterRemoval = ProviderRegistry.mergeProviderSnapshot(previousProvider, provider);
2076 assert.deepStrictEqual(afterRemoval.models, []);
2077
2078 const afterFailure = ProviderRegistry.mergeProviderSnapshot(afterRemoval, {
2079 ...emptyProvider,
2080 status: "error",
2081 auth: { status: "unknown" },
2082 });
2083 assert.deepStrictEqual(afterFailure.models, []);
2084 }
2085 });
2086 });
2087
2088 describe("Antigravity saved account", () => {
2089 const signedIn = {
2090 instanceId: ProviderInstanceId.make("antigravity-personal"),
2091 driver: ProviderDriverKind.make("antigravity"),
2092 status: "ready",
2093 enabled: true,
2094 installed: true,
2095 auth: { status: "authenticated", type: "oauth-personal", label: "Google account" },
2096 checkedAt: "2026-09-05T00:00:00.000Z",
2097 version: "1.5.12",
2098 models: [
2099 {
2100 slug: "gemini-3.7-flash-high",
2101 name: "Gemini 3.7 Flash",
2102 isCustom: false,
2103 capabilities: null,
2104 },
2105 ],
2106 slashCommands: [{ name: "plan" }],
2107 skills: [],
2108 } as const satisfies ServerProvider;
2109 const uncheckedMessage =
2110 "Antigravity is installed. Google account access is not checked yet.";
2111 const restartProbe = {
2112 ...signedIn,
2113 status: "warning",
2114 auth: { status: "unknown" },
2115 checkedAt: "2026-09-05T00:01:00.000Z",
2116 message: uncheckedMessage,
2117 models: [],
2118 } as const satisfies ServerProvider;
2119
2120 it("keeps the saved Google account through restart health checks", () => {
2121 const merged = ProviderRegistry.mergeProviderSnapshot(signedIn, restartProbe);
2122 const { message: _uncheckedMessage, ...probeWithoutMessage } = restartProbe;
2123 assert.deepStrictEqual(merged, {
2124 ...probeWithoutMessage,
2125 status: "ready",
2126 auth: signedIn.auth,
2127 models: signedIn.models,
2128 });
2129 assert.equal("message" in merged, false);
2130 assert.deepStrictEqual(
2131 ProviderRegistry.mergeProviderSnapshot(merged, restartProbe),
2132 merged,
2133 );
2134 });
2135
2136 it("does not invent an account after sign-out, disable, uninstall, or for other providers", () => {
2137 const untouched = [
2138 { ...restartProbe, auth: { status: "unauthenticated" } },
2139 { ...restartProbe, status: "disabled", enabled: false },
2140 { ...restartProbe, status: "error", installed: false },
2141 { ...restartProbe, driver: ProviderDriverKind.make("codex") },
2142 { ...restartProbe, auth: { status: "unknown", type: "gemini-api-key" } },
2143 ] satisfies ReadonlyArray<ServerProvider>;
2144 for (const next of untouched) {
2145 const merged = ProviderRegistry.mergeProviderSnapshot(signedIn, next);
2146 assert.deepStrictEqual(merged.auth, next.auth);
2147 assert.equal(merged.status, next.status);
2148 assert.equal(merged.message, next.message);
2149 }
2150 assert.deepStrictEqual(
2151 ProviderRegistry.mergeProviderSnapshot(
2152 { ...signedIn, auth: { status: "unknown" } },
2153 restartProbe,
2154 ).auth,
2155 { status: "unknown" },
2156 );
2157 assert.equal(
2158 ProviderRegistry.mergeProviderSnapshot(
2159 { ...signedIn, driver: ProviderDriverKind.make("codex") },
2160 restartProbe,
2161 ).auth.status,
2162 "unknown",
2163 );
2164 assert.deepStrictEqual(
2165 ProviderRegistry.mergeProviderSnapshot(signedIn, {
2166 ...restartProbe,
2167 auth: { status: "unknown", type: "oauth-personal" },
2168 }).auth,
2169 signedIn.auth,
2170 );
2171 });
2172
2173 it("keeps scanned folders through health checks until Antigravity cannot run", () => {
2174 const scanned = ["/project", "/plain"].reduce<ServerProvider>(
2175 (provider, cwd) =>
2176 ProviderRegistry.upsertProviderWorkspaceSnapshot(provider, cwd, {
2177 ...signedIn,
2178 skills: [{ name: "review", path: `${cwd}/SKILL.md`, enabled: true }],
2179 }),
2180 signedIn,
2181 );
2182 const healthCheck = { ...signedIn, checkedAt: "2026-09-05T00:01:00.000Z" };
2183 const sessionFolder = {
2184 cwd: "/project",
2185 checkedAt: healthCheck.checkedAt,
2186 slashCommands: [{ name: "swarm" }],
2187 skills: [],
2188 };
2189 const kept = [
2190 healthCheck,
2191 restartProbe,
2192 { ...restartProbe, installed: false, version: null },
2193 ] satisfies ReadonlyArray<ServerProvider>;
2194 for (const next of kept) {
2195 assert.deepStrictEqual(
2196 ProviderRegistry.mergeProviderSnapshot(scanned, { ...next, workspaceSnapshots: [] })
2197 .workspaceSnapshots,
2198 scanned.workspaceSnapshots,
2199 );
2200 }
2201 assert.deepStrictEqual(
2202 ProviderRegistry.mergeProviderSnapshot(scanned, {
2203 ...healthCheck,
2204 workspaceSnapshots: [sessionFolder],
2205 }).workspaceSnapshots,
2206 [...scanned.workspaceSnapshots!.slice(1), sessionFolder],
2207 );
2208 const cleared = [
2209 { ...healthCheck, auth: { status: "unauthenticated" } },
2210 { ...healthCheck, status: "disabled", enabled: false },
2211 { ...healthCheck, status: "error", installed: false },
2212 ] satisfies ReadonlyArray<ServerProvider>;
2213 for (const next of cleared) {
2214 assert.deepStrictEqual(
2215 ProviderRegistry.mergeProviderSnapshot(scanned, { ...next, workspaceSnapshots: [] })
2216 .workspaceSnapshots,
2217 [],
2218 );
2219 }
2220 });
2221 });
2222
2223 it("fills missing capabilities from the previous provider snapshot", () => {
2224 const previousProvider = {
2225 instanceId: ProviderInstanceId.make("cursor"),
2226 driver: ProviderDriverKind.make("cursor"),
2227 status: "ready",
2228 enabled: true,
2229 installed: true,
2230 auth: { status: "authenticated" },
2231 checkedAt: "2026-04-14T00:00:00.000Z",
2232 version: "2026.04.09-f2b0fcd",
2233 models: [
2234 {
2235 slug: "claude-opus-4-6",
2236 name: "Opus 4.6",
2237 isCustom: false,
2238 capabilities: createModelCapabilities({
2239 optionDescriptors: [
2240 selectDescriptor("reasoning", "Reasoning", [
2241 { id: "high", label: "High", isDefault: true },
2242 ]),
2243 booleanDescriptor("fastMode", "Fast Mode"),
2244 booleanDescriptor("thinking", "Thinking"),
2245 ],
2246 }),
2247 },
2248 ],
2249 slashCommands: [],
2250 skills: [],
2251 } as const satisfies ServerProvider;
2252 const refreshedProvider = {
2253 ...previousProvider,
2254 checkedAt: "2026-04-14T00:01:00.000Z",
2255 models: [
2256 {
2257 slug: "claude-opus-4-6",
2258 name: "Opus 4.6",
2259 isCustom: false,
2260 capabilities: createModelCapabilities({
2261 optionDescriptors: [],
2262 }),
2263 },
2264 ],
2265 } satisfies ServerProvider;
2266
2267 assert.deepStrictEqual(
2268 ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models,
2269 [...previousProvider.models],
2270 );
2271 });
2272
2273 it.effect("invalidates model caches only for an explicit model refresh", () =>
2274 Effect.gen(function* () {
2275 const forceRefreshCalls = yield* Ref.make(0);
2276 const manifest = yield* Ref.make(ModelManifest.BUNDLED_MODEL_MANIFEST);
2277 const updateEvents = yield* Ref.make<ReadonlyArray<string>>([]);
2278 const hookFails = yield* Ref.make(false);
2279 const makeInstance = (name: string) =>
2280 Effect.gen(function* () {
2281 const driver = ProviderDriverKind.make("codex");
2282 const instanceId = ProviderInstanceId.make(name);
2283 const provider = {
2284 instanceId,
2285 driver,
2286 status: "ready",
2287 enabled: true,
2288 installed: true,
2289 auth: { status: "authenticated" },
2290 checkedAt: "2026-06-10T00:00:00.000Z",
2291 version: "1.0.0",
2292 models: [],
2293 slashCommands: [],
2294 skills: [],
2295 } as const satisfies ServerProvider;
2296 const invalidations = yield* Ref.make(0);
2297 const probes = yield* Ref.make(0);
2298 const maintenanceReads = yield* Ref.make<ReadonlyArray<boolean | "afterUpdate">>([]);
2299 const instance = {
2300 instanceId,
2301 driverKind: driver,
2302 continuationIdentity: {
2303 driverKind: driver,
2304 continuationKey: `codex:instance:${name}`,
2305 },
2306 displayName: undefined,
2307 enabled: true,
2308 snapshot: {
2309 resolveMaintenance: (options) =>
2310 Ref.update(maintenanceReads, (reads) => [...reads, options?.fresh === true]).pipe(
2311 Effect.as(
2312 makeManualOnlyProviderMaintenanceCapabilities({
2313 provider: driver,
2314 packageName: `${name}-package`,
2315 }),
2316 ),
2317 ),
2318 getSnapshot: Effect.succeed(provider),
2319 refresh: Ref.update(probes, (count) => count + 1).pipe(Effect.as(provider)),
2320 streamChanges: Stream.empty,
2321 applyUsageLimits: () => Effect.void,
2322 },
2323 invalidateCaches: Ref.update(invalidations, (count) => count + 1).pipe(
2324 Effect.andThen(
2325 Ref.update(updateEvents, (events) => [...events, `invalidate:${name}`]),
2326 ),
2327 ),
2328 afterUpdate: Ref.update(maintenanceReads, (reads) => [
2329 ...reads,
2330 "afterUpdate" as const,
2331 ]).pipe(
2332 Effect.andThen(
2333 Ref.update(updateEvents, (events) => [...events, `afterUpdate:${name}`]),
2334 ),
2335 Effect.andThen(Ref.get(hookFails)),
2336 Effect.flatMap((fails) =>
2337 fails
2338 ? Effect.fail(new ProviderDriverError({ driver, instanceId, detail: "hook" }))
2339 : Effect.void,
2340 ),
2341 ),
2342 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
2343 textGeneration: {} as ProviderInstance["textGeneration"],
2344 } satisfies ProviderInstance;
2345 const takeMaintenanceReads = Ref.getAndSet(maintenanceReads, []);
2346 return { instance, invalidations, probes, takeMaintenanceReads };
2347 });
2348 const first = yield* makeInstance("codex_first");
2349 const second = yield* makeInstance("codex_second");
2350 const instances = [first.instance, second.instance];
2351 const layerInstanceRegistry = Layer.succeed(
2352 ProviderInstanceRegistry.ProviderInstanceRegistry,
2353 {
2354 getInstance: (instanceId) =>
2355 Effect.succeed(instances.find((instance) => instance.instanceId === instanceId)),
2356 listInstances: Effect.succeed(instances),
2357 listUnavailable: Effect.succeed([]),
2358 streamChanges: Stream.empty,
2359 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
2360 },
2361 );
2362 const layerModelManifest = Layer.succeed(ModelManifest.ModelManifest, {
2363 current: Ref.get(manifest),
2364 refresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
2365 forceRefresh: Ref.update(forceRefreshCalls, (count) => count + 1).pipe(
2366 Effect.as(ModelManifest.BUNDLED_MODEL_MANIFEST),
2367 ),
2368 refreshOnDemand: Ref.get(manifest),
2369 refreshInBackground: Effect.void,
2370 });
2371 const layerLatestVersions = Layer.effect(
2372 ProviderLatestVersions.ProviderLatestVersions,
2373 ProviderLatestVersions.make([
2374 ["codex_first-package", "1.0.0"],
2375 ["codex_second-package", "1.0.0"],
2376 ]),
2377 );
2378 const readCachedVersion = (key: string, latest = "2.0.0") =>
2379 ProviderLatestVersions.ProviderLatestVersions.use((latestVersions) =>
2380 latestVersions.cached(key, Effect.succeed(latest)),
2381 );
2382
2383 yield* Effect.gen(function* () {
2384 const registry = yield* ProviderRegistry.ProviderRegistry;
2385
2386 yield* registry.refreshInstance(first.instance.instanceId);
2387 yield* registry.refresh();
2388 assert.strictEqual(yield* Ref.get(forceRefreshCalls), 0);
2389 assert.strictEqual(yield* Ref.get(first.invalidations), 0);
2390 assert.strictEqual(yield* readCachedVersion("codex_first-package"), "1.0.0");
2391 yield* first.takeMaintenanceReads;
2392
2393 yield* registry.invalidateModelCaches({ instanceId: first.instance.instanceId });
2394 // The instance refresh that follows resolves installer metadata fresh itself.
2395 assert.deepStrictEqual(yield* first.takeMaintenanceReads, [false]);
2396 assert.strictEqual(yield* Ref.get(forceRefreshCalls), 1);
2397 assert.strictEqual(yield* Ref.get(first.invalidations), 1);
2398 assert.strictEqual(yield* Ref.get(second.invalidations), 0);
2399 assert.strictEqual(yield* readCachedVersion("codex_first-package"), "2.0.0");
2400 assert.strictEqual(yield* readCachedVersion("codex_second-package"), "1.0.0");
2401
2402 yield* registry.invalidateModelCaches({});
2403 assert.strictEqual(yield* Ref.get(first.invalidations), 2);
2404 assert.strictEqual(yield* Ref.get(second.invalidations), 1);
2405 assert.strictEqual(yield* readCachedVersion("codex_second-package"), "2.0.0");
2406 yield* first.takeMaintenanceReads;
2407
2408 // Only a cached workspace refresh leaves the fresh resolution to this call.
2409 const workspace = { instanceId: first.instance.instanceId, cwd: process.cwd() };
2410 yield* registry.invalidateModelCaches(workspace);
2411 assert.deepStrictEqual(yield* first.takeMaintenanceReads, [true]);
2412 yield* registry.invalidateModelCaches({ ...workspace, fresh: true });
2413 assert.deepStrictEqual(yield* first.takeMaintenanceReads, [false]);
2414
2415 // An opened model picker probes only when the manifest differs from what the last pass saw.
2416 const probesBefore = yield* Ref.get(second.probes);
2417 yield* registry.refreshModelCatalog;
2418 assert.strictEqual(yield* Ref.get(second.probes), probesBefore);
2419 assert.strictEqual(yield* readCachedVersion("codex_second-package", "3.0.0"), "2.0.0");
2420 yield* Ref.set(manifest, {
2421 ...ModelManifest.BUNDLED_MODEL_MANIFEST,
2422 updatedAt: "2999-01-01T00:00:00Z",
2423 });
2424 yield* registry.refreshModelCatalog;
2425 yield* registry.refreshModelCatalog;
2426 assert.strictEqual(yield* Ref.get(second.probes), probesBefore + 1);
2427 // A changed manifest also rechecks latest CLI versions.
2428 assert.strictEqual(yield* readCachedVersion("codex_second-package", "3.0.0"), "3.0.0");
2429
2430 yield* first.takeMaintenanceReads;
2431 yield* Ref.set(updateEvents, []);
2432 yield* registry.refreshAfterUpdate(first.instance.driverKind, first.instance.instanceId);
2433 assert.deepStrictEqual((yield* first.takeMaintenanceReads).slice(0, 2), [
2434 "afterUpdate",
2435 true,
2436 ]);
2437 assert.notInclude(yield* second.takeMaintenanceReads, "afterUpdate");
2438 // Instances sharing the replaced service must not cache its old version.
2439 assert.strictEqual((yield* Ref.get(updateEvents))[0], "afterUpdate:codex_first");
2440
2441 // A failed hook leaves the probe to report what is running.
2442 yield* Ref.set(hookFails, true);
2443 const probesBeforeFailedHook = yield* Ref.get(first.probes);
2444 const refreshed = yield* registry.refreshAfterUpdate(
2445 first.instance.driverKind,
2446 first.instance.instanceId,
2447 );
2448 assert.strictEqual(yield* Ref.get(first.probes), probesBeforeFailedHook + 1);
2449 assert.include(
2450 refreshed.map((provider) => provider.instanceId),
2451 first.instance.instanceId,
2452 );
2453 }).pipe(
2454 Effect.provide(
2455 ProviderRegistry.layer.pipe(
2456 Layer.provideMerge(layerInstanceRegistry),
2457 Layer.provideMerge(layerModelManifest),
2458 Layer.provideMerge(layerLatestVersions),
2459 Layer.provide(layerUnusedMutator),
2460 Layer.provideMerge(
2461 ServerConfig.layerTest(process.cwd(), {
2462 prefix: "t3-provider-registry-model-cache-",
2463 }),
2464 ),
2465 Layer.provideMerge(NodeServices.layer),
2466 ),
2467 ),
2468 );
2469 }),
2470 );
2471
2472 it.effect(
2473 "a second request for a cwd being scanned gets its result, even if the first leaves",
2474 () =>
2475 Effect.gen(function* () {
2476 const driver = ProviderDriverKind.make("codex");
2477 const instanceId = ProviderInstanceId.make("codex");
2478 const provider = {
2479 instanceId,
2480 driver,
2481 status: "ready",
2482 enabled: true,
2483 installed: true,
2484 auth: { status: "authenticated" },
2485 checkedAt: "2026-06-10T00:00:00.000Z",
2486 version: "1.0.0",
2487 models: [],
2488 slashCommands: [],
2489 skills: [],
2490 } as const satisfies ServerProvider;
2491 const scanStarted = yield* Deferred.make<void>();
2492 const releaseScan = yield* Deferred.make<void>();
2493 const scans = yield* Ref.make(0);
2494 const instance: ProviderInstance = {
2495 instanceId,
2496 driverKind: driver,
2497 continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" },
2498 displayName: undefined,
2499 enabled: true,
2500 snapshot: {
2501 resolveMaintenance: () =>
2502 Effect.succeed(
2503 makeManualOnlyProviderMaintenanceCapabilities({
2504 provider: driver,
2505 packageName: null,
2506 }),
2507 ),
2508 getSnapshot: Effect.succeed(provider),
2509 refresh: Effect.succeed(provider),
2510 streamChanges: Stream.empty,
2511 applyUsageLimits: () => Effect.void,
2512 },
2513 snapshotForCwd: () =>
2514 Ref.update(scans, (count) => count + 1).pipe(
2515 Effect.andThen(Deferred.succeed(scanStarted, undefined)),
2516 Effect.andThen(Deferred.await(releaseScan)),
2517 Effect.as(provider),
2518 ),
2519 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
2520 textGeneration: {} as ProviderInstance["textGeneration"],
2521 };
2522 const layerInstanceRegistry = Layer.succeed(
2523 ProviderInstanceRegistry.ProviderInstanceRegistry,
2524 {
2525 getInstance: (requestedId) =>
2526 Effect.succeed(requestedId === instanceId ? instance : undefined),
2527 listInstances: Effect.succeed([instance]),
2528 listUnavailable: Effect.succeed([]),
2529 streamChanges: Stream.empty,
2530 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
2531 },
2532 );
2533 const scope = yield* Scope.make();
2534 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
2535 const runtimeServices = yield* Layer.build(
2536 ProviderRegistry.layer.pipe(
2537 Layer.provide(layerUnusedMutator),
2538 Layer.provideMerge(layerInstanceRegistry),
2539 Layer.provideMerge(
2540 ServerConfig.layerTest(process.cwd(), {
2541 prefix: "t3-provider-registry-shared-workspace-scan-",
2542 }),
2543 ),
2544 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
2545 ),
2546 ).pipe(Scope.provide(scope));
2547
2548 yield* Effect.gen(function* () {
2549 const registry = yield* ProviderRegistry.ProviderRegistry;
2550 const refresh = registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" });
2551 const first = yield* Effect.forkChild(refresh);
2552 yield* Deferred.await(scanStarted);
2553 const second = yield* Effect.forkChild(refresh, { startImmediately: true });
2554 yield* Fiber.interrupt(first);
2555 yield* Deferred.succeed(releaseScan, undefined);
2556 assert.deepStrictEqual(
2557 (yield* Fiber.join(second))[0]?.workspaceSnapshots?.map((snapshot) => snapshot.cwd),
2558 ["/workspace"],
2559 );
2560 assert.strictEqual(yield* Ref.get(scans), 1);
2561 }).pipe(Effect.provide(runtimeServices));
2562 }),
2563 );
2564
2565 it.effect(
2566 "rebuilds only instances missing their CLI when a refresh finds a new Windows PATH",
2567 () => {
2568 const env: NodeJS.ProcessEnv = { PATH: "C:\\Windows" };
2569 return Effect.gen(function* () {
2570 const driver = ProviderDriverKind.make("codex");
2571 const makeInstance = (id: string, installed: boolean): ProviderInstance => {
2572 const instanceId = ProviderInstanceId.make(id);
2573 const provider = {
2574 instanceId,
2575 driver,
2576 status: installed ? "ready" : "error",
2577 enabled: true,
2578 installed,
2579 auth: { status: "unknown" },
2580 checkedAt: "1970-01-01T00:00:00.000Z",
2581 version: null,
2582 models: [],
2583 slashCommands: [],
2584 skills: [],
2585 } as const satisfies ServerProvider;
2586 return {
2587 instanceId,
2588 driverKind: driver,
2589 continuationIdentity: { driverKind: driver, continuationKey: `codex:${id}` },
2590 displayName: undefined,
2591 enabled: true,
2592 snapshot: {
2593 resolveMaintenance: () =>
2594 Effect.succeed(
2595 makeManualOnlyProviderMaintenanceCapabilities({
2596 provider: driver,
2597 packageName: null,
2598 }),
2599 ),
2600 getSnapshot: Effect.succeed(provider),
2601 refresh: Effect.succeed(provider),
2602 streamChanges: Stream.empty,
2603 applyUsageLimits: () => Effect.void,
2604 },
2605 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
2606 textGeneration: {} as ProviderInstance["textGeneration"],
2607 };
2608 };
2609 const instances = [makeInstance("present", true), makeInstance("missing", false)];
2610 const rebuilt: Array<ReadonlyArray<ProviderInstanceId>> = [];
2611 const changes = yield* PubSub.unbounded<void>();
2612 const registry = yield* ProviderRegistry.ProviderRegistry.pipe(
2613 Effect.provide(
2614 ProviderRegistry.layer.pipe(
2615 Layer.provide(
2616 Layer.mock(ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator)({
2617 rebuild: (ids) => Effect.sync(() => void rebuilt.push(ids)),
2618 }),
2619 ),
2620 Layer.provideMerge(
2621 Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, {
2622 getInstance: (id) => Effect.succeed(instances.find((i) => i.instanceId === id)),
2623 listInstances: Effect.succeed(instances),
2624 listUnavailable: Effect.succeed([]),
2625 streamChanges: Stream.fromPubSub(changes),
2626 subscribeChanges: PubSub.subscribe(changes),
2627 }),
2628 ),
2629 Layer.provideMerge(
2630 ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-path-" }),
2631 ),
2632 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
2633 ),
2634 ),
2635 );
2636
2637 yield* registry.refresh();
2638
2639 assert.strictEqual(env.PATH, "C:\\Windows;C:\\Tools");
2640 assert.deepStrictEqual(rebuilt, [[ProviderInstanceId.make("missing")]]);
2641 }).pipe(
2642 Effect.provideService(HostProcess.Platform, "win32"),
2643 Effect.provideService(HostProcess.Environment, env),
2644 Effect.provideService(WindowsShellEnvironment, () =>
2645 Effect.succeed({ PATH: "C:\\Windows;C:\\Tools" }),
2646 ),
2647 );
2648 },
2649 );
2650
2651 it.effect("rescans a requested cwd whose snapshot is still current", () =>
2652 Effect.gen(function* () {
2653 const h = yield* makeWorkspaceRescanHarness;
2654 yield* h.seed("/barrier");
2655 yield* h.seed("/workspace");
2656 assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]);
2657 yield* Queue.offer(h.first.rescans, "/workspace");
2658 const complete = yield* h.nextScan("/workspace");
2659 yield* complete("hook");
2660 yield* h.drainRescans;
2661 assert.deepEqual(yield* h.skillsOf("/workspace"), ["hook"]);
2662 // Clients that fetched the old skills are told to fetch again.
2663 const scannedAt = (yield* h.registry.getProviders)[0]?.workspaceSnapshots?.find(
2664 (snapshot) => snapshot.cwd === "/workspace",
2665 )?.checkedAt;
2666 assert.isString(scannedAt);
2667 assert.equal(yield* h.rescannedAtOf, scannedAt);
2668 }),
2669 );
2670
2671 it.effect("stamps a rescan whose awaited scan already published the change", () =>
2672 Effect.gen(function* () {
2673 const h = yield* makeWorkspaceRescanHarness;
2674 yield* h.seed("/barrier");
2675 yield* h.seed("/workspace");
2676 const ordinary = yield* h.refresh("/workspace", true).pipe(Effect.forkChild);
2677 const completeOrdinary = yield* h.nextScan("/workspace");
2678 yield* Queue.offer(h.first.rescans, "/workspace");
2679 yield* Queue.take(h.first.reports);
2680 // Let the consumer reach its wait on the running scan.
2681 yield* TestClock.adjust(0);
2682 yield* completeOrdinary("hook");
2683 yield* Fiber.join(ordinary);
2684 const completeRescan = yield* h.nextScan("/workspace");
2685 yield* completeRescan("hook");
2686 yield* h.drainRescans;
2687 assert.isString(yield* h.rescannedAtOf);
2688 }),
2689 );
2690
2691 it.effect("leaves workspaceRescannedAt unset when a rescan changes nothing", () =>
2692 Effect.gen(function* () {
2693 const h = yield* makeWorkspaceRescanHarness;
2694 yield* h.seed("/barrier");
2695 yield* h.seed("/workspace");
2696 yield* Queue.offer(h.first.rescans, "/workspace");
2697 const complete = yield* h.nextScan("/workspace");
2698 yield* complete("initial");
2699 yield* h.drainRescans;
2700 assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]);
2701 assert.equal(yield* h.rescannedAtOf, undefined);
2702 }),
2703 );
2704
2705 it.effect("starts no scan for a reported cwd nobody requested", () =>
2706 Effect.gen(function* () {
2707 const h = yield* makeWorkspaceRescanHarness;
2708 yield* h.seed("/barrier");
2709 yield* Queue.offer(h.first.rescans, "/unrequested");
2710 // The next scan being the barrier's shows the report started none.
2711 yield* h.drainRescans;
2712 assert.deepEqual(yield* h.skillsOf("/unrequested"), undefined);
2713 }),
2714 );
2715
2716 it.effect("rescans after an initial scan in flight when the hook report arrives", () =>
2717 Effect.gen(function* () {
2718 const h = yield* makeWorkspaceRescanHarness;
2719 yield* h.seed("/barrier");
2720 const initial = yield* h.refresh("/workspace").pipe(Effect.forkChild);
2721 const completeInitial = yield* h.nextScan("/workspace");
2722 yield* Queue.offer(h.first.rescans, "/workspace");
2723 yield* Queue.take(h.first.reports);
2724 // Let the consumer reach its wait on the running scan.
2725 yield* TestClock.adjust(0);
2726 yield* completeInitial("initial");
2727 // The requesting client's reply is its only copy of the scan, so the rescan must not
2728 // supersede it.
2729 const reply = yield* Fiber.join(initial);
2730 assert.deepEqual(
2731 reply[0]?.workspaceSnapshots
2732 ?.find((s) => s.cwd === "/workspace")
2733 ?.skills?.map((s) => s.name),
2734 ["initial"],
2735 );
2736 const completeRescan = yield* h.nextScan("/workspace");
2737 yield* completeRescan("hook");
2738 yield* h.drainRescans;
2739 assert.deepEqual(yield* h.skillsOf("/workspace"), ["hook"]);
2740 }),
2741 );
2742
2743 it.effect("lets a fresh refresh started while a rescan waits keep its own result", () =>
2744 Effect.gen(function* () {
2745 const h = yield* makeWorkspaceRescanHarness;
2746 yield* h.seed("/barrier");
2747 const initial = yield* h.refresh("/workspace").pipe(Effect.forkChild);
2748 const completeInitial = yield* h.nextScan("/workspace");
2749 yield* Queue.offer(h.first.rescans, "/workspace");
2750 yield* Queue.take(h.first.reports);
2751 // Let the consumer reach its wait on the running scan.
2752 yield* TestClock.adjust(0);
2753 const fresh = yield* h.refresh("/workspace", true).pipe(Effect.forkChild);
2754 const completeFresh = yield* h.nextScan("/workspace");
2755 yield* completeInitial("initial");
2756 yield* completeFresh("fresh");
2757 yield* Fiber.join(initial);
2758 const reply = yield* Fiber.join(fresh);
2759 assert.deepEqual(
2760 reply[0]?.workspaceSnapshots
2761 ?.find((s) => s.cwd === "/workspace")
2762 ?.skills?.map((s) => s.name),
2763 ["fresh"],
2764 );
2765 // The rescan joins the fresh scan, so the next scan started is the barrier's.
2766 yield* h.drainRescans;
2767 assert.deepEqual(yield* h.skillsOf("/workspace"), ["fresh"]);
2768 }),
2769 );
2770
2771 it.effect("ignores a queued rescan from a replaced instance", () =>
2772 Effect.gen(function* () {
2773 const h = yield* makeWorkspaceRescanHarness;
2774 yield* h.seed("/workspace");
2775 const replacement = yield* h.makeInstance;
2776 const rebuilt = yield* h.registry.streamChanges.pipe(
2777 Stream.filter((providers) => providers[0]?.workspaceSnapshots === undefined),
2778 Stream.runHead,
2779 Effect.forkChild({ startImmediately: true }),
2780 );
2781 yield* Ref.set(h.instances, [replacement.instance]);
2782 yield* PubSub.publish(h.changes, undefined);
2783 yield* Fiber.join(rebuilt);
2784 yield* h.seed("/workspace");
2785 yield* h.seed("/barrier");
2786 // The forwarder pulls the second report only after queueing the first.
2787 yield* Queue.offerAll(h.first.rescans, ["/workspace", "/workspace"]);
2788 yield* Queue.take(h.first.reports);
2789 yield* Queue.take(h.first.reports);
2790 yield* Queue.offer(replacement.rescans, "/barrier");
2791 // A scan started for the stale report would come before the barrier's.
2792 const completeBarrier = yield* h.nextScan("/barrier");
2793 yield* completeBarrier("barrier");
2794 assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]);
2795 }),
2796 );
2797
2798 it.effect("scans scanCwd and keys the workspace snapshot by cwd", () =>
2799 Effect.gen(function* () {
2800 const driver = ProviderDriverKind.make("codex");
2801 const instanceId = ProviderInstanceId.make("codex");
2802 const provider = {
2803 instanceId,
2804 driver,
2805 status: "ready",
2806 enabled: true,
2807 installed: true,
2808 auth: { status: "authenticated" },
2809 checkedAt: "2026-06-10T00:00:00.000Z",
2810 version: "1.0.0",
2811 models: [],
2812 slashCommands: [],
2813 skills: [],
2814 } as const satisfies ServerProvider;
2815 const scannedDirectories = yield* Ref.make<ReadonlyArray<string>>([]);
2816 const instance: ProviderInstance = {
2817 instanceId,
2818 driverKind: driver,
2819 continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" },
2820 displayName: undefined,
2821 enabled: true,
2822 snapshot: {
2823 resolveMaintenance: () =>
2824 Effect.succeed(
2825 makeManualOnlyProviderMaintenanceCapabilities({
2826 provider: driver,
2827 packageName: null,
2828 }),
2829 ),
2830 getSnapshot: Effect.succeed(provider),
2831 refresh: Effect.succeed(provider),
2832 streamChanges: Stream.empty,
2833 applyUsageLimits: () => Effect.void,
2834 },
2835 snapshotForCwd: (directory) =>
2836 Ref.update(scannedDirectories, (directories) => [...directories, directory]).pipe(
2837 Effect.as({
2838 ...provider,
2839 skills: [{ name: "finalize", path: `${directory}/finalize`, enabled: true }],
2840 }),
2841 ),
2842 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
2843 textGeneration: {} as ProviderInstance["textGeneration"],
2844 };
2845 const layerInstanceRegistry = Layer.succeed(
2846 ProviderInstanceRegistry.ProviderInstanceRegistry,
2847 {
2848 getInstance: (requestedId) =>
2849 Effect.succeed(requestedId === instanceId ? instance : undefined),
2850 listInstances: Effect.succeed([instance]),
2851 listUnavailable: Effect.succeed([]),
2852 streamChanges: Stream.empty,
2853 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
2854 },
2855 );
2856 const scope = yield* Scope.make();
2857 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
2858 const runtimeServices = yield* Layer.build(
2859 ProviderRegistry.layer.pipe(
2860 Layer.provide(layerUnusedMutator),
2861 Layer.provideMerge(layerInstanceRegistry),
2862 Layer.provideMerge(
2863 ServerConfig.layerTest(process.cwd(), {
2864 prefix: "t3-provider-registry-scan-cwd-",
2865 }),
2866 ),
2867 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
2868 ),
2869 ).pipe(Scope.provide(scope));
2870
2871 yield* Effect.gen(function* () {
2872 const registry = yield* ProviderRegistry.ProviderRegistry;
2873 const providers = yield* registry.refreshWorkspaceSnapshot({
2874 instanceId,
2875 cwd: "/worktree",
2876 scanCwd: "/project",
2877 });
2878 assert.deepStrictEqual(yield* Ref.get(scannedDirectories), ["/project"]);
2879 assert.deepStrictEqual(
2880 providers[0]?.workspaceSnapshots
2881 ?.find((snapshot) => snapshot.cwd === "/worktree")
2882 ?.skills?.map((skill) => skill.path),
2883 ["/project/finalize"],
2884 );
2885 }).pipe(Effect.provide(runtimeServices));
2886 }),
2887 );
2888
2889 it.effect("publishes workspace skills while machine health is in error", () =>
2890 Effect.gen(function* () {
2891 const driver = ProviderDriverKind.make("codex");
2892 const instanceId = ProviderInstanceId.make("codex");
2893 const healthyProvider = {
2894 instanceId,
2895 driver,
2896 status: "ready",
2897 enabled: true,
2898 installed: true,
2899 auth: { status: "authenticated" },
2900 checkedAt: "2026-06-10T00:00:00.000Z",
2901 version: "1.0.0",
2902 models: [],
2903 slashCommands: [COMPACT_SLASH_COMMAND],
2904 skills: [],
2905 } as const satisfies ServerProvider;
2906 const unhealthyProvider = {
2907 ...healthyProvider,
2908 status: "error",
2909 auth: { status: "unknown" },
2910 message: "Codex app-server provider probe failed: unauthorized (401).",
2911 slashCommands: [],
2912 } as const satisfies ServerProvider;
2913 const firstSkills = [{ name: "first", path: "/workspace/first/SKILL.md", enabled: true }];
2914 const laterSkills = [{ name: "later", path: "/workspace/later/SKILL.md", enabled: true }];
2915 const scanResult = yield* Ref.make<ProviderWorkspaceSnapshot>({
2916 ...healthyProvider,
2917 skills: firstSkills,
2918 });
2919 const instance: ProviderInstance = {
2920 instanceId,
2921 driverKind: driver,
2922 continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" },
2923 displayName: undefined,
2924 enabled: true,
2925 snapshot: {
2926 resolveMaintenance: () =>
2927 Effect.succeed(
2928 makeManualOnlyProviderMaintenanceCapabilities({
2929 provider: driver,
2930 packageName: null,
2931 }),
2932 ),
2933 getSnapshot: Effect.succeed(unhealthyProvider),
2934 refresh: Effect.succeed(unhealthyProvider),
2935 streamChanges: Stream.empty,
2936 applyUsageLimits: () => Effect.void,
2937 },
2938 snapshotForCwd: () => Ref.get(scanResult),
2939 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
2940 textGeneration: {} as ProviderInstance["textGeneration"],
2941 };
2942 const layerInstanceRegistry = Layer.succeed(
2943 ProviderInstanceRegistry.ProviderInstanceRegistry,
2944 {
2945 getInstance: (requestedId) =>
2946 Effect.succeed(requestedId === instanceId ? instance : undefined),
2947 listInstances: Effect.succeed([instance]),
2948 listUnavailable: Effect.succeed([]),
2949 streamChanges: Stream.empty,
2950 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
2951 },
2952 );
2953 const scope = yield* Scope.make();
2954 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
2955 const runtimeServices = yield* Layer.build(
2956 ProviderRegistry.layer.pipe(
2957 Layer.provide(layerUnusedMutator),
2958 Layer.provideMerge(layerInstanceRegistry),
2959 Layer.provideMerge(
2960 ServerConfig.layerTest(process.cwd(), {
2961 prefix: "t3-provider-registry-unhealthy-workspace-",
2962 }),
2963 ),
2964 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
2965 ),
2966 ).pipe(Scope.provide(scope));
2967
2968 yield* Effect.gen(function* () {
2969 const registry = yield* ProviderRegistry.ProviderRegistry;
2970 const workspaceOf = Effect.map(
2971 registry.getProviders,
2972 (providers) => providers[0]?.workspaceSnapshots?.[0],
2973 );
2974 yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" });
2975 assert.deepStrictEqual((yield* workspaceOf)?.slashCommands, [COMPACT_SLASH_COMMAND]);
2976
2977 yield* TestClock.adjust(PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS);
2978 yield* Ref.set(scanResult, { ...unhealthyProvider, skills: laterSkills });
2979 yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" });
2980 const unhealthy = yield* workspaceOf;
2981 assert.deepStrictEqual(unhealthy?.skills, laterSkills);
2982 assert.deepStrictEqual(unhealthy?.slashCommands, [COMPACT_SLASH_COMMAND]);
2983 assert.strictEqual(unhealthy?.slashCommandsPending, true);
2984 const provider = (yield* registry.getProviders)[0];
2985 assert.strictEqual(provider?.status, "error");
2986 assert.strictEqual(provider?.message, unhealthyProvider.message);
2987
2988 yield* Ref.set(scanResult, { ...unhealthyProvider, skills: [] });
2989 yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" });
2990 assert.deepStrictEqual((yield* workspaceOf)?.skills, []);
2991
2992 const discoveredCommand = { name: "review", description: "Review changes" };
2993 yield* Ref.set(scanResult, {
2994 ...unhealthyProvider,
2995 slashCommands: [discoveredCommand],
2996 slashCommandsPending: false,
2997 });
2998 yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" });
2999 const discovered = yield* workspaceOf;
3000 assert.deepStrictEqual(discovered?.slashCommands, [discoveredCommand]);
3001 assert.strictEqual(discovered?.slashCommandsPending, undefined);
3002
3003 yield* TestClock.adjust(PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS);
3004 yield* Ref.set(scanResult, { ...healthyProvider, skills: laterSkills });
3005 yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" });
3006 const recovered = yield* workspaceOf;
3007 assert.deepStrictEqual(recovered?.skills, laterSkills);
3008 assert.deepStrictEqual(recovered?.slashCommands, [COMPACT_SLASH_COMMAND]);
3009 assert.strictEqual(recovered?.slashCommandsPending, undefined);
3010 }).pipe(Effect.provide(runtimeServices));
3011 }),
3012 );
3013
3014 it.effect("rescans a folder whose model catalog could not be read before its TTL", () =>
3015 Effect.gen(function* () {
3016 const driver = ProviderDriverKind.make("opencode");
3017 const instanceId = ProviderInstanceId.make("opencode");
3018 const machineModel = {
3019 slug: "opencode/big-pickle",
3020 name: "Big Pickle",
3021 isCustom: false,
3022 capabilities: null,
3023 } satisfies ServerProvider["models"][number];
3024 const projectModel = { ...machineModel, slug: "uni/medium-gpt", name: "Medium GPT" };
3025 const provider = {
3026 instanceId,
3027 driver,
3028 status: "ready",
3029 enabled: true,
3030 installed: true,
3031 auth: { status: "authenticated" },
3032 checkedAt: "2026-06-10T00:00:00.000Z",
3033 version: "2.0.0",
3034 models: [machineModel],
3035 slashCommands: [],
3036 skills: [],
3037 } as const satisfies ServerProvider;
3038 const machineProvider = yield* Ref.make<ServerProvider>(provider);
3039 const scanResult = yield* Ref.make<ProviderWorkspaceSnapshot>({
3040 ...provider,
3041 slashCommandsPending: false,
3042 workspaceModelsPending: true,
3043 });
3044 const instance: ProviderInstance = {
3045 instanceId,
3046 driverKind: driver,
3047 continuationIdentity: {
3048 driverKind: driver,
3049 continuationKey: "opencode:instance:opencode",
3050 },
3051 displayName: undefined,
3052 enabled: true,
3053 snapshot: {
3054 resolveMaintenance: () =>
3055 Effect.succeed(
3056 makeManualOnlyProviderMaintenanceCapabilities({
3057 provider: driver,
3058 packageName: null,
3059 }),
3060 ),
3061 getSnapshot: Ref.get(machineProvider),
3062 refresh: Ref.get(machineProvider),
3063 streamChanges: Stream.empty,
3064 applyUsageLimits: () => Effect.void,
3065 },
3066 snapshotForCwd: () => Ref.get(scanResult),
3067 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
3068 textGeneration: {} as ProviderInstance["textGeneration"],
3069 };
3070 const layerInstanceRegistry = Layer.succeed(
3071 ProviderInstanceRegistry.ProviderInstanceRegistry,
3072 {
3073 getInstance: (requestedId) =>
3074 Effect.succeed(requestedId === instanceId ? instance : undefined),
3075 listInstances: Effect.succeed([instance]),
3076 listUnavailable: Effect.succeed([]),
3077 streamChanges: Stream.empty,
3078 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
3079 },
3080 );
3081 const scope = yield* Scope.make();
3082 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
3083 const runtimeServices = yield* Layer.build(
3084 ProviderRegistry.layer.pipe(
3085 Layer.provide(layerUnusedMutator),
3086 Layer.provideMerge(layerInstanceRegistry),
3087 Layer.provideMerge(
3088 ServerConfig.layerTest(process.cwd(), {
3089 prefix: "t3-provider-registry-pending-workspace-models-",
3090 }),
3091 ),
3092 Layer.provideMerge(NodeServices.layer),
3093 ),
3094 ).pipe(Scope.provide(scope));
3095
3096 yield* Effect.gen(function* () {
3097 const registry = yield* ProviderRegistry.ProviderRegistry;
3098 const workspaceOf = Effect.map(
3099 registry.getProviders,
3100 (providers) => providers[0]?.workspaceSnapshots?.[0],
3101 );
3102 yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/project" });
3103 const unread = yield* workspaceOf;
3104 assert.strictEqual(unread?.models, undefined);
3105 assert.strictEqual(unread?.modelsPending, true);
3106
3107 const workspaceModels = [machineModel, projectModel];
3108 yield* Ref.set(scanResult, { ...provider, slashCommandsPending: false, workspaceModels });
3109 yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/project" });
3110 const recovered = yield* workspaceOf;
3111 assert.deepStrictEqual(recovered?.models, workspaceModels);
3112 assert.strictEqual(recovered?.modelsPending, undefined);
3113
3114 // A fresh refresh whose machine models change still publishes the folder read it ran.
3115 const addedModel = { ...machineModel, slug: "opencode/new", name: "New" };
3116 const nextWorkspaceModels = [machineModel, addedModel, projectModel];
3117 yield* Ref.set(machineProvider, { ...provider, models: [machineModel, addedModel] });
3118 yield* Ref.set(scanResult, {
3119 ...provider,
3120 slashCommandsPending: false,
3121 workspaceModels: nextWorkspaceModels,
3122 });
3123 yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/project", fresh: true });
3124 const rescanned = yield* workspaceOf;
3125 assert.deepStrictEqual(rescanned?.models, nextWorkspaceModels);
3126 assert.strictEqual(rescanned?.modelsPending, undefined);
3127 }).pipe(Effect.provide(runtimeServices));
3128 }),
3129 );
3130
3131 it.effect("shares one in-flight pass between concurrent untargeted refreshes", () =>
3132 Effect.gen(function* () {
3133 const driver = ProviderDriverKind.make("codex");
3134 const instanceId = ProviderInstanceId.make("codex");
3135 const provider = {
3136 instanceId,
3137 driver,
3138 status: "ready",
3139 enabled: true,
3140 installed: true,
3141 auth: { status: "authenticated" },
3142 checkedAt: "2026-06-10T00:00:00.000Z",
3143 version: "1.0.0",
3144 models: [],
3145 slashCommands: [],
3146 skills: [],
3147 } as const satisfies ServerProvider;
3148 const refreshCalls = yield* Ref.make(0);
3149 const probeStarted = yield* Deferred.make<void>();
3150 const releaseProbe = yield* Deferred.make<void>();
3151 const instances = [
3152 {
3153 instanceId,
3154 driverKind: driver,
3155 continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" },
3156 displayName: undefined,
3157 enabled: true,
3158 snapshot: {
3159 resolveMaintenance: () =>
3160 Effect.succeed(
3161 makeManualOnlyProviderMaintenanceCapabilities({
3162 provider: driver,
3163 packageName: null,
3164 }),
3165 ),
3166 getSnapshot: Effect.succeed(provider),
3167 refresh: Effect.gen(function* () {
3168 yield* Ref.update(refreshCalls, (count) => count + 1);
3169 yield* Deferred.succeed(probeStarted, undefined);
3170 yield* Deferred.await(releaseProbe);
3171 return provider;
3172 }),
3173 streamChanges: Stream.empty,
3174 applyUsageLimits: () => Effect.void,
3175 },
3176 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
3177 textGeneration: {} as ProviderInstance["textGeneration"],
3178 },
3179 ] satisfies ReadonlyArray<ProviderInstance>;
3180 const instanceRegistryLayer = Layer.succeed(
3181 ProviderInstanceRegistry.ProviderInstanceRegistry,
3182 {
3183 getInstance: (requestedId) =>
3184 Effect.succeed(instances.find((instance) => instance.instanceId === requestedId)),
3185 listInstances: Effect.succeed(instances),
3186 listUnavailable: Effect.succeed([]),
3187 streamChanges: Stream.empty,
3188 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
3189 },
3190 );
3191 const scope = yield* Scope.make();
3192 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
3193 const runtimeServices = yield* Layer.build(
3194 ProviderRegistry.layer.pipe(
3195 Layer.provide(layerUnusedMutator),
3196 Layer.provideMerge(instanceRegistryLayer),
3197 Layer.provideMerge(
3198 ServerConfig.layerTest(process.cwd(), {
3199 prefix: "t3-provider-registry-shared-refresh-",
3200 }),
3201 ),
3202 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
3203 ),
3204 ).pipe(Scope.provide(scope));
3205
3206 yield* Effect.gen(function* () {
3207 const registry = yield* ProviderRegistry.ProviderRegistry;
3208 const first = yield* registry.refresh().pipe(Effect.forkChild);
3209 yield* Deferred.await(probeStarted);
3210 const second = yield* registry.refresh().pipe(Effect.forkChild);
3211 yield* Effect.yieldNow;
3212 assert.strictEqual(yield* Ref.get(refreshCalls), 1);
3213 yield* Deferred.succeed(releaseProbe, undefined);
3214 expect(yield* Fiber.join(first)).toEqual([expect.objectContaining(provider)]);
3215 expect(yield* Fiber.join(second)).toEqual([expect.objectContaining(provider)]);
3216 assert.strictEqual(yield* Ref.get(refreshCalls), 1);
3217
3218 yield* registry.refresh();
3219 assert.strictEqual(yield* Ref.get(refreshCalls), 2);
3220 }).pipe(Effect.provide(runtimeServices));
3221 }),
3222 );
3223
3224 it.effect("ignores a probe from an instance that settings replaced mid-refresh", () =>
3225 Effect.gen(function* () {
3226 const scenario = Effect.fn(function* (
3227 probeFails: boolean,
3228 run: (
3229 registry: ProviderRegistry.ProviderRegistry["Service"],
3230 ) => Effect.Effect<ReadonlyArray<ServerProvider>>,
3231 ) {
3232 const driver = ProviderDriverKind.make("codex");
3233 const instanceId = ProviderInstanceId.make("codex");
3234 const provider = {
3235 instanceId,
3236 driver,
3237 status: "ready",
3238 enabled: true,
3239 installed: true,
3240 auth: { status: "authenticated" },
3241 checkedAt: "2026-06-10T00:00:00.000Z",
3242 version: "2.0.0",
3243 models: [],
3244 slashCommands: [],
3245 skills: [],
3246 } as const satisfies ServerProvider;
3247 const retiredProbe = {
3248 ...provider,
3249 status: "error",
3250 installed: false,
3251 version: "1.0.0",
3252 message: "Codex CLI is not installed.",
3253 } as const satisfies ServerProvider;
3254 const probeStarted = yield* Deferred.make<void>();
3255 const releaseProbe = yield* Deferred.make<void>();
3256 const makeInstance = (snapshot: ServerProvider, refresh: Effect.Effect<void>) =>
3257 ({
3258 instanceId,
3259 driverKind: driver,
3260 continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" },
3261 displayName: undefined,
3262 enabled: true,
3263 snapshot: {
3264 resolveMaintenance: () =>
3265 Effect.succeed(
3266 makeManualOnlyProviderMaintenanceCapabilities({
3267 provider: driver,
3268 packageName: null,
3269 }),
3270 ),
3271 getSnapshot: Effect.succeed(snapshot),
3272 refresh: Effect.as(refresh, snapshot),
3273 streamChanges: Stream.empty,
3274 applyUsageLimits: () => Effect.void,
3275 },
3276 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
3277 textGeneration: {} as ProviderInstance["textGeneration"],
3278 }) satisfies ProviderInstance;
3279 const retiredInstance = makeInstance(
3280 retiredProbe,
3281 Deferred.succeed(probeStarted, undefined).pipe(
3282 Effect.andThen(Deferred.await(releaseProbe)),
3283 Effect.andThen(probeFails ? Effect.die(new Error("probe failed")) : Effect.void),
3284 ),
3285 );
3286 const rebuiltInstance = makeInstance(provider, Effect.void);
3287 const instances = yield* Ref.make<ReadonlyArray<ProviderInstance>>([retiredInstance]);
3288 const changes = yield* PubSub.unbounded<void>();
3289 const instanceRegistryLayer = Layer.succeed(
3290 ProviderInstanceRegistry.ProviderInstanceRegistry,
3291 {
3292 getInstance: (requestedId) =>
3293 Ref.get(instances).pipe(
3294 Effect.map((current) =>
3295 current.find((instance) => instance.instanceId === requestedId),
3296 ),
3297 ),
3298 listInstances: Ref.get(instances),
3299 listUnavailable: Effect.succeed([]),
3300 streamChanges: Stream.empty,
3301 subscribeChanges: PubSub.subscribe(changes),
3302 },
3303 );
3304 const scope = yield* Scope.make();
3305 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
3306 const runtimeServices = yield* Layer.build(
3307 ProviderRegistry.layer.pipe(
3308 Layer.provide(layerUnusedMutator),
3309 Layer.provideMerge(instanceRegistryLayer),
3310 Layer.provideMerge(
3311 ServerConfig.layerTest(process.cwd(), {
3312 prefix: "t3-provider-registry-retired-refresh-",
3313 }),
3314 ),
3315 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
3316 ),
3317 ).pipe(Scope.provide(scope));
3318
3319 return yield* Effect.gen(function* () {
3320 const registry = yield* ProviderRegistry.ProviderRegistry;
3321 const rebuiltPublished = yield* Stream.toPull(
3322 registry.streamChanges.pipe(
3323 Stream.filter((providers) => providers[0]?.version === provider.version),
3324 ),
3325 );
3326 const refresh = yield* run(registry).pipe(Effect.forkChild);
3327 yield* Deferred.await(probeStarted);
3328 yield* Ref.set(instances, [rebuiltInstance]);
3329 yield* PubSub.publish(changes, undefined);
3330 yield* rebuiltPublished;
3331 yield* Deferred.succeed(releaseProbe, undefined);
3332 return {
3333 provider,
3334 result: yield* Fiber.join(refresh),
3335 providers: yield* registry.getProviders,
3336 };
3337 }).pipe(Effect.provide(runtimeServices));
3338 });
3339 const driver = ProviderDriverKind.make("codex");
3340 const instanceId = ProviderInstanceId.make("codex");
3341
3342 const manual = yield* scenario(false, (registry) => registry.refresh());
3343 expect(manual.result).toEqual([expect.objectContaining(manual.provider)]);
3344 expect(manual.providers).toEqual([expect.objectContaining(manual.provider)]);
3345
3346 // Neither the retired probe's failure nor its cached row can stand in for the replacement.
3347 for (const probeFails of [true, false]) {
3348 const afterUpdate = yield* scenario(probeFails, (registry) =>
3349 registry.refreshAfterUpdate(driver, instanceId),
3350 );
3351 expect(afterUpdate.result).toEqual([]);
3352 expect(afterUpdate.providers).toEqual([expect.objectContaining(afterUpdate.provider)]);
3353 }
3354 }),
3355 );
3356
3357 it.effect("keeps an enriched snapshot that streams in before a manual refresh returns", () =>
3358 Effect.gen(function* () {
3359 const driver = ProviderDriverKind.make("acpRegistry");
3360 const instanceId = ProviderInstanceId.make("gemini");
3361 const initialProvider = {
3362 instanceId,
3363 driver,
3364 status: "ready",
3365 enabled: true,
3366 installed: true,
3367 auth: { status: "authenticated" },
3368 checkedAt: "2026-06-10T00:00:00.000Z",
3369 version: "1.0.0",
3370 models: [],
3371 slashCommands: [],
3372 skills: [],
3373 } as const satisfies ServerProvider;
3374 const pendingProvider = {
3375 ...initialProvider,
3376 status: "warning",
3377 auth: { status: "unknown" },
3378 checkedAt: "2026-06-10T00:01:00.000Z",
3379 message: "Checking ACP authentication, models, and commands in the background...",
3380 } as const satisfies ServerProvider;
3381 const enrichedProvider = {
3382 ...initialProvider,
3383 status: "error",
3384 auth: { status: "unauthenticated" },
3385 checkedAt: "2026-06-10T00:01:01.000Z",
3386 message: "Sign in to Gemini to use this agent.",
3387 } as const satisfies ServerProvider;
3388 const snapshotRef = yield* Ref.make<ServerProvider>(initialProvider);
3389 const changes = yield* PubSub.unbounded<ServerProvider>();
3390 const publishSnapshot = (provider: ServerProvider) =>
3391 Ref.set(snapshotRef, provider).pipe(Effect.andThen(PubSub.publish(changes, provider)));
3392 const releaseRefresh = yield* Deferred.make<void>();
3393 const instance = {
3394 instanceId,
3395 driverKind: driver,
3396 continuationIdentity: { driverKind: driver, continuationKey: "acpRegistry:gemini" },
3397 displayName: undefined,
3398 enabled: true,
3399 snapshot: {
3400 resolveMaintenance: () =>
3401 Effect.succeed(
3402 makeManualOnlyProviderMaintenanceCapabilities({
3403 provider: driver,
3404 packageName: null,
3405 }),
3406 ),
3407 getSnapshot: Ref.get(snapshotRef),
3408 // Like a managed provider: publish the probe, let enrichment publish its result,
3409 // then return the probe after a slow tail such as ACP's refreshMethods.
3410 refresh: Effect.gen(function* () {
3411 yield* publishSnapshot(pendingProvider);
3412 yield* publishSnapshot(enrichedProvider);
3413 yield* Deferred.await(releaseRefresh);
3414 return pendingProvider;
3415 }),
3416 streamChanges: Stream.fromPubSub(changes),
3417 applyUsageLimits: () => Effect.void,
3418 },
3419 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
3420 textGeneration: {} as ProviderInstance["textGeneration"],
3421 } satisfies ProviderInstance;
3422 const instanceRegistryLayer = Layer.succeed(
3423 ProviderInstanceRegistry.ProviderInstanceRegistry,
3424 {
3425 getInstance: (requestedId) =>
3426 Effect.succeed(requestedId === instanceId ? instance : undefined),
3427 listInstances: Effect.succeed([instance]),
3428 listUnavailable: Effect.succeed([]),
3429 streamChanges: Stream.empty,
3430 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
3431 },
3432 );
3433 const scope = yield* Scope.make();
3434 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
3435 const runtimeServices = yield* Layer.build(
3436 ProviderRegistry.layer.pipe(
3437 Layer.provide(layerUnusedMutator),
3438 Layer.provideMerge(instanceRegistryLayer),
3439 Layer.provideMerge(
3440 ServerConfig.layerTest(process.cwd(), {
3441 prefix: "t3-provider-registry-enriched-refresh-",
3442 }),
3443 ),
3444 Layer.provideMerge(NodeServices.layer),
3445 ),
3446 ).pipe(Scope.provide(scope));
3447
3448 yield* Effect.gen(function* () {
3449 const registry = yield* ProviderRegistry.ProviderRegistry;
3450 const config = yield* ServerConfig.ServerConfig;
3451 const filePath = yield* resolveProviderStatusCachePath({
3452 cacheDir: config.providerStatusCacheDir,
3453 instanceId,
3454 });
3455 expect(yield* registry.getProviders).toEqual([expect.objectContaining(initialProvider)]);
3456
3457 const enrichedObserved = yield* awaitPersistedProvider(
3458 registry,
3459 enrichedProvider.checkedAt,
3460 );
3461 const refreshed = yield* registry.refreshInstance(instanceId).pipe(Effect.forkChild);
3462 yield* Fiber.join(enrichedObserved);
3463 yield* Deferred.succeed(releaseRefresh, undefined);
3464 const returned = yield* Fiber.join(refreshed);
3465
3466 const enriched = {
3467 status: enrichedProvider.status,
3468 auth: enrichedProvider.auth,
3469 message: enrichedProvider.message,
3470 checkedAt: enrichedProvider.checkedAt,
3471 };
3472 expect(
3473 yield* registry.getProviders,
3474 "getProviders should hold the enriched snapshot, not the stale pending one refresh returned",
3475 ).toEqual([expect.objectContaining(enriched)]);
3476 expect(returned).toEqual([expect.objectContaining(enriched)]);
3477 expect(yield* readProviderStatusCache(filePath)).toEqual(
3478 expect.objectContaining(enriched),
3479 );
3480 }).pipe(Effect.provide(runtimeServices));
3481 }),
3482 );
3483
3484 it.effect("persists the merged snapshot when a live update has empty models", () =>
3485 Effect.gen(function* () {
3486 const cursorDriver = ProviderDriverKind.make("cursor");
3487 const cursorInstanceId = ProviderInstanceId.make("cursor");
3488 const initialProvider = {
3489 instanceId: cursorInstanceId,
3490 driver: cursorDriver,
3491 status: "ready",
3492 enabled: true,
3493 installed: true,
3494 auth: { status: "authenticated" },
3495 checkedAt: "2026-04-14T00:00:00.000Z",
3496 version: "2026.04.09-f2b0fcd",
3497 models: [
3498 {
3499 slug: "claude-opus-4-6",
3500 name: "Opus 4.6",
3501 isCustom: false,
3502 capabilities: createModelCapabilities({
3503 optionDescriptors: [
3504 selectDescriptor("reasoning", "Reasoning", [
3505 { id: "high", label: "High", isDefault: true },
3506 ]),
3507 ],
3508 }),
3509 },
3510 ],
3511 slashCommands: [],
3512 skills: [],
3513 } as const satisfies ServerProvider;
3514 const refreshedProvider = {
3515 ...initialProvider,
3516 status: "warning",
3517 checkedAt: "2026-04-14T00:01:00.000Z",
3518 models: [],
3519 } satisfies ServerProvider;
3520 const changes = yield* PubSub.unbounded<ServerProvider>();
3521 const instance = {
3522 instanceId: cursorInstanceId,
3523 driverKind: cursorDriver,
3524 continuationIdentity: {
3525 driverKind: cursorDriver,
3526 continuationKey: "cursor:instance:cursor",
3527 },
3528 displayName: undefined,
3529 enabled: true,
3530 snapshot: {
3531 resolveMaintenance: () =>
3532 Effect.succeed(
3533 makeManualOnlyProviderMaintenanceCapabilities({
3534 provider: cursorDriver,
3535 packageName: null,
3536 }),
3537 ),
3538 getSnapshot: Effect.succeed(initialProvider),
3539 refresh: Effect.succeed(refreshedProvider),
3540 streamChanges: Stream.fromPubSub(changes),
3541 applyUsageLimits: () => Effect.void,
3542 },
3543 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
3544 textGeneration: {} as ProviderInstance["textGeneration"],
3545 } satisfies ProviderInstance;
3546 const layerInstanceRegistry = Layer.succeed(
3547 ProviderInstanceRegistry.ProviderInstanceRegistry,
3548 {
3549 getInstance: (instanceId) =>
3550 Effect.succeed(instanceId === cursorInstanceId ? instance : undefined),
3551 listInstances: Effect.succeed([instance]),
3552 listUnavailable: Effect.succeed([]),
3553 streamChanges: Stream.empty,
3554 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
3555 PubSub.subscribe(pubsub),
3556 ),
3557 },
3558 );
3559 const scope = yield* Scope.make();
3560 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
3561 const runtimeServices = yield* Layer.build(
3562 ProviderRegistry.layer.pipe(
3563 Layer.provide(layerUnusedMutator),
3564 Layer.provideMerge(layerInstanceRegistry),
3565 Layer.provideMerge(
3566 ServerConfig.layerTest(process.cwd(), {
3567 prefix: "t3-provider-registry-merged-persist-",
3568 }),
3569 ),
3570 Layer.provideMerge(layerBackgroundPolicyAlwaysRun),
3571 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
3572 ),
3573 ).pipe(Scope.provide(scope));
3574
3575 yield* Effect.gen(function* () {
3576 const registry = yield* ProviderRegistry.ProviderRegistry;
3577 const config = yield* ServerConfig.ServerConfig;
3578 const filePath = yield* resolveProviderStatusCachePath({
3579 cacheDir: config.providerStatusCacheDir,
3580 instanceId: cursorInstanceId,
3581 });
3582
3583 assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
3584 ...initialProvider.models,
3585 ]);
3586 const persisted = yield* awaitPersistedProvider(registry, refreshedProvider.checkedAt);
3587 yield* PubSub.publish(changes, refreshedProvider);
3588 yield* Fiber.join(persisted);
3589 const cachedProvider = yield* readProviderStatusCache(filePath);
3590
3591 assert.deepStrictEqual(
3592 cachedProvider,
3593 withBundledCompatibility({
3594 ...refreshedProvider,
3595 models: [...initialProvider.models],
3596 modelsRetained: true,
3597 }),
3598 );
3599 }).pipe(Effect.provide(runtimeServices));
3600 }),
3601 );
3602
3603 it.effect("streams the terminal update state when it lands during a slow cache write", () =>
3604 Effect.gen(function* () {
3605 const claudeDriver = ProviderDriverKind.make("claude");
3606 const claudeInstanceId = ProviderInstanceId.make("claude");
3607 const initialProvider = {
3608 instanceId: claudeInstanceId,
3609 driver: claudeDriver,
3610 status: "ready",
3611 enabled: true,
3612 installed: true,
3613 auth: { status: "authenticated" },
3614 checkedAt: "2026-04-14T00:00:00.000Z",
3615 version: "2.1.300",
3616 models: [],
3617 slashCommands: [],
3618 skills: [],
3619 } as const satisfies ServerProvider;
3620 const verifyingProvider = { ...initialProvider, checkedAt: "2026-04-14T00:01:00.000Z" };
3621 const laterProvider = { ...initialProvider, checkedAt: "2026-04-14T00:02:00.000Z" };
3622 const changes = yield* PubSub.unbounded<ServerProvider>();
3623 const instance = {
3624 instanceId: claudeInstanceId,
3625 driverKind: claudeDriver,
3626 continuationIdentity: {
3627 driverKind: claudeDriver,
3628 continuationKey: "claude:instance:claude",
3629 },
3630 displayName: undefined,
3631 enabled: true,
3632 snapshot: {
3633 resolveMaintenance: () =>
3634 Effect.succeed(
3635 makeManualOnlyProviderMaintenanceCapabilities({
3636 provider: claudeDriver,
3637 packageName: null,
3638 }),
3639 ),
3640 getSnapshot: Effect.succeed(initialProvider),
3641 refresh: Effect.succeed(initialProvider),
3642 streamChanges: Stream.fromPubSub(changes),
3643 applyUsageLimits: () => Effect.void,
3644 },
3645 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
3646 textGeneration: {} as ProviderInstance["textGeneration"],
3647 } satisfies ProviderInstance;
3648 const layerInstanceRegistry = Layer.succeed(
3649 ProviderInstanceRegistry.ProviderInstanceRegistry,
3650 {
3651 getInstance: (instanceId) =>
3652 Effect.succeed(instanceId === claudeInstanceId ? instance : undefined),
3653 listInstances: Effect.succeed([instance]),
3654 listUnavailable: Effect.succeed([]),
3655 streamChanges: Stream.empty,
3656 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
3657 PubSub.subscribe(pubsub),
3658 ),
3659 },
3660 );
3661 const writeStarted = yield* Deferred.make<void>();
3662 const releaseWrite = yield* Deferred.make<void>();
3663 const gatedCachePath = yield* Ref.make<string | undefined>(undefined);
3664 const layerGatedFileSystem = Layer.effect(
3665 FileSystem.FileSystem,
3666 Effect.gen(function* () {
3667 const fileSystem = yield* FileSystem.FileSystem;
3668 return {
3669 ...fileSystem,
3670 rename: (from, to) =>
3671 Ref.modify(gatedCachePath, (path) =>
3672 path === to ? [true, undefined] : [false, path],
3673 ).pipe(
3674 Effect.flatMap((gated) =>
3675 gated
3676 ? Deferred.succeed(writeStarted, undefined).pipe(
3677 Effect.andThen(Deferred.await(releaseWrite)),
3678 )
3679 : Effect.void,
3680 ),
3681 Effect.andThen(fileSystem.rename(from, to)),
3682 ),
3683 } satisfies FileSystem.FileSystem;
3684 }),
3685 ).pipe(Layer.provide(NodeServices.layer));
3686 const scope = yield* Scope.make();
3687 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
3688 const runtimeServices = yield* Layer.build(
3689 ProviderRegistry.layer.pipe(
3690 Layer.provide(layerUnusedMutator),
3691 Layer.provideMerge(layerInstanceRegistry),
3692 Layer.provideMerge(
3693 ServerConfig.layerTest(process.cwd(), {
3694 prefix: "t3-provider-registry-update-state-race-",
3695 }),
3696 ),
3697 Layer.provideMerge(layerBackgroundPolicyAlwaysRun),
3698 Layer.provideMerge(layerGatedFileSystem),
3699 Layer.provideMerge(NodeServices.layer),
3700 ),
3701 ).pipe(Scope.provide(scope));
3702
3703 yield* Effect.gen(function* () {
3704 const registry = yield* ProviderRegistry.ProviderRegistry;
3705 const config = yield* ServerConfig.ServerConfig;
3706 const running = {
3707 status: "running",
3708 startedAt: "2026-04-14T00:00:30.000Z",
3709 finishedAt: null,
3710 message: "Verifying the installed version",
3711 output: null,
3712 } as const;
3713 const unchanged = {
3714 ...running,
3715 status: "unchanged",
3716 finishedAt: "2026-04-14T00:01:30.000Z",
3717 message:
3718 "Update command completed, but T3 Code still detects an outdated provider version.",
3719 } as const;
3720 yield* registry.setProviderMaintenanceActionState({
3721 instanceId: claudeInstanceId,
3722 action: "update",
3723 state: running,
3724 });
3725 const streamed = yield* registry.streamChanges.pipe(
3726 Stream.takeUntil((providers) =>
3727 providers.some((provider) => provider.checkedAt === laterProvider.checkedAt),
3728 ),
3729 Stream.runCollect,
3730 Effect.forkScoped({ startImmediately: true }),
3731 );
3732
3733 yield* Ref.set(
3734 gatedCachePath,
3735 yield* resolveProviderStatusCachePath({
3736 cacheDir: config.providerStatusCacheDir,
3737 instanceId: claudeInstanceId,
3738 }),
3739 );
3740 yield* PubSub.publish(changes, verifyingProvider);
3741 yield* Deferred.await(writeStarted);
3742 yield* registry.setProviderMaintenanceActionState({
3743 instanceId: claudeInstanceId,
3744 action: "update",
3745 state: unchanged,
3746 });
3747 yield* Deferred.succeed(releaseWrite, undefined);
3748 // The snapshot stream is consumed in order, so this lands after the slow write publishes.
3749 yield* PubSub.publish(changes, laterProvider);
3750
3751 const updateStateOf = (providers: ReadonlyArray<ServerProvider> | undefined) =>
3752 providers?.find((provider) => provider.instanceId === claudeInstanceId)?.updateState;
3753 const beforeLater = (yield* Fiber.join(streamed)).slice(0, -1);
3754 assert.deepStrictEqual(updateStateOf(yield* registry.getProviders), unchanged);
3755 assert.deepStrictEqual(
3756 updateStateOf(beforeLater.at(-1)),
3757 unchanged,
3758 "the last streamed providers before the next snapshot should carry the terminal update state",
3759 );
3760 }).pipe(Effect.provide(runtimeServices));
3761 }),
3762 );
3763
3764 it.effect(
3765 "persists authoritative OpenCode removals without resurrecting them on a failed live refresh",
3766 () =>
3767 Effect.gen(function* () {
3768 const openCodeDriver = ProviderDriverKind.make("opencode");
3769 const openCodeInstanceId = ProviderInstanceId.make("opencode");
3770 const initialProvider = {
3771 instanceId: openCodeInstanceId,
3772 driver: openCodeDriver,
3773 status: "ready",
3774 enabled: true,
3775 installed: true,
3776 auth: { status: "authenticated" },
3777 checkedAt: "2026-07-17T00:00:00.000Z",
3778 version: "1.0.0",
3779 models: [
3780 {
3781 slug: "github/gpt-5",
3782 name: "GPT-5",
3783 subProvider: "GitHub",
3784 isCustom: false,
3785 capabilities: null,
3786 },
3787 {
3788 slug: "removed-plugin/model",
3789 name: "Removed Plugin Model",
3790 subProvider: "Removed Plugin",
3791 isCustom: false,
3792 capabilities: null,
3793 },
3794 ],
3795 slashCommands: [],
3796 skills: [],
3797 } as const satisfies ServerProvider;
3798 const authoritativeProvider = {
3799 ...initialProvider,
3800 checkedAt: "2026-07-17T00:01:00.000Z",
3801 models: [initialProvider.models[0]!],
3802 } satisfies ServerProvider;
3803 const failedProvider = {
3804 ...authoritativeProvider,
3805 status: "error",
3806 auth: { status: "unknown" },
3807 checkedAt: "2026-07-17T00:02:00.000Z",
3808 models: [],
3809 message: "Failed to refresh OpenCode models.",
3810 } satisfies ServerProvider;
3811 const changes = yield* PubSub.unbounded<ServerProvider>();
3812 const instance = {
3813 instanceId: openCodeInstanceId,
3814 driverKind: openCodeDriver,
3815 continuationIdentity: {
3816 driverKind: openCodeDriver,
3817 continuationKey: "opencode:instance:opencode",
3818 },
3819 displayName: undefined,
3820 enabled: true,
3821 snapshot: {
3822 resolveMaintenance: () =>
3823 Effect.succeed(
3824 makeManualOnlyProviderMaintenanceCapabilities({
3825 provider: openCodeDriver,
3826 packageName: null,
3827 }),
3828 ),
3829 getSnapshot: Effect.succeed(initialProvider),
3830 refresh: Effect.succeed(authoritativeProvider),
3831 streamChanges: Stream.fromPubSub(changes),
3832 applyUsageLimits: () => Effect.void,
3833 },
3834 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
3835 textGeneration: {} as ProviderInstance["textGeneration"],
3836 } satisfies ProviderInstance;
3837 const layerInstanceRegistry = Layer.succeed(
3838 ProviderInstanceRegistry.ProviderInstanceRegistry,
3839 {
3840 getInstance: (instanceId) =>
3841 Effect.succeed(instanceId === openCodeInstanceId ? instance : undefined),
3842 listInstances: Effect.succeed([instance]),
3843 listUnavailable: Effect.succeed([]),
3844 streamChanges: Stream.empty,
3845 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
3846 PubSub.subscribe(pubsub),
3847 ),
3848 },
3849 );
3850 const scope = yield* Scope.make();
3851 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
3852 const runtimeServices = yield* Layer.build(
3853 ProviderRegistry.layer.pipe(
3854 Layer.provide(layerUnusedMutator),
3855 Layer.provideMerge(layerInstanceRegistry),
3856 Layer.provideMerge(
3857 ServerConfig.layerTest(process.cwd(), {
3858 prefix: "t3-provider-registry-opencode-authoritative-persist-",
3859 }),
3860 ),
3861 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
3862 ),
3863 ).pipe(Scope.provide(scope));
3864
3865 yield* Effect.gen(function* () {
3866 const registry = yield* ProviderRegistry.ProviderRegistry;
3867 const config = yield* ServerConfig.ServerConfig;
3868 const filePath = yield* resolveProviderStatusCachePath({
3869 cacheDir: config.providerStatusCacheDir,
3870 instanceId: openCodeInstanceId,
3871 });
3872
3873 const authoritativePersisted = yield* awaitPersistedProvider(
3874 registry,
3875 authoritativeProvider.checkedAt,
3876 );
3877 yield* PubSub.publish(changes, authoritativeProvider);
3878 yield* Fiber.join(authoritativePersisted);
3879 let cachedProvider = yield* readProviderStatusCache(filePath);
3880
3881 assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]);
3882
3883 const failedPersisted = yield* awaitPersistedProvider(
3884 registry,
3885 failedProvider.checkedAt,
3886 );
3887 yield* PubSub.publish(changes, failedProvider);
3888 yield* Fiber.join(failedPersisted);
3889 cachedProvider = yield* readProviderStatusCache(filePath);
3890
3891 assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]);
3892 assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [
3893 authoritativeProvider.models[0]!,
3894 ]);
3895 }).pipe(Effect.provide(runtimeServices));
3896 }),
3897 );
3898
3899 it.effect("returns the cached provider list when a manual refresh fails", () =>
3900 Effect.gen(function* () {
3901 const codexDriver = ProviderDriverKind.make("codex");
3902 const codexInstanceId = ProviderInstanceId.make("codex");
3903 const cachedProvider = {
3904 instanceId: codexInstanceId,
3905 driver: codexDriver,
3906 status: "ready",
3907 enabled: true,
3908 installed: true,
3909 auth: { status: "authenticated" },
3910 checkedAt: "2026-04-29T10:00:00.000Z",
3911 version: "1.0.0",
3912 models: [],
3913 slashCommands: [],
3914 skills: [],
3915 } as const satisfies ServerProvider;
3916 const instance = {
3917 instanceId: codexInstanceId,
3918 driverKind: codexDriver,
3919 continuationIdentity: {
3920 driverKind: codexDriver,
3921 continuationKey: "codex:instance:codex",
3922 },
3923 displayName: undefined,
3924 enabled: true,
3925 snapshot: {
3926 resolveMaintenance: () =>
3927 Effect.succeed(
3928 makeManualOnlyProviderMaintenanceCapabilities({
3929 provider: codexDriver,
3930 packageName: null,
3931 }),
3932 ),
3933 getSnapshot: Effect.succeed(cachedProvider),
3934 refresh: Effect.die(new Error("simulated refresh failure")),
3935 streamChanges: Stream.empty,
3936 applyUsageLimits: () => Effect.void,
3937 },
3938 orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
3939 textGeneration: {} as ProviderInstance["textGeneration"],
3940 } satisfies ProviderInstance;
3941 const layerInstanceRegistry = Layer.succeed(
3942 ProviderInstanceRegistry.ProviderInstanceRegistry,
3943 {
3944 getInstance: (instanceId) =>
3945 Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
3946 listInstances: Effect.succeed([instance]),
3947 listUnavailable: Effect.succeed([]),
3948 streamChanges: Stream.empty,
3949 subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
3950 PubSub.subscribe(pubsub),
3951 ),
3952 },
3953 );
3954 const scope = yield* Scope.make();
3955 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
3956 const runtimeServices = yield* Layer.build(
3957 ProviderRegistry.layer.pipe(
3958 Layer.provide(layerUnusedMutator),
3959 Layer.provideMerge(layerInstanceRegistry),
3960 Layer.provideMerge(
3961 ServerConfig.layerTest(process.cwd(), {
3962 prefix: "t3-provider-registry-refresh-failure-",
3963 }),
3964 ),
3965 Layer.provideMerge(layerBackgroundPolicyAlwaysRun),
3966 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
3967 ),
3968 ).pipe(Scope.provide(scope));
3969
3970 yield* Effect.gen(function* () {
3971 const registry = yield* ProviderRegistry.ProviderRegistry;
3972
3973 assert.deepStrictEqual(yield* registry.getProviders, [
3974 withBundledCompatibility(cachedProvider),
3975 ]);
3976 assert.deepStrictEqual(yield* registry.refresh(codexDriver), [
3977 withBundledCompatibility(cachedProvider),
3978 ]);
3979 assert.deepStrictEqual(yield* registry.refreshInstance(codexInstanceId), [
3980 withBundledCompatibility(cachedProvider),
3981 ]);
3982 }).pipe(Effect.provide(runtimeServices));
3983 }),
3984 );
3985
3986 describe("update results across refreshes", () => {
3987 const instanceId = ProviderInstanceId.make("codex");
3988
3989 it.effect.each([
3990 { status: "unchanged", advisory: "current", retired: true },
3991 { status: "failed", advisory: "current", retired: true },
3992 { status: "unchanged", advisory: "behind_latest", retired: false },
3993 { status: "failed", advisory: "behind_latest", retired: false },
3994 // The probe publishes `unknown` until the latest-version check lands.
3995 { status: "unchanged", advisory: "unknown", retired: false },
3996 { status: "queued", advisory: "current", retired: false },
3997 { status: "running", advisory: "current", retired: false },
3998 { status: "succeeded", advisory: "current", retired: false },
3999 { status: "failed", advisory: "unknown", retired: false },
4000 ] as const)(
4001 "a $status update result is retired: $retired when a refresh reports the provider $advisory",
4002 ({ status, advisory, retired }) =>
4003 Effect.gen(function* () {
4004 const snapshot = yield* Ref.make<ServerProvider>(codexUpdateSnapshot("behind_latest"));
4005 const runtimeServices = yield* buildRegistryOverSnapshot(snapshot);
4006
4007 yield* Effect.gen(function* () {
4008 const registry = yield* ProviderRegistry.ProviderRegistry;
4009 const state = makeUpdateState(status);
4010 yield* registry.setProviderMaintenanceActionState({
4011 instanceId,
4012 action: "update",
4013 state,
4014 });
4015 yield* Ref.set(snapshot, codexUpdateSnapshot(advisory));
4016
4017 const [refreshed] = yield* registry.refresh(ProviderDriverKind.make("codex"));
4018
4019 expect(refreshed?.updateState).toEqual(retired ? undefined : state);
4020 }).pipe(Effect.provide(runtimeServices));
4021 }),
4022 );
4023
4024 it.effect.each(["failed", "unchanged"] as const)(
4025 "keeps a %s recommended-version install after a current refresh",
4026 (status) =>
4027 Effect.gen(function* () {
4028 const snapshot = yield* Ref.make<ServerProvider>(codexUpdateSnapshot("current"));
4029 const runtimeServices = yield* buildRegistryOverSnapshot(snapshot);
4030 yield* Effect.gen(function* () {
4031 const registry = yield* ProviderRegistry.ProviderRegistry;
4032 const state = makeUpdateState(status);
4033 const input = {
4034 instanceId,
4035 action: "update" as const,
4036 state,
4037 targetVersion: "0.9.0",
4038 };
4039 yield* registry.setProviderMaintenanceActionState(input);
4040 const [refreshed] = yield* registry.refresh(ProviderDriverKind.make("codex"));
4041 expect(refreshed?.updateState).toEqual(state);
4042 }).pipe(Effect.provide(runtimeServices));
4043 }),
4044 );
4045 });
4046
4047 it.effect("re-probes when settings change the codex binaryPath", () =>
4048 Effect.gen(function* () {
4049 const firstMissing = `t3code_codex_first_`;
4050 const secondMissing = `t3code_codex_second_`;
4051 const spawnedCommands: Array<string> = [];
4052 const secondProbeStarted = yield* Deferred.make<void>();
4053 const releaseSecondProbe = yield* Deferred.make<void>();
4054 const allowLazySettingsStream = yield* Deferred.make<void>();
4055 const mutableServerSettings = yield* makeMutableServerSettingsService(
4056 decodeServerSettings(
4057 deepMerge(encodedDefaultServerSettings, {
4058 providerInstances: {
4059 ...disabledDefaultSlots("claudeAgent", "cursor", "grok", "opencode"),
4060 [ProviderInstanceId.make("codex")]: {
4061 driver: ProviderDriverKind.make("codex"),
4062 enabled: true,
4063 config: { binaryPath: firstMissing },
4064 },
4065 },
4066 }),
4067 ),
4068 );
4069 const serverSettings = {
4070 ...mutableServerSettings,
4071 streamChanges: Stream.unwrap(
4072 Deferred.await(allowLazySettingsStream).pipe(
4073 Effect.as(mutableServerSettings.streamChanges),
4074 ),
4075 ),
4076 } satisfies ServerSettingsModule.ServerSettingsService["Service"];
4077 const scope = yield* Scope.make();
4078 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
4079 const layerProviderRegistry = ProviderRegistry.layer.pipe(
4080 Layer.provideMerge(
4081 ProviderInstanceRegistryHydration.layer.pipe(
4082 Layer.provide(
4083 Layer.mergeAll(
4084 PortScanner.layerTest,
4085 ProviderInstallationGate.layer,
4086 SqlitePersistence.layerMemory,
4087 ),
4088 ),
4089 ),
4090 ),
4091 Layer.provideMerge(AntigravityInstallation.AntigravityInstallation.layer),
4092 Layer.provideMerge(
4093 Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
4094 ),
4095 Layer.provideMerge(ServerSecretStore.layer),
4096 Layer.provideMerge(
4097 ServerConfig.layerTest(process.cwd(), {
4098 prefix: "t3-provider-registry-",
4099 }),
4100 ),
4101 Layer.provideMerge(layerTestHttpClient),
4102 Layer.provideMerge(
4103 Layer.succeed(
4104 ProviderEventLoggers.ProviderEventLoggers,
4105 ProviderEventLoggers.NoOpProviderEventLoggers,
4106 ),
4107 ),
4108 Layer.provideMerge(ProviderLatestVersions.layer),
4109 Layer.provideMerge(McpProviderSessions.layer),
4110 Layer.provideMerge(ModelManifest.layerTest),
4111 Layer.provideMerge(ResetCreditCoordinator.layerTest),
4112 Layer.provideMerge(
4113 OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)),
4114 ),
4115 Layer.updateService(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>
4116 ChildProcessSpawner.make((command) => {
4117 if (command._tag !== "StandardCommand") return spawner.spawn(command);
4118 spawnedCommands.push(command.command);
4119 const beforeSpawn =
4120 command.command === secondMissing
4121 ? Deferred.succeed(secondProbeStarted, undefined).pipe(
4122 Effect.andThen(Deferred.await(releaseSecondProbe)),
4123 )
4124 : Effect.void;
4125 return beforeSpawn.pipe(Effect.andThen(spawner.spawn(command)));
4126 }),
4127 ),
4128 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
4129 Layer.provideMerge(layerBackgroundPolicyAlwaysRun),
4130 );
4131 const runtimeServices = yield* Layer.build(layerProviderRegistry).pipe(
4132 Scope.provide(scope),
4133 );
4134
4135 yield* Effect.gen(function* () {
4136 const registry = yield* ProviderRegistry.ProviderRegistry;
4137 const codexSnapshots = registry.streamChanges.pipe(
4138 Stream.map((providers) =>
4139 providers.find((provider) => provider.instanceId === "codex"),
4140 ),
4141 Stream.filter((provider): provider is ServerProvider => provider !== undefined),
4142 );
4143 const firstError = yield* Stream.toPull(
4144 codexSnapshots.pipe(Stream.filter((provider) => provider.status === "error")),
4145 );
4146 const currentCodex = (yield* registry.getProviders).find(
4147 (provider) => provider.instanceId === "codex",
4148 );
4149 const initialCodex =
4150 currentCodex?.status === "error" ? currentCodex : (yield* firstError)[0];
4151 assert.strictEqual(initialCodex?.status, "error");
4152 assert.strictEqual(initialCodex?.installed, false);
4153 assert.deepStrictEqual(spawnedCommands, [firstMissing]);
4154
4155 const pendingRebuild = yield* Stream.toPull(
4156 codexSnapshots.pipe(
4157 Stream.filter((provider) => provider.status === "warning" && !provider.installed),
4158 ),
4159 );
4160 yield* serverSettings.updateSettings({
4161 providerInstances: {
4162 ...disabledDefaultSlots("claudeAgent", "cursor", "grok", "opencode"),
4163 [ProviderInstanceId.make("codex")]: {
4164 driver: ProviderDriverKind.make("codex"),
4165 enabled: true,
4166 config: { binaryPath: secondMissing },
4167 },
4168 },
4169 });
4170 yield* Deferred.succeed(allowLazySettingsStream, undefined);
4171
4172 yield* Deferred.await(secondProbeStarted);
4173 yield* pendingRebuild;
4174 const rebuiltError = yield* Stream.toPull(
4175 codexSnapshots.pipe(Stream.filter((provider) => provider.status === "error")),
4176 );
4177 yield* Deferred.succeed(releaseSecondProbe, undefined);
4178 const [reprobedCodex] = yield* rebuiltError;
4179 assert.deepStrictEqual(spawnedCommands, [firstMissing, secondMissing]);
4180 assert.strictEqual(reprobedCodex?.status, "error");
4181 assert.strictEqual(reprobedCodex?.installed, false);
4182 }).pipe(Effect.provide(runtimeServices));
4183 }),
4184 );
4185
4186 it.effect("includes unavailable instance snapshots in getProviders", () =>
4187 Effect.gen(function* () {
4188 const serverSettings = yield* makeMutableServerSettingsService(
4189 decodeServerSettings(
4190 deepMerge(encodedDefaultServerSettings, {
4191 providerInstances: {
4192 ...disabledDefaultSlots("codex", "claudeAgent", "cursor", "grok", "opencode"),
4193 ghost_main: {
4194 driver: "ghostDriver",
4195 displayName: "A fork-only driver we don't ship",
4196 enabled: false,
4197 config: { arbitrary: "payload" },
4198 },
4199 } as unknown as (typeof ServerSettings.Encoded)["providerInstances"],
4200 }),
4201 ),
4202 );
4203 const scope = yield* Scope.make();
4204 yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
4205 const layerProviderRegistry = ProviderRegistry.layer.pipe(
4206 Layer.provideMerge(
4207 ProviderInstanceRegistryHydration.layer.pipe(
4208 Layer.provide(
4209 Layer.mergeAll(
4210 PortScanner.layerTest,
4211 ProviderInstallationGate.layer,
4212 SqlitePersistence.layerMemory,
4213 ),
4214 ),
4215 ),
4216 ),
4217 Layer.provideMerge(AntigravityInstallation.AntigravityInstallation.layer),
4218 Layer.provideMerge(
4219 Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
4220 ),
4221 Layer.provideMerge(ServerSecretStore.layer),
4222 Layer.provideMerge(
4223 ServerConfig.layerTest(process.cwd(), {
4224 prefix: "t3-provider-registry-",
4225 }),
4226 ),
4227 Layer.provideMerge(layerTestHttpClient),
4228 Layer.provideMerge(
4229 Layer.succeed(
4230 ProviderEventLoggers.ProviderEventLoggers,
4231 ProviderEventLoggers.NoOpProviderEventLoggers,
4232 ),
4233 ),
4234 Layer.provideMerge(ProviderLatestVersions.layer),
4235 Layer.provideMerge(McpProviderSessions.layer),
4236 Layer.provideMerge(ModelManifest.layerTest),
4237 Layer.provideMerge(ResetCreditCoordinator.layerTest),
4238 Layer.provideMerge(
4239 OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)),
4240 ),
4241 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
4242 Layer.provideMerge(layerBackgroundPolicyAlwaysRun),
4243 );
4244 const runtimeServices = yield* Layer.build(layerProviderRegistry).pipe(
4245 Scope.provide(scope),
4246 );
4247
4248 yield* Effect.gen(function* () {
4249 const registry = yield* ProviderRegistry.ProviderRegistry;
4250 const providers = yield* registry.getProviders;
4251 const ghost = providers.find((provider) => provider.instanceId === "ghost_main");
4252
4253 assert.notStrictEqual(ghost, undefined);
4254 assert.strictEqual(ghost?.driver, "ghostDriver");
4255 assert.strictEqual(ghost?.availability, "unavailable");
4256 assert.strictEqual(Object.hasOwn(ghost ?? {}, "setup"), false);
4257 assert.match(ghost?.unavailableReason ?? "", /ghostDriver/);
4258 }).pipe(Effect.provide(runtimeServices));
4259 }),
4260 );
4261
4262 const startupSettings = (instanceId?: string) =>
4263 decodeServerSettings({
4264 ...encodedDefaultServerSettings,
4265 providerInstances: {
4266 ...disabledDefaultSlots(
4267 "codex",
4268 "claudeAgent",
4269 "cursor",
4270 "grok",
4271 "opencode",
4272 "antigravity",
4273 "pi",
4274 "muse",
4275 ),
4276 ...(instanceId ? { [instanceId]: { driver: "ghostDriver" } } : {}),
4277 },
4278 });
4279
4280 const hydrateDuringSettingsChange = Effect.fnUntraced(function* (input: {
4281 seed: ContractServerSettings;
4282 saved: ContractServerSettings;
4283 current: ContractServerSettings;
4284 failCurrentRead?: boolean;
4285 }) {
4286 const changes = yield* PubSub.unbounded<ContractServerSettings | undefined>();
4287 const consume = yield* Deferred.make<void>();
4288 const drained: Array<Deferred.Deferred<void>> = [];
4289 let readSeed = true;
4290 let failCurrentRead = false;
4291 const settings = yield* makeMutableServerSettingsService(input.current);
4292 const serverSettings = {
4293 ...settings,
4294 getSettings: Effect.suspend(() => {
4295 if (!readSeed) {
4296 readSeed = true;
4297 return PubSub.publish(changes, input.saved).pipe(Effect.as(input.seed));
4298 }
4299 return failCurrentRead
4300 ? Effect.fail(
4301 new ServerSettingsError({
4302 settingsPath: "<memory>",
4303 operation: "read-secret",
4304 cause: new Error("secret materialization failed"),
4305 }),
4306 )
4307 : settings.getSettings;
4308 }),
4309 streamChanges: Stream.empty,
4310 subscribeChanges: Effect.gen(function* () {
4311 const subscription = yield* PubSub.subscribe(changes);
4312 const done = yield* Deferred.make<void>();
4313 drained.push(done);
4314 // The terminal marker acknowledges preceding reconciles, including no-op/failed reads.
4315 return Stream.fromEffectRepeat(
4316 Deferred.await(consume).pipe(Effect.andThen(PubSub.take(subscription))),
4317 ).pipe(
4318 Stream.takeWhile((next): next is ContractServerSettings => next !== undefined),
4319 Stream.ensuring(Deferred.succeed(done, undefined)),
4320 );
4321 }),
4322 } satisfies ServerSettingsModule.ServerSettingsService["Service"];
4323 const dependencies = yield* Layer.build(
4324 Layer.mergeAll(
4325 AntigravityInstallation.AntigravityInstallation.layer,
4326 ServerSecretStore.layer,
4327 OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)),
4328 ).pipe(
4329 Layer.provideMerge(
4330 Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings),
4331 ),
4332 Layer.provideMerge(
4333 ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-" }),
4334 ),
4335 Layer.provideMerge(layerTestHttpClient),
4336 Layer.provideMerge(
4337 Layer.succeed(
4338 ProviderEventLoggers.ProviderEventLoggers,
4339 ProviderEventLoggers.NoOpProviderEventLoggers,
4340 ),
4341 ),
4342 Layer.provideMerge(ProviderLatestVersions.layer),
4343 Layer.provideMerge(McpProviderSessions.layer),
4344 Layer.provideMerge(ResetCreditCoordinator.layerTest),
4345 Layer.provideMerge(layerBackgroundPolicyAlwaysRun),
4346 ),
4347 );
4348 readSeed = false;
4349 const services = yield* Layer.build(
4350 ProviderInstanceRegistryHydration.layer.pipe(
4351 Layer.provide(
4352 Layer.mergeAll(
4353 PortScanner.layerTest,
4354 ProviderInstallationGate.layer,
4355 SqlitePersistence.layerMemory,
4356 ),
4357 ),
4358 ),
4359 ).pipe(Effect.provide(dependencies));
4360 failCurrentRead = input.failCurrentRead ?? false;
4361 yield* PubSub.publish(changes, undefined);
4362 yield* Deferred.succeed(consume, undefined);
4363 yield* Effect.forEach(drained, Deferred.await);
4364 const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry.pipe(
4365 Effect.provide(services),
4366 );
4367 return (yield* registry.listUnavailable).map(
4368 (provider): string | undefined => provider.instanceId,
4369 );
4370 });
4371
4372 it.effect("applies a settings change saved while the provider registry starts", () =>
4373 Effect.gen(function* () {
4374 const saved = startupSettings("ghost_late");
4375 const unavailable = yield* hydrateDuringSettingsChange({
4376 seed: startupSettings(),
4377 saved,
4378 current: saved,
4379 });
4380 assert.include(unavailable, "ghost_late");
4381 }),
4382 );
4383
4384 it.effect("does not apply a queued settings change older than the registry seed", () =>
4385 Effect.gen(function* () {
4386 const seed = startupSettings("ghost_current");
4387 const unavailable = yield* hydrateDuringSettingsChange({
4388 seed,
4389 saved: startupSettings("ghost_stale"),
4390 current: seed,
4391 });
4392 assert.include(unavailable, "ghost_current");
4393 assert.notInclude(unavailable, "ghost_stale");
4394 }),
4395 );
4396
4397 it.effect(
4398 "retains the newer registry seed when a queued stale change cannot read current settings",
4399 () =>
4400 Effect.gen(function* () {
4401 const seed = startupSettings("ghost_current");
4402 const unavailable = yield* hydrateDuringSettingsChange({
4403 seed,
4404 saved: startupSettings("ghost_stale"),
4405 current: seed,
4406 failCurrentRead: true,
4407 });
4408 assert.include(unavailable, "ghost_current");
4409 assert.notInclude(unavailable, "ghost_stale");
4410 }),
4411 );
4412 });
4413
4414 describe("checkClaudeProviderStatus", () => {
4415 it.effect("adds models Claude Code reports that the catalog does not know", () =>
4416 Effect.gen(function* () {
4417 const status = yield* checkClaudeProviderStatus(
4418 {
4419 ...defaultClaudeSettings,
4420 customModels: [{ slug: "gateway/kimi-3[1m]", name: "Kimi (mine)" }],
4421 },
4422 claudeCapabilities({
4423 models: [
4424 { value: "default", displayName: "Default", description: "" },
4425 { value: "sonnet", displayName: "Sonnet", description: "" },
4426 { value: "claude-haiku-4-5[1m]", displayName: "Haiku", description: "" },
4427 {
4428 value: "best",
4429 resolvedModel: "claude-opus-5[1m]",
4430 displayName: "Best",
4431 description: "",
4432 },
4433 { value: "gateway/kimi-3[1m]", displayName: "Kimi 3", description: "" },
4434 { value: "gateway/glm-5[1m]", displayName: "GLM 5", description: "" },
4435 { value: "gateway/glm-5", displayName: "GLM 5 again", description: "" },
4436 {
4437 value: "gateway/claude-relay",
4438 displayName: "Claude Relay",
4439 description: "",
4440 supportsEffort: true,
4441 supportedEffortLevels: ["low", "high"],
4442 },
4443 ],
4444 }),
4445 );
4446 const catalogSlugs = new Set(BUNDLED_CLAUDE_MODEL_CATALOG.models.map((m) => m.model.slug));
4447 const added = status.models.filter((model) => !catalogSlugs.has(model.slug));
4448
4449 assert.deepStrictEqual(
4450 added.map((model) => [model.slug, model.name, model.isCustom]),
4451 [
4452 ["gateway/glm-5[1m]", "GLM 5", false],
4453 ["gateway/claude-relay", "Claude Relay", false],
4454 ["gateway/kimi-3[1m]", "Kimi (mine)", true],
4455 ],
4456 );
4457 assert.deepStrictEqual(added[0]?.capabilities?.optionDescriptors, []);
4458 assert.deepStrictEqual(added[1]?.capabilities?.optionDescriptors, [
4459 {
4460 id: "effort",
4461 label: "Reasoning",
4462 type: "select",
4463 options: [
4464 { id: "default", label: "Default", isDefault: true },
4465 { id: "low", label: "Low" },
4466 { id: "high", label: "High" },
4467 ],
4468 },
4469 ]);
4470 }).pipe(
4471 Effect.provide(
4472 layerMockSpawner((args) => {
4473 const joined = args.join(" ");
4474 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
4475 throw new Error(`Unexpected args: ${joined}`);
4476 }),
4477 ),
4478 ),
4479 );
4480
4481 it.effect("does not let a lazy mise shim install Claude during a status check (#33415)", () =>
4482 Effect.gen(function* () {
4483 if ((yield* HostProcess.Platform) === "win32") return;
4484 const fs = yield* FileSystem.FileSystem;
4485 const path = yield* Path.Path;
4486 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-fake-mise-claude-" });
4487 const installMarker = path.join(directory, "installed");
4488 const binaryPath = path.join(directory, "claude");
4489 // A `lazy = true` mise shim downloads and installs the tool unless MISE_OFFLINE is set.
4490 yield* fs.writeFileString(
4491 binaryPath,
4492 [
4493 `#!/bin/sh`,
4494 `case "$MISE_OFFLINE" in`,
4495 ` 1|true) cat >&2 <<'EOF'`,
4496 `mise WARN Failed to resolve tool version list for claude: [/home/u/.config/mise/config.toml] claude@latest: no versions found for claude`,
4497 `mise ERROR Failed to install aqua:anthropics/claude-code@latest: no versions found for claude`,
4498 `mise ERROR Version: 2026.11.5 linux-x64 (2026-11-09)`,
4499 `mise ERROR Run with --verbose or MISE_VERBOSE=1 for more information`,
4500 `EOF`,
4501 ` exit 1 ;;`,
4502 `esac`,
4503 `touch "${installMarker}"`,
4504 `echo "2.1.0 (Claude Code)"`,
4505 ].join("\n"),
4506 );
4507 yield* fs.chmod(binaryPath, 0o755);
4508 const { MISE_OFFLINE: _, ...environment } = process.env;
4509
4510 const status = yield* checkClaudeProviderStatus(
4511 { ...defaultClaudeSettings, binaryPath },
4512 claudeCapabilities(),
4513 environment,
4514 );
4515
4516 assert.isFalse(
4517 yield* fs.exists(installMarker),
4518 "the Claude --version status probe let mise install Claude",
4519 );
4520 assert.isNull(status.version, "mise's own version is not Claude's");
4521 }),
4522 );
4523
4524 it.effect("reports a logged-out CLI as unauthenticated", () =>
4525 Effect.gen(function* () {
4526 const status = yield* checkClaudeProviderStatus(
4527 defaultClaudeSettings,
4528 claudeCapabilities({
4529 tokenSource: "none",
4530 apiKeySource: "none",
4531 apiProvider: "firstParty",
4532 }),
4533 { ANTHROPIC_BASE_URL: "" },
4534 );
4535 assert.strictEqual(status.status, "error");
4536 assert.strictEqual(status.auth.status, "unauthenticated");
4537 }).pipe(
4538 Effect.provide(
4539 layerMockSpawner((args) => {
4540 const joined = args.join(" ");
4541 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
4542 throw new Error(`Unexpected args: ${joined}`);
4543 }),
4544 ),
4545 ),
4546 );
4547
4548 it.effect.each([
4549 {
4550 name: "its own home path",
4551 homePath: "/srv/claude-personal",
4552 environment: { ANTHROPIC_BASE_URL: "" },
4553 configDir: "/srv/claude-personal",
4554 },
4555 {
4556 name: "an inherited CLAUDE_CONFIG_DIR",
4557 homePath: "",
4558 environment: { ANTHROPIC_BASE_URL: "", CLAUDE_CONFIG_DIR: "/srv/claude-work" },
4559 configDir: "/srv/claude-work",
4560 },
4561 {
4562 name: "the default config dir",
4563 homePath: "",
4564 environment: { ANTHROPIC_BASE_URL: "" },
4565 configDir: undefined,
4566 },
4567 ])(
4568 "tells a logged-out instance on $name where to sign in",
4569 ({ homePath, environment, configDir }) =>
4570 Effect.gen(function* () {
4571 const status = yield* checkClaudeProviderStatus(
4572 { ...defaultClaudeSettings, homePath },
4573 claudeCapabilities({
4574 tokenSource: "none",
4575 apiKeySource: "none",
4576 apiProvider: "firstParty",
4577 }),
4578 environment,
4579 );
4580 assert.strictEqual(status.auth.status, "unauthenticated");
4581 if (configDir === undefined) {
4582 assert.strictEqual(
4583 status.message,
4584 "Claude Code is not authenticated. Run `claude auth login` and try again.",
4585 );
4586 } else {
4587 // A home path is resolved to a native path; an inherited value is kept literal.
4588 const expected = homePath ? (yield* Path.Path).resolve(configDir) : configDir;
4589 assert.include(
4590 status.message ?? "",
4591 `CLAUDE_CONFIG_DIR set to ${JSON.stringify(expected)}`,
4592 "a bare `claude auth login` signs in ~/.claude, not this instance's config dir",
4593 );
4594 }
4595 }).pipe(
4596 Effect.provide(
4597 layerMockSpawner((args) => {
4598 const joined = args.join(" ");
4599 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
4600 throw new Error(`Unexpected args: ${joined}`);
4601 }),
4602 ),
4603 ),
4604 );
4605
4606 it.effect("tells a logged-out CLI which models need a Claude Code update", () =>
4607 Effect.gen(function* () {
4608 const status = yield* checkClaudeProviderStatus(
4609 defaultClaudeSettings,
4610 claudeCapabilities({
4611 tokenSource: "none",
4612 apiKeySource: "none",
4613 apiProvider: "firstParty",
4614 }),
4615 { ANTHROPIC_BASE_URL: "" },
4616 undefined,
4617 {
4618 models: [
4619 {
4620 model: { slug: "claude-next", name: "Next", isCustom: false, capabilities: null },
4621 runtime: {},
4622 compatibility: { minVersion: "1.1.0" },
4623 },
4624 ],
4625 },
4626 );
4627 assert.strictEqual(status.auth.status, "unauthenticated");
4628 assert.deepStrictEqual(status.updateRequiredModels, [
4629 { slug: "claude-next", name: "Next", minVersion: "1.1.0" },
4630 ]);
4631 }).pipe(
4632 Effect.provide(
4633 layerMockSpawner((args) => {
4634 const joined = args.join(" ");
4635 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
4636 throw new Error(`Unexpected args: ${joined}`);
4637 }),
4638 ),
4639 ),
4640 );
4641
4642 it.effect.each([
4643 { source: "inherited HTTPS endpoint", baseUrl: "https://proxy.example/api", overrides: [] },
4644 {
4645 source: "instance HTTP endpoint overriding Anthropic",
4646 baseUrl: "https://api.anthropic.com",
4647 overrides: [
4648 { name: "ANTHROPIC_BASE_URL", value: "http://localhost:8080", sensitive: false },
4649 ],
4650 },
4651 ])("keeps Claude ready with an empty first-party account: $source", ({ baseUrl, overrides }) =>
4652 Effect.gen(function* () {
4653 const environment = yield* mergeProviderInstanceEnvironment(overrides, {
4654 ANTHROPIC_BASE_URL: baseUrl,
4655 });
4656 const status = yield* checkClaudeProviderStatus(
4657 defaultClaudeSettings,
4658 claudeCapabilities({
4659 tokenSource: "none",
4660 apiKeySource: "none",
4661 apiProvider: "firstParty",
4662 }),
4663 environment,
4664 );
4665 assert.strictEqual(status.status, "ready");
4666 assert.strictEqual(status.auth.status, "authenticated");
4667 assert.strictEqual(status.auth.type, "customEndpoint");
4668 assert.strictEqual(status.auth.label, "Custom API endpoint");
4669 }).pipe(
4670 Effect.provide(
4671 layerMockSpawner((args) => {
4672 const joined = args.join(" ");
4673 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
4674 throw new Error(`Unexpected args: ${joined}`);
4675 }),
4676 ),
4677 ),
4678 );
4679
4680 it.effect.each([
4681 {
4682 settings: { env: { ANTHROPIC_BASE_URL: "https://hub.example.ts.net:8317" } },
4683 baseUrl: "https://api.anthropic.com",
4684 type: "customEndpoint",
4685 label: "Custom API endpoint",
4686 },
4687 {
4688 settings: { env: { ANTHROPIC_BASE_URL: "https://api.anthropic.com" } },
4689 baseUrl: "https://proxy.example",
4690 type: "apiKey",
4691 label: "Claude API Key",
4692 },
4693 {
4694 settings: {},
4695 baseUrl: "https://proxy.example",
4696 type: "customEndpoint",
4697 label: "Custom API endpoint",
4698 },
4699 ])(
4700 "uses the settings endpoint before the process endpoint: $type / $baseUrl",
4701 ({ settings, baseUrl, type, label }) =>
4702 Effect.gen(function* () {
4703 const fileSystem = yield* FileSystem.FileSystem;
4704 const path = yield* Path.Path;
4705 const configDir = yield* fileSystem.makeTempDirectoryScoped({
4706 prefix: "t3-claude-settings-",
4707 });
4708 yield* fileSystem.writeFileString(
4709 path.join(configDir, "settings.json"),
4710 JSON.stringify(settings),
4711 );
4712 const stateDir = yield* fileSystem.makeTempDirectoryScoped();
4713 yield* fileSystem.makeDirectory(path.join(stateDir, ".claude"));
4714 yield* fileSystem.writeFileString(
4715 path.join(stateDir, ".claude", "settings.json"),
4716 JSON.stringify({ env: { ANTHROPIC_BASE_URL: "https://state-dir.example" } }),
4717 );
4718 const status = yield* checkClaudeProviderStatus(
4719 { ...defaultClaudeSettings, homePath: configDir },
4720 claudeCapabilities({
4721 tokenSource: "ANTHROPIC_AUTH_TOKEN",
4722 apiKeySource: "none",
4723 apiProvider: "firstParty",
4724 }),
4725 { ANTHROPIC_BASE_URL: baseUrl },
4726 stateDir,
4727 );
4728 assert.strictEqual(status.status, "ready");
4729 assert.strictEqual(status.auth.type, type);
4730 assert.strictEqual(status.auth.label, label);
4731 }).pipe(
4732 Effect.provide(
4733 layerMockSpawner((args) => {
4734 const joined = args.join(" ");
4735 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
4736 throw new Error(`Unexpected args: ${joined}`);
4737 }),
4738 ),
4739 ),
4740 );
4741
4742 it.effect.each([
4743 "https://api.anthropic.com",
4744 "https://api.anthropic.com:443",
4745 "https://api.anthropic.com:8443",
4746 "openrouter.ai/api",
4747 "localhost:8080",
4748 "ftp://proxy.example",
4749 ])("keeps Claude logged out when the instance endpoint is %s", (baseUrl) =>
4750 Effect.gen(function* () {
4751 const environment = yield* mergeProviderInstanceEnvironment(
4752 [{ name: "ANTHROPIC_BASE_URL", value: baseUrl, sensitive: false }],
4753 { ANTHROPIC_BASE_URL: "https://proxy.example/api" },
4754 );
4755 const status = yield* checkClaudeProviderStatus(
4756 defaultClaudeSettings,
4757 claudeCapabilities({
4758 tokenSource: "none",
4759 apiKeySource: "none",
4760 apiProvider: "firstParty",
4761 }),
4762 environment,
4763 );
4764 assert.strictEqual(status.status, "error");
4765 assert.strictEqual(status.auth.status, "unauthenticated");
4766 assert.strictEqual(status.auth.type, undefined);
4767 }).pipe(
4768 Effect.provide(
4769 layerMockSpawner((args) => {
4770 const joined = args.join(" ");
4771 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
4772 throw new Error(`Unexpected args: ${joined}`);
4773 }),
4774 ),
4775 ),
4776 );
4777
4778 it.effect("keeps an API key install authenticated when it reports no token source", () =>
4779 Effect.gen(function* () {
4780 const status = yield* checkClaudeProviderStatus(
4781 defaultClaudeSettings,
4782 claudeCapabilities({
4783 tokenSource: "none",
4784 apiKeySource: "ANTHROPIC_API_KEY",
4785 apiProvider: "firstParty",
4786 }),
4787 );
4788 assert.strictEqual(status.status, "ready");
4789 assert.strictEqual(status.auth.status, "authenticated");
4790 assert.strictEqual(status.auth.label, "Claude API Key");
4791 }).pipe(
4792 Effect.provide(
4793 layerMockSpawner((args) => {
4794 const joined = args.join(" ");
4795 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
4796 throw new Error(`Unexpected args: ${joined}`);
4797 }),
4798 ),
4799 ),
4800 );
4801
4802 it.effect("keeps a CLI that says nothing about its account authenticated", () =>
4803 Effect.gen(function* () {
4804 const status = yield* checkClaudeProviderStatus(
4805 defaultClaudeSettings,
4806 claudeCapabilities(),
4807 );
4808 assert.strictEqual(status.status, "ready");
4809 assert.strictEqual(status.auth.status, "authenticated");
4810 }).pipe(
4811 Effect.provide(
4812 layerMockSpawner((args) => {
4813 const joined = args.join(" ");
4814 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
4815 throw new Error(`Unexpected args: ${joined}`);
4816 }),
4817 ),
4818 ),
4819 );
4820
4821 it.effect("advertises Ultracode as a toggle on custom models", () =>
4822 Effect.gen(function* () {
4823 const status = yield* checkClaudeProviderStatus(
4824 {
4825 ...defaultClaudeSettings,
4826 customModels: [
4827 {
4828 slug: "claude-custom-tuned",
4829 capabilities: {
4830 optionDescriptors: [
4831 {
4832 id: "effort",
4833 label: "Reasoning",
4834 type: "select",
4835 options: [
4836 { id: "high", label: "High", isDefault: true },
4837 { id: "ultracode", label: "Ultracode" },
4838 ],
4839 },
4840 ],
4841 },
4842 },
4843 ],
4844 },
4845 claudeCapabilities(),
4846 );
4847 const custom = status.models.find((model) => model.slug === "claude-custom-tuned");
4848 assert.deepStrictEqual(
4849 custom?.capabilities?.optionDescriptors?.map((descriptor) =>
4850 descriptor.type === "select"
4851 ? `${descriptor.id}:${descriptor.options.map((option) => option.id).join("|")}`
4852 : `${descriptor.id}:${descriptor.type}`,
4853 ),
4854 ["effort:high|xhigh", "ultracode:boolean"],
4855 );
4856 }).pipe(
4857 Effect.provide(
4858 layerMockSpawner((args) => {
4859 const joined = args.join(" ");
4860 if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
4861 throw new Error(`Unexpected args: ${joined}`);
4862 }),
4863 ),
4864 ),
4865 );
4866 });
4867 });