@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,437 @@
1
+ /**
2
+ * The ZCode wire, typed: every notification, session event and
3
+ * request of the generated snapshot has a fixture here, read by the parser and mapped by the dispatch,
4
+ * and a snapshot that grows a variant fails the guards below until the variant has both. The real
5
+ * frames of a ZCode 0.17.3 (`test/fixtures/zcode`) go through the same parser, so the snapshot (3.18.2's
6
+ * protocol) is checked against what a newer server really sends. No process runs.
7
+ */
8
+
9
+ import { expect, test } from "bun:test";
10
+ import { readFileSync } from "node:fs";
11
+ import { join } from "node:path";
12
+
13
+ import { notificationAction, requestAction, sessionEventAction } from "../src/dispatch.ts";
14
+ import type { EventAction, RequestAction } from "../src/dispatch.ts";
15
+ import {
16
+ ANSWER_SCHEMAS,
17
+ NOTIFICATION_SCHEMAS,
18
+ REQUEST_SCHEMAS,
19
+ SESSION_EVENT_TYPES,
20
+ SessionMessageSchema,
21
+ V4_NOTIFICATION_METHODS,
22
+ } from "../src/protocol/generated/zcode-protocol.ts";
23
+ import { readNotification, readRequest, unknownDetail } from "../src/protocol/index.ts";
24
+ import type { NotificationMethod, RequestMethod } from "../src/protocol/index.ts";
25
+ import { readPermission, readUserInput } from "../src/reverse.ts";
26
+
27
+ const FIXTURES = join(import.meta.dir, "fixtures/zcode");
28
+
29
+ const workspace = { workspacePath: "/w", workspaceKey: "/w" };
30
+ const part = { partId: "p1", sessionId: "sess_a", messageId: "m1", type: "text", text: "t" };
31
+ const options = [{ optionId: "allow_once", kind: "allow_once", name: "Allow once", response: { decision: "allow", reason: "Approved once" } }];
32
+ const bound = (input: unknown) => ({ callerSessionId: "sess_a", callId: "call-1", input });
33
+ const ref = { kind: "app", workspacePath: "/w", sessionId: "sess_a" };
34
+
35
+ /** The payload of each session event the snapshot has, as small as it can be. */
36
+ const EVENT_PAYLOADS: Record<(typeof SESSION_EVENT_TYPES)[number], unknown> = {
37
+ "session.created": { mode: "build", contextWindow: 1000 },
38
+ "session.resumed": { directory: "/w", interruptedToolCount: 0, messageCount: 1, partCount: 1 },
39
+ "session.updated": { providerId: "p", modelId: "m" },
40
+ "session.titleUpdated": { previousTitle: "", source: "generated", title: "T" },
41
+ "session.closed": { reason: "done" },
42
+ "turn.started": { turnNumber: 0, input: "hi" },
43
+ "turn.steerQueued": { pendingInputId: "p1", input: "x", inputPreview: "x", inputSize: 1, targetTurnId: "t1", queueLength: 1 },
44
+ "turn.steerDrained": { pendingInputIds: ["p1"], targetTurnId: "t1", injectedMessageIds: ["m1"] },
45
+ "turn.completed": { response: "ok", tokenCount: 1, toolCallCount: 0, duration: 1, resultType: "success" },
46
+ "turn.failed": { error: { type: "execution", message: "boom" }, turnPhase: "execution" },
47
+ "message.upserted": { content: "c" },
48
+ "message.removed": { messageId: "m1" },
49
+ "part.started": { part },
50
+ "part.delta": { messageId: "m1", partId: "p1", delta: "d" },
51
+ "part.upserted": { part },
52
+ "part.removed": { messageId: "m1", partId: "p1" },
53
+ "model.streaming": { kind: "text_delta", delta: "x" },
54
+ "tool.updated": { kind: "started", toolCallId: "c1", startedAt: 1 },
55
+ "permission.requested": { toolCallId: "c1", toolName: "Bash", riskLevel: "low", reason: "r", input: { command: "ls" }, options },
56
+ "permission.resolved": { requestId: "r1", toolCallId: "c1", decision: "deny" },
57
+ "userInput.requested": { requestId: "r1", prompt: "p" },
58
+ "userInput.resolved": { requestId: "r1" },
59
+ "checkpoint.created": {},
60
+ "rewind.triggered": {},
61
+ "streamRecovery.updated": {},
62
+ };
63
+
64
+ /** What each session event comes to. */
65
+ const EVENT_ACTIONS: Record<(typeof SESSION_EVENT_TYPES)[number], string> = {
66
+ "session.created": "activity",
67
+ "session.resumed": "activity",
68
+ "session.updated": "activity",
69
+ "session.titleUpdated": "activity",
70
+ "session.closed": "activity",
71
+ "turn.started": "activity",
72
+ "turn.steerQueued": "activity",
73
+ "turn.steerDrained": "activity",
74
+ "turn.completed": "end-turn completed",
75
+ "turn.failed": "end-turn failed",
76
+ "message.upserted": "activity",
77
+ "message.removed": "activity",
78
+ "part.started": "activity",
79
+ "part.delta": "activity",
80
+ "part.upserted": "activity",
81
+ "part.removed": "activity",
82
+ "model.streaming": "activity",
83
+ "tool.updated": "activity",
84
+ "permission.requested": "activity",
85
+ "permission.resolved": "stop-asking",
86
+ "userInput.requested": "activity",
87
+ "userInput.resolved": "stop-asking",
88
+ "checkpoint.created": "activity",
89
+ "rewind.triggered": "activity",
90
+ "streamRecovery.updated": "activity",
91
+ };
92
+
93
+ const envelope = (type: string, payload: unknown) => ({ eventId: "e1", sessionId: "sess_a", seq: 1, timestamp: 1, type, payload });
94
+
95
+ /** The params of each notification the snapshot has (a session event is in `EVENT_PAYLOADS`). */
96
+ const NOTIFICATION_PARAMS: Record<NotificationMethod, unknown> = {
97
+ "session/event": envelope("turn.started", EVENT_PAYLOADS["turn.started"]),
98
+ "state.updated": { type: "state.updated", scope: "session", revision: 1, patch: {} },
99
+ "session/lifecycle/changed": { sessionId: "sess_a", state: "ready", lastError: null },
100
+ "startup/pluginsDegraded": { reason: "timeout" },
101
+ "startup/storageState": { schemaVersion: 1, attemptId: "a", sequence: 1, databaseId: "d", databaseKind: "session", phase: "ready", elapsedMs: 1 },
102
+ "interaction/providerRuntimeHeadersCancelled": { requestId: "r", sessionId: "sess_a", workspace },
103
+ "process/mcpTelemetry": {
104
+ arch: "arm64",
105
+ kind: "process_start",
106
+ mcpId: "builtin:spreadsheets:spreadsheets",
107
+ mcpInstanceId: "i",
108
+ mcpIsolation: "workspace",
109
+ mcpSource: "builtin",
110
+ occurredAt: 1,
111
+ platform: "darwin",
112
+ },
113
+ "process/mcpResourceSamples": [],
114
+ "process/toolExecResource": { platform: "darwin", toolName: "bash", durationMs: 20000, exitKind: "completed", sampleCount: 1, cliRssKb: 1, systemFreeMemoryKb: 1 },
115
+ "plugins/operationProgress": { operationId: "op", state: "refreshing" },
116
+ "process/resourceSample": { platform: "darwin", arch: "arm64", logicalCpuCount: 8, intervalMs: 1000, cpuCores: 1, cpuPercent: 10, rssKb: 1 },
117
+ "process/networkRequests": { captureId: "c", records: [], dropped: 0 },
118
+ "computer-use/operation-event": { eventId: "e", sequenceNumber: 1, sessionId: "sess_a", timestamp: 1, kind: "session-closed" },
119
+ };
120
+
121
+ /** The params of each request the snapshot has. */
122
+ const REQUEST_PARAMS: Record<RequestMethod, unknown> = {
123
+ "session/requestRuntimePreferences": { sessionId: "sess_a", scope: "user-execution" },
124
+ "interaction/requestPermission": {
125
+ requestId: "r1",
126
+ sessionId: "sess_a",
127
+ toolCallId: "c1",
128
+ toolName: "Bash",
129
+ reason: "the tool wants to run",
130
+ riskLevel: "low",
131
+ input: { command: "ls" },
132
+ options,
133
+ },
134
+ "interaction/requestUserInput": { requestId: "r1", sessionId: "sess_a", prompt: "your name?" },
135
+ "interaction/requestProviderRuntimeHeaders": {
136
+ requestId: "r1",
137
+ sessionId: "sess_a",
138
+ workspace,
139
+ modelSelection: { providerId: "p", modelId: "m" },
140
+ providerId: "p",
141
+ reason: "model-request",
142
+ },
143
+ "interaction/requestOfficialMcpAuthHeaders": { requestId: "r1", workspace, pluginId: "plugin", mcpKey: "sites", targetOrigin: "https://zcode.z.ai" },
144
+ "interaction/requestCredentialCipher": { requestId: "6f1b1f3e-2f43-4b0e-8c1f-0d3e8a1f9a11", operation: "decrypt", value: "x" },
145
+ "interaction/browserList": { requestId: "r1", sessionId: "sess_a", workspaceKey: "/w", workspacePath: "/w", clientMode: "desktop-continuous", sessionContext: "live" },
146
+ "interaction/browserExecute": { requestId: "r1", sessionId: "sess_a", command: { method: "back" } },
147
+ "subagents/readRuntimeConfig": { sessionId: "sess_a" },
148
+ "bot/channel/reply": { taskId: "t", inputId: "i", toolCallId: "c", parts: [{ type: "text", text: "hi" }] },
149
+ "topic/resource/read": { requestId: "r1", taskId: "t", inputId: "i", authorizationId: "a", messageId: "m", resourceIndex: 0 },
150
+ "topic/resource/cancel": { requestId: "r1", taskId: "t" },
151
+ "appControl/listProjects": bound({}),
152
+ "appControl/listSessions": bound({}),
153
+ "appControl/readSession": bound({ session: ref, view: "summary" }),
154
+ "appControl/createSession": bound({ project: { kind: "app", projectId: "pr" }, prompt: "go", requestId: "r1" }),
155
+ "appControl/forkSession": bound({ session: ref, atMessage: "m1", requestId: "r1" }),
156
+ "appControl/sendToSession": bound({ session: ref, prompt: "go", requestId: "r1" }),
157
+ "appControl/waitSessions": bound({ operations: [{ session: ref, commandId: "c1" }], mode: "any" }),
158
+ "appControl/interruptSession": bound({ session: ref, expectedExecutionId: "x1", requestId: "r1" }),
159
+ "appControl/renameSession": bound({ session: ref, title: "T", requestId: "r1" }),
160
+ "appControl/openSession": bound({ session: ref }),
161
+ "appControl/setSessionArchived": bound({ session: ref, archived: true, requestId: "r1" }),
162
+ "appControl/setSessionPinned": bound({ session: ref, pinned: true, requestId: "r1" }),
163
+ "appControl/cancel": { callerSessionId: "sess_a", callId: "call-1" },
164
+ };
165
+
166
+ /** What each request comes to: `answer` and `error` are what goes back, the others are for whoever answers for the session. */
167
+ const REQUEST_ACTIONS: Record<RequestMethod, RequestAction["do"]> = {
168
+ "session/requestRuntimePreferences": "answer",
169
+ "interaction/requestPermission": "permission",
170
+ "interaction/requestUserInput": "user-input",
171
+ "interaction/requestProviderRuntimeHeaders": "answer",
172
+ "interaction/requestOfficialMcpAuthHeaders": "answer",
173
+ "interaction/requestCredentialCipher": "answer",
174
+ "interaction/browserList": "answer",
175
+ "interaction/browserExecute": "error",
176
+ "subagents/readRuntimeConfig": "error",
177
+ "bot/channel/reply": "error",
178
+ "topic/resource/read": "error",
179
+ "topic/resource/cancel": "answer",
180
+ "appControl/listProjects": "error",
181
+ "appControl/listSessions": "error",
182
+ "appControl/readSession": "error",
183
+ "appControl/createSession": "error",
184
+ "appControl/forkSession": "error",
185
+ "appControl/sendToSession": "error",
186
+ "appControl/waitSessions": "error",
187
+ "appControl/interruptSession": "error",
188
+ "appControl/renameSession": "error",
189
+ "appControl/openSession": "error",
190
+ "appControl/setSessionArchived": "error",
191
+ "appControl/setSessionPinned": "error",
192
+ "appControl/cancel": "error",
193
+ };
194
+
195
+ const describe = (action: EventAction): string => (action.do === "end-turn" ? `end-turn ${action.end.outcome}` : action.do);
196
+
197
+ const sorted = (values: Iterable<string>): string[] => [...values].sort();
198
+
199
+ const NOTIFICATION_METHODS = Object.keys(NOTIFICATION_SCHEMAS) as NotificationMethod[];
200
+ const REQUEST_METHODS = Object.keys(REQUEST_SCHEMAS) as RequestMethod[];
201
+
202
+ // -- the guards: the fixtures are the snapshot's variants, no more and no fewer ----------------------
203
+
204
+ test("every session event, notification and request of the snapshot has a fixture and a mapping, and only those", () => {
205
+ expect(sorted(Object.keys(EVENT_PAYLOADS))).toEqual(sorted(SESSION_EVENT_TYPES));
206
+ expect(sorted(Object.keys(EVENT_ACTIONS))).toEqual(sorted(SESSION_EVENT_TYPES));
207
+ expect(sorted(Object.keys(NOTIFICATION_PARAMS))).toEqual(sorted(Object.keys(NOTIFICATION_SCHEMAS)));
208
+ expect(sorted(Object.keys(REQUEST_PARAMS))).toEqual(sorted(Object.keys(REQUEST_SCHEMAS)));
209
+ expect(sorted(Object.keys(REQUEST_ACTIONS))).toEqual(sorted(Object.keys(REQUEST_SCHEMAS)));
210
+ expect(sorted(Object.keys(ANSWER_SCHEMAS))).toEqual(sorted(Object.keys(REQUEST_SCHEMAS)));
211
+ });
212
+
213
+ // -- session events -----------------------------------------------------------------------------------
214
+
215
+ for (const type of SESSION_EVENT_TYPES) {
216
+ test(`the session event ${type} is read and mapped: ${EVENT_ACTIONS[type]}`, () => {
217
+ const read = readNotification("session/event", envelope(type, EVENT_PAYLOADS[type]));
218
+ expect(read.kind).toBe("known");
219
+ if (read.kind !== "known" || read.notification.method !== "session/event") throw new Error("not a session event");
220
+ expect(read.notification.params.type).toBe(type);
221
+ expect(describe(sessionEventAction(read.notification.params))).toBe(EVENT_ACTIONS[type]);
222
+ expect(describe(notificationAction(read.notification))).toBe(EVENT_ACTIONS[type]);
223
+ });
224
+ }
225
+
226
+ test("a session event may come with no payload at all, and a turn that ends so still ends", () => {
227
+ const read = readNotification("session/event", { eventId: "e1", sessionId: "sess_a", seq: 1, timestamp: 1, type: "turn.completed" });
228
+ expect(read.kind).toBe("known");
229
+ if (read.kind !== "known" || read.notification.method !== "session/event") throw new Error("not a session event");
230
+ expect(sessionEventAction(read.notification.params)).toEqual({ do: "end-turn", end: { outcome: "completed", response: "" } });
231
+ });
232
+
233
+ test("the result of a turn decides how it ended: only success completes, a stop is cancelled, every error result fails it", () => {
234
+ const ended = (resultType: string) => {
235
+ const payload = { ...(EVENT_PAYLOADS["turn.completed"] as Record<string, unknown>), resultType };
236
+ const read = readNotification("session/event", envelope("turn.completed", payload));
237
+ if (read.kind !== "known" || read.notification.method !== "session/event") throw new Error(`${resultType} is not read`);
238
+ return sessionEventAction(read.notification.params);
239
+ };
240
+ expect(ended("success")).toEqual({ do: "end-turn", end: { outcome: "completed", response: "ok" } });
241
+ expect(ended("cancelled")).toEqual({ do: "end-turn", end: { outcome: "cancelled", response: "ok" } });
242
+ for (const failure of ["error_max_turns", "error_max_budget", "error_during_execution", "error_max_tool_calls"]) {
243
+ expect(ended(failure)).toEqual({ do: "end-turn", end: { outcome: "failed", response: "", error: `the turn ended with ${failure}` } });
244
+ }
245
+ });
246
+
247
+ test("a failed turn says what the server said; a request that was resolved is named by the ids the server gave", () => {
248
+ const failed = readNotification("session/event", envelope("turn.failed", EVENT_PAYLOADS["turn.failed"]));
249
+ if (failed.kind !== "known" || failed.notification.method !== "session/event") throw new Error("not read");
250
+ expect(sessionEventAction(failed.notification.params)).toEqual({ do: "end-turn", end: { outcome: "failed", response: "", error: "boom" } });
251
+ const resolved = readNotification("session/event", envelope("permission.resolved", { requestId: "r1", toolCallId: "c1" }));
252
+ if (resolved.kind !== "known" || resolved.notification.method !== "session/event") throw new Error("not read");
253
+ expect(sessionEventAction(resolved.notification.params)).toEqual({ do: "stop-asking", requestId: "r1", toolCallId: "c1", detail: "permission.resolved" });
254
+ const input = readNotification("session/event", envelope("userInput.resolved", { requestId: "r2" }));
255
+ if (input.kind !== "known" || input.notification.method !== "session/event") throw new Error("not read");
256
+ expect(sessionEventAction(input.notification.params)).toEqual({ do: "stop-asking", requestId: "r2", toolCallId: undefined, detail: "userInput.resolved" });
257
+ });
258
+
259
+ test("a session event framed as { event } by some bundles is read as the event it holds", () => {
260
+ const read = readNotification("session/event", { event: envelope("turn.completed", EVENT_PAYLOADS["turn.completed"]) });
261
+ expect(read.kind).toBe("known");
262
+ });
263
+
264
+ // -- notifications ------------------------------------------------------------------------------------
265
+
266
+ for (const method of NOTIFICATION_METHODS) {
267
+ test(`the notification ${method} is read and, but for a session event, nothing for a driver`, () => {
268
+ const read = readNotification(method, NOTIFICATION_PARAMS[method]);
269
+ expect(read.kind).toBe("known");
270
+ if (read.kind !== "known") return;
271
+ expect(read.notification.method).toBe(method);
272
+ expect(describe(notificationAction(read.notification))).toBe(method === "session/event" ? "activity" : "ignore");
273
+ });
274
+ }
275
+
276
+ test("the messages of ZCode's v4 side channel are known by name and mean nothing to a driver", () => {
277
+ expect(V4_NOTIFICATION_METHODS.length).toBeGreaterThan(0);
278
+ for (const method of V4_NOTIFICATION_METHODS) expect(readNotification(method, { anything: 1 })).toEqual({ kind: "side-channel", method });
279
+ });
280
+
281
+ // -- requests -----------------------------------------------------------------------------------------
282
+
283
+ for (const method of REQUEST_METHODS) {
284
+ test(`the request ${method} is read and comes to ${REQUEST_ACTIONS[method]}`, () => {
285
+ const read = readRequest(7, method, REQUEST_PARAMS[method]);
286
+ expect(read.unknown).toBeUndefined();
287
+ expect(read.request?.method).toBe(method);
288
+ const action = requestAction(read.request, { asksQuestions: false });
289
+ expect(action.do).toBe(REQUEST_ACTIONS[method]);
290
+ // An answer goes back in the words of its method: the server refuses one that does not fit.
291
+ if (action.do === "answer") expect(ANSWER_SCHEMAS[method].safeParse(action.result).success).toBe(true);
292
+ if (action.do === "error") expect(action).toEqual({ do: "error", code: -32601, message: `niwa does not serve ${method}` });
293
+ });
294
+ }
295
+
296
+ test("a session whose questions go to nobody has the server answer them itself; one that asks keeps them", () => {
297
+ const read = readRequest(1, "session/requestRuntimePreferences", REQUEST_PARAMS["session/requestRuntimePreferences"]);
298
+ expect(requestAction(read.request, { asksQuestions: false })).toMatchObject({ result: { askUserQuestionAutoResolutionEnabled: true } });
299
+ expect(requestAction(read.request, { asksQuestions: true })).toMatchObject({ result: { askUserQuestionAutoResolutionEnabled: false } });
300
+ });
301
+
302
+ test("a permission or a question that does not fit the snapshot is answered at once: no leave, declined", () => {
303
+ const permission = readRequest(1, "interaction/requestPermission", { requestId: "r1" });
304
+ expect(permission.unknown?.why).toBe("does not fit the snapshot");
305
+ expect(requestAction(permission.request, { asksQuestions: true })).toEqual({
306
+ do: "answer",
307
+ result: { decision: "deny", reason: "niwa could not read this permission request" },
308
+ });
309
+ const question = readRequest(1, "interaction/requestUserInput", { requestId: "r1" });
310
+ expect(requestAction(question.request, { asksQuestions: true })).toEqual({
311
+ do: "answer",
312
+ result: { action: "decline", reason: "niwa could not read this question" },
313
+ });
314
+ });
315
+
316
+ test("the credential cipher is refused in the words of its own answer, with the id of the request in it", () => {
317
+ const read = readRequest(1, "interaction/requestCredentialCipher", REQUEST_PARAMS["interaction/requestCredentialCipher"]);
318
+ expect(requestAction(read.request, { asksQuestions: true })).toMatchObject({
319
+ do: "answer",
320
+ result: { requestId: "6f1b1f3e-2f43-4b0e-8c1f-0d3e8a1f9a11", result: { ok: false } },
321
+ });
322
+ });
323
+
324
+ // -- what the snapshot does not know ------------------------------------------------------------------
325
+
326
+ test("a method the snapshot does not know is an unknown variant that keeps the protocol, the method and the raw message", () => {
327
+ const raw = { method: "session/newThing", params: { a: 1 } };
328
+ const read = readNotification(raw.method, raw.params);
329
+ expect(read).toEqual({ kind: "unknown", unknown: { protocol: "zcode", discriminator: "method", value: "session/newThing", why: "not in the snapshot", raw } });
330
+ if (read.kind !== "unknown") return;
331
+ expect(unknownDetail(read.unknown)).toBe(`unknown zcode method "session/newThing" (not in the snapshot): {"method":"session/newThing","params":{"a":1}}`);
332
+ });
333
+
334
+ test("a session event type the snapshot does not know is an unknown variant by its type", () => {
335
+ const params = envelope("turn.hypothetical", { x: 1 });
336
+ expect(readNotification("session/event", params)).toEqual({
337
+ kind: "unknown",
338
+ unknown: { protocol: "zcode", discriminator: "event type", value: "turn.hypothetical", why: "not in the snapshot", raw: { method: "session/event", params } },
339
+ });
340
+ });
341
+
342
+ test("a type the snapshot knows whose payload does not fit it is an unknown variant too, and does not end a turn", () => {
343
+ const params = envelope("turn.completed", { response: 5 });
344
+ const read = readNotification("session/event", params);
345
+ expect(read).toMatchObject({ kind: "unknown", unknown: { discriminator: "event type", value: "turn.completed", why: "does not fit the snapshot" } });
346
+ });
347
+
348
+ test("a notification of a known method with params that do not fit is an unknown variant by its method", () => {
349
+ expect(readNotification("startup/pluginsDegraded", { reason: "never" })).toMatchObject({
350
+ kind: "unknown",
351
+ unknown: { discriminator: "method", value: "startup/pluginsDegraded", why: "does not fit the snapshot" },
352
+ });
353
+ });
354
+
355
+ test("a request the snapshot does not know is read with no request, so that the control side answers it empty", () => {
356
+ const read = readRequest("server-9", "session/readReplyLanguage", { sessionId: "sess_a" });
357
+ expect(read.request).toBeUndefined();
358
+ expect(read.unknown).toEqual({
359
+ protocol: "zcode",
360
+ discriminator: "method",
361
+ value: "session/readReplyLanguage",
362
+ why: "not in the snapshot",
363
+ raw: { id: "server-9", method: "session/readReplyLanguage", params: { sessionId: "sess_a" } },
364
+ });
365
+ expect(requestAction(read.request, { asksQuestions: true })).toEqual({ do: "answer", result: {} });
366
+ });
367
+
368
+ test("an unknown variant's raw message is cut in the log, and the cut says how much was left out", () => {
369
+ const detail = unknownDetail({ protocol: "zcode", discriminator: "method", value: "x", why: "not in the snapshot", raw: { text: "a".repeat(5000) } });
370
+ expect(detail.length).toBeLessThan(4200);
371
+ expect(detail).toMatch(/\.\.\. \(\d+ more characters\)$/);
372
+ });
373
+
374
+ // -- what a real ZCode sends --------------------------------------------------------------------------
375
+
376
+ /** The frames a ZCode 0.17.3 sent (`zcode app-server --stdio`), one of each method and event type. */
377
+ const captured = readFileSync(join(FIXTURES, "captured-0.17.3.ndjson"), "utf8")
378
+ .trim()
379
+ .split("\n")
380
+ .map((line) => JSON.parse(line) as { id?: string; method: string; params: unknown });
381
+
382
+ test("the real frames of a ZCode newer than the snapshot are all read, but for the one request the snapshot predates", () => {
383
+ const unknown: string[] = [];
384
+ for (const frame of captured) {
385
+ const read = frame.id === undefined ? readNotification(frame.method, frame.params) : undefined;
386
+ if (read !== undefined) {
387
+ if (read.kind === "unknown") unknown.push(frame.method);
388
+ continue;
389
+ }
390
+ const request = readRequest(frame.id ?? "", frame.method, frame.params);
391
+ if (request.unknown !== undefined) unknown.push(frame.method);
392
+ }
393
+ expect(unknown).toEqual(["session/readReplyLanguage"]);
394
+ // The fixtures hold at least a request, an event of each family the driver acts on and a v4 message.
395
+ const methods = new Set(captured.map((frame) => frame.method));
396
+ for (const method of ["session/requestRuntimePreferences", "interaction/requestUserInput", "session/event", "v4/telemetry/event"]) {
397
+ expect(methods.has(method)).toBe(true);
398
+ }
399
+ });
400
+
401
+ test("the real question of an AskUserQuestion is asked as a choice, and a real permission event is read whole", () => {
402
+ const frame = captured.find((candidate) => candidate.method === "interaction/requestUserInput");
403
+ if (frame === undefined) throw new Error("no captured user input request");
404
+ const read = readRequest("server-5", frame.method, frame.params);
405
+ const action = requestAction(read.request, { asksQuestions: true });
406
+ if (action.do !== "user-input") throw new Error(`a question came to ${action.do}`);
407
+ const asked = readUserInput(action.params);
408
+ expect(asked.ask.questions).toHaveLength(1);
409
+ expect(asked.ask.questions[0]?.question).toMatchObject({ kind: "choice", title: "Which color do you prefer?" });
410
+ const event = captured.find((candidate) => candidate.method === "session/event" && (candidate.params as { type?: string }).type === "permission.requested");
411
+ expect(readNotification("session/event", event?.params).kind).toBe("known");
412
+ });
413
+
414
+ test("a permission request is a question with the once-only options, and its answer carries only the decision and its reason", () => {
415
+ const read = readRequest("server-2", "interaction/requestPermission", {
416
+ ...(REQUEST_PARAMS["interaction/requestPermission"] as Record<string, unknown>),
417
+ options: [
418
+ { optionId: "allow_once", kind: "allow_once", name: "Allow once", response: { decision: "allow", reason: "Approved once", modifiedInput: { x: 1 } } },
419
+ { optionId: "deny", kind: "deny", name: "Deny", response: { decision: "deny", reason: "no" } },
420
+ ],
421
+ });
422
+ const action = requestAction(read.request, { asksQuestions: true });
423
+ if (action.do !== "permission") throw new Error(`a permission came to ${action.do}`);
424
+ const asked = readPermission(action.params);
425
+ const allow = asked.ask.question.kind === "permission" ? asked.ask.question.options[0] : undefined;
426
+ expect(allow?.id).toBeDefined();
427
+ expect(asked.ask.answer({ ids: allow === undefined ? [] : [allow.id] })).toEqual({ decision: "allow", reason: "Approved once" });
428
+ });
429
+
430
+ test("the messages of a real session/messages result fit the snapshot, and the assistant's text is in the parts of its message", () => {
431
+ const result = JSON.parse(readFileSync(join(FIXTURES, "session-messages-0.17.3.json"), "utf8")) as { messages: unknown[] };
432
+ const messages = result.messages.map((item) => SessionMessageSchema.parse(item));
433
+ expect(messages.map((message) => message.info.role)).toEqual(["user", "assistant", "assistant"]);
434
+ const texts = messages.flatMap((message) => message.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])));
435
+ expect(texts).toContain("Done — the command printed `capture-ok`.");
436
+ expect(messages[1]?.parts.map((part) => part.type)).toEqual(["step-start", "text", "tool", "step-finish"]);
437
+ });