@niwa-labs/sessions 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.
package/src/support.ts ADDED
@@ -0,0 +1,93 @@
1
+ /**
2
+ * "Can harness X do capability Y": the question as an action.
3
+ *
4
+ * A harness declares what each of its sides can do (`capabilities.ts`). That declaration is a
5
+ * fact about the installation, known before any call, and a client (a script, an agent, a person at
6
+ * the CLI) needs to ask it without holding the registry. `harness.supports` answers it from the
7
+ * registry the plugin was given.
8
+ *
9
+ * The answer is the declaration, nothing more: `true` means the side declares the ability,
10
+ * `false` means it does not, or the side does not exist. Whether the installation can serve it
11
+ * right now is a different fact, and it is `Unavailable` at the call, not here. An id that is
12
+ * not registered is not "no": it is an error that lists the ids there are.
13
+ */
14
+
15
+ import { z } from "zod";
16
+
17
+ import { action, actionRef } from "@niwa-labs/core";
18
+ import { plugin } from "@niwa-labs/plugin";
19
+ import type { Plugin } from "@niwa-labs/plugin";
20
+ import {
21
+ ControlCapabilitiesSchema,
22
+ InsertCapabilitiesSchema,
23
+ ReadingCapabilitiesSchema,
24
+ supports,
25
+ } from "@niwa-labs/harness";
26
+ import type { Harness, HarnessInstanceRegistry } from "@niwa-labs/harness";
27
+
28
+ /** The question, one variant per side: the ability must be one the side has. */
29
+ const SupportsInput = z.discriminatedUnion("side", [
30
+ z.object({
31
+ harness: z.string().min(1),
32
+ side: z.literal("reading"),
33
+ ability: z.enum(ReadingCapabilitiesSchema.keyof().options),
34
+ }),
35
+ z.object({
36
+ harness: z.string().min(1),
37
+ side: z.literal("control"),
38
+ ability: z.enum(ControlCapabilitiesSchema.omit({ launch: true, tools: true }).keyof().options),
39
+ }),
40
+ z.object({
41
+ harness: z.string().min(1),
42
+ side: z.literal("insert"),
43
+ ability: z.enum(InsertCapabilitiesSchema.keyof().options),
44
+ }),
45
+ ]);
46
+
47
+ /** The answer: the question again, and whether the side declares the ability. */
48
+ const SupportsOutput = z.object({
49
+ harness: z.string().min(1),
50
+ side: z.enum(["reading", "control", "insert"]),
51
+ ability: z.string().min(1),
52
+ supported: z.boolean(),
53
+ });
54
+
55
+ /** Can this harness do this? The typed reference a caller imports to ask. */
56
+ export const harnessSupports = actionRef("harness.supports", {
57
+ description:
58
+ "Whether a harness declares an ability on one of its sides (reading, control, insert). It answers what the instance declares; whether the installation can serve it right now is known at the call.",
59
+ input: SupportsInput,
60
+ output: SupportsOutput,
61
+ });
62
+
63
+ /** Whether the instance declares what the question asks; the side narrows the ability. */
64
+ function declares(instance: Harness, question: z.output<typeof SupportsInput>): boolean {
65
+ switch (question.side) {
66
+ case "reading":
67
+ return supports(instance, "reading", question.ability);
68
+ case "control":
69
+ return supports(instance, "control", question.ability);
70
+ case "insert":
71
+ return supports(instance, "insert", question.ability);
72
+ }
73
+ }
74
+
75
+ /** The plugin that serves `harness.supports` from a registry of instances. */
76
+ export function harnessSupport(registry: HarnessInstanceRegistry): Plugin {
77
+ return plugin("harness-support", (api) => {
78
+ api.action(
79
+ action(harnessSupports, {
80
+ // A read of a declaration: it may be made again.
81
+ recovery: "repeat",
82
+ effect: "read",
83
+ world: "niwa",
84
+ run: (input) => ({
85
+ harness: input.harness,
86
+ side: input.side,
87
+ ability: input.ability,
88
+ supported: declares(registry.resolve(input.harness), input),
89
+ }),
90
+ }),
91
+ );
92
+ });
93
+ }
package/src/visible.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Visible actions: which niwa actions a session sees and which harness tools are switched off.
3
+ *
4
+ * They are set at start and do not change under the session. Nothing is implied: a session that
5
+ * is given nothing sees no niwa action at all.
6
+ */
7
+
8
+ import { z } from "zod";
9
+
10
+ import { RuleSpecSchema, rule } from "@niwa-labs/core";
11
+ import { NO_VISIBLE_ACTIONS } from "@niwa-labs/harness";
12
+ import type { VisibleActions } from "@niwa-labs/harness";
13
+
14
+ /** What a caller gives when it starts a session. */
15
+ export const VisibleActionsInputSchema = z.object({
16
+ /** The niwa actions the session sees. */
17
+ actions: z.array(RuleSpecSchema).optional(),
18
+ /** The harness tools that are switched off for the session. */
19
+ disabledTools: z.array(z.string().min(1)).optional(),
20
+ });
21
+
22
+ export type VisibleActionsInput = z.output<typeof VisibleActionsInputSchema>;
23
+
24
+ /** The visible actions of a session, from what the caller gave. */
25
+ export function visibleActionsOf(input?: VisibleActionsInput): VisibleActions {
26
+ if (input === undefined) return NO_VISIBLE_ACTIONS;
27
+ return { actions: [...new Set((input.actions ?? []).map((spec) => rule(spec).name))], disabledTools: input.disabledTools ?? [] };
28
+ }
@@ -0,0 +1,197 @@
1
+ // Access asks are owner-only requests. The owner answers them through request.answer.
2
+
3
+ import { afterEach, expect, test } from "bun:test";
4
+
5
+ import { z } from "zod";
6
+
7
+ import { action, actionName, grant, principalOf } from "@niwa-labs/core";
8
+ import type { RuleSpec, Token } from "@niwa-labs/core";
9
+ import { plugin } from "@niwa-labs/plugin";
10
+ import { REQUEST_ANSWER, REQUEST_GET, REQUEST_OPEN, REQUEST_RESOLVE, requestOpen } from "@niwa-labs/requests/records";
11
+ import {
12
+ connect,
13
+ connectAsOwner,
14
+ createNiwa,
15
+ eventually,
16
+ HostError,
17
+ pick,
18
+ requests,
19
+ tempHome,
20
+ token,
21
+ } from "@niwa-labs/testing";
22
+ import type { Host } from "@niwa-labs/testing";
23
+
24
+ import { SUBMIT_ANSWER_ACTION, submitAnswerAction } from "../src/index.ts";
25
+
26
+ const ran: string[] = [];
27
+
28
+ const probe = plugin("self-answer-probe", (api) => {
29
+ api.action(
30
+ action("probe.run", {
31
+ description: "Records the call.",
32
+ input: z.object({ n: z.string() }),
33
+ output: z.object({ ran: z.string() }),
34
+ recovery: "repeat",
35
+ effect: "write",
36
+ run: async (input) => {
37
+ ran.push(input.n);
38
+ return { ran: input.n };
39
+ },
40
+ }),
41
+ );
42
+ api.action(submitAnswerAction(() => api.journal?.()));
43
+ });
44
+
45
+ const cleanups: Array<() => Promise<void>> = [];
46
+ afterEach(async () => {
47
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
48
+ ran.length = 0;
49
+ });
50
+
51
+ /** A host with the default binding, one session that asks under a rule, and the owner. */
52
+ async function served(rules: RuleSpec[]) {
53
+ const home = await tempHome();
54
+ cleanups.push(() => home.cleanup());
55
+ const host: Host = createNiwa({ home: home.path });
56
+ cleanups.push(() => host.close());
57
+ host.use(probe, requests());
58
+ await host.serve();
59
+ const secret: Token = host.issueToken(principalOf("session", "s1"), { grant: grant(rules) });
60
+ const owner = await connectAsOwner(home.path);
61
+ cleanups.push(() => owner.close());
62
+ const session = await connect({ home: home.path, id: "s1", token: secret });
63
+ cleanups.push(() => session.close());
64
+ const watcher = await connect({ home: home.path, id: "s1-second", token: secret });
65
+ cleanups.push(() => watcher.close());
66
+
67
+ const open = async () => requestOpen.output.parse(await owner.call(REQUEST_OPEN, {})).requests;
68
+ const waitForAsk = async (otherId?: string) => {
69
+ const next = async () => (await open()).find((entry) => "id" in entry && entry.id !== otherId);
70
+ await eventually(async () => (await next()) !== undefined);
71
+ const asked = await next();
72
+ if (asked === undefined || !("id" in asked)) throw new Error("the access request is no longer open");
73
+ return asked;
74
+ };
75
+ const run = (n: string) => {
76
+ const pending = session.call(actionName("probe.run"), { n });
77
+ // A failed assertion can close the client before this call is awaited.
78
+ void pending.catch(() => {});
79
+ return pending;
80
+ };
81
+ return { host, home: home.path, owner, watcher, open, waitForAsk, run };
82
+ }
83
+
84
+ async function refusal(promise: Promise<unknown>): Promise<string> {
85
+ const error = await promise.then(
86
+ () => undefined,
87
+ (thrown: unknown) => thrown,
88
+ );
89
+ expect(error).toBeInstanceOf(HostError);
90
+ return (error as HostError).message;
91
+ }
92
+
93
+ const ASKING: RuleSpec[] = [
94
+ { do: "probe.run", ask: true },
95
+ SUBMIT_ANSWER_ACTION,
96
+ "request.resolve",
97
+ "request.answer",
98
+ ];
99
+
100
+ test("a session cannot answer the access ask about its own call, by submit-answer, resolve or answer", async () => {
101
+ const s = await served(ASKING);
102
+ const pending = s.run("mine");
103
+ const asked = await s.waitForAsk();
104
+ const { id } = asked;
105
+ expect(id).toMatch(/^req-[0-9a-f]{6,8}$/);
106
+ expect(asked).toMatchObject({
107
+ answerPolicy: "owner-only",
108
+ to: { kind: "owner" },
109
+ question: "access.ask",
110
+ input: { kind: "permission", subject: { who: "session:s1", action: "probe.run", input: { n: "mine" } } },
111
+ });
112
+
113
+ const answer = pick("once");
114
+ expect(await s.watcher.call(actionName(SUBMIT_ANSWER_ACTION), { question: id, value: "once" })).toEqual({ accepted: false });
115
+ expect(await s.watcher.call(REQUEST_RESOLVE, { id, answer })).toEqual({ answered: false });
116
+ expect(await refusal(s.watcher.call(REQUEST_ANSWER, { id, answer }))).toContain("Only the owner");
117
+
118
+ expect(ran).toEqual([]);
119
+ expect(await s.open()).toEqual([asked]);
120
+
121
+ expect(await s.owner.call(REQUEST_ANSWER, { id, answer })).toEqual({ id, accepted: true });
122
+ expect(await pending).toEqual({ ran: "mine" });
123
+ expect(await s.owner.call(REQUEST_GET, { id })).toMatchObject({ id, status: "answered", by: { kind: "owner" }, answer });
124
+ expect(await s.open()).toEqual([]);
125
+ expect(ran).toEqual(["mine"]);
126
+ });
127
+
128
+ test("the owner can allow only the call named by the request answer", async () => {
129
+ const s = await served(ASKING);
130
+ const first = s.run("first");
131
+ const asked = await s.waitForAsk();
132
+ const second = s.run("second");
133
+ const { id } = await s.waitForAsk(asked.id);
134
+
135
+ const answer = pick("once");
136
+ expect(await s.owner.call(REQUEST_RESOLVE, { id, answer })).toEqual({ answered: false });
137
+ expect(await s.owner.call(REQUEST_GET, { id })).toMatchObject({ status: "open" });
138
+ expect(ran).toEqual([]);
139
+
140
+ expect(await s.owner.call(REQUEST_ANSWER, { id, answer })).toEqual({ id, accepted: true });
141
+ expect(await second).toEqual({ ran: "second" });
142
+ expect(await s.open()).toEqual([asked]);
143
+ expect(ran).toEqual(["second"]);
144
+
145
+ expect(await s.owner.call(REQUEST_ANSWER, { id: asked.id, answer })).toEqual({ id: asked.id, accepted: true });
146
+ expect(await first).toEqual({ ran: "first" });
147
+ expect(await s.open()).toEqual([]);
148
+ expect(ran).toEqual(["second", "first"]);
149
+ });
150
+
151
+ test("the host cannot decide an access ask and the owner's refusal ends the call", async () => {
152
+ const s = await served(ASKING);
153
+ const pending = s.run("refused");
154
+ const asked = await s.waitForAsk();
155
+ const { id } = asked;
156
+ expect(await s.host.call(REQUEST_RESOLVE, { id, answer: pick("once") })).toEqual({ answered: false });
157
+ await expect(s.host.call(REQUEST_ANSWER, { id, answer: pick("once") })).rejects.toThrow("Only the owner");
158
+ expect(await s.open()).toEqual([asked]);
159
+ expect(ran).toEqual([]);
160
+
161
+ const answer = pick("no");
162
+ expect(await s.owner.call(REQUEST_ANSWER, { id, answer })).toEqual({ id, accepted: true });
163
+ expect(await refusal(pending)).toContain("refused by the owner");
164
+ expect(await s.owner.call(REQUEST_GET, { id })).toMatchObject({ id, status: "answered", by: { kind: "owner" }, answer });
165
+ expect(await s.open()).toEqual([]);
166
+ expect(ran).toEqual([]);
167
+ });
168
+
169
+ test("a connection with no token stands on the default profile, and the owner's token is the owner", async () => {
170
+ const s = await served(ASKING);
171
+ const plain = await connect({ home: s.home, id: "owner:web" });
172
+ const unknown = await connect({ home: s.home, token: token("zzzz") });
173
+ cleanups.push(async () => {
174
+ await plain.close();
175
+ await unknown.close();
176
+ });
177
+ for (const client of [plain, unknown]) {
178
+ expect(await refusal(client.call(actionName("probe.run"), { n: "x" }))).toContain("not in the grant");
179
+ expect(await refusal(client.call(REQUEST_OPEN, {}))).toContain("not in the grant");
180
+ expect(await refusal(client.call(actionName("access.switch"), { all: "off" }))).toContain("not in the grant");
181
+ expect(await refusal(client.call(actionName("access.mine"), {}))).toContain("not in the grant");
182
+ }
183
+ expect(ran).toEqual([]);
184
+
185
+ // The owner, with the owner's token, is not limited: the same calls go through.
186
+ expect(await s.owner.call(actionName("probe.run"), { n: "owner" })).toEqual({ ran: "owner" });
187
+ expect(await s.open()).toEqual([]);
188
+ });
189
+
190
+ test("the default profile is what a connection with no token may do, and the owner may change it", async () => {
191
+ const s = await served([]);
192
+ const plain = await connect({ home: s.home, id: "plain" });
193
+ cleanups.push(() => plain.close());
194
+ await s.owner.call(actionName("access.profile.set"), { name: "default", rules: ["probe.run"] });
195
+ expect(await plain.call(actionName("probe.run"), { n: "allowed-now" })).toEqual({ ran: "allowed-now" });
196
+ expect(await refusal(plain.call(REQUEST_OPEN, {}))).toContain("not in the grant");
197
+ });
@@ -0,0 +1,132 @@
1
+ // A boxed session reaches niwa's socket on a real machine.
2
+ //
3
+ // A session is started through `session.start` in the host's default box: the sessions module
4
+ // puts the host's socket into the box, and the session's shell, inside the real srt or nono, speaks
5
+ // to the running host with its `NIWA_ID` and calls `access.mine`. gitlab.com, which the box does
6
+ // not name, stays unreachable. A box made without the socket does not reach the host: the socket
7
+ // is there because the module put it there.
8
+ //
9
+ // Skipped unless NIWA_LIVE=1 and the sandbox works on this machine.
10
+
11
+ import { afterAll, describe, expect, test } from "bun:test";
12
+
13
+ import { mkdtemp, readFile, realpath, rm } from "node:fs/promises";
14
+ import { homedir } from "node:os";
15
+ import { join } from "node:path";
16
+
17
+ import { actionName } from "@niwa-labs/core";
18
+ import { harnessId, harnessKind, machineId, sessionId } from "@niwa-labs/harness";
19
+ import type { Harness, SessionControl, StartOptions } from "@niwa-labs/harness";
20
+ import { boxSpec, nono, sandbox as sandboxHost, spawnAgent, srt } from "@niwa-labs/sandbox";
21
+ import type { Sandbox } from "@niwa-labs/sandbox";
22
+ import { createNiwa, live, tempDir, tempHome } from "@niwa-labs/testing";
23
+
24
+ import { sessions } from "../src/index.ts";
25
+
26
+
27
+ const HARNESS = "shell";
28
+
29
+ const cleanups: Array<() => Promise<void>> = [];
30
+ afterAll(async () => {
31
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
32
+ });
33
+
34
+ /** A control side whose session is one shell command, run by the funnel inside the box the grant made. */
35
+ class ShellControl implements SessionControl {
36
+ constructor(private readonly script: (cwd: string) => string) {}
37
+
38
+ async start(options: StartOptions) {
39
+ const child = await spawnAgent({
40
+ harness: HARNESS,
41
+ program: "/bin/sh",
42
+ args: ["-c", this.script(String(options.cwd))],
43
+ cwd: options.cwd,
44
+ env: options.env,
45
+ box: options.box,
46
+ });
47
+ await new Promise<void>((resolve) => child.once("close", () => resolve()));
48
+ return { session: sessionId(harnessId(HARNESS), "s1") };
49
+ }
50
+ async resume(): Promise<void> {}
51
+ async send() {
52
+ return { status: "started" as const };
53
+ }
54
+ async interrupt(): Promise<void> {}
55
+ async ask(): Promise<never> {
56
+ throw new Error("a shell is not asked");
57
+ }
58
+ async *life() {}
59
+ async state() {
60
+ return "idle" as const;
61
+ }
62
+ }
63
+
64
+ /** One hello with the token in `NIWA_ID`, then `access.mine`, over the socket: the line-framed wire of the host. */
65
+ const callMine = (socket: string) =>
66
+ `{ printf '{"id":0,"op":"hello","client":"box","token":"%s"}\\n{"id":1,"op":"call","action":"access.mine","input":{}}\\n' "$NIWA_ID"; sleep 2; } | nc -U ${socket}`;
67
+
68
+ const CURL = (url: string) => `curl -sS -m 10 -o /dev/null -w '%{http_code}' ${url}`;
69
+
70
+ function instance(dir: string): Harness {
71
+ return {
72
+ id: harnessId(HARNESS),
73
+ kind: harnessKind("shell"),
74
+ machine: machineId("machine-1"),
75
+ home: dir,
76
+ sides: {
77
+ reading: { list: false, read: false, watch: false },
78
+ control: { start: true, resume: false, send: false, interrupt: false, ask: false, structuredOutput: false, launch: { model: false, effort: [], modes: [] } },
79
+ },
80
+ };
81
+ }
82
+
83
+ for (const sandbox of [srt(), nono()]) {
84
+ const present = live && (await sandbox.available());
85
+ describe(sandbox.name, () => {
86
+ test.skipIf(!present)("a session in its box calls the running host with its NIWA_ID; gitlab.com stays closed", async () => {
87
+ const dir = await realpath(await tempDir("box-socket"));
88
+ cleanups.push(() => rm(dir, { recursive: true, force: true }));
89
+ // A home under the user's home, as the host's is: nono grants the temp area on its own, so
90
+ // it cannot close the host's keys inside it.
91
+ const home = { path: await realpath(await mkdtemp(join(homedir(), ".niwa-box-home-"))), cleanup: () => rm(home.path, { recursive: true, force: true }) };
92
+ const out = join(dir, "answers.txt");
93
+ const control = new ShellControl(
94
+ () => `( ${callMine(join(home.path, "niwa.sock"))}; echo; echo "gitlab $(${CURL("https://gitlab.com")} 2>&1)" ) > ${out} 2>&1`,
95
+ );
96
+ const host = createNiwa({ home: home.path });
97
+ host.use(sessions({ harnesses: [{ instance: instance(dir), control }], sandbox: sandboxHost({ adapter: sandbox }) }));
98
+ await host.serve();
99
+ cleanups.push(async () => {
100
+ await host.close();
101
+ await home.cleanup();
102
+ });
103
+
104
+ await host.call(actionName("session.start"), { harness: HARNESS, prompt: "", cwd: dir });
105
+
106
+ const answers = await readFile(out, "utf8");
107
+ expect(answers).toContain('"id":1,"ok":true');
108
+ expect(answers).not.toContain("gitlab 200");
109
+ });
110
+
111
+ test.skipIf(!present)("a box made without the socket does not reach the host", async () => {
112
+ const dir = await realpath(await tempDir("box-nosocket"));
113
+ cleanups.push(() => rm(dir, { recursive: true, force: true }));
114
+ const home = await tempHome();
115
+ const host = createNiwa({ home: home.path });
116
+ await host.serve();
117
+ cleanups.push(async () => {
118
+ await host.close();
119
+ await home.cleanup();
120
+ });
121
+ await expectNoReach(sandbox, dir, join(home.path, "niwa.sock"));
122
+ });
123
+ });
124
+ }
125
+
126
+ async function expectNoReach(sandbox: Sandbox, cwd: string, socket: string): Promise<void> {
127
+ const spec = boxSpec({ cwd, env: { PATH: "/usr/bin:/bin", HOME: homedir() } });
128
+ const box = await sandbox.launch(spec, ["/bin/sh", "-c", `printf '{"id":0,"op":"hello","client":"box"}\\n' | nc -U ${socket}`]);
129
+ const [stdout, code] = await Promise.all([new Response(box.stdout).text(), box.exited]);
130
+ expect(stdout).not.toContain('"op"');
131
+ expect(code).not.toBe(0);
132
+ }
@@ -0,0 +1,19 @@
1
+ // The copy of the session actions the cockpit module keeps reads what the host answers and sends what it takes.
2
+
3
+ import { expect, test } from "bun:test";
4
+ import { unreadable, unsendable } from "@niwa-labs/testing";
5
+
6
+ import { sessionList, sessionRead } from "../src/index.ts";
7
+ import { listAction, readAction } from "../src/cockpit/actions.ts";
8
+
9
+ test("the session list is read from what the host answers", () => {
10
+ expect(listAction.name).toBe(String(sessionList.name));
11
+ expect(unsendable(listAction.input, sessionList.input)).toEqual([]);
12
+ expect(unreadable(listAction.output, sessionList.output)).toEqual([]);
13
+ });
14
+
15
+ test("a transcript is read from what the host answers", () => {
16
+ expect(readAction.name).toBe(String(sessionRead.name));
17
+ expect(unsendable(readAction.input, sessionRead.input)).toEqual([]);
18
+ expect(unreadable(readAction.output, sessionRead.output)).toEqual([]);
19
+ });
@@ -0,0 +1,71 @@
1
+ // A transcript as the session page draws it.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import type { TranscriptRecord } from "../src/cockpit/actions.ts";
6
+ import { itemsOf } from "../src/cockpit/transcript.ts";
7
+
8
+ test("turns keep their order and say who spoke", () => {
9
+ const items = itemsOf([
10
+ { kind: "user", text: "hi", locator: "1" },
11
+ { kind: "assistant", text: "hello", model: "m", locator: "2" },
12
+ ]);
13
+ expect(items).toMatchObject([
14
+ { kind: "turn", role: "user", text: "hi", key: "1" },
15
+ { kind: "turn", role: "assistant", text: "hello", model: "m" },
16
+ ]);
17
+ });
18
+
19
+ test("a tool result joins its call by id, wherever it lies after it", () => {
20
+ const records: TranscriptRecord[] = [
21
+ { kind: "tool-call", callId: "c1", name: "read", input: { path: "a" } },
22
+ { kind: "tool-call", callId: "c2", name: "write", input: {} },
23
+ { kind: "tool-result", callId: "c2", ok: false, output: "denied" },
24
+ { kind: "tool-result", callId: "c1", output: "text" },
25
+ ];
26
+ expect(itemsOf(records)).toMatchObject([
27
+ { kind: "tool", name: "read", input: { path: "a" }, output: "text", state: "done" },
28
+ { kind: "tool", name: "write", output: "denied", state: "failed" },
29
+ ]);
30
+ });
31
+
32
+ test("a call with no result is running, and a result whose call lies before the window stands alone", () => {
33
+ const items = itemsOf([
34
+ { kind: "tool-result", callId: "early", name: "grep", output: "x" },
35
+ { kind: "tool-call", callId: "late", name: "bash" },
36
+ ]);
37
+ expect(items).toMatchObject([
38
+ { kind: "tool", name: "grep", state: "done", input: undefined },
39
+ { kind: "tool", name: "bash", state: "running" },
40
+ ]);
41
+ });
42
+
43
+ test("notes name the nested session and keep a sealed thought sealed", () => {
44
+ const items = itemsOf([
45
+ { kind: "thinking", text: "secret", redacted: true },
46
+ { kind: "compaction", summary: "so far" },
47
+ { kind: "nested", child: { harness: "claude", native: "abc" } },
48
+ { kind: "unknown" },
49
+ ]);
50
+ expect(items.map((item) => (item.kind === "note" ? [item.label, item.text] : item.kind))).toEqual([
51
+ ["Thinking", "Kept sealed by the harness."],
52
+ ["Compacted", "so far"],
53
+ ["Nested session", "claude/abc"],
54
+ ["Unrecognised record", ""],
55
+ ]);
56
+ });
57
+
58
+ test("a record without a locator is keyed by its place", () => {
59
+ expect(itemsOf([{ kind: "user", text: "a" }, { kind: "user", text: "b" }]).map((item) => item.key)).toEqual(["#0", "#1"]);
60
+ });
61
+
62
+ test("a checklist is drawn as how far it is, and a permission as its tool and outcome", () => {
63
+ const items = itemsOf([
64
+ { kind: "checklist", items: [{ text: "a", state: "done" }, { text: "b", state: "active" }] },
65
+ { kind: "permission", tool: "Bash", outcome: "denied" },
66
+ ]);
67
+ expect(items.map((item) => (item.kind === "note" ? [item.label, item.text] : item.kind))).toEqual([
68
+ ["Checklist", "1 of 2 done"],
69
+ ["Permission", "Bash: denied"],
70
+ ]);
71
+ });