pi-dual-engine 0.0.0-stage → 0.2.0

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 +1096 -0
  4. package/package.json +27 -4
  5. package/scripts/smoke.ts +141 -0
  6. package/src/assignment.ts +173 -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 +78 -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 +81 -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,193 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { deriveAssignments, type ProviderGroup } from "../src/assignment.ts";
5
+ import { familyOf, hostOf } from "../src/families.ts";
6
+ import type { EngineState } from "../src/types.ts";
7
+
8
+ const helpers = { familyOf, hostOf };
9
+
10
+ function engine(
11
+ engineId: "caveman" | "headroom",
12
+ upstreams: { family: "anthropic" | "openai" | "gemini"; host: string }[],
13
+ ): EngineState {
14
+ return { engine: engineId, port: 1000, upstreams, owned: false };
15
+ }
16
+
17
+ function group(provider: string, models: { api: string; baseUrl: string }[]): ProviderGroup {
18
+ return {
19
+ provider,
20
+ models: models.map((model, index) => ({
21
+ id: `${provider}-${index}`,
22
+ name: `${provider}-${index}`,
23
+ reasoning: false,
24
+ input: ["text"],
25
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
26
+ contextWindow: 1000,
27
+ maxTokens: 100,
28
+ ...model,
29
+ })),
30
+ };
31
+ }
32
+
33
+ describe("derived assignment", () => {
34
+ test("a provider with a known wire family routes without configuration", () => {
35
+ const groups = [group("zzz", [{ api: "openai-completions", baseUrl: "https://api.example.com/v1" }])];
36
+ const engines = [engine("headroom", [{ family: "openai", host: "api.example.com" }])];
37
+ const { plans } = deriveAssignments(groups, engines, [], helpers);
38
+ expect(plans).toHaveLength(1);
39
+ expect(plans[0]?.engine).toBe("headroom");
40
+ expect(plans[0]?.families).toEqual(["openai"]);
41
+ });
42
+
43
+ test("a provider unknown to every engine runs direct with a notice", () => {
44
+ const groups = [group("qqq", [{ api: "unknown-wire", baseUrl: "https://api.unknown.test/v1" }])];
45
+ const engines = [engine("headroom", [{ family: "openai", host: "api.example.com" }])];
46
+ const { plans, notices } = deriveAssignments(groups, engines, [], helpers);
47
+ expect(plans).toHaveLength(0);
48
+ expect(notices.some((notice) => notice.includes("qqq"))).toBe(true);
49
+ });
50
+
51
+ test("gemini on Google's host derives to the harness engine", () => {
52
+ const groups = [
53
+ group("rrr", [{ api: "google-generative-ai", baseUrl: "https://generativelanguage.googleapis.com" }]),
54
+ ];
55
+ const engines = [
56
+ engine("caveman", [{ family: "gemini", host: "generativelanguage.googleapis.com" }]),
57
+ engine("headroom", [{ family: "openai", host: "api.example.com" }]),
58
+ ];
59
+ const { plans } = deriveAssignments(groups, engines, [], helpers);
60
+ expect(plans[0]?.engine).toBe("caveman");
61
+ });
62
+
63
+ test("multi-family provider is carried by one instance with one upstream per family", () => {
64
+ const groups = [
65
+ group("mmm", [
66
+ { api: "openai-completions", baseUrl: "https://a.example.com/v1" },
67
+ { api: "anthropic-messages", baseUrl: "https://a.example.com" },
68
+ { api: "google-generative-ai", baseUrl: "https://b.example.com/v1beta" },
69
+ ]),
70
+ ];
71
+ const engines = [
72
+ engine("headroom", [
73
+ { family: "openai", host: "a.example.com" },
74
+ { family: "anthropic", host: "a.example.com" },
75
+ ]),
76
+ ];
77
+ const { plans, notices } = deriveAssignments(groups, engines, [], helpers);
78
+ expect(plans[0]?.families).toEqual(["openai", "anthropic"]);
79
+ expect(plans[0]?.upstreams).toHaveLength(2);
80
+ expect(plans[0]?.direct).toEqual(["gemini"]);
81
+ expect(notices.some((notice) => notice.includes("gemini"))).toBe(true);
82
+ });
83
+
84
+ test("an explicit assignment beats the derived one and leaves others untouched", () => {
85
+ const groups = [
86
+ group("aaa", [{ api: "openai-completions", baseUrl: "https://a.example.com/v1" }]),
87
+ group("bbb", [{ api: "openai-completions", baseUrl: "https://b.example.com/v1" }]),
88
+ ];
89
+ const engines = [
90
+ engine("headroom", [
91
+ { family: "openai", host: "a.example.com" },
92
+ { family: "openai", host: "b.example.com" },
93
+ ]),
94
+ engine("caveman", [{ family: "openai", host: "a.example.com" }]),
95
+ ];
96
+ const { plans } = deriveAssignments(groups, engines, [{ provider: "aaa", engine: "caveman" }], helpers);
97
+ expect(plans.find((plan) => plan.provider === "aaa")?.engine).toBe("caveman");
98
+ expect(plans.find((plan) => plan.provider === "bbb")?.engine).toBe("headroom");
99
+ });
100
+
101
+ test("unknown engine names and conflicting entries are skipped with one notice each", () => {
102
+ const groups = [group("aaa", [{ api: "openai-completions", baseUrl: "https://a.example.com/v1" }])];
103
+ const engines = [engine("headroom", [{ family: "openai", host: "a.example.com" }])];
104
+ const unknown = deriveAssignments(groups, engines, [{ provider: "aaa", engine: "bogus" }], helpers);
105
+ expect(unknown.plans[0]?.engine).toBe("headroom");
106
+ expect(unknown.notices).toHaveLength(1);
107
+
108
+ const conflicting = deriveAssignments(
109
+ groups,
110
+ engines,
111
+ [
112
+ { provider: "aaa", engine: "caveman" },
113
+ { provider: "aaa", engine: "headroom" },
114
+ ],
115
+ helpers,
116
+ );
117
+ expect(conflicting.plans[0]?.engine).toBe("headroom");
118
+ expect(conflicting.notices).toHaveLength(1);
119
+ });
120
+
121
+ test("derivation code carries no provider or model names", () => {
122
+ const source = readFileSync(join(import.meta.dir, "..", "src", "assignment.ts"), "utf8").toLowerCase();
123
+ for (const name of [
124
+ "openrouter",
125
+ "commandcode",
126
+ "opencode",
127
+ "openai-codex",
128
+ "typesafe",
129
+ "xiaomi",
130
+ "google",
131
+ ]) {
132
+ expect(source).not.toContain(name);
133
+ }
134
+ });
135
+
136
+ test("a family the chosen engine cannot carry stays direct", () => {
137
+ const groups = [
138
+ group("aaa", [
139
+ { api: "openai-completions", baseUrl: "https://a.example.com/v1" },
140
+ { api: "google-generative-ai", baseUrl: "https://b.example.com/v1beta" },
141
+ ]),
142
+ ];
143
+ const engines = [
144
+ engine("headroom", [{ family: "openai", host: "a.example.com" }]),
145
+ engine("caveman", [{ family: "gemini", host: "b.example.com" }]),
146
+ ];
147
+ const { plans } = deriveAssignments(groups, engines, [], helpers);
148
+ const plan = plans[0];
149
+ expect(plan?.families).toEqual(["openai"]);
150
+ expect(plan?.direct).toEqual(["gemini"]);
151
+ expect(plan?.upstreams.every((upstream) => upstream.family !== "gemini")).toBe(true);
152
+ });
153
+
154
+ test("a provider is carried by exactly one engine", () => {
155
+ const groups = [
156
+ group("aaa", [{ api: "openai-completions", baseUrl: "https://a.example.com/v1" }]),
157
+ group("bbb", [{ api: "openai-completions", baseUrl: "https://b.example.com/v1" }]),
158
+ ];
159
+ const engines = [
160
+ engine("headroom", [{ family: "openai", host: "a.example.com" }]),
161
+ engine("caveman", [{ family: "openai", host: "b.example.com" }]),
162
+ ];
163
+ const { plans } = deriveAssignments(groups, engines, [], helpers);
164
+ expect(plans).toHaveLength(groups.length);
165
+ expect(new Set(plans.map((plan) => plan.provider)).size).toBe(groups.length);
166
+ expect(plans.map((plan) => plan.engine).sort()).toEqual(["caveman", "headroom"]);
167
+ });
168
+
169
+ test("a provider added after an earlier derivation is planned without configuration", () => {
170
+ const early = deriveAssignments(
171
+ [group("aaa", [{ api: "openai-completions", baseUrl: "https://a.example.com/v1" }])],
172
+ [engine("headroom", [{ family: "openai", host: "a.example.com" }])],
173
+ [],
174
+ helpers,
175
+ );
176
+ expect(early.plans.map((plan) => plan.provider)).toEqual(["aaa"]);
177
+
178
+ const later = deriveAssignments(
179
+ [
180
+ group("aaa", [{ api: "openai-completions", baseUrl: "https://a.example.com/v1" }]),
181
+ group("bbb", [{ api: "openai-completions", baseUrl: "https://b.example.com/v1" }]),
182
+ ],
183
+ [
184
+ engine("headroom", [{ family: "openai", host: "a.example.com" }]),
185
+ engine("caveman", [{ family: "openai", host: "b.example.com" }]),
186
+ ],
187
+ [],
188
+ helpers,
189
+ );
190
+ expect(later.plans.map((plan) => plan.provider).sort()).toEqual(["aaa", "bbb"]);
191
+ expect(later.plans.find((plan) => plan.provider === "bbb")?.engine).toBe("caveman");
192
+ });
193
+ });
package/test/boot.ts ADDED
@@ -0,0 +1,84 @@
1
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { HEADROOM_BASE_PORT, portForKey } from "../src/locks.ts";
5
+ import type { ProbeResult } from "../src/probe.ts";
6
+ import { createDualEngine } from "../src/index.ts";
7
+ import { type ChatModel, type FakePi, makePi } from "./fakes.ts";
8
+
9
+ const dirs: string[] = [];
10
+
11
+ export function cleanupDirs(): void {
12
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
13
+ }
14
+
15
+ function tempDir(prefix: string): string {
16
+ const dir = mkdtempSync(join(tmpdir(), prefix));
17
+ dirs.push(dir);
18
+ return dir;
19
+ }
20
+
21
+ export type BootOptions = {
22
+ readonly models: readonly ChatModel[];
23
+ readonly caveman?: ProbeResult;
24
+ readonly headroom?: (provider: string) => ProbeResult;
25
+ readonly exposure?: boolean;
26
+ readonly config?: unknown;
27
+ readonly mcpServers?: Record<string, unknown>;
28
+ readonly extras?: { image?: readonly ChatModel[]; classifier?: readonly ChatModel[] };
29
+ };
30
+
31
+ export type Booted = {
32
+ readonly pi: FakePi;
33
+ readonly stateDir: string;
34
+ readonly agentDir: string;
35
+ readonly notices: { readonly type: string; readonly message: string }[];
36
+ };
37
+
38
+ export async function boot(options: BootOptions): Promise<Booted> {
39
+ const stateDir = tempDir("dual-engine-state-");
40
+ const cavemanHome = tempDir("dual-engine-caveman-");
41
+ const agentDir = tempDir("dual-engine-agent-");
42
+ if (options.config !== undefined) {
43
+ writeFileSync(join(stateDir, "config.json"), JSON.stringify(options.config), "utf8");
44
+ }
45
+ if (options.mcpServers !== undefined) {
46
+ writeFileSync(join(agentDir, "mcp.json"), JSON.stringify({ mcpServers: options.mcpServers }), "utf8");
47
+ }
48
+ mkdirSync(agentDir, { recursive: true });
49
+
50
+ const pi = makePi(options.models, { exposure: options.exposure, extras: options.extras });
51
+ const notify = (type: "info" | "warning" | "error", message: string) => pi.notices.push({ type, message });
52
+ const providers = new Map<string, string>();
53
+ let clock = 0;
54
+ for (const model of options.models)
55
+ providers.set(String(portForKey(HEADROOM_BASE_PORT, model.provider)), model.provider);
56
+
57
+ createDualEngine({
58
+ stateDir,
59
+ cavemanHome,
60
+ agentDir,
61
+ deps: {
62
+ notify,
63
+ lifecycle: {
64
+ stateDir,
65
+ cavemanHome,
66
+ timeoutMs: 50,
67
+ spawn: () => ({ pid: undefined }),
68
+ kill: () => {},
69
+ now: () => clock,
70
+ sleep: async (ms) => {
71
+ clock += ms;
72
+ },
73
+ probeCaveman: async () => options.caveman ?? { ok: false, reason: "caveman down" },
74
+ probeHeadroom: async ({ port }) => {
75
+ const provider = providers.get(String(port)) ?? "";
76
+ return options.headroom?.(provider) ?? { ok: false, reason: `headroom down for ${provider}` };
77
+ },
78
+ },
79
+ },
80
+ })(pi.api);
81
+
82
+ await pi.emit("session_start", {});
83
+ return { pi, stateDir, agentDir, notices: pi.notices };
84
+ }
@@ -0,0 +1,92 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { Api, Model as PiModel } from "@earendil-works/pi-ai";
3
+ import { onProviderResponse } from "../src/breaker.ts";
4
+
5
+ const asModel = (model: Model): PiModel<Api> => model as unknown as PiModel<Api>;
6
+
7
+ type Model = { provider: string; id: string; baseUrl: string };
8
+
9
+ function state(direct: Model) {
10
+ const notices: string[] = [];
11
+ return {
12
+ notices,
13
+ values: {
14
+ tripped: new Set<string>(),
15
+ directModels: new Map([[direct.provider, asModel(direct)]]),
16
+ notify: (message: string) => notices.push(message),
17
+ },
18
+ };
19
+ }
20
+
21
+ describe("fail-open breaker", () => {
22
+ test("a proxy failure restores the direct endpoint once and reports once", async () => {
23
+ const direct: Model = { provider: "aaa", id: "aaa-model", baseUrl: "https://a.example.com/v1" };
24
+ const breaker = state(direct);
25
+ const restored: Model[] = [];
26
+ const routed: Model = { ...direct, baseUrl: "http://127.0.0.1:8801" };
27
+ const input = {
28
+ event: { status: 502 },
29
+ model: asModel(routed),
30
+ setModel: async (model: PiModel<Api>) => {
31
+ restored.push(model as Model);
32
+ return true;
33
+ },
34
+ };
35
+
36
+ await onProviderResponse(breaker.values, input);
37
+ expect(restored).toEqual([direct]);
38
+ expect(breaker.notices).toHaveLength(1);
39
+ expect(breaker.notices[0]).toContain("502");
40
+
41
+ await onProviderResponse(breaker.values, input);
42
+ expect(restored).toHaveLength(1);
43
+ expect(breaker.notices).toHaveLength(1);
44
+ });
45
+
46
+ test("a later selection of the same provider does not route again", async () => {
47
+ const direct: Model = { provider: "aaa", id: "aaa-model", baseUrl: "https://a.example.com/v1" };
48
+ const breaker = state(direct);
49
+ breaker.values.tripped.add("aaa");
50
+ let called = 0;
51
+ await onProviderResponse(breaker.values, {
52
+ event: { status: 500 },
53
+ model: asModel({ ...direct, baseUrl: "http://127.0.0.1:8801" }),
54
+ setModel: async () => {
55
+ called += 1;
56
+ return true;
57
+ },
58
+ });
59
+ expect(called).toBe(0);
60
+ expect(breaker.notices).toHaveLength(0);
61
+ });
62
+
63
+ test("a success response leaves routing alone", async () => {
64
+ const direct: Model = { provider: "aaa", id: "aaa-model", baseUrl: "https://a.example.com/v1" };
65
+ const breaker = state(direct);
66
+ let called = 0;
67
+ await onProviderResponse(breaker.values, {
68
+ event: { status: 200 },
69
+ model: asModel(direct),
70
+ setModel: async () => {
71
+ called += 1;
72
+ return true;
73
+ },
74
+ });
75
+ expect(called).toBe(0);
76
+ });
77
+
78
+ test("a provider with no direct model is left untouched", async () => {
79
+ const direct: Model = { provider: "aaa", id: "aaa-model", baseUrl: "https://a.example.com/v1" };
80
+ const breaker = state(direct);
81
+ let called = 0;
82
+ await onProviderResponse(breaker.values, {
83
+ event: { status: 503 },
84
+ model: asModel({ provider: "other", id: "x", baseUrl: "http://127.0.0.1:1" }),
85
+ setModel: async () => {
86
+ called += 1;
87
+ return true;
88
+ },
89
+ });
90
+ expect(called).toBe(0);
91
+ });
92
+ });
@@ -0,0 +1,133 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { HEADROOM_BASE_PORT, portForKey } from "../src/locks.ts";
6
+ import { createDualEngine } from "../src/index.ts";
7
+ import { type ChatModel, makePi } from "./fakes.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-cold-"));
17
+ dirs.push(dir);
18
+ return dir;
19
+ }
20
+
21
+ const models: ChatModel[] = [
22
+ {
23
+ provider: "aaa",
24
+ id: "aaa-model",
25
+ name: "aaa-model",
26
+ api: "openai-completions",
27
+ baseUrl: "https://a.example.com/v1",
28
+ reasoning: false,
29
+ input: ["text"],
30
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
31
+ contextWindow: 1000,
32
+ maxTokens: 100,
33
+ },
34
+ {
35
+ provider: "bbb",
36
+ id: "bbb-model",
37
+ name: "bbb-model",
38
+ api: "google-generative-ai",
39
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta",
40
+ reasoning: false,
41
+ input: ["text"],
42
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
43
+ contextWindow: 1000,
44
+ maxTokens: 100,
45
+ },
46
+ ];
47
+
48
+ async function runCold(options: { start?: { caveman: boolean; headroom: boolean } } = {}) {
49
+ const stateDir = tempDir();
50
+ const cavemanHome = tempDir();
51
+ const agentDir = tempDir();
52
+ const spawned: { command: string; args: readonly string[] }[] = [];
53
+ const pi = makePi(models);
54
+ const providers = new Map<string, string>();
55
+ for (const model of models)
56
+ providers.set(String(portForKey(HEADROOM_BASE_PORT, model.provider)), model.provider);
57
+
58
+ createDualEngine({
59
+ stateDir,
60
+ cavemanHome,
61
+ agentDir,
62
+ deps: {
63
+ start: options.start ?? { caveman: true, headroom: true },
64
+ notify: (type, message) => pi.notices.push({ type, message }),
65
+ lifecycle: {
66
+ stateDir,
67
+ cavemanHome,
68
+ timeoutMs: 100,
69
+ spawn: (command, args) => {
70
+ spawned.push({ command, args });
71
+ return { pid: 4321 };
72
+ },
73
+ kill: () => {},
74
+ now: () => 0,
75
+ sleep: async () => {},
76
+ probeCaveman: async () =>
77
+ spawned.some((entry) => entry.command === "caveman")
78
+ ? {
79
+ ok: true,
80
+ state: {
81
+ engine: "caveman",
82
+ port: 8787,
83
+ owned: true,
84
+ upstreams: [{ family: "gemini", host: "generativelanguage.googleapis.com" }],
85
+ },
86
+ }
87
+ : { ok: false, reason: "down" },
88
+ probeHeadroom: async ({ port }) => {
89
+ if (!spawned.some((entry) => entry.command === "headroom")) return { ok: false, reason: "down" };
90
+ const provider = providers.get(String(port)) ?? "";
91
+ return {
92
+ ok: true,
93
+ state: {
94
+ engine: "headroom",
95
+ port,
96
+ owned: true,
97
+ upstreams: provider === "aaa" ? [{ family: "openai", host: "a.example.com" }] : [],
98
+ },
99
+ };
100
+ },
101
+ },
102
+ },
103
+ })(pi.api);
104
+
105
+ await pi.emit("session_start", {});
106
+ return { pi, spawned, stateDir };
107
+ }
108
+
109
+ describe("cold start with every engine stopped", () => {
110
+ test("the engines the current providers prefer are started before an assignment is derived", async () => {
111
+ const { pi, spawned } = await runCold();
112
+ expect(spawned.map((entry) => entry.command).sort()).toEqual(["caveman", "headroom"]);
113
+ expect(pi.providers.map((entry) => entry.name)).toEqual(["aaa"]);
114
+ const config = pi.providers[0]?.config as { baseUrl: string };
115
+ expect(config.baseUrl).toBe(`http://127.0.0.1:${portForKey(HEADROOM_BASE_PORT, "aaa")}`);
116
+ });
117
+
118
+ test("a started engine is recorded as owned so it stops with the session", async () => {
119
+ const { pi } = await runCold();
120
+ const status = pi.commands.find((entry) => entry.name === "dual-engine");
121
+ await status?.handler("", pi.ctx);
122
+ const report = pi.notices.at(-1)?.message ?? "";
123
+ expect(report).toContain("headroom (started");
124
+ expect(report).toContain("caveman (started");
125
+ });
126
+
127
+ test("start disabled keeps every provider direct and reports once per engine", async () => {
128
+ const { pi, spawned } = await runCold({ start: { caveman: false, headroom: false } });
129
+ expect(spawned).toHaveLength(0);
130
+ expect(pi.providers).toHaveLength(0);
131
+ expect(pi.notices.filter((notice) => notice.message.includes("is unavailable"))).toHaveLength(2);
132
+ });
133
+ });
@@ -0,0 +1,16 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { loadConfig } from "../src/config.ts";
3
+ import { DEFAULT_CONFIG } from "../src/types.ts";
4
+
5
+ describe("ready-on-install defaults", () => {
6
+ test("starting both engines is on and the wait covers a cold Python start", () => {
7
+ expect(DEFAULT_CONFIG.start).toEqual({ caveman: true, headroom: true });
8
+ expect(DEFAULT_CONFIG.timeoutMs).toBe(30_000);
9
+ });
10
+
11
+ test("an absent configuration narrows nothing", () => {
12
+ const { config, notices } = loadConfig("/nonexistent/dual-engine-state");
13
+ expect(config).toEqual(DEFAULT_CONFIG);
14
+ expect(notices).toEqual([]);
15
+ });
16
+ });
@@ -0,0 +1,69 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import { HEADROOM_BASE_PORT, portForKey } from "../src/locks.ts";
3
+ import { boot, cleanupDirs } from "./boot.ts";
4
+ import { chatModel } from "./fakes.ts";
5
+
6
+ afterEach(cleanupDirs);
7
+
8
+ const models = [
9
+ chatModel("aaa", "openai-completions", "a.example.com"),
10
+ chatModel("bbb", "google-generative-ai", "generativelanguage.googleapis.com"),
11
+ ];
12
+
13
+ const cavemanUp = {
14
+ ok: true as const,
15
+ state: {
16
+ engine: "caveman" as const,
17
+ port: 8787,
18
+ owned: false,
19
+ upstreams: [{ family: "gemini" as const, host: "generativelanguage.googleapis.com" }],
20
+ },
21
+ };
22
+
23
+ const headroomUp = {
24
+ ok: true as const,
25
+ state: {
26
+ engine: "headroom" as const,
27
+ port: portForKey(HEADROOM_BASE_PORT, "aaa"),
28
+ owned: false,
29
+ upstreams: [{ family: "openai" as const, host: "a.example.com" }],
30
+ },
31
+ };
32
+
33
+ describe("honest degradation", () => {
34
+ test("wire engine missing: one notice, nothing registered on its behalf", async () => {
35
+ const { pi, notices } = await boot({ models, caveman: cavemanUp });
36
+ expect(pi.providers).toHaveLength(0);
37
+ expect(pi.mcp).toHaveLength(0);
38
+ const matching = notices.filter((notice) => notice.message.includes("headroom is unavailable"));
39
+ expect(matching).toHaveLength(1);
40
+ expect(matching[0]?.message).toContain("continues without it");
41
+ });
42
+
43
+ test("harness engine missing: one notice and the wire engine still serves its providers", async () => {
44
+ const { pi, notices } = await boot({ models, headroom: () => headroomUp });
45
+ expect(pi.providers.map((entry) => entry.name)).toEqual(["aaa"]);
46
+ const matching = notices.filter((notice) => notice.message.includes("caveman is unavailable"));
47
+ expect(matching).toHaveLength(1);
48
+ });
49
+
50
+ test("both missing: one notice per engine and the session still starts uncompressed", async () => {
51
+ const { pi, notices } = await boot({ models });
52
+ expect(pi.providers).toHaveLength(0);
53
+ expect(pi.mcp).toHaveLength(0);
54
+ expect(notices.filter((notice) => notice.message.includes("is unavailable"))).toHaveLength(2);
55
+ expect(pi.tools.map((tool) => tool.name)).toEqual(["retrieve"]);
56
+ });
57
+
58
+ test("register after proof: a failing identity registers no provider for it", async () => {
59
+ const failing = { ok: false as const, reason: "instance token mismatch" };
60
+ const { pi, notices } = await boot({ models, caveman: cavemanUp, headroom: () => failing });
61
+ expect(pi.providers).toHaveLength(0);
62
+ expect(notices.some((notice) => notice.message.includes("headroom is unavailable"))).toBe(true);
63
+ });
64
+
65
+ test("providers assigned to the harness engine are never registered against the wire engine", async () => {
66
+ const { pi } = await boot({ models, caveman: cavemanUp, headroom: () => headroomUp });
67
+ expect(pi.providers.map((entry) => entry.name)).toEqual(["aaa"]);
68
+ });
69
+ });