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,158 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import { readFileSync, readdirSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { HEADROOM_BASE_PORT, portForKey } from "../src/locks.ts";
5
+ import { boot, cleanupDirs } from "./boot.ts";
6
+ import { chatModel } from "./fakes.ts";
7
+
8
+ afterEach(cleanupDirs);
9
+
10
+ const models = [
11
+ chatModel("aaa", "openai-completions", "a.example.com"),
12
+ chatModel("bbb", "google-generative-ai", "generativelanguage.googleapis.com"),
13
+ ];
14
+
15
+ const healthyCaveman = {
16
+ ok: true as const,
17
+ state: {
18
+ engine: "caveman" as const,
19
+ port: 8787,
20
+ owned: false,
21
+ upstreams: [{ family: "gemini" as const, host: "generativelanguage.googleapis.com" }],
22
+ },
23
+ };
24
+
25
+ const healthyHeadroom = (provider: string) =>
26
+ provider === "aaa"
27
+ ? {
28
+ ok: true as const,
29
+ state: {
30
+ engine: "headroom" as const,
31
+ port: portForKey(HEADROOM_BASE_PORT, provider),
32
+ owned: false,
33
+ upstreams: [{ family: "openai" as const, host: "a.example.com" }],
34
+ },
35
+ }
36
+ : { ok: false as const, reason: "down" };
37
+
38
+ describe("extension surface", () => {
39
+ test("the factory registers exactly one tool named retrieve", async () => {
40
+ const { pi } = await boot({ models, caveman: healthyCaveman, headroom: healthyHeadroom });
41
+ expect(pi.tools.map((tool) => tool.name)).toEqual(["retrieve"]);
42
+ });
43
+
44
+ test("no capability to hide declarations means no retrieve tool and one error notice", async () => {
45
+ const { pi, notices } = await boot({
46
+ models,
47
+ caveman: healthyCaveman,
48
+ headroom: healthyHeadroom,
49
+ exposure: false,
50
+ });
51
+ expect(pi.tools).toHaveLength(0);
52
+ expect(notices.filter((notice) => notice.type === "error")).toHaveLength(1);
53
+ expect(notices[0]?.message).toContain("cannot hide tool declarations");
54
+ });
55
+
56
+ test("session start registers one Headroom MCP server in codemode and keeps retrieval callable", async () => {
57
+ const { pi } = await boot({ models, caveman: healthyCaveman, headroom: healthyHeadroom });
58
+ expect(pi.mcp).toHaveLength(1);
59
+ const entry = pi.mcp[0];
60
+ expect(entry?.name).toBe("headroom");
61
+ expect(entry?.config.exposure).toBe("codemode");
62
+ expect(entry?.config.toolExposure).toEqual({ headroom_retrieve: "codemode" });
63
+ expect(entry?.config.args).toContain("--proxy-url");
64
+ });
65
+
66
+ test("provider registration points carried models at the proxy and keeps uncarried families direct", async () => {
67
+ const mixed = [
68
+ chatModel("aaa", "openai-completions", "a.example.com"),
69
+ chatModel("aaa", "google-generative-ai", "gemini.example.com", "gemini-model"),
70
+ ];
71
+ const { pi, notices } = await boot({ models: mixed, caveman: healthyCaveman, headroom: healthyHeadroom });
72
+ expect(pi.providers).toHaveLength(1);
73
+ const config = pi.providers[0]?.config as { baseUrl: string; models: { id: string; baseUrl: string }[] };
74
+ const port = portForKey(HEADROOM_BASE_PORT, "aaa");
75
+ expect(config.baseUrl).toBe(`http://127.0.0.1:${port}`);
76
+ expect(config.models.find((model) => model.id === "aaa-model")?.baseUrl).toBe(`http://127.0.0.1:${port}`);
77
+ expect(config.models.find((model) => model.id === "gemini-model")?.baseUrl).toBe(
78
+ "https://gemini.example.com/v1",
79
+ );
80
+ expect(notices.some((notice) => notice.message.includes("gemini routed direct"))).toBe(true);
81
+ });
82
+
83
+ test("a user mcp.json entry of the same name is reported, not fatal", async () => {
84
+ const { pi, notices } = await boot({
85
+ models,
86
+ caveman: healthyCaveman,
87
+ headroom: healthyHeadroom,
88
+ mcpServers: { headroom: { url: "https://example.test/mcp" } },
89
+ });
90
+ expect(pi.mcp).toHaveLength(1);
91
+ const override = notices.find((notice) => notice.message.includes("takes precedence"));
92
+ expect(override?.message).toContain("mcp.json");
93
+ });
94
+
95
+ test("startup leaves user configuration byte-identical", async () => {
96
+ const { pi, agentDir } = await boot({ models, caveman: healthyCaveman, headroom: healthyHeadroom });
97
+ const files = {
98
+ "settings.json": '{"theme":"dark"}\n',
99
+ "models.json": '{"providers":{}}\n',
100
+ "mcp.json": '{"mcpServers":{}}\n',
101
+ };
102
+ for (const [name, contents] of Object.entries(files))
103
+ writeFileSync(join(agentDir, name), contents, "utf8");
104
+ const before = new Map(
105
+ Object.entries(files).map(([name]) => [name, readFileSync(join(agentDir, name), "utf8")]),
106
+ );
107
+ const listing = readdirSync(agentDir).sort();
108
+ await pi.emit("session_start", {});
109
+ for (const [name, contents] of before) {
110
+ expect(readFileSync(join(agentDir, name), "utf8")).toBe(contents);
111
+ }
112
+ expect(readdirSync(agentDir).sort()).toEqual(listing);
113
+ });
114
+
115
+ test("the assignment report names every provider with its families and engine", async () => {
116
+ const { stateDir } = await boot({ models, caveman: healthyCaveman, headroom: healthyHeadroom });
117
+ const report = JSON.parse(readFileSync(join(stateDir, "assignment.json"), "utf8")) as {
118
+ providers: { provider: string; engine: string | null; families: string[]; direct: string[] }[];
119
+ };
120
+ expect(report.providers).toEqual([
121
+ { provider: "aaa", engine: "headroom", families: ["openai"], direct: [] },
122
+ { provider: "bbb", engine: "caveman", families: ["gemini"], direct: [] },
123
+ ]);
124
+ });
125
+
126
+ test("a provider with no chat models is reported direct and named once", async () => {
127
+ const classifier = chatModel(
128
+ "typesafe",
129
+ "typesafe-classifier",
130
+ "typesafe.example.com",
131
+ "classifier-model",
132
+ );
133
+ const { notices, stateDir } = await boot({
134
+ models,
135
+ caveman: healthyCaveman,
136
+ headroom: healthyHeadroom,
137
+ extras: { classifier: [classifier] },
138
+ });
139
+ const report = JSON.parse(readFileSync(join(stateDir, "assignment.json"), "utf8")) as {
140
+ providers: { provider: string; engine: string | null }[];
141
+ };
142
+ expect(report.providers.find((entry) => entry.provider === "typesafe")?.engine).toBeNull();
143
+ const named = notices.filter((notice) => notice.message.includes("Non-chat providers"));
144
+ expect(named).toHaveLength(1);
145
+ expect(named[0]?.message).toContain("typesafe");
146
+ });
147
+
148
+ test("the status command reports each engine under its own label", async () => {
149
+ const { pi } = await boot({ models, caveman: healthyCaveman, headroom: healthyHeadroom });
150
+ const command = pi.commands.find((entry) => entry.name === "dual-engine");
151
+ expect(command).toBeDefined();
152
+ await command?.handler("", pi.ctx);
153
+ const status = pi.notices.at(-1)?.message ?? "";
154
+ expect(status).toContain("headroom (");
155
+ expect(status).toContain("caveman (");
156
+ expect(status.toLowerCase()).not.toContain("total");
157
+ });
158
+ });
package/test/fakes.ts ADDED
@@ -0,0 +1,155 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ export type ChatModel = {
4
+ readonly provider: string;
5
+ readonly id: string;
6
+ readonly name: string;
7
+ readonly api: string;
8
+ readonly baseUrl?: string;
9
+ readonly reasoning: boolean;
10
+ readonly input: readonly ("text" | "image")[];
11
+ readonly cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
12
+ readonly contextWindow: number;
13
+ readonly maxTokens: number;
14
+ };
15
+
16
+ export function chatModel(provider: string, api: string, host: string, id = `${provider}-model`): ChatModel {
17
+ return {
18
+ provider,
19
+ id,
20
+ name: id,
21
+ api,
22
+ baseUrl: `https://${host}/v1`,
23
+ reasoning: false,
24
+ input: ["text"],
25
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
26
+ contextWindow: 1000,
27
+ maxTokens: 100,
28
+ };
29
+ }
30
+
31
+ export type FakePi = {
32
+ api: ExtensionAPI;
33
+ tools: { name: string; definition: Record<string, unknown> }[];
34
+ providers: { name: string; config: Record<string, unknown> }[];
35
+ mcp: { name: string; config: Record<string, unknown> }[];
36
+ commands: { name: string; handler: (args: string, ctx: FakeCtx) => Promise<void> }[];
37
+ handlers: Map<string, ((event: unknown, ctx: FakeCtx) => Promise<void>)[]>;
38
+ models: ChatModel[];
39
+ notices: { type: string; message: string }[];
40
+ setModelCalls: ChatModel[];
41
+ emit(event: string, payload: unknown, ctx?: FakeCtx): Promise<void>;
42
+ ctx: FakeCtx;
43
+ };
44
+
45
+ export type FakeCtx = {
46
+ ui: { notify(message: string, type?: "info" | "warning" | "error"): void };
47
+ model: ChatModel | undefined;
48
+ setModel(model: ChatModel): Promise<boolean>;
49
+ modelRegistry: {
50
+ getModelsOfType(type: "chat"): readonly ChatModel[];
51
+ getAvailableOfType(type: "chat"): Promise<readonly ChatModel[]>;
52
+ };
53
+ executeTool(
54
+ name: string,
55
+ args: unknown,
56
+ ): Promise<{ result: { content: { type: "text"; text: string }[] }; isError: boolean }>;
57
+ calls: { name: string; args: unknown }[];
58
+ };
59
+
60
+ type Extras = Partial<Record<"image" | "classifier", readonly ChatModel[]>>;
61
+
62
+ export function makeCtx(models: readonly ChatModel[], current?: ChatModel, extras: Extras = {}): FakeCtx {
63
+ const calls: { name: string; args: unknown }[] = [];
64
+ const ctx: FakeCtx = {
65
+ ui: { notify: () => {} },
66
+ model: current ?? models[0],
67
+ calls,
68
+ setModel: async (model) => {
69
+ ctx.model = model;
70
+ return true;
71
+ },
72
+ modelRegistry: {
73
+ getModelsOfType: (type: string) =>
74
+ type === "chat" ? models : (extras[type as "image" | "classifier"] ?? []),
75
+ getAvailableOfType: async () => models,
76
+ },
77
+ executeTool: async (name, args) => {
78
+ calls.push({ name, args });
79
+ return {
80
+ result: { content: [{ type: "text", text: `${name}:${JSON.stringify(args)}` }] },
81
+ isError: false,
82
+ };
83
+ },
84
+ };
85
+ return ctx;
86
+ }
87
+
88
+ export function makePi(
89
+ models: readonly ChatModel[],
90
+ options: { exposure?: boolean; extras?: Extras } = {},
91
+ ): FakePi {
92
+ const tools: FakePi["tools"] = [];
93
+ const providers: FakePi["providers"] = [];
94
+ const mcp: FakePi["mcp"] = [];
95
+ const commands: FakePi["commands"] = [];
96
+ const handlers = new Map<string, ((event: unknown, ctx: FakeCtx) => Promise<void>)[]>();
97
+ const notices: { type: string; message: string }[] = [];
98
+ const setModelCalls: ChatModel[] = [];
99
+ const ctx = makeCtx(models, undefined, options.extras);
100
+ ctx.ui.notify = (message, type = "info") => {
101
+ notices.push({ type, message });
102
+ };
103
+ ctx.setModel = async (model) => {
104
+ setModelCalls.push(model);
105
+ ctx.model = model;
106
+ return true;
107
+ };
108
+
109
+ const api = {
110
+ registerTool: (definition: { name: string } & Record<string, unknown>) => {
111
+ tools.push({ name: definition.name, definition });
112
+ },
113
+ registerProvider: (name: string, config: Record<string, unknown>) => {
114
+ providers.push({ name, config });
115
+ },
116
+ registerMcpServer: (name: string, config: Record<string, unknown>) => {
117
+ mcp.push({ name, config });
118
+ },
119
+ registerCommand: (name: string, options: { handler: FakePi["commands"][number]["handler"] }) => {
120
+ commands.push({ name, handler: options.handler });
121
+ },
122
+ on: (event: string, handler: (event: unknown, ctx: FakeCtx) => Promise<void>) => {
123
+ handlers.set(event, [...(handlers.get(event) ?? []), handler]);
124
+ return () => {};
125
+ },
126
+ getAllTools: () =>
127
+ options.exposure === false
128
+ ? [{ name: "caveman_retrieve" }]
129
+ : [{ name: "caveman_retrieve", exposure: "direct" }],
130
+ getActiveTools: () => ["caveman_retrieve"],
131
+ setModel: async (model: ChatModel) => {
132
+ setModelCalls.push(model);
133
+ return true;
134
+ },
135
+ } as unknown as ExtensionAPI;
136
+
137
+ const fake: FakePi = {
138
+ api,
139
+ tools,
140
+ providers,
141
+ mcp,
142
+ commands,
143
+ handlers,
144
+ models: [...models],
145
+ notices,
146
+ setModelCalls,
147
+ ctx,
148
+ async emit(event, payload, target) {
149
+ for (const handler of handlers.get(event) ?? []) await handler(payload, target ?? ctx);
150
+ },
151
+ };
152
+ return fake;
153
+ }
154
+
155
+ export type { ExtensionContext };
@@ -0,0 +1,37 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { normalizeHandle, dispatchHandle } from "../src/handles.ts";
3
+
4
+ describe("handle dispatch", () => {
5
+ const cases: { input: string; engine: "caveman" | "headroom" | "error" }[] = [
6
+ { input: "ccr_0aa4e9800c2526914d4c1edb00b2cfa9", engine: "caveman" },
7
+ { input: "0aa4e9800c25", engine: "headroom" },
8
+ { input: "0aa4e9800c2526914d4c1edb", engine: "headroom" },
9
+ { input: "<<ccr:ccr_abc123>>", engine: "caveman" },
10
+ { input: "<<ccr:0aa4e9800c25>>", engine: "headroom" },
11
+ { input: "ccr://ccr_abc123", engine: "caveman" },
12
+ { input: "ccr://0aa4e9800c25", engine: "headroom" },
13
+ { input: "", engine: "error" },
14
+ { input: "not-a-handle", engine: "error" },
15
+ { input: "0aa4e9800c25AB", engine: "error" },
16
+ { input: "0aa4e9800c2526914d4c1edb00b2cfa9", engine: "error" },
17
+ { input: "ccr_", engine: "error" },
18
+ ];
19
+
20
+ for (const { input, engine } of cases) {
21
+ test(`"${input}" dispatches to ${engine}`, () => {
22
+ const target = dispatchHandle(input);
23
+ expect("engine" in target ? target.engine : "error").toBe(engine);
24
+ });
25
+ }
26
+
27
+ test("normalization strips marker and scheme wrappers only", () => {
28
+ expect(normalizeHandle(" <<ccr:ccr_abc>> ")).toBe("ccr_abc");
29
+ expect(normalizeHandle("ccr://ccr_abc")).toBe("ccr_abc");
30
+ expect(normalizeHandle("ccr_abc")).toBe("ccr_abc");
31
+ });
32
+
33
+ test("an unrecognized shape never names an engine", () => {
34
+ const target = dispatchHandle("randomword");
35
+ expect("error" in target && target.error).toContain("Unrecognized recovery handle");
36
+ });
37
+ });
@@ -0,0 +1,39 @@
1
+ import type { LifecycleDeps } from "../src/lifecycle.ts";
2
+ import type { ProbeResult } from "../src/probe.ts";
3
+
4
+ export type Harness = {
5
+ readonly deps: LifecycleDeps;
6
+ readonly spawns: { command: string; args: readonly string[] }[];
7
+ readonly kills: number[];
8
+ readonly clock: { value: number };
9
+ };
10
+
11
+ export function identify(engine: "caveman" | "headroom", port: number, owned: boolean): ProbeResult {
12
+ return { ok: true, state: { engine, port, upstreams: [], owned } };
13
+ }
14
+
15
+ export function harness(
16
+ overrides: Partial<LifecycleDeps>,
17
+ dirs: { stateDir: string; cavemanHome: string },
18
+ ): Harness {
19
+ const spawns: { command: string; args: readonly string[] }[] = [];
20
+ const kills: number[] = [];
21
+ const clock = { value: 0 };
22
+ const base: LifecycleDeps = {
23
+ stateDir: dirs.stateDir,
24
+ cavemanHome: dirs.cavemanHome,
25
+ timeoutMs: 100,
26
+ spawn: (command, args) => {
27
+ spawns.push({ command, args });
28
+ return { pid: 4242 };
29
+ },
30
+ kill: (pid) => kills.push(pid),
31
+ now: () => clock.value,
32
+ sleep: async (ms) => {
33
+ clock.value += ms;
34
+ },
35
+ probeCaveman: async () => ({ ok: false, reason: "down" }),
36
+ probeHeadroom: async () => ({ ok: false, reason: "down" }),
37
+ };
38
+ return { deps: { ...base, ...overrides }, spawns, kills, clock };
39
+ }
@@ -0,0 +1,99 @@
1
+ import { afterAll, describe, expect, test } from "bun:test";
2
+ import { createServer, type Server } from "node:http";
3
+ import { retrieveFromHeadroom } from "../src/headroom-http.ts";
4
+
5
+ const servers: Server[] = [];
6
+
7
+ afterAll(() => {
8
+ for (const server of servers) server.close();
9
+ });
10
+
11
+ type Stub = { readonly port: number; readonly server: Server };
12
+
13
+ /** A stub proxy that answers `/v1/retrieve` with the given status and body. */
14
+ function listen(status: number, body: unknown, delayMs = 0): Promise<Stub> {
15
+ return new Promise((resolve) => {
16
+ const server = createServer((request, response) => {
17
+ request.resume();
18
+ request.on("end", () => {
19
+ const send = () => {
20
+ response.writeHead(status, { "content-type": "application/json" });
21
+ response.end(JSON.stringify(body));
22
+ };
23
+ if (delayMs > 0) setTimeout(send, delayMs);
24
+ else send();
25
+ });
26
+ });
27
+ servers.push(server);
28
+ server.listen(0, "127.0.0.1", () => {
29
+ const address = server.address();
30
+ resolve({ server, port: typeof address === "object" && address ? address.port : 0 });
31
+ });
32
+ });
33
+ }
34
+
35
+ /** A port that refuses connections: bound, then closed before use. */
36
+ async function deadPort(): Promise<number> {
37
+ const stub = await listen(200, {});
38
+ servers.splice(servers.indexOf(stub.server), 1);
39
+ await new Promise<void>((resolve) => stub.server.close(() => resolve()));
40
+ return stub.port;
41
+ }
42
+
43
+ describe("Headroom retrieval over HTTP", () => {
44
+ test("a present handle returns the original bytes unchanged", async () => {
45
+ const payload = "z".repeat(120_000);
46
+ const { port } = await listen(200, { hash: "0aa4e9800c25", original_content: payload });
47
+ const outcome = await retrieveFromHeadroom([port], "0aa4e9800c25");
48
+ expect(outcome.isError).toBe(false);
49
+ expect(outcome.content).toHaveLength(1);
50
+ expect(outcome.content[0]).toEqual({ type: "text", text: payload });
51
+ });
52
+
53
+ test("an expired handle reports the store's own reason and is an error", async () => {
54
+ const { port } = await listen(404, { detail: "Entry not found (CCR TTL: 1800 seconds)" });
55
+ const outcome = await retrieveFromHeadroom([port], "0aa4e9800c25");
56
+ expect(outcome.isError).toBe(true);
57
+ expect(outcome.content[0]).toMatchObject({
58
+ type: "text",
59
+ text: expect.stringContaining("Entry not found (CCR TTL: 1800 seconds)"),
60
+ });
61
+ });
62
+
63
+ test("the same 404 is not retried on another instance", async () => {
64
+ const first = await listen(404, { detail: "Entry not found" });
65
+ const second = await listen(200, { original_content: "should not be reached" });
66
+ let secondHit = false;
67
+ second.server.on("request", () => {
68
+ secondHit = true;
69
+ });
70
+ const outcome = await retrieveFromHeadroom([first.port, second.port], "0aa4e9800c25");
71
+ expect(outcome.isError).toBe(true);
72
+ expect(secondHit).toBe(false);
73
+ });
74
+
75
+ test("a dead instance falls through to the next live one", async () => {
76
+ const dead = await deadPort();
77
+ const { port } = await listen(200, { original_content: "recovered" });
78
+ const outcome = await retrieveFromHeadroom([dead, port], "0aa4e9800c25");
79
+ expect(outcome.isError).toBe(false);
80
+ expect(outcome.content[0]).toEqual({ type: "text", text: "recovered" });
81
+ });
82
+
83
+ test("no running instance fails loudly without a request", async () => {
84
+ const outcome = await retrieveFromHeadroom([], "0aa4e9800c25");
85
+ expect(outcome.isError).toBe(true);
86
+ expect(outcome.content[0]).toMatchObject({
87
+ type: "text",
88
+ text: expect.stringContaining("No Headroom instance is running this session"),
89
+ });
90
+ });
91
+
92
+ test("a hung instance is bounded by the timeout", async () => {
93
+ const { port } = await listen(200, { original_content: "too late" }, 5_000);
94
+ const started = Date.now();
95
+ const outcome = await retrieveFromHeadroom([port], "0aa4e9800c25", 100);
96
+ expect(outcome.isError).toBe(true);
97
+ expect(Date.now() - started).toBeLessThan(2_000);
98
+ });
99
+ });
@@ -0,0 +1,75 @@
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 { ensureEngine } from "../src/lifecycle.ts";
6
+ import { lockPath, readLock } 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
+ describe("engine lifecycle", () => {
26
+ test("a reachable engine with matching identity is adopted, not spawned", async () => {
27
+ const h = harness({ probeCaveman: async () => identify("caveman", 8787, false) }, dirsPair());
28
+ const result = await ensureEngine({ engine: "caveman", start: true }, h.deps);
29
+ expect(result.ok).toBe(true);
30
+ expect(h.spawns).toHaveLength(0);
31
+ if (result.ok) expect(result.state.owned).toBe(false);
32
+ });
33
+
34
+ test("an absent engine starts under a lock and is verified before use", async () => {
35
+ const dirs = dirsPair();
36
+ let spawned = false;
37
+ const h = harness(
38
+ {
39
+ spawn: () => {
40
+ spawned = true;
41
+ return { pid: 4242 };
42
+ },
43
+ probeCaveman: async () => (spawned ? identify("caveman", 8787, true) : { ok: false, reason: "down" }),
44
+ },
45
+ dirs,
46
+ );
47
+ const result = await ensureEngine({ engine: "caveman", start: true }, h.deps);
48
+ expect(result.ok).toBe(true);
49
+ expect(readLock(lockPath(dirs.stateDir, "caveman", "main"))?.pid).toBe(4242);
50
+ if (result.ok) expect(result.state.owned).toBe(true);
51
+ });
52
+
53
+ test("a second session adopts the started engine and spawns nothing", async () => {
54
+ const h = harness({ probeCaveman: async () => identify("caveman", 8787, false) }, dirsPair());
55
+ await ensureEngine({ engine: "caveman", start: true }, h.deps);
56
+ await ensureEngine({ engine: "caveman", start: true }, h.deps);
57
+ expect(h.spawns).toHaveLength(0);
58
+ });
59
+
60
+ test("a started engine that never verifies is stopped and reported", async () => {
61
+ const dirs = dirsPair();
62
+ const h = harness({}, dirs);
63
+ const result = await ensureEngine({ engine: "caveman", start: true }, h.deps);
64
+ expect(result.ok).toBe(false);
65
+ expect(h.kills).toEqual([4242]);
66
+ expect(readLock(lockPath(dirs.stateDir, "caveman", "main"))).toBeUndefined();
67
+ });
68
+
69
+ test("start disabled reports without spawning", async () => {
70
+ const h = harness({}, dirsPair());
71
+ const result = await ensureEngine({ engine: "caveman", start: false }, h.deps);
72
+ expect(result.ok).toBe(false);
73
+ expect(h.spawns).toHaveLength(0);
74
+ });
75
+ });
@@ -0,0 +1,41 @@
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 = [chatModel("aaa", "openai-responses", "a.example.com", "responses-model")];
9
+
10
+ const headroomUp = {
11
+ ok: true as const,
12
+ state: {
13
+ engine: "headroom" as const,
14
+ port: portForKey(HEADROOM_BASE_PORT, "aaa"),
15
+ owned: false,
16
+ upstreams: [{ family: "openai" as const, host: "a.example.com" }],
17
+ },
18
+ };
19
+
20
+ describe("OpenAI Responses opt-in", () => {
21
+ test("passthrough stays unset and the affected models are named once", async () => {
22
+ const { notices } = await boot({ models, headroom: () => headroomUp });
23
+ expect(process.env.HEADROOM_COMPRESS_PASSTHROUGH).toBeUndefined();
24
+ const responses = notices.filter((notice) => notice.message.includes("OpenAI Responses models"));
25
+ expect(responses).toHaveLength(1);
26
+ expect(responses[0]?.message).toContain("aaa/responses-model");
27
+ expect(responses[0]?.message).toContain("HEADROOM_COMPRESS_PASSTHROUGH=1");
28
+ });
29
+
30
+ test("no savings claim is made for those models", async () => {
31
+ const { notices } = await boot({ models, headroom: () => headroomUp });
32
+ const claim = notices.find((notice) => notice.message.includes("OpenAI Responses models"));
33
+ expect(claim?.message.toLowerCase()).not.toContain("saving");
34
+ });
35
+
36
+ test("the notice is absent when no Responses model is carried", async () => {
37
+ const plain = [chatModel("aaa", "openai-completions", "a.example.com")];
38
+ const { notices } = await boot({ models: plain, headroom: () => headroomUp });
39
+ expect(notices.some((notice) => notice.message.includes("OpenAI Responses models"))).toBe(false);
40
+ });
41
+ });