pi-dual-engine 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +103 -2
  2. package/biome.json +22 -0
  3. package/dist/index.js +1089 -0
  4. package/package.json +27 -4
  5. package/scripts/smoke.ts +141 -0
  6. package/src/assignment.ts +176 -0
  7. package/src/breaker.ts +33 -0
  8. package/src/config.ts +55 -0
  9. package/src/engine-pool.ts +163 -0
  10. package/src/families.ts +58 -0
  11. package/src/handles.ts +31 -0
  12. package/src/headroom-http.ts +58 -0
  13. package/src/index.ts +96 -0
  14. package/src/lifecycle.ts +145 -0
  15. package/src/locks.ts +93 -0
  16. package/src/probe.ts +154 -0
  17. package/src/providers.ts +71 -0
  18. package/src/retrieve.ts +65 -0
  19. package/src/session.ts +150 -0
  20. package/src/setup.ts +230 -0
  21. package/src/state.ts +49 -0
  22. package/src/status.ts +64 -0
  23. package/src/types.ts +47 -0
  24. package/test/assignment.test.ts +193 -0
  25. package/test/boot.ts +84 -0
  26. package/test/breaker.test.ts +92 -0
  27. package/test/coldstart.test.ts +133 -0
  28. package/test/defaults.test.ts +16 -0
  29. package/test/degradation.test.ts +69 -0
  30. package/test/factory.test.ts +158 -0
  31. package/test/fakes.ts +155 -0
  32. package/test/handles.test.ts +37 -0
  33. package/test/harness.ts +39 -0
  34. package/test/headroom-http.test.ts +99 -0
  35. package/test/lifecycle.test.ts +75 -0
  36. package/test/optin.test.ts +41 -0
  37. package/test/ownership.test.ts +160 -0
  38. package/test/probe.test.ts +195 -0
  39. package/test/providers.test.ts +156 -0
  40. package/test/retrieve.test.ts +137 -0
  41. package/test/windows-spawn.test.ts +93 -0
  42. package/tsconfig.json +17 -0
  43. package/wiki/01-getting-started.md +17 -0
  44. package/wiki/02-guides-and-workflows.md +22 -0
  45. package/wiki/03-architecture-and-internals.md +15 -0
  46. package/wiki/index.md +15 -0
@@ -0,0 +1,160 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { ensureEngine, stopOwned } from "../src/lifecycle.ts";
6
+ import { lockPath, portForKey, readLock, takeLock } from "../src/locks.ts";
7
+ import { harness, identify } from "./harness.ts";
8
+
9
+ const dirs: string[] = [];
10
+
11
+ afterEach(() => {
12
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
13
+ });
14
+
15
+ function tempDir(): string {
16
+ const dir = mkdtempSync(join(tmpdir(), "dual-engine-"));
17
+ dirs.push(dir);
18
+ return dir;
19
+ }
20
+
21
+ function dirsPair(): { stateDir: string; cavemanHome: string } {
22
+ return { stateDir: tempDir(), cavemanHome: tempDir() };
23
+ }
24
+
25
+ const upstreams = [
26
+ { family: "openai" as const, url: "https://a.example.com/v1" },
27
+ { family: "anthropic" as const, url: "https://a.example.com" },
28
+ { family: "gemini" as const, url: "https://b.example.com/v1beta" },
29
+ ];
30
+
31
+ describe("engine ownership and ports", () => {
32
+ test("Headroom spawns one upstream flag per family and one process per provider", async () => {
33
+ const h = harness({}, dirsPair());
34
+ const first = await ensureEngine({ engine: "headroom", key: "aaa", start: true, upstreams }, h.deps);
35
+ const second = await ensureEngine({ engine: "headroom", key: "bbb", start: true, upstreams }, h.deps);
36
+ expect(h.spawns).toHaveLength(2);
37
+ const args = h.spawns[0]?.args ?? [];
38
+ expect(args).toContain("--openai-api-url");
39
+ expect(args).toContain("--anthropic-api-url");
40
+ expect(args).toContain("--gemini-api-url");
41
+ expect(args.filter((arg) => arg === "--openai-api-url")).toHaveLength(1);
42
+ if (first.ok && second.ok) expect(first.state.port).not.toBe(second.state.port);
43
+ });
44
+
45
+ test("a lock held by another live process blocks takeover", async () => {
46
+ const dirs = dirsPair();
47
+ const path = lockPath(dirs.stateDir, "caveman", "main");
48
+ mkdirSync(dirname(path), { recursive: true });
49
+ writeFileSync(path, JSON.stringify({ pid: process.ppid, port: 8787, startedAt: 0 }), "utf8");
50
+ const h = harness({}, dirs);
51
+ const result = await ensureEngine({ engine: "caveman", start: true }, h.deps);
52
+ expect(result.ok).toBe(false);
53
+ expect(h.spawns).toHaveLength(0);
54
+ if (!result.ok) expect(result.reason).toContain("another session holds");
55
+ });
56
+
57
+ test("a lock naming a dead pid is taken over", () => {
58
+ const dirs = dirsPair();
59
+ const path = lockPath(dirs.stateDir, "caveman", "main");
60
+ mkdirSync(dirname(path), { recursive: true });
61
+ writeFileSync(path, JSON.stringify({ pid: 999_999, port: 8787, startedAt: 0 }), "utf8");
62
+ expect(readLock(path)?.pid).toBe(999_999);
63
+ expect(takeLock(path, 8787, () => 1)).toBe(true);
64
+ expect(readLock(path)?.pid).toBe(process.pid);
65
+ });
66
+
67
+ test("a port held by a proxy serving another upstream is refused, never spawned onto", async () => {
68
+ const h = harness(
69
+ {
70
+ probeHeadroom: async () => ({
71
+ ok: false,
72
+ occupied: true,
73
+ reason: "Headroom on port 8801 serves openai@stale.example.com; expected openai@a.example.com",
74
+ }),
75
+ },
76
+ dirsPair(),
77
+ );
78
+ const result = await ensureEngine({ engine: "headroom", key: "aaa", start: true, upstreams }, h.deps);
79
+ expect(result.ok).toBe(false);
80
+ expect(h.spawns).toHaveLength(0);
81
+ if (!result.ok) expect(result.reason).toContain("stale.example.com");
82
+ });
83
+
84
+ test("only a process this session started is stopped", () => {
85
+ const h = harness({}, dirsPair());
86
+ stopOwned({ engine: "caveman", port: 8787, upstreams: [], owned: false }, h.deps);
87
+ expect(h.kills).toHaveLength(0);
88
+ const owned = { engine: "caveman" as const, port: 8787, upstreams: [], owned: true };
89
+ const path = lockPath(h.deps.stateDir, "caveman", "main");
90
+ mkdirSync(dirname(path), { recursive: true });
91
+ writeFileSync(path, JSON.stringify({ pid: process.ppid, port: 8787, startedAt: 0 }), "utf8");
92
+ stopOwned(owned, h.deps);
93
+ expect(h.kills).toEqual([process.ppid]);
94
+ expect(readLock(path)).toBeUndefined();
95
+ });
96
+
97
+ test("a started engine is stopped through the door that created it", () => {
98
+ const h = harness({}, dirsPair());
99
+ const stops: string[] = [];
100
+ const deps = { ...h.deps, cavemanStop: () => stops.push("caveman stop") };
101
+ const caveman = {
102
+ engine: "caveman" as const,
103
+ port: 8787,
104
+ upstreams: [],
105
+ owned: true,
106
+ shutdown: "caveman" as const,
107
+ };
108
+ const headroom = {
109
+ engine: "headroom" as const,
110
+ port: 8801,
111
+ upstreams: [],
112
+ owned: true,
113
+ };
114
+ mkdirSync(dirname(lockPath(h.deps.stateDir, "caveman", "main")), { recursive: true });
115
+ writeFileSync(
116
+ lockPath(h.deps.stateDir, "caveman", "main"),
117
+ JSON.stringify({ pid: process.ppid, port: 8787, startedAt: 0 }),
118
+ "utf8",
119
+ );
120
+ writeFileSync(
121
+ lockPath(h.deps.stateDir, "headroom", "8801"),
122
+ JSON.stringify({ pid: process.ppid, port: 8801, startedAt: 0 }),
123
+ "utf8",
124
+ );
125
+
126
+ stopOwned(caveman, deps);
127
+ stopOwned(headroom, deps);
128
+ expect(stops).toEqual(["caveman stop"]);
129
+ expect(h.kills).toEqual([process.ppid]);
130
+ });
131
+
132
+ test("adopted engines are never stopped at session end", async () => {
133
+ const h = harness({ probeHeadroom: async () => identify("headroom", 8801, false) }, dirsPair());
134
+ const result = await ensureEngine({ engine: "headroom", key: "aaa", start: true, upstreams }, h.deps);
135
+ expect(result.ok).toBe(true);
136
+ if (result.ok) stopOwned(result.state, h.deps);
137
+ expect(h.kills).toHaveLength(0);
138
+ });
139
+
140
+ test("per-key ports stay in their range and separate providers that shared a 20-slot bucket", () => {
141
+ const base = 8788;
142
+ const keys = [
143
+ "openrouter",
144
+ "commandcode",
145
+ "opencode",
146
+ "opencode-go",
147
+ "google",
148
+ "xiaomi-token-plan-ams",
149
+ "typesafe",
150
+ ];
151
+ const ports = keys.map((key) => portForKey(base, key));
152
+ for (const port of ports) {
153
+ expect(port).toBeGreaterThanOrEqual(base);
154
+ expect(port).toBeLessThan(base + 100);
155
+ }
156
+ // `opencode` and `typesafe` landed on the same slot at 20; the wider space must keep them apart.
157
+ expect(portForKey(base, "opencode")).not.toBe(portForKey(base, "typesafe"));
158
+ expect(new Set(ports).size).toBe(keys.length);
159
+ });
160
+ });
@@ -0,0 +1,195 @@
1
+ import { afterAll, describe, expect, test } from "bun:test";
2
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { createServer, type Server } from "node:http";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { probeCaveman, probeHeadroom } from "../src/probe.ts";
7
+
8
+ const servers: Server[] = [];
9
+ const dirs: string[] = [];
10
+
11
+ afterAll(() => {
12
+ for (const server of servers) server.close();
13
+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
14
+ });
15
+
16
+ function listen(handle: Parameters<typeof createServer>[1]): Promise<number> {
17
+ return new Promise((resolve) => {
18
+ const server = createServer(handle);
19
+ servers.push(server);
20
+ server.listen(0, "127.0.0.1", () => {
21
+ const address = server.address();
22
+ resolve(typeof address === "object" && address ? address.port : 0);
23
+ });
24
+ });
25
+ }
26
+
27
+ function cavemanHome(port: number, state: Record<string, unknown>): string {
28
+ const home = mkdtempSync(join(tmpdir(), "caveman-home-"));
29
+ dirs.push(home);
30
+ mkdirSync(join(home, "run"), { recursive: true });
31
+ writeFileSync(join(home, "run", `${port}.json`), JSON.stringify(state), "utf8");
32
+ return home;
33
+ }
34
+
35
+ const cavemanState = (token: string, extra: Record<string, unknown> = {}) => ({
36
+ instance_token: token,
37
+ recovery_via_mcp: true,
38
+ provider_upstreams: {
39
+ anthropic: "https://api.anthropic.com",
40
+ "openai-codex": "https://chatgpt.com/backend-api",
41
+ },
42
+ compat_upstreams: { exchange: "https://exchange.example.com/v1" },
43
+ ...extra,
44
+ });
45
+
46
+ describe("Caveman readiness", () => {
47
+ test("identity match with a matching token is ready and publishes upstreams", async () => {
48
+ const port = await listen((request, response) => {
49
+ response.writeHead(200, { "x-caveman-instance": "tok" });
50
+ response.end("ok");
51
+ void request;
52
+ });
53
+ const home = cavemanHome(port, cavemanState("tok"));
54
+ const result = await probeCaveman({ port, home, timeoutMs: 1000, owned: false });
55
+ expect(result.ok).toBe(true);
56
+ if (result.ok) {
57
+ expect(result.state.engine).toBe("caveman");
58
+ expect(result.state.upstreams).toContainEqual({ family: "anthropic", host: "api.anthropic.com" });
59
+ expect(result.state.upstreams).toContainEqual({ family: "openai", host: "chatgpt.com" });
60
+ expect(result.state.upstreams).toContainEqual({ family: "openai", host: "exchange.example.com" });
61
+ }
62
+ });
63
+
64
+ test("a mismatched instance token is not ready", async () => {
65
+ const port = await listen((_request, response) => {
66
+ response.writeHead(200, { "x-caveman-instance": "other" });
67
+ response.end("ok");
68
+ });
69
+ const home = cavemanHome(port, cavemanState("tok"));
70
+ const result = await probeCaveman({ port, home, timeoutMs: 1000, owned: false });
71
+ expect(result.ok).toBe(false);
72
+ if (!result.ok) expect(result.reason).toContain("instance token");
73
+ });
74
+
75
+ test("missing recovery-over-MCP is not ready", async () => {
76
+ const port = await listen((_request, response) => {
77
+ response.writeHead(200, { "x-caveman-instance": "tok" });
78
+ response.end("ok");
79
+ });
80
+ const home = cavemanHome(port, cavemanState("tok", { recovery_via_mcp: false }));
81
+ const result = await probeCaveman({ port, home, timeoutMs: 1000, owned: false });
82
+ expect(result.ok).toBe(false);
83
+ if (!result.ok) expect(result.reason).toContain("recovery_via_mcp");
84
+ });
85
+
86
+ test("a missing run state is not ready even when the port answers", async () => {
87
+ const port = await listen((_request, response) => {
88
+ response.writeHead(200);
89
+ response.end("ok");
90
+ });
91
+ const home = mkdtempSync(join(tmpdir(), "caveman-home-"));
92
+ dirs.push(home);
93
+ const result = await probeCaveman({ port, home, timeoutMs: 1000, owned: false });
94
+ expect(result.ok).toBe(false);
95
+ if (!result.ok) expect(result.reason).toContain("run state");
96
+ });
97
+ });
98
+
99
+ describe("Headroom readiness", () => {
100
+ const healthy = (request: { url?: string }, response: import("node:http").ServerResponse) => {
101
+ if (request.url === "/livez") {
102
+ response.writeHead(200, { "content-type": "application/json" });
103
+ response.end(JSON.stringify({ service: "headroom-proxy", status: "healthy" }));
104
+ return;
105
+ }
106
+ response.writeHead(200, { "content-type": "application/json" });
107
+ response.end(
108
+ JSON.stringify({
109
+ service: "headroom-proxy",
110
+ config: {
111
+ anthropic_api_url: "https://api.anthropic.com",
112
+ openai_api_url: "https://openrouter.ai/api/v1",
113
+ gemini_api_url: null,
114
+ },
115
+ }),
116
+ );
117
+ };
118
+
119
+ test("livez plus a loopback health config naming upstreams is ready", async () => {
120
+ const port = await listen(healthy);
121
+ const result = await probeHeadroom({ port, timeoutMs: 1000, owned: false });
122
+ expect(result.ok).toBe(true);
123
+ if (result.ok) {
124
+ expect(result.state.upstreams).toEqual([
125
+ { family: "anthropic", host: "api.anthropic.com" },
126
+ { family: "openai", host: "openrouter.ai" },
127
+ ]);
128
+ }
129
+ });
130
+
131
+ test("a foreign service on the port is refused", async () => {
132
+ const port = await listen((_request, response) => {
133
+ response.writeHead(200, { "content-type": "application/json" });
134
+ response.end(JSON.stringify({ service: "something-else" }));
135
+ });
136
+ const result = await probeHeadroom({ port, timeoutMs: 1000, owned: false });
137
+ expect(result.ok).toBe(false);
138
+ if (!result.ok) expect(result.reason).toContain("not a Headroom proxy");
139
+ });
140
+
141
+ test("a malformed body is not readiness", async () => {
142
+ const port = await listen((_request, response) => {
143
+ response.writeHead(200);
144
+ response.end("not json");
145
+ });
146
+ const result = await probeHeadroom({ port, timeoutMs: 1000, owned: false });
147
+ expect(result.ok).toBe(false);
148
+ });
149
+
150
+ test("a timeout is not readiness", async () => {
151
+ const port = await listen(() => {
152
+ // Never answer: the probe must time out rather than hang.
153
+ });
154
+ const result = await probeHeadroom({ port, timeoutMs: 100, owned: false });
155
+ expect(result.ok).toBe(false);
156
+ });
157
+
158
+ test("a proxy serving a different upstream is a foreign instance, not readiness", async () => {
159
+ const port = await listen(healthy);
160
+ const result = await probeHeadroom({
161
+ port,
162
+ timeoutMs: 1000,
163
+ owned: false,
164
+ expect: [{ family: "openai", host: "other.example.com" }],
165
+ });
166
+ expect(result.ok).toBe(false);
167
+ if (!result.ok) {
168
+ expect(result.occupied).toBe(true);
169
+ expect(result.reason).toContain("expected openai@other.example.com");
170
+ }
171
+ });
172
+
173
+ test("a proxy serving the expected upstream is ready when an expectation is given", async () => {
174
+ const port = await listen(healthy);
175
+ const result = await probeHeadroom({
176
+ port,
177
+ timeoutMs: 1000,
178
+ owned: false,
179
+ expect: [{ family: "openai", host: "openrouter.ai" }],
180
+ });
181
+ expect(result.ok).toBe(true);
182
+ });
183
+
184
+ test("health without a proven upstream is not readiness", async () => {
185
+ const port = await listen((request, response) => {
186
+ response.writeHead(200, { "content-type": "application/json" });
187
+ response.end(
188
+ JSON.stringify({ service: "headroom-proxy", config: request.url === "/livez" ? undefined : {} }),
189
+ );
190
+ });
191
+ const result = await probeHeadroom({ port, timeoutMs: 1000, owned: false });
192
+ expect(result.ok).toBe(false);
193
+ if (!result.ok) expect(result.reason).toContain("no upstream");
194
+ });
195
+ });
@@ -0,0 +1,156 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { AssignmentPlan, ProviderGroup } from "../src/assignment.ts";
3
+ import { planProviderConfig, planRegistrations, registerAll } from "../src/providers.ts";
4
+
5
+ const plan: AssignmentPlan = {
6
+ provider: "aaa",
7
+ engine: "headroom",
8
+ families: ["openai"],
9
+ direct: ["gemini"],
10
+ upstreams: [{ family: "openai", url: "https://a.example.com/v1" }],
11
+ };
12
+
13
+ const group: ProviderGroup = {
14
+ provider: "aaa",
15
+ models: [
16
+ {
17
+ id: "chat",
18
+ name: "chat",
19
+ api: "openai-completions",
20
+ baseUrl: "https://a.example.com/v1",
21
+ reasoning: false,
22
+ input: ["text"],
23
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
24
+ contextWindow: 1000,
25
+ maxTokens: 100,
26
+ },
27
+ {
28
+ id: "gemini",
29
+ name: "gemini",
30
+ api: "google-generative-ai",
31
+ baseUrl: "https://b.example.com/v1",
32
+ reasoning: false,
33
+ input: ["text"],
34
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
35
+ contextWindow: 1000,
36
+ maxTokens: 100,
37
+ },
38
+ ],
39
+ };
40
+
41
+ describe("provider registration", () => {
42
+ test("carried models point at the proxy, uncarried families keep their base URL", () => {
43
+ const config = planProviderConfig(plan, group, "http://127.0.0.1:8801");
44
+ const models = config.models as { id: string; baseUrl: string }[];
45
+ expect(models.find((model) => model.id === "chat")?.baseUrl).toBe("http://127.0.0.1:8801");
46
+ expect(models.find((model) => model.id === "gemini")?.baseUrl).toBe("https://b.example.com/v1");
47
+ });
48
+
49
+ test("thinkingLevelMap with xhigh/max survives re-registration", () => {
50
+ const mapped: ProviderGroup = {
51
+ provider: "aaa",
52
+ models: [
53
+ {
54
+ id: "spark",
55
+ name: "spark",
56
+ api: "openai-completions",
57
+ baseUrl: "https://a.example.com/v1",
58
+ reasoning: false,
59
+ input: ["text"],
60
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
61
+ contextWindow: 1000,
62
+ maxTokens: 100,
63
+ thinkingLevelMap: { minimal: "minimal", low: "low", medium: "medium", high: "high", xhigh: "xhigh" },
64
+ },
65
+ ],
66
+ };
67
+ const config = planProviderConfig(plan, mapped, "http://127.0.0.1:8801");
68
+ const models = config.models as { id: string; thinkingLevelMap?: Record<string, string | null> }[];
69
+ expect(models.find((model) => model.id === "spark")?.thinkingLevelMap?.["xhigh"]).toBe("xhigh");
70
+ });
71
+
72
+ test("null-disabled thinking levels stay disabled", () => {
73
+ const mapped: ProviderGroup = {
74
+ provider: "aaa",
75
+ models: [
76
+ {
77
+ id: "spark",
78
+ name: "spark",
79
+ api: "openai-completions",
80
+ baseUrl: "https://a.example.com/v1",
81
+ reasoning: false,
82
+ input: ["text"],
83
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
84
+ contextWindow: 1000,
85
+ maxTokens: 100,
86
+ thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high" },
87
+ },
88
+ ],
89
+ };
90
+ const config = planProviderConfig(plan, mapped, "http://127.0.0.1:8801");
91
+ const models = config.models as { id: string; thinkingLevelMap?: Record<string, string | null> }[];
92
+ const found = models.find((model) => model.id === "spark")?.thinkingLevelMap;
93
+ expect(found && "off" in found && found["off"]).toBeNull();
94
+ expect(found?.["low"]).toBe("low");
95
+ });
96
+
97
+ test("optional compat/inputLimits survive with scoped baseUrl override", () => {
98
+ const mapped: ProviderGroup = {
99
+ provider: "aaa",
100
+ models: [
101
+ {
102
+ id: "chat",
103
+ name: "chat",
104
+ api: "openai-completions",
105
+ baseUrl: "https://a.example.com/v1",
106
+ reasoning: false,
107
+ input: ["text"],
108
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
109
+ contextWindow: 1000,
110
+ maxTokens: 100,
111
+ compat: { strict: true },
112
+ inputLimits: { maxImages: 4 },
113
+ },
114
+ ],
115
+ };
116
+ const config = planProviderConfig(plan, mapped, "http://127.0.0.1:8801");
117
+ const models = config.models as { id: string; baseUrl: string; compat?: unknown; inputLimits?: unknown }[];
118
+ const found = models.find((model) => model.id === "chat");
119
+ expect(found?.baseUrl).toBe("http://127.0.0.1:8801");
120
+ expect(found?.compat).toEqual({ strict: true });
121
+ expect(found?.inputLimits).toEqual({ maxImages: 4 });
122
+ });
123
+
124
+ test("non-chat models are carried through a registration untouched", () => {
125
+ const extras = new Map([["aaa", [{ id: "image-model", api: "openai-images" }]]]);
126
+ const config = planProviderConfig(plan, group, "http://127.0.0.1:8801", extras);
127
+ const ids = (config.models as { id: string }[]).map((model) => model.id);
128
+ expect(ids).toEqual(["chat", "gemini", "image-model"]);
129
+ });
130
+
131
+ test("registrations are skipped for providers without a proven port", () => {
132
+ const registrations = planRegistrations([plan], [group], new Map());
133
+ expect(registrations).toHaveLength(0);
134
+ });
135
+
136
+ test("a failing registration is reported and the next one still lands", () => {
137
+ const errors: string[] = [];
138
+ const registered: string[] = [];
139
+ const api = {
140
+ registerProvider: (name: string) => {
141
+ if (name === "aaa") throw new Error("auth missing");
142
+ registered.push(name);
143
+ },
144
+ };
145
+ registerAll(
146
+ api,
147
+ [
148
+ { provider: "aaa", engine: "headroom", config: {} },
149
+ { provider: "bbb", engine: "headroom", config: {} },
150
+ ],
151
+ (message) => errors.push(message),
152
+ );
153
+ expect(registered).toEqual(["bbb"]);
154
+ expect(errors[0]).toContain("auth missing");
155
+ });
156
+ });
@@ -0,0 +1,137 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
3
+ import { createRetrieveTool, executeEngineTool, type EngineOutcome } from "../src/retrieve.ts";
4
+
5
+ type Call = { engine: "caveman" | "headroom"; handle: string };
6
+
7
+ function tool(resolve: (engine: "caveman" | "headroom", handle: string) => EngineOutcome) {
8
+ const calls: Call[] = [];
9
+ const definition = createRetrieveTool({
10
+ resolve: async (engine, handle) => {
11
+ calls.push({ engine, handle });
12
+ return resolve(engine, handle);
13
+ },
14
+ });
15
+ const run = (handle: string) =>
16
+ definition.execute?.(
17
+ "call-1",
18
+ { handle },
19
+ undefined as never,
20
+ undefined as never,
21
+ {} as ExtensionToolContext,
22
+ ) as Promise<{ content: { type: string; text: string }[]; isError?: boolean }>;
23
+ return { definition, calls, run };
24
+ }
25
+
26
+ describe("single retrieval surface", () => {
27
+ test("upstream retrieval declarations are hidden and stay active", () => {
28
+ const { definition } = tool(() => ({ content: [], isError: false }));
29
+ const changes = definition.prepareLoadout?.({
30
+ declared: [],
31
+ callable: [],
32
+ registered: [
33
+ { name: "caveman_retrieve" },
34
+ { name: "mcp__headroom__headroom_retrieve" },
35
+ { name: "read" },
36
+ ],
37
+ getExposure: () => "direct",
38
+ getNamespace: () => undefined,
39
+ getPromptGuidelines: () => [],
40
+ } as never);
41
+ expect(changes?.hiddenDeclarations).toEqual(["caveman_retrieve", "mcp__headroom__headroom_retrieve"]);
42
+ expect(Object.keys(changes ?? {})).toEqual(["hiddenDeclarations"]);
43
+ });
44
+
45
+ test("an adapter that names the tool without the MCP prefix is hidden too", () => {
46
+ const { definition } = tool(() => ({ content: [], isError: false }));
47
+ const changes = definition.prepareLoadout?.({
48
+ declared: [],
49
+ callable: [],
50
+ registered: [{ name: "caveman_retrieve" }, { name: "headroom_retrieve" }],
51
+ getExposure: () => "direct",
52
+ getNamespace: () => undefined,
53
+ getPromptGuidelines: () => [],
54
+ } as never);
55
+ expect(changes?.hiddenDeclarations).toEqual(["caveman_retrieve", "headroom_retrieve"]);
56
+ });
57
+
58
+ test("a Caveman handle reaches Caveman and a Headroom handle reaches Headroom", async () => {
59
+ const { calls, run } = tool((engine) => ({ content: [{ type: "text", text: engine }], isError: false }));
60
+ await run("ccr_abc123");
61
+ await run("0aa4e9800c25");
62
+ expect(calls).toEqual([
63
+ { engine: "caveman", handle: "ccr_abc123" },
64
+ { engine: "headroom", handle: "0aa4e9800c25" },
65
+ ]);
66
+ });
67
+
68
+ test("an unknown shape queries no engine and fails loudly", async () => {
69
+ const { calls, run } = tool(() => ({ content: [], isError: false }));
70
+ const result = await run("not-a-handle");
71
+ expect(calls).toHaveLength(0);
72
+ expect(result.isError).toBe(true);
73
+ expect(result.content[0]?.text).toContain("Unrecognized recovery handle");
74
+ });
75
+
76
+ test("the engine's result is returned unchanged, including a large payload", async () => {
77
+ const payload = "x".repeat(120_000);
78
+ const { run } = tool(() => ({ content: [{ type: "text", text: payload }], isError: false }));
79
+ const result = await run("ccr_abc123");
80
+ expect(result.content).toHaveLength(1);
81
+ expect(result.content[0]?.text).toBe(payload);
82
+ });
83
+
84
+ test("an engine error stays an error with its bytes intact", async () => {
85
+ const { run } = tool(() => ({ content: [{ type: "text", text: "no such handle" }], isError: true }));
86
+ const result = await run("0aa4e9800c25");
87
+ expect(result.isError).toBe(true);
88
+ expect(result.content[0]?.text).toBe("no such handle");
89
+ });
90
+
91
+ test("the tool is named retrieve and takes a handle", () => {
92
+ const { definition } = tool(() => ({ content: [], isError: false }));
93
+ expect(definition.name).toBe("retrieve");
94
+ expect(Object.keys(definition.parameters.properties)).toEqual(["handle"]);
95
+ });
96
+ });
97
+
98
+ describe("engine dispatch through ctx.executeTool", () => {
99
+ test("each engine is called by its own tool name and its bytes come back unchanged", async () => {
100
+ const calls: { name: string; args: unknown }[] = [];
101
+ const payload = "y".repeat(120_000);
102
+ const ctx = {
103
+ executeTool: async (name: string, args: unknown) => {
104
+ calls.push({ name, args });
105
+ return { result: { content: [{ type: "text", text: payload }] }, isError: false };
106
+ },
107
+ } as never;
108
+ const caveman = await executeEngineTool(ctx, "caveman", "ccr_abc");
109
+ const headroom = await executeEngineTool(ctx, "headroom", "0aa4e9800c25");
110
+ expect(calls.map((call) => call.name)).toEqual(["caveman_retrieve", "mcp__headroom__headroom_retrieve"]);
111
+ expect(calls[0]?.args).toEqual({ recovery_handle: "ccr_abc" });
112
+ expect(caveman.content[0]).toEqual({ type: "text", text: payload });
113
+ expect(headroom.isError).toBe(false);
114
+ });
115
+
116
+ test("a nested tool error is reported as an error, not thrown", async () => {
117
+ const ctx = {
118
+ executeTool: async () => ({ result: { content: [{ type: "text", text: "boom" }] }, isError: true }),
119
+ } as never;
120
+ const outcome = await executeEngineTool(ctx, "headroom", "0aa4e9800c25");
121
+ expect(outcome.isError).toBe(true);
122
+ });
123
+
124
+ test("dispatch follows the name the runtime actually registered", async () => {
125
+ const calls: string[] = [];
126
+ const ctx = {
127
+ tools: [{ name: "headroom_retrieve" }],
128
+ executeTool: async (name: string) => {
129
+ calls.push(name);
130
+ return { result: { content: [{ type: "text", text: "ok" }] }, isError: false };
131
+ },
132
+ } as never;
133
+ const outcome = await executeEngineTool(ctx, "headroom", "0aa4e9800c25");
134
+ expect(calls).toEqual(["headroom_retrieve"]);
135
+ expect(outcome.isError).toBe(false);
136
+ });
137
+ });