@niwa-labs/harness-zcode 0.0.0-stage → 0.0.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.
@@ -0,0 +1,983 @@
1
+ /**
2
+ * The ZCode control side against a stand-in for
3
+ * `zcode app-server --stdio`: it speaks the wire as the real server does (NDJSON without the
4
+ * `jsonrpc` field, requests of its own to the client, `session/event` notifications among other
5
+ * noise) and writes what it was given into files, so a test can read what the control side asked.
6
+ *
7
+ * The signs of life are a forward-only stream, so a test subscribes before the action that starts
8
+ * a turn. Every test disposes its control side, so no child outlives it.
9
+ */
10
+
11
+ import { afterEach, beforeEach, expect, test } from "bun:test";
12
+ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
13
+ import { join } from "node:path";
14
+
15
+ import { z } from "zod";
16
+
17
+ import {
18
+ controlConformance,
19
+ harnessId,
20
+ harnessKind,
21
+ machineId,
22
+ modelName,
23
+ promptFromText,
24
+ sessionId,
25
+ } from "@niwa-labs/harness";
26
+ import type { Harness, LifeEvent, ReverseHandler, SessionId } from "@niwa-labs/harness";
27
+ import { onBoxManifest, onSpawn, useSandbox } from "@niwa-labs/sandbox";
28
+ import type { BoxRecord, LaunchedBox, Sandbox } from "@niwa-labs/sandbox";
29
+ import { ZCODE_FAKE as FAKE, tempDir } from "@niwa-labs/testing";
30
+
31
+ import { ZCODE_LAUNCH, zcodeControl } from "../src/control.ts";
32
+ import { ANSWER_SCHEMAS } from "../src/protocol/generated/zcode-protocol.ts";
33
+ import type { ZcodeControlOptions, ZcodeSessionControl } from "../src/control.ts";
34
+ import { assistant, createDatabase, user, writeSession } from "../src/fixtures.ts";
35
+ import { dbPathOf } from "../src/paths.ts";
36
+
37
+ let dir = "";
38
+ let bin = "";
39
+ const controls: ZcodeSessionControl[] = [];
40
+ const spawned: string[][] = [];
41
+ let unsubscribe = (): void => {};
42
+
43
+ beforeEach(async () => {
44
+ dir = await tempDir("zcode-control");
45
+ bin = join(dir, "zcode");
46
+ await writeFile(bin, FAKE);
47
+ await chmod(bin, 0o755);
48
+ unsubscribe = onSpawn((event) => spawned.push([...event.argv]));
49
+ });
50
+
51
+ afterEach(async () => {
52
+ unsubscribe();
53
+ spawned.length = 0;
54
+ for (const control of controls.splice(0)) await control.dispose();
55
+ await rm(dir, { recursive: true, force: true });
56
+ });
57
+
58
+ function control(extra: Partial<ZcodeControlOptions> = {}): ZcodeSessionControl {
59
+ const made = zcodeControl({ harness: "zcode-fake", binary: bin, stopGraceMs: 300, ...extra });
60
+ controls.push(made);
61
+ return made;
62
+ }
63
+
64
+ const logOf = async (name: string): Promise<Array<Record<string, unknown>>> =>
65
+ (await readFile(join(dir, name), "utf8").catch(() => ""))
66
+ .trim()
67
+ .split("\n")
68
+ .filter((line) => line !== "")
69
+ .map((line) => JSON.parse(line) as Record<string, unknown>);
70
+
71
+ /** The params of every request the fake got under a method. */
72
+ const requestsOf = async (method: string): Promise<Array<Record<string, unknown>>> =>
73
+ (await logOf("requests.log")).filter((frame) => frame["method"] === method).map((frame) => frame["params"] as Record<string, unknown>);
74
+
75
+ /** Watches the signs of life until `count` turns have ended. */
76
+ function turnsEnded(c: ZcodeSessionControl, id: SessionId, count = 1): Promise<LifeEvent[]> {
77
+ const seen: LifeEvent[] = [];
78
+ const stream = c.life(id)[Symbol.asyncIterator]();
79
+ return (async () => {
80
+ let ended = 0;
81
+ while (ended < count) {
82
+ const next = await stream.next();
83
+ if (next.done === true) throw new Error("the session ended before the turn did");
84
+ seen.push(next.value);
85
+ if (next.value.kind === "turn-ended") ended += 1;
86
+ }
87
+ void stream.return?.();
88
+ return seen;
89
+ })();
90
+ }
91
+
92
+ const hello = promptFromText("hello");
93
+
94
+ test("a start spawns one process, pings it, names the session and begins its first turn", async () => {
95
+ const c = control();
96
+ const started = await c.start({ prompt: hello, cwd: dir, env: { NIWA_ID: "k3f9" } });
97
+ expect(String(started.session.native)).toBe("sess_fake-1");
98
+ expect(started.first).toMatchObject({ status: "started", turn: 1 });
99
+
100
+ expect(spawned).toEqual([[bin, "app-server", "--stdio", "--cwd", dir]]);
101
+ expect((await logOf("env.log"))[0]).toMatchObject({ id: "k3f9" });
102
+ const methods = (await logOf("requests.log")).map((frame) => frame["method"]);
103
+ expect(methods.slice(0, 4)).toEqual(["runtime/capabilities", "session/create", "session/subscribe", "session/send"]);
104
+ // The model does not go to the create; no mode was chosen, so the session is an `auto` one: ZCode's `edit`.
105
+ expect(started.mode).toBe("auto");
106
+ expect((await requestsOf("session/create"))[0]).toEqual({ workspace: { workspacePath: dir, workspaceKey: dir }, mode: "edit" });
107
+ expect((await requestsOf("session/subscribe"))[0]).toMatchObject({ deliveryKind: "desktop-continuous", includeSnapshot: false });
108
+ // Nothing was chosen, so the send names no model.
109
+ expect((await requestsOf("session/send"))[0]).toEqual({ sessionId: "sess_fake-1", content: "hello" });
110
+
111
+ // The first turn began inside the start: its signs are kept for the first stream.
112
+ // No model was asked for, so the model the session runs is the one the server names, and it is the first sign.
113
+ const signs = await turnsEnded(c, started.session);
114
+ expect(signs.map((event) => event.kind).filter((kind) => kind !== "activity" && kind !== "unknown-variant")).toEqual(["model", "turn-started", "turn-ended"]);
115
+ expect(signs[0]).toEqual({ kind: "model", model: modelName("fake/default-model") });
116
+ expect(await c.state(started.session)).toBe("idle");
117
+ });
118
+
119
+ test("every request of the server is answered, whenever it comes, and unknown ones with an empty answer", async () => {
120
+ const c = control();
121
+ const { session } = await c.start({ prompt: hello, cwd: dir });
122
+ await turnsEnded(c, session);
123
+ const answers = await logOf("answers.log");
124
+ const answerTo = (id: string) => answers.find((frame) => frame["id"] === id)?.["result"];
125
+ // Preferences are asked when the session materializes and again with the send.
126
+ expect(answerTo("server-1")).toMatchObject({ memoryEnabled: false, askUserQuestionAutoResolutionEnabled: true });
127
+ expect(answerTo("server-2")).toMatchObject({ memoryEnabled: false });
128
+ // The official MCP identity headers are asked for; niwa holds none and says so in the words of that answer.
129
+ expect(answerTo("server-3")).toEqual({ ok: false, reason: "official_auth_unavailable" });
130
+ // A request the snapshot does not know is answered with an empty answer, as the real server's `session/readReplyLanguage` takes it.
131
+ expect(answerTo("server-4")).toEqual({});
132
+ });
133
+
134
+ test("every answer to a request of the server fits the schema of its method", async () => {
135
+ const c = control();
136
+ const { session } = await c.start({ prompt: promptFromText("needs permission"), cwd: dir });
137
+ await turnsEnded(c, session);
138
+ const asked = new Map((await logOf("asked.log")).map((frame) => [frame["id"], frame["method"]]));
139
+ const answers = (await logOf("answers.log")).filter((frame) => asked.has(frame["id"]));
140
+ expect(answers.length).toBeGreaterThanOrEqual(4);
141
+ for (const frame of answers) {
142
+ const method = String(asked.get(frame["id"]));
143
+ if (!Object.hasOwn(ANSWER_SCHEMAS, method)) continue;
144
+ const schema = ANSWER_SCHEMAS[method as keyof typeof ANSWER_SCHEMAS];
145
+ expect(schema.safeParse(frame["result"]).success, `${method}: ${JSON.stringify(frame["result"])}`).toBe(true);
146
+ }
147
+ });
148
+
149
+ test("a permission follows the policy: allowed by default and denied when denied; the mode is the working mode either way", async () => {
150
+ const allowing = control();
151
+ const first = await allowing.start({ prompt: promptFromText("needs permission"), cwd: dir });
152
+ await turnsEnded(allowing, first.session);
153
+ expect((await logOf("answers.log")).some((frame) => (frame["result"] as { decision?: string })?.decision === "allow")).toBe(true);
154
+
155
+ await rm(join(dir, "answers.log"));
156
+ await rm(join(dir, "requests.log"));
157
+ const denying = control({ permissions: "deny" });
158
+ const second = await denying.start({ prompt: promptFromText("needs permission"), cwd: dir });
159
+ await turnsEnded(denying, second.session);
160
+ expect((await logOf("answers.log")).some((frame) => (frame["result"] as { decision?: string })?.decision === "deny")).toBe(true);
161
+ // The mode is always named: left out, the config of the user or the project would choose it.
162
+ expect((await requestsOf("session/create"))[0]).toEqual({ workspace: { workspacePath: dir, workspaceKey: dir }, mode: "edit" });
163
+ });
164
+
165
+ test("a working mode is the mode of the created session: ask is guarded, auto is edit, full is yolo; the control option is the default", async () => {
166
+ const modes = [
167
+ ["ask", "guarded"],
168
+ ["auto", "edit"],
169
+ ["full", "yolo"],
170
+ ] as const;
171
+ for (const [mode, native] of modes) {
172
+ await rm(join(dir, "requests.log"), { force: true });
173
+ const started = await control().start({ prompt: promptFromText(""), cwd: dir, mode });
174
+ expect(started.mode).toBe(mode);
175
+ expect((await requestsOf("session/create"))[0]?.["mode"]).toBe(native);
176
+ }
177
+ await rm(join(dir, "requests.log"), { force: true });
178
+ const configured = await control({ mode: "full" }).start({ prompt: promptFromText(""), cwd: dir });
179
+ expect(configured.mode).toBe("full");
180
+ expect((await requestsOf("session/create"))[0]?.["mode"]).toBe("yolo");
181
+ // A mode the call names wins over the instance's.
182
+ await rm(join(dir, "requests.log"), { force: true });
183
+ expect((await control({ mode: "full" }).start({ prompt: promptFromText(""), cwd: dir, mode: "ask" })).mode).toBe("ask");
184
+ expect((await requestsOf("session/create"))[0]?.["mode"]).toBe("guarded");
185
+ });
186
+
187
+ test("a model and an effort go with every send, never with the create", async () => {
188
+ const c = control();
189
+ const { session } = await c.start({
190
+ prompt: promptFromText(""),
191
+ cwd: dir,
192
+ model: "builtin:zai-coding-plan/GLM-5.3-Flash",
193
+ effort: "high",
194
+ });
195
+ expect((await requestsOf("session/create"))[0]).not.toHaveProperty("model");
196
+ const selection = { providerId: "builtin:zai-coding-plan", modelId: "GLM-5.3-Flash", options: { reasoningLevel: "high" } };
197
+ const ended = turnsEnded(c, session);
198
+ await c.send(session, "one");
199
+ // ZCode names no model back for a send that names one: the request is not taken for what runs.
200
+ expect((await ended).filter((event) => event.kind === "model")).toEqual([]);
201
+ expect((await requestsOf("session/send")).map((params) => params["modelSelection"])).toEqual([selection]);
202
+ });
203
+
204
+ test("a model id may hold slashes, and the control options are the defaults of a start", async () => {
205
+ const c = control({ model: "2eafb73d/minimax/MiniMax-M3", effort: "max" });
206
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir });
207
+ const ended = turnsEnded(c, session);
208
+ await c.send(session, "one");
209
+ await ended;
210
+ expect((await requestsOf("session/send"))[0]?.["modelSelection"]).toEqual({
211
+ providerId: "2eafb73d",
212
+ modelId: "minimax/MiniMax-M3",
213
+ options: { reasoningLevel: "max" },
214
+ });
215
+ });
216
+
217
+ test("an effort with no model chosen is applied to the model the server names", async () => {
218
+ const c = control();
219
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir, effort: "low" });
220
+ const ended = turnsEnded(c, session);
221
+ await c.send(session, "one");
222
+ await ended;
223
+ expect((await requestsOf("session/send"))[0]?.["modelSelection"]).toEqual({
224
+ providerId: "fake",
225
+ modelId: "default-model",
226
+ options: { reasoningLevel: "low" },
227
+ });
228
+ });
229
+
230
+ test("what ZCode cannot do is refused by name before any process is born", async () => {
231
+ const c = control();
232
+ const refuse = async (options: Parameters<ZcodeSessionControl["start"]>[0], detail: string) => {
233
+ const refusal = await c.start(options).catch((error: unknown) => error);
234
+ expect(refusal).toMatchObject({ code: "Unsupported" });
235
+ expect((refusal as Error).message).toContain(detail);
236
+ };
237
+ await refuse({ prompt: hello, effort: "xhigh" }, "is not one of low, high, max");
238
+ await refuse({ prompt: hello, model: "no-provider" }, "providerId/modelId");
239
+ await refuse({ prompt: hello, model: "provider/" }, "providerId/modelId");
240
+ expect(spawned).toEqual([]);
241
+ expect(ZCODE_LAUNCH).toEqual({ model: true, effort: ["low", "high", "max"], modes: ["ask", "auto", "full"] });
242
+ });
243
+
244
+ test("an allow-list gets niwa's own server tools appended; foreign server tools pass only when listed", async () => {
245
+ const c = control();
246
+ const niwa = { name: "niwa", command: "niwa", args: [], env: {}, tools: ["session_send", "submit_answer"] };
247
+ const github = { name: "github", command: "gh-mcp", args: [], env: {} };
248
+ const base = { workspace: { workspacePath: dir, workspaceKey: dir }, mode: "edit" };
249
+ await c.start({ prompt: promptFromText(""), cwd: dir, servers: [niwa, github], tools: { allow: ["Read"] } });
250
+ await c.start({ prompt: promptFromText(""), cwd: dir, servers: [niwa, github], tools: { allow: ["Read", "mcp__github__create_issue", "mcp__niwa__session_send"] } });
251
+ // Without an allow-list nothing is filtered, so nothing is added.
252
+ await c.start({ prompt: promptFromText(""), cwd: dir, servers: [niwa] });
253
+ const created = await requestsOf("session/create");
254
+ const wire = (server: { name: string; command: string }) => ({ name: server.name, command: server.command, args: [], env: [] });
255
+ expect(created[0]).toEqual({ ...base, mcpServers: [wire(niwa), wire(github)], toolAllowlist: ["Read", "mcp__niwa__session_send", "mcp__niwa__submit_answer"] });
256
+ expect(created[1]).toEqual({
257
+ ...base,
258
+ mcpServers: [wire(niwa), wire(github)],
259
+ toolAllowlist: ["Read", "mcp__github__create_issue", "mcp__niwa__session_send", "mcp__niwa__submit_answer"],
260
+ });
261
+ expect(created[2]).toEqual({ ...base, mcpServers: [wire(niwa)] });
262
+ expect(spawned.length).toBeGreaterThan(0);
263
+ });
264
+
265
+ test("a session of niwa's tools only allows none of ZCode's own tools, only those niwa's server lists", async () => {
266
+ const c = control();
267
+ const niwa = { name: "niwa", command: "niwa", args: [], env: {}, tools: ["session_send"] };
268
+ const github = { name: "github", command: "gh-mcp", args: [], env: {} };
269
+ await c.start({ prompt: promptFromText(""), cwd: dir, servers: [niwa, github], tools: "niwa-only" });
270
+ await c.start({ prompt: promptFromText(""), cwd: dir, tools: "niwa-only" });
271
+ await c.start({ prompt: promptFromText(""), cwd: dir, tools: "all" });
272
+ const created = await requestsOf("session/create");
273
+ expect(created[0]?.["toolAllowlist"]).toEqual(["mcp__niwa__session_send"]);
274
+ expect(created[1]?.["toolAllowlist"]).toEqual([]);
275
+ expect(created[2]).not.toHaveProperty("toolAllowlist");
276
+ });
277
+
278
+ test("the servers and the tool sets of a session go to session/create in ZCode's own shape", async () => {
279
+ const c = control();
280
+ const niwa = { name: "niwa", command: "niwa", args: ["--home", "/h", "mcp"], env: { NIWA_ID: "k3f9", EMPTY: "" } };
281
+ // The deny-list and the servers together.
282
+ await c.start({ prompt: promptFromText(""), cwd: dir, servers: [niwa], visible: { actions: ["a"], disabledTools: ["Bash", "Write"] } });
283
+ expect((await requestsOf("session/create"))[0]).toEqual({
284
+ workspace: { workspacePath: dir, workspaceKey: dir },
285
+ mode: "edit",
286
+ mcpServers: [
287
+ { name: "niwa", command: "niwa", args: ["--home", "/h", "mcp"], env: [{ name: "NIWA_ID", value: "k3f9" }, { name: "EMPTY", value: "" }] },
288
+ ],
289
+ toolDenylist: ["Bash", "Write"],
290
+ });
291
+ // The allow-list alone, an empty one too: it allows nothing.
292
+ await c.start({ prompt: promptFromText(""), cwd: dir, tools: { allow: ["Read", "Grep"] } });
293
+ await c.start({ prompt: promptFromText(""), cwd: dir, tools: { allow: [] } });
294
+ const created = await requestsOf("session/create");
295
+ expect(created[1]).toEqual({ workspace: { workspacePath: dir, workspaceKey: dir }, mode: "edit", toolAllowlist: ["Read", "Grep"] });
296
+ expect(created[2]).toEqual({ workspace: { workspacePath: dir, workspaceKey: dir }, mode: "edit", toolAllowlist: [] });
297
+ // Visible actions that switch nothing off, and no servers, send nothing of the kind.
298
+ await c.start({ prompt: promptFromText(""), cwd: dir, servers: [], visible: { actions: ["a"], disabledTools: [] } });
299
+ expect((await requestsOf("session/create"))[3]).toEqual({ workspace: { workspacePath: dir, workspaceKey: dir }, mode: "edit" });
300
+ });
301
+
302
+ test("a message to a busy session waits for the turn after, and a steer goes into the running one", async () => {
303
+ const c = control();
304
+ const { session } = await c.start({ prompt: promptFromText("slow"), cwd: dir });
305
+ const ended = turnsEnded(c, session, 2);
306
+ const queued = await c.send(session, "second");
307
+ expect(queued).toMatchObject({ status: "queued", turn: 2 });
308
+ // The server has seen the first message only: the second waits on this side.
309
+ expect((await requestsOf("session/send")).map((params) => params["content"])).toEqual(["slow"]);
310
+ const events = await ended;
311
+ expect(events.filter((event) => event.kind === "turn-ended").map((event) => (event as { turn: number }).turn)).toEqual([1, 2]);
312
+ expect((await requestsOf("session/send")).map((params) => params["content"])).toEqual(["slow", "second"]);
313
+
314
+ const running = await c.send(session, "third");
315
+ expect(running).toMatchObject({ status: "started", turn: 3 });
316
+ const steered = await c.send(session, "steer", { into: "turn" });
317
+ expect(steered).toMatchObject({ status: "delivered", turn: 3 });
318
+ });
319
+
320
+ test("a steer goes through v4/command as a guided sendText, never as a session/send, which a running turn refuses", async () => {
321
+ const c = control();
322
+ const { session } = await c.start({ prompt: promptFromText("slow"), cwd: dir });
323
+ const steered = await c.send(session, "steer", { into: "turn" });
324
+ expect(steered).toMatchObject({ status: "delivered", turn: 1 });
325
+ expect((await requestsOf("session/send")).map((params) => params["content"])).toEqual(["slow"]);
326
+ const [command] = await requestsOf("v4/command");
327
+ expect(command).toMatchObject({
328
+ sessionId: "sess_fake-1",
329
+ type: "sendText",
330
+ payload: { text: "steer", requestedDelivery: "guide" },
331
+ workspace: { workspacePath: dir, workspaceKey: dir },
332
+ });
333
+ expect(typeof command?.["commandId"]).toBe("string");
334
+ // Each steer is a command of its own.
335
+ await c.send(session, "again", { into: "turn" });
336
+ const ids = (await requestsOf("v4/command")).map((params) => params["commandId"]);
337
+ expect(new Set(ids).size).toBe(2);
338
+ // What the command did not take is a message that was not sent.
339
+ await expect(c.send(session, "reject this", { into: "turn" })).rejects.toMatchObject({ code: "InputNotSent" });
340
+ });
341
+
342
+ test("a ZCode without v4/command refuses a steer by name and sends nothing", async () => {
343
+ await writeFile(join(dir, "no-v4"), "");
344
+ const c = control();
345
+ const { session } = await c.start({ prompt: promptFromText("slow"), cwd: dir });
346
+ await expect(c.send(session, "steer", { into: "turn" })).rejects.toMatchObject({ code: "Unsupported" });
347
+ expect((await requestsOf("session/send")).map((params) => params["content"])).toEqual(["slow"]);
348
+ });
349
+
350
+ test("a message the server refuses releases the session, and what queued behind it gets its turn", async () => {
351
+ const c = control();
352
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir });
353
+ // The ask holds the session while the server weighs its message; another message waits behind it.
354
+ const refused = c.ask(session, { schema: z.string(), prompt: promptFromText("refuse") }).catch((error: unknown) => error);
355
+ expect(await c.send(session, "after")).toMatchObject({ status: "queued" });
356
+ expect(await refused).toMatchObject({ code: "InputNotSent" });
357
+ while (!(await requestsOf("session/send")).some((params) => params["content"] === "after")) await Bun.sleep(10);
358
+ expect(await c.state(session)).toBe("running");
359
+ });
360
+
361
+ test("a message whose answer never came keeps the session busy, so a later turn is not taken for it", async () => {
362
+ const c = control({ callTimeoutMs: 200 });
363
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir });
364
+ const ended = turnsEnded(c, session, 2);
365
+ await expect(c.send(session, "mute slow")).rejects.toMatchObject({ code: "InputPossiblySent" });
366
+ // The turn may be running: it is not over, and the next message waits for it.
367
+ expect(await c.state(session)).toBe("running");
368
+ expect(await c.send(session, "next")).toMatchObject({ status: "queued", turn: 2 });
369
+ const events = await ended;
370
+ expect(events.filter((event) => event.kind === "turn-ended").map((event) => (event as { turn: number }).turn)).toEqual([1, 2]);
371
+ expect((await requestsOf("session/send")).map((params) => params["content"])).toEqual(["mute slow", "next"]);
372
+ });
373
+
374
+ test("an answer to a send that is no acceptance of it is a message that may have gone", async () => {
375
+ const c = control();
376
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir });
377
+ const ended = turnsEnded(c, session);
378
+ await expect(c.send(session, "bad ack")).rejects.toMatchObject({ code: "InputPossiblySent" });
379
+ await ended;
380
+ const bare = turnsEnded(c, session);
381
+ await expect(c.send(session, "bare ack")).rejects.toMatchObject({ code: "InputPossiblySent" });
382
+ await bare;
383
+ expect(await c.state(session)).toBe("idle");
384
+ });
385
+
386
+ test("a resume of a held session with a prompt waits behind the running turn", async () => {
387
+ const c = control();
388
+ const { session } = await c.start({ prompt: promptFromText("slow"), cwd: dir });
389
+ const ended = turnsEnded(c, session, 2);
390
+ await c.resume(session, { prompt: promptFromText("after") });
391
+ expect((await requestsOf("session/send")).map((params) => params["content"])).toEqual(["slow"]);
392
+ await ended;
393
+ expect((await requestsOf("session/send")).map((params) => params["content"])).toEqual(["slow", "after"]);
394
+ });
395
+
396
+ test("an ask returns the value that passed the schema, from the JSON in the answer or the answer itself", async () => {
397
+ const c = control();
398
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir });
399
+ const word = await c.ask(session, { schema: z.object({ word: z.string() }), prompt: promptFromText("give the word") });
400
+ expect(word.value).toEqual({ word: "ok" });
401
+ expect((await requestsOf("session/send"))[0]?.["content"]).toContain("Answer with JSON only");
402
+
403
+ const fenced = await c.ask(session, { schema: z.object({ word: z.string() }), prompt: promptFromText("give the fenced word") });
404
+ expect(fenced.value).toEqual({ word: "fenced" });
405
+ const plain = await c.ask(session, { schema: z.string(), prompt: promptFromText("plain") });
406
+ expect(plain.value).toBe("fake reply");
407
+ // An answer the turn did not carry is read back from the transcript.
408
+ const silent = await c.ask(session, { schema: z.string(), prompt: promptFromText("silent") });
409
+ expect(silent.value).toBe("from the transcript");
410
+ await expect(c.ask(session, { schema: z.object({ word: z.number() }), prompt: promptFromText("give the word") })).rejects.toThrow("did not pass the schema: word");
411
+ });
412
+
413
+ test("a turn that left no text of its own does not answer with the text of an earlier turn", async () => {
414
+ const c = control();
415
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir });
416
+ const word = z.object({ word: z.string() });
417
+ // The transcript holds a valid answer from this turn; the next turn says nothing, anywhere.
418
+ expect((await c.ask(session, { schema: word, prompt: promptFromText("give the word") })).value).toEqual({ word: "ok" });
419
+ await expect(c.ask(session, { schema: word, prompt: promptFromText("empty") })).rejects.toThrow("the turn left no answer");
420
+ await expect(c.ask(session, { schema: z.string(), prompt: promptFromText("empty") })).rejects.toThrow("the turn left no answer");
421
+ // Its own answer is still read back for the turn that has one.
422
+ expect((await c.ask(session, { schema: z.string(), prompt: promptFromText("silent") })).value).toBe("from the transcript");
423
+ });
424
+
425
+ test("a server that names no message for a turn is read by what was sent", async () => {
426
+ await writeFile(join(dir, "no-message-id"), "");
427
+ const c = control();
428
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir });
429
+ expect((await c.ask(session, { schema: z.object({ word: z.string() }), prompt: promptFromText("give the word") })).value).toEqual({ word: "ok" });
430
+ expect((await c.ask(session, { schema: z.string(), prompt: promptFromText("silent") })).value).toBe("from the transcript");
431
+ await expect(c.ask(session, { schema: z.string(), prompt: promptFromText("empty") })).rejects.toThrow("the turn left no answer");
432
+ });
433
+
434
+ test("an ask to a busy session is answered after the turn that runs", async () => {
435
+ const c = control();
436
+ const { session } = await c.start({ prompt: promptFromText("slow"), cwd: dir });
437
+ const answer = await c.ask(session, { schema: z.object({ word: z.string() }), prompt: promptFromText("give the word") });
438
+ expect(answer.value).toEqual({ word: "ok" });
439
+ expect((await requestsOf("session/send")).map((params) => String(params["content"]).slice(0, 4))).toEqual(["slow", "give"]);
440
+ });
441
+
442
+ test("an interrupt stops the turn through session/stop, ends it, and drops what waited behind it", async () => {
443
+ const c = control();
444
+ const { session } = await c.start({ prompt: promptFromText("hang"), cwd: dir });
445
+ await c.send(session, "never sent");
446
+ const ended = turnsEnded(c, session);
447
+ await c.interrupt(session);
448
+ await ended;
449
+ expect(await requestsOf("session/stop")).toEqual([{ sessionId: "sess_fake-1" }]);
450
+ expect(await c.state(session)).toBe("idle");
451
+ expect((await requestsOf("session/send")).map((params) => params["content"])).toEqual(["hang"]);
452
+ await expect(c.interrupt(session)).rejects.toMatchObject({ code: "Unavailable" });
453
+ });
454
+
455
+ test("a turn that fails is an error for its asker, and a turn that was cut is one too", async () => {
456
+ const c = control();
457
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir });
458
+ await expect(c.ask(session, { schema: z.string(), prompt: promptFromText("fail") })).rejects.toThrow("the turn was failed: model exploded");
459
+ expect(await c.state(session)).toBe("idle");
460
+
461
+ const hanging = c.ask(session, { schema: z.string(), prompt: promptFromText("hang") });
462
+ const settled = hanging.catch((error: unknown) => error);
463
+ while ((await requestsOf("session/send")).length < 2) await Bun.sleep(10);
464
+ await c.interrupt(session);
465
+ expect(String(await settled)).toContain("the turn was cancelled");
466
+ });
467
+
468
+ test("a session whose process dies ends its stream and is unknown from then on", async () => {
469
+ const c = control();
470
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir });
471
+ const events: LifeEvent[] = [];
472
+ const watching = (async () => {
473
+ for await (const event of c.life(session)) events.push(event);
474
+ })();
475
+ await c.send(session, "die");
476
+ await watching;
477
+ expect(events.some((event) => event.kind === "activity" && event.detail?.includes("exited (3)"))).toBe(true);
478
+ expect(await c.state(session)).toBe("unknown");
479
+ // The process is gone: the message is never written, so sending it again is safe.
480
+ await expect(c.send(session, "again")).rejects.toMatchObject({ code: "InputNotSent" });
481
+ });
482
+
483
+ test("a stray end of a turn when none runs is not a turn", async () => {
484
+ const c = control();
485
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir });
486
+ const events: LifeEvent[] = [];
487
+ const watching = (async () => {
488
+ for await (const event of c.life(session)) {
489
+ events.push(event);
490
+ if (event.kind === "activity" && event.detail?.includes("while none was running")) return;
491
+ }
492
+ })();
493
+ await c.send(session, "stray");
494
+ await watching;
495
+ expect(events.filter((event) => event.kind === "turn-ended")).toHaveLength(1);
496
+ expect(events.filter((event) => event.kind === "turn-started")).toHaveLength(1);
497
+ });
498
+
499
+ /** Starts a session with no turn, watches it, sends a turn and gives its signs once it ended. */
500
+ async function signsOf(c: ZcodeSessionControl, content: string): Promise<LifeEvent[]> {
501
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir });
502
+ const events: LifeEvent[] = [];
503
+ const watching = (async () => {
504
+ for await (const event of c.life(session)) {
505
+ events.push(event);
506
+ if (event.kind === "turn-ended") return;
507
+ }
508
+ })();
509
+ await c.send(session, content);
510
+ await watching;
511
+ return events;
512
+ }
513
+
514
+ const detailsOf = (events: readonly LifeEvent[]): string[] =>
515
+ events.flatMap((event) => (event.kind === "activity" && event.detail !== undefined ? [event.detail] : []));
516
+
517
+ test("what the snapshot does not know is told in the log, with its raw message, and does not end or break the turn", async () => {
518
+ await writeFile(join(dir, "script.json"), JSON.stringify([{ event: { type: "turn.hypothetical", payload: { x: 1 } } }]));
519
+ const events = await signsOf(control(), "script");
520
+ const details = detailsOf(events);
521
+ // An event type that is new, and the request of the real server that the snapshot predates.
522
+ expect(details.some((detail) => detail.startsWith('unknown zcode event type "turn.hypothetical" (not in the snapshot):') && detail.includes('"x":1'))).toBe(true);
523
+ expect(details.some((detail) => detail.startsWith('unknown zcode method "session/readReplyLanguage" (not in the snapshot):'))).toBe(true);
524
+ // The same two are the typed unknown the sessions plugin records: the protocol, the discriminator's value, the raw message.
525
+ const unknown = events.flatMap((event) => (event.kind === "unknown-variant" ? [event] : []));
526
+ expect(unknown.map((event) => [event.protocol, event.variant])).toEqual(
527
+ expect.arrayContaining([
528
+ ["zcode app-server", "session/event turn.hypothetical"],
529
+ ["zcode app-server", "session/readReplyLanguage"],
530
+ ]),
531
+ );
532
+ expect(unknown.find((event) => event.variant === "session/event turn.hypothetical")?.raw).toMatchObject({
533
+ method: "session/event",
534
+ params: { type: "turn.hypothetical", payload: { x: 1 } },
535
+ });
536
+ // The turn still ended by the event that ends it.
537
+ expect(events.filter((event) => event.kind === "turn-ended")).toHaveLength(1);
538
+ });
539
+
540
+ test("the messages of the v4 side channel and the notifications that are not about a turn leave no sign in the log", async () => {
541
+ const details = detailsOf(await signsOf(control(), "hello"));
542
+ expect(details.filter((detail) => detail.includes("v4/") || detail.includes("state.updated"))).toEqual([]);
543
+ expect(details).toContain("turn.started");
544
+ expect(details).toContain("model.streaming");
545
+ });
546
+
547
+ test("a turn that ends with an error result is a failed turn that says which result it ended with", async () => {
548
+ await writeFile(join(dir, "script.json"), JSON.stringify([{ event: { type: "turn.completed", payload: { resultType: "error_max_turns" } } }]));
549
+ const details = detailsOf(await signsOf(control(), "script"));
550
+ expect(details).toContain("the turn ended with error_max_turns");
551
+ });
552
+
553
+ const outcomeOf = (events: readonly LifeEvent[]): unknown => events.find((event) => event.kind === "turn-ended")?.outcome;
554
+
555
+ test("a turn ends as completed when it was answered, and as failed when it ran out or broke", async () => {
556
+ expect(outcomeOf(await signsOf(control(), "hello"))).toBe("completed");
557
+ await writeFile(join(dir, "script.json"), JSON.stringify([{ event: { type: "turn.completed", payload: { resultType: "error_max_turns" } } }]));
558
+ expect(outcomeOf(await signsOf(control(), "script"))).toBe("failed");
559
+ });
560
+
561
+ test("a turn that was cut ends as failed", async () => {
562
+ const c = control();
563
+ const { session } = await c.start({ prompt: promptFromText("hang"), cwd: dir });
564
+ const ended = turnsEnded(c, session);
565
+ await c.interrupt(session);
566
+ expect(outcomeOf(await ended)).toBe("failed");
567
+ });
568
+
569
+ test("a process whose readiness answer is no capabilities report is refused, and left no process behind", async () => {
570
+ await writeFile(join(dir, "bad-capabilities"), "");
571
+ await expect(control().start({ prompt: hello, cwd: dir })).rejects.toThrow("no capabilities report");
572
+ const pid = (await logOf("env.log"))[0]?.["pid"] as number;
573
+ await Bun.sleep(100);
574
+ expect(() => process.kill(pid, 0)).toThrow();
575
+ expect(await requestsOf("session/create")).toEqual([]);
576
+ });
577
+
578
+ test("a subscription falls back to the older spelling, and a start is refused when the server takes none", async () => {
579
+ await writeFile(join(dir, "old-subscribe"), "");
580
+ const c = control();
581
+ await c.start({ prompt: promptFromText(""), cwd: dir });
582
+ expect((await requestsOf("session/subscribe")).map((params) => params["deliveryKind"])).toEqual(["desktop-continuous", "desktop"]);
583
+
584
+ await writeFile(join(dir, "no-subscribe"), "");
585
+ await expect(control().start({ prompt: promptFromText(""), cwd: dir })).rejects.toMatchObject({ code: "Unavailable" });
586
+ });
587
+
588
+ test("a resume that is given the model of the session pins it in its sends, and one that is given none reports the model the server names", async () => {
589
+ const id = sessionId(harnessId("zcode-fake"), "sess_old");
590
+ const pinned = control();
591
+ await pinned.resume(id, { model: modelName("fake/pinned") });
592
+ const pinnedEnded = turnsEnded(pinned, id);
593
+ await pinned.send(id, "go");
594
+ // The model was recorded when it was named: the pin goes with the sends, and nothing names it again.
595
+ expect((await pinnedEnded).filter((event) => event.kind === "model")).toEqual([]);
596
+ expect((await requestsOf("session/send"))[0]?.["modelSelection"]).toEqual({ providerId: "fake", modelId: "pinned" });
597
+
598
+ const unpinned = control();
599
+ await unpinned.resume(id);
600
+ const unpinnedEnded = turnsEnded(unpinned, id);
601
+ await unpinned.send(id, "go");
602
+ expect((await unpinnedEnded)[0]).toEqual({ kind: "model", model: modelName("fake/default-model") });
603
+ });
604
+
605
+ test("a session that was not started here is resumed in a process of its own, in the directory it ran in", async () => {
606
+ const home = join(dir, "home");
607
+ await mkdir(join(home, "cli", "db"), { recursive: true });
608
+ const db = createDatabase(dbPathOf(home));
609
+ writeSession(db, "sess_old", [user("m1", "hi"), assistant("m2", "hello")], { directory: dir });
610
+ db.close();
611
+
612
+ const c = control({ home });
613
+ const id = sessionId(harnessId("zcode-fake"), "sess_old");
614
+ const ended = new Promise<void>((resolve, reject) => {
615
+ c.resume(id, { prompt: promptFromText("go on") }).then(resolve, reject);
616
+ });
617
+ await ended;
618
+ expect(spawned[0]).toEqual([bin, "app-server", "--stdio", "--cwd", dir]);
619
+ expect((await requestsOf("session/resume"))[0]).toEqual({ sessionId: "sess_old", workspace: { workspacePath: dir, workspaceKey: dir } });
620
+ expect((await requestsOf("session/send")).map((params) => params["sessionId"])).toEqual(["sess_old"]);
621
+ expect(await c.state(id)).toBe("idle");
622
+
623
+ // A resume that launches a process again gives it the servers and tool sets too, for the runtime it rebuilds.
624
+ const again = control({ home });
625
+ await again.resume(id, {
626
+ servers: [{ name: "niwa", command: "niwa", args: ["mcp"], env: { NIWA_ID: "t" } }],
627
+ visible: { actions: [], disabledTools: ["Bash"] },
628
+ });
629
+ expect((await requestsOf("session/resume"))[1]).toEqual({
630
+ sessionId: "sess_old",
631
+ workspace: { workspacePath: dir, workspaceKey: dir },
632
+ mcpServers: [{ name: "niwa", command: "niwa", args: ["mcp"], env: [{ name: "NIWA_ID", value: "t" }] }],
633
+ toolDenylist: ["Bash"],
634
+ });
635
+ // The allow-list of a resume carries niwa's own server tools as well.
636
+ await control({ home }).resume(id, { servers: [{ name: "niwa", command: "niwa", args: [], env: {}, tools: ["session_send"] }], tools: { allow: ["Read"] } });
637
+ expect(((await requestsOf("session/resume"))[2] as Record<string, unknown>)["toolAllowlist"]).toEqual(["Read", "mcp__niwa__session_send"]);
638
+
639
+ // Held now: a resume goes on in the same process, and cannot take another box.
640
+ await c.resume(id);
641
+ expect(spawned).toHaveLength(3);
642
+ await expect(c.resume(id, { box: { sandbox: "srt", spec: { cwd: dir } } })).rejects.toMatchObject({ code: "Unsupported" });
643
+ // Visible actions that switch nothing off take no tool set.
644
+ await c.resume(id, { visible: { actions: ["a"], disabledTools: [] } });
645
+ });
646
+
647
+ test("a session the database does not know is resumed in the directory its caller says it started in", async () => {
648
+ const where = join(dir, "workspace");
649
+ await mkdir(where);
650
+ const c = control();
651
+ await c.resume(sessionId(harnessId("zcode-fake"), "sess_unlisted"), { cwd: where });
652
+ expect(spawned[0]).toEqual([bin, "app-server", "--stdio", "--cwd", where]);
653
+ expect((await requestsOf("session/resume"))[0]).toMatchObject({ workspace: { workspacePath: where, workspaceKey: where } });
654
+ });
655
+
656
+ test("resumes of one session that is not held yet share one process, and a prompt does not hold the others up", async () => {
657
+ const c = control();
658
+ const id = sessionId(harnessId("zcode-fake"), "sess_twice");
659
+ // Both look for the session while it is absent: only the first launches it, the other finds it held.
660
+ await Promise.all([c.resume(id), c.resume(id)]);
661
+ expect(spawned).toHaveLength(1);
662
+ expect(await requestsOf("session/resume")).toHaveLength(1);
663
+ // The turn of a prompt runs after the session is let go of, so a second resume is not held up by it.
664
+ const other = sessionId(harnessId("zcode-fake"), "sess_other");
665
+ const first = c.resume(other, { prompt: promptFromText("slow") });
666
+ const second = c.resume(other);
667
+ await second;
668
+ expect(await c.state(other)).toBe("running");
669
+ await first;
670
+ expect(spawned).toHaveLength(2);
671
+ });
672
+
673
+ test("a resume of a held session with the same surface changes nothing; with another, a new process takes the session on", async () => {
674
+ const c = control();
675
+ const server = { name: "niwa", command: "niwa", args: ["mcp"], env: { NIWA_ID: "t" } };
676
+ const { session } = await c.start({ prompt: promptFromText(""), cwd: dir, servers: [server], visible: { actions: [], disabledTools: ["Bash"] } });
677
+ const events: string[] = [];
678
+ const watching = (async () => { for await (const event of c.life(session)) events.push(event.kind); })();
679
+ expect(spawned).toHaveLength(1);
680
+ // The same: accepted silently, no new process.
681
+ await c.resume(session, { servers: [server], visible: { actions: [], disabledTools: ["Bash"] } });
682
+ expect(spawned).toHaveLength(1);
683
+ // Nothing asked: the process keeps what it has.
684
+ await c.resume(session);
685
+ expect(spawned).toHaveLength(1);
686
+ // Another: the held process is ended and a new one resumes the session with the new surface.
687
+ await c.resume(session, { servers: [server], tools: { allow: ["Read"] } });
688
+ expect(spawned).toHaveLength(2);
689
+ const resumed = await requestsOf("session/resume");
690
+ expect(resumed).toHaveLength(1);
691
+ expect(resumed[0]).toMatchObject({ sessionId: session.native, toolAllowlist: ["Read"] });
692
+ // What the resume did not name is what the session had: the deny-list stays.
693
+ expect(resumed[0]?.["toolDenylist"]).toEqual(["Bash"]);
694
+ expect(await c.state(session)).toBe("idle");
695
+ // Under a running turn the surface cannot change.
696
+ await c.send(session, "slow");
697
+ await expect(c.resume(session, { tools: { allow: [] } })).rejects.toMatchObject({ code: "Unavailable" });
698
+ expect(spawned).toHaveLength(2);
699
+ });
700
+
701
+ test("a process that replaces a held one keeps its box, environment, tool restrictions, model and effort", async () => {
702
+ const records: BoxRecord[] = [];
703
+ const restore = useSandbox("nono", plainNono());
704
+ const forget = onBoxManifest((record) => void records.push(record));
705
+ try {
706
+ const c = control();
707
+ const niwa = { name: "niwa", command: "niwa", args: [], env: {}, tools: ["session_send"] };
708
+ const { session } = await c.start({
709
+ prompt: promptFromText(""),
710
+ cwd: dir,
711
+ env: { NIWA_ID: "k3f9" },
712
+ box: { sandbox: "nono", spec: { cwd: dir, write: [dir], env: {} } },
713
+ servers: [niwa],
714
+ tools: { allow: ["Read"] },
715
+ visible: { actions: [], disabledTools: ["Bash"] },
716
+ model: "builtin:p/GLM-5.3",
717
+ effort: "high",
718
+ });
719
+ // Only the servers change: the process is replaced.
720
+ await c.resume(session, { servers: [niwa, { name: "extra", command: "extra", args: [], env: {} }] });
721
+ expect(spawned).toHaveLength(2);
722
+ // The new process is boxed as the old one was, with its environment and grants.
723
+ expect(records).toHaveLength(2);
724
+ expect(records[1]?.spec.write.map(String)).toEqual(records[0]?.spec.write.map(String));
725
+ expect(Object.entries(records[1]?.spec.env ?? {})).toContainEqual(["NIWA_ID", "k3f9"]);
726
+ expect((await logOf("env.log"))[1]).toMatchObject({ id: "k3f9" });
727
+ // Its restrictions are the old ones, with the new server.
728
+ const [resumed] = await requestsOf("session/resume");
729
+ expect(resumed).toMatchObject({ toolAllowlist: ["Read", "mcp__niwa__session_send"], toolDenylist: ["Bash"] });
730
+ expect((resumed?.["mcpServers"] as Array<{ name: string }>).map((server) => server.name)).toEqual(["niwa", "extra"]);
731
+ // And it runs the model the old one did.
732
+ const ended = turnsEnded(c, session);
733
+ await c.send(session, "go");
734
+ await ended;
735
+ expect((await requestsOf("session/send")).at(-1)?.["modelSelection"]).toEqual({
736
+ providerId: "builtin:p",
737
+ modelId: "GLM-5.3",
738
+ options: { reasoningLevel: "high" },
739
+ });
740
+ } finally {
741
+ forget();
742
+ restore();
743
+ }
744
+ });
745
+
746
+ test("a resume that is refused does not change who answers the session's requests; one that is accepted does", async () => {
747
+ const permission = {
748
+ requestId: "perm-x",
749
+ sessionId: "sess_fake-1",
750
+ toolCallId: "call-perm-x",
751
+ toolName: "Bash",
752
+ reason: "the tool wants to run",
753
+ riskLevel: "medium",
754
+ input: { command: "ls" },
755
+ options: [
756
+ { optionId: "allow_once", kind: "allow_once", name: "Allow once", response: { decision: "allow", reason: "Approved once" } },
757
+ { optionId: "deny", kind: "deny", name: "Deny", response: { decision: "deny", reason: "No" } },
758
+ ],
759
+ };
760
+ await writeFile(join(dir, "script.json"), JSON.stringify([{ ms: 400 }, { ask: { method: "interaction/requestPermission", params: permission } }]));
761
+ const first: string[] = [];
762
+ const second: string[] = [];
763
+ const answering = (log: string[]): ReverseHandler => async (_session, request) => {
764
+ log.push(request.raw.method);
765
+ return { cancelled: true };
766
+ };
767
+ const c = control();
768
+ const { session } = await c.start({ prompt: promptFromText("script"), cwd: dir, reverse: answering(first) });
769
+ // The turn runs, so the tools cannot change: the resume is refused, and it must leave the first handler in place.
770
+ await expect(c.resume(session, { tools: { allow: [] }, reverse: answering(second) })).rejects.toMatchObject({ code: "Unavailable" });
771
+ while (first.length + second.length === 0) await Bun.sleep(10);
772
+ expect([first.length, second.length]).toEqual([1, 0]);
773
+ // An accepted resume hands the requests to its caller.
774
+ while ((await c.state(session)) !== "idle") await Bun.sleep(10);
775
+ await writeFile(join(dir, "script.json"), JSON.stringify([{ ms: 400 }, { ask: { method: "interaction/requestPermission", params: { ...permission, requestId: "perm-y", toolCallId: "call-perm-y" } } }]));
776
+ await c.send(session, "script");
777
+ await c.resume(session, { reverse: answering(second) });
778
+ while (second.length === 0) await Bun.sleep(10);
779
+ expect([first.length, second.length]).toEqual([1, 1]);
780
+ });
781
+
782
+ test("the ZCode fields the installation sets for a server go through to its mcpServers entry, and are absent by default", async () => {
783
+ const c = control({ mcp: { b: { alwaysLoad: true, timeoutMs: 5000, isolation: "session", scope: "workspace", cwd: "/w" } } });
784
+ const plain = { name: "a", command: "a", args: [], env: {} };
785
+ const set = { name: "b", command: "b", args: [], env: {} };
786
+ await c.start({ prompt: promptFromText(""), cwd: dir, servers: [plain, set] });
787
+ expect((await requestsOf("session/create"))[0]?.["mcpServers"]).toEqual([
788
+ { name: "a", command: "a", args: [], env: [] },
789
+ { name: "b", command: "b", args: [], env: [], alwaysLoad: true, timeoutMs: 5000, isolation: "session", scope: "workspace", cwd: "/w" },
790
+ ]);
791
+ });
792
+
793
+ test("a cold resume is refused when ZCode restores another mode than niwa started the session in", async () => {
794
+ const home = join(dir, "home");
795
+ await mkdir(join(home, "cli", "db"), { recursive: true });
796
+ const db = createDatabase(dbPathOf(home));
797
+ const stamped = (id: string, mode: string) => {
798
+ const message = assistant(id, "hello");
799
+ return { ...message, data: { ...message.data, mode } };
800
+ };
801
+ writeSession(db, "sess_edit", [user("m1", "hi"), stamped("m2", "edit")], { directory: dir });
802
+ writeSession(db, "sess_unstamped", [user("m3", "hi"), assistant("m4", "hello")], { directory: dir });
803
+ writeSession(db, "sess_project", [user("m5", "hi"), assistant("m6", "hello")], { directory: dir, project: "proj" });
804
+ db.query("insert into local_setting values ('project', 'proj', 'permission', 'mode', ?, 1, 1, 1)").run(JSON.stringify({ mode: "yolo" }));
805
+ db.close();
806
+ const c = control({ home });
807
+ const edit = sessionId(harnessId("zcode-fake"), "sess_edit");
808
+ // niwa's `ask` is ZCode's `guarded`; the session was stamped `edit`: refused, no process left running, not held.
809
+ await expect(c.resume(edit, { mode: "ask", prompt: promptFromText("go") })).rejects.toThrow(/restores the session in the mode "edit".*"guarded"/);
810
+ expect((await requestsOf("session/send")).length).toBe(0);
811
+ expect(await c.state(edit)).toBe("unknown");
812
+ // The same mode: resumed, and the turn runs. No mode is named to ZCode.
813
+ await c.resume(edit, { mode: "auto", prompt: promptFromText("go") });
814
+ expect((await requestsOf("session/send")).length).toBe(1);
815
+ expect((await requestsOf("session/resume")).at(-1)?.["mode"]).toBeUndefined();
816
+ // No assistant message: the project's permission mode, else ZCode's built-in `build`; either must be niwa's.
817
+ const unstamped = sessionId(harnessId("zcode-fake"), "sess_unstamped");
818
+ await expect(c.resume(unstamped, { mode: "full" })).rejects.toThrow(/restores the session in the mode "build".*"yolo"/);
819
+ const withProject = sessionId(harnessId("zcode-fake"), "sess_project");
820
+ await expect(c.resume(withProject, { mode: "auto" })).rejects.toThrow(/restores the session in the mode "yolo".*"edit"/);
821
+ await c.resume(withProject, { mode: "full" });
822
+ // A session the database does not know: the mode cannot be determined, and the resume fails.
823
+ await expect(c.resume(sessionId(harnessId("zcode-fake"), "sess_nowhere"), { mode: "auto" })).rejects.toThrow(/cannot be read/);
824
+ });
825
+
826
+ test("a resume the server refuses leaves no process behind", async () => {
827
+ await writeFile(join(dir, "resume-fail"), "");
828
+ const c = control();
829
+ await expect(c.resume(sessionId(harnessId("zcode-fake"), "sess_gone"))).rejects.toMatchObject({ code: "Unavailable" });
830
+ const pid = (await logOf("env.log"))[0]?.["pid"] as number;
831
+ await Bun.sleep(100);
832
+ expect(() => process.kill(pid, 0)).toThrow();
833
+ });
834
+
835
+ /** A sandbox that wraps nothing: the process it launches is the program itself. */
836
+ function plainNono(): Sandbox {
837
+ return {
838
+ name: "nono",
839
+ class: "process",
840
+ available: async () => true,
841
+ manifest: (spec) => ({ sandbox: "nono", cwd: spec.cwd, env: spec.env }),
842
+ async launch(spec, argv): Promise<LaunchedBox> {
843
+ const child = Bun.spawn([...argv], { cwd: spec.cwd, env: { ...spec.env }, stdin: "pipe", stdout: "pipe", stderr: "pipe" });
844
+ return { pid: child.pid, stdin: child.stdin, stdout: child.stdout, stderr: child.stderr, exited: child.exited, kill: () => child.kill() };
845
+ },
846
+ };
847
+ }
848
+
849
+ test("a session starts inside the box it is given, whose manifest is recorded before the process", async () => {
850
+ const records: BoxRecord[] = [];
851
+ const restore = useSandbox("nono", plainNono());
852
+ const forget = onBoxManifest((record) => void records.push(record));
853
+ try {
854
+ const c = control();
855
+ const started = await c.start({
856
+ prompt: hello,
857
+ cwd: dir,
858
+ env: { NIWA_ID: "k3f9" },
859
+ box: { sandbox: "nono", spec: { cwd: dir, write: [dir], env: {} } },
860
+ });
861
+ expect(String(started.session.native)).toBe("sess_fake-1");
862
+ expect(records[0]?.spec.write.map(String)).toEqual([dir]);
863
+ expect(Object.entries(records[0]?.spec.env ?? {})).toContainEqual(["NIWA_ID", "k3f9"]);
864
+ expect((await logOf("env.log"))[0]).toMatchObject({ id: "k3f9" });
865
+ } finally {
866
+ forget();
867
+ restore();
868
+ }
869
+ });
870
+
871
+ test("the child, the box and the reader all use the installation the control side is given", async () => {
872
+ const home = join(dir, "installation");
873
+ const records: BoxRecord[] = [];
874
+ const restore = useSandbox("nono", plainNono());
875
+ const forget = onBoxManifest((record) => void records.push(record));
876
+ try {
877
+ await control({ home }).start({ prompt: hello, cwd: dir, box: { sandbox: "nono", spec: { cwd: dir, write: [dir], env: {} } } });
878
+ // The box is the one given, the installation's profile in it; the child keeps its sessions where the reader looks.
879
+ expect(records[0]?.spec.write.map(String)).toEqual([dir]);
880
+ expect((await logOf("env.log"))[0]).toMatchObject({ storage: home, db: dbPathOf(home) });
881
+ } finally {
882
+ forget();
883
+ restore();
884
+ }
885
+ // Without one the child is left to its own default.
886
+ await rm(join(dir, "env.log"));
887
+ await control().start({ prompt: hello, cwd: dir });
888
+ expect((await logOf("env.log"))[0]?.["storage"]).toBeUndefined();
889
+ });
890
+
891
+ test("dispose stops the process of every session", async () => {
892
+ const c = control();
893
+ await c.start({ prompt: promptFromText("hang"), cwd: dir });
894
+ const pid = (await logOf("env.log"))[0]?.["pid"] as number;
895
+ expect(() => process.kill(pid, 0)).not.toThrow();
896
+ await c.dispose();
897
+ expect(() => process.kill(pid, 0)).toThrow();
898
+ await expect(c.start({ prompt: hello, cwd: dir })).rejects.toMatchObject({ code: "Unavailable" });
899
+ });
900
+
901
+ test("close stops the process of one session, as the contract's release", async () => {
902
+ const c = control();
903
+ const { session } = await c.start({ prompt: promptFromText("hang"), cwd: dir });
904
+ const pid = (await logOf("env.log"))[0]?.["pid"] as number;
905
+ expect(() => process.kill(pid, 0)).not.toThrow();
906
+ await c.close!(session);
907
+ expect(() => process.kill(pid, 0)).toThrow();
908
+ expect(await c.state(session)).toBe("unknown");
909
+ });
910
+
911
+ test("a start tells the caller the session before its first prompt goes out", async () => {
912
+ const named: string[] = [];
913
+ let prompted: number | undefined;
914
+ const { session } = await control().start({
915
+ prompt: hello,
916
+ cwd: dir,
917
+ named: async (id) => {
918
+ named.push(String(id.native));
919
+ prompted = (await requestsOf("session/send")).length;
920
+ },
921
+ });
922
+ expect(named).toEqual([String(session.native)]);
923
+ expect(prompted).toBe(0);
924
+ });
925
+
926
+ test("a start whose session could not be written down gives it no work and stops the process", async () => {
927
+ const c = control();
928
+ await expect(
929
+ c.start({
930
+ prompt: hello,
931
+ cwd: dir,
932
+ named: async () => {
933
+ throw new Error("the journal is full");
934
+ },
935
+ }),
936
+ ).rejects.toThrow("the journal is full");
937
+ expect(await requestsOf("session/send")).toEqual([]);
938
+ const pid = (await logOf("env.log"))[0]?.["pid"] as number;
939
+ expect(() => process.kill(pid, 0)).toThrow();
940
+ });
941
+
942
+ test("a start still being born when the control side is disposed leaves no session and no process", async () => {
943
+ // The manifest of the box is waited for before the process exists: the launch is held there.
944
+ let open: () => void = () => {};
945
+ const gate = new Promise<void>((resolve) => {
946
+ open = resolve;
947
+ });
948
+ const restore = useSandbox("nono", plainNono());
949
+ const forget = onBoxManifest(() => gate);
950
+ try {
951
+ const c = control();
952
+ const starting = c.start({ prompt: hello, cwd: dir, box: { sandbox: "nono", spec: { cwd: dir, write: [dir], env: {} } } }).catch((error: unknown) => error);
953
+ await Bun.sleep(50);
954
+ const disposing = c.dispose();
955
+ open();
956
+ await disposing;
957
+ expect(await starting).toMatchObject({ code: "Unavailable" });
958
+ const pid = (await logOf("env.log"))[0]?.["pid"] as number | undefined;
959
+ await Bun.sleep(100);
960
+ if (pid !== undefined) expect(() => process.kill(pid, 0)).toThrow();
961
+ expect(await requestsOf("session/create")).toEqual([]);
962
+ } finally {
963
+ open();
964
+ forget();
965
+ restore();
966
+ }
967
+ });
968
+
969
+ test("zcode passes the control conformance suite", async () => {
970
+ const id = harnessId("zcode-fake");
971
+ const instance: Harness = {
972
+ id,
973
+ kind: harnessKind("zcode"),
974
+ machine: machineId("machine-1"),
975
+ home: dir,
976
+ sides: {
977
+ control: { start: true, resume: true, send: true, interrupt: true, ask: true, structuredOutput: true, launch: ZCODE_LAUNCH },
978
+ },
979
+ };
980
+ const report = await controlConformance("zcode", { instance, control: control() })();
981
+ expect(report.results.filter((result) => !result.passed).map((result) => `${result.name}: ${result.detail ?? ""}`)).toEqual([]);
982
+ expect(report.results.length).toBeGreaterThan(15);
983
+ });