@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/LICENSE +21 -0
- package/README.md +17 -2
- package/package.json +46 -4
- package/src/actions.ts +350 -0
- package/src/ask.ts +230 -0
- package/src/box.ts +87 -0
- package/src/caps.ts +149 -0
- package/src/catalog.ts +146 -0
- package/src/cockpit/actions.ts +52 -0
- package/src/cockpit/index.tsx +36 -0
- package/src/cockpit/pages.tsx +190 -0
- package/src/cockpit/transcript.ts +64 -0
- package/src/confirm.ts +228 -0
- package/src/discover.ts +107 -0
- package/src/identity.ts +64 -0
- package/src/index.ts +1874 -0
- package/src/insert-plugin.ts +263 -0
- package/src/insert-routing.ts +84 -0
- package/src/life.ts +59 -0
- package/src/prompt.ts +50 -0
- package/src/records-entry.ts +91 -0
- package/src/records.ts +395 -0
- package/src/refusal.ts +13 -0
- package/src/reverse.ts +260 -0
- package/src/support.ts +93 -0
- package/src/visible.ts +28 -0
- package/test/access-self-answer.test.ts +197 -0
- package/test/box-socket.test.ts +132 -0
- package/test/cockpit-actions.test.ts +19 -0
- package/test/cockpit-transcript.test.ts +71 -0
- package/test/fixtures/restart-host.ts +175 -0
- package/test/grant-box.test.ts +102 -0
- package/test/insert-permission.test.ts +285 -0
- package/test/restart.test.ts +168 -0
- package/test/sessions-reverse.test.ts +341 -0
- package/test/sessions.test.ts +658 -0
- package/tsconfig.json +15 -0
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
// The sessions module against a fake reading side and a fake journal reader: list, read, running.
|
|
2
|
+
// No host is started; the plugin's own setup is driven with a minimal PluginApi.
|
|
3
|
+
|
|
4
|
+
import { expect, test } from "bun:test";
|
|
5
|
+
|
|
6
|
+
import { principalOf, seq } from "@niwa-labs/core";
|
|
7
|
+
import type { Action, ActionName, JournalReader, StoredRecord, Timestamp } from "@niwa-labs/core";
|
|
8
|
+
import {
|
|
9
|
+
AssistantRecordSchema,
|
|
10
|
+
CompactionRecordSchema,
|
|
11
|
+
harnessId,
|
|
12
|
+
harnessKind,
|
|
13
|
+
machineId,
|
|
14
|
+
NestedRecordSchema,
|
|
15
|
+
sessionId,
|
|
16
|
+
ToolCallRecordSchema,
|
|
17
|
+
ToolResultRecordSchema,
|
|
18
|
+
UnknownRecordSchema,
|
|
19
|
+
UserRecordSchema,
|
|
20
|
+
} from "@niwa-labs/harness";
|
|
21
|
+
import type { Coverage, Harness, SessionInfo, SessionReading, SessionRecord } from "@niwa-labs/harness";
|
|
22
|
+
import type { PluginApi } from "@niwa-labs/plugin";
|
|
23
|
+
import { connect, createNiwa, tempHome } from "@niwa-labs/testing";
|
|
24
|
+
|
|
25
|
+
import {
|
|
26
|
+
lifeOf,
|
|
27
|
+
SessionActivity,
|
|
28
|
+
SessionBelongs,
|
|
29
|
+
SessionCatalog,
|
|
30
|
+
SessionEnded,
|
|
31
|
+
SessionModel,
|
|
32
|
+
sessionRef,
|
|
33
|
+
sessions,
|
|
34
|
+
SessionStarted,
|
|
35
|
+
SessionTurnEnded,
|
|
36
|
+
SessionTurnStarted,
|
|
37
|
+
} from "../src/index.ts";
|
|
38
|
+
|
|
39
|
+
const BOOT = 1_000 as Timestamp;
|
|
40
|
+
const BEFORE = 500;
|
|
41
|
+
const AFTER = 2_000;
|
|
42
|
+
|
|
43
|
+
function instance(id: string, reading: boolean): Harness {
|
|
44
|
+
return {
|
|
45
|
+
id: harnessId(id),
|
|
46
|
+
kind: harnessKind("fake"),
|
|
47
|
+
machine: machineId("here"),
|
|
48
|
+
home: "/tmp/fake",
|
|
49
|
+
sides: reading ? { reading: { list: true, read: true, watch: false } } : {},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let counter = 0;
|
|
54
|
+
function stored(type: string, data: object, at: number): StoredRecord {
|
|
55
|
+
counter += 1;
|
|
56
|
+
return {
|
|
57
|
+
id: `r${counter}`,
|
|
58
|
+
seq: seq(counter),
|
|
59
|
+
stream: "s",
|
|
60
|
+
type,
|
|
61
|
+
schema: 1,
|
|
62
|
+
data,
|
|
63
|
+
actor: "test",
|
|
64
|
+
cause: null,
|
|
65
|
+
root: `r${counter}`,
|
|
66
|
+
at: at as Timestamp,
|
|
67
|
+
} as unknown as StoredRecord;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function reader(records: StoredRecord[]): JournalReader {
|
|
71
|
+
return {
|
|
72
|
+
get: (id) => records.find((record) => record.id === id),
|
|
73
|
+
since: (from, types) =>
|
|
74
|
+
records.filter((record) => record.seq > from && (types === undefined || types.includes(record.type))),
|
|
75
|
+
find: (query) => records.filter((record) => query.type === undefined || record.type === query.type),
|
|
76
|
+
last: () => seq(records.length),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const info = (harness: string, native: string, cwd?: string, title?: string): SessionInfo => ({
|
|
81
|
+
id: sessionId(harnessId(harness), native),
|
|
82
|
+
cwd,
|
|
83
|
+
...(title === undefined ? {} : { title }),
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
function fakeReading(options: {
|
|
87
|
+
list?: SessionInfo[];
|
|
88
|
+
listFails?: boolean;
|
|
89
|
+
records?: SessionRecord[];
|
|
90
|
+
readFailsAfter?: number;
|
|
91
|
+
coverage?: Coverage;
|
|
92
|
+
}): SessionReading {
|
|
93
|
+
return {
|
|
94
|
+
async *list() {
|
|
95
|
+
if (options.listFails) throw new Error("the directory is gone");
|
|
96
|
+
yield* options.list ?? [];
|
|
97
|
+
},
|
|
98
|
+
async *read(_id, from) {
|
|
99
|
+
const records = options.records ?? [];
|
|
100
|
+
const start = from === undefined ? 0 : records.findIndex((record) => record.locator === from) + 1;
|
|
101
|
+
let given = 0;
|
|
102
|
+
for (const record of records.slice(start)) {
|
|
103
|
+
if (options.readFailsAfter !== undefined && given >= options.readFailsAfter) throw new Error("torn file");
|
|
104
|
+
given += 1;
|
|
105
|
+
yield record;
|
|
106
|
+
}
|
|
107
|
+
},
|
|
108
|
+
raw: async () => undefined,
|
|
109
|
+
rawSchema: { parse: (value: unknown) => value } as never,
|
|
110
|
+
coverage: async () => options.coverage ?? { status: "not-scanned" },
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Install the plugin on a minimal API and hand back its actions by name.
|
|
116
|
+
*
|
|
117
|
+
* The output is parsed by the action's own schema, the way the host checks it on every call: an
|
|
118
|
+
* action that returns something its schema does not accept is a failure, and the test sees it.
|
|
119
|
+
*/
|
|
120
|
+
function install(
|
|
121
|
+
options: Parameters<typeof sessions>[0],
|
|
122
|
+
journal: JournalReader | undefined,
|
|
123
|
+
): Record<string, (input: unknown) => Promise<any>> {
|
|
124
|
+
const found: Record<string, (input: unknown) => Promise<any>> = {};
|
|
125
|
+
const api: Partial<PluginApi> = {
|
|
126
|
+
declare: () => {},
|
|
127
|
+
action: (a: Action<any, any>) => {
|
|
128
|
+
found[a.name] = async (input) => a.output.parse(await a.run(a.input.parse(input), undefined as never));
|
|
129
|
+
},
|
|
130
|
+
// The cockpit module is offered by its path; this stub lists none.
|
|
131
|
+
offer: () => {},
|
|
132
|
+
// The plugin handles the questions of the sessions it serves; this stub serves none.
|
|
133
|
+
on: () => {},
|
|
134
|
+
// The disposal of the control sides is a service; this stub runs none.
|
|
135
|
+
service: () => {},
|
|
136
|
+
summarize: () => {},
|
|
137
|
+
journal: () => journal,
|
|
138
|
+
};
|
|
139
|
+
sessions(options).setup(api as PluginApi);
|
|
140
|
+
return found;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const text = (locator: string): SessionRecord =>
|
|
144
|
+
({ kind: "user", text: "hello", locator, incomplete: false }) as unknown as SessionRecord;
|
|
145
|
+
|
|
146
|
+
test("list merges niwa's records with the reading side and states a failing side", async () => {
|
|
147
|
+
const a = sessionRef(sessionId(harnessId("a"), "s1"));
|
|
148
|
+
const journal = reader([
|
|
149
|
+
stored(SessionStarted.name, { session: a, id: "s-a1a1a1", cwd: "/w" }, BEFORE),
|
|
150
|
+
stored(SessionBelongs.name, { session: a, to: { kind: "agent", id: "x" }, source: "explicit" }, BEFORE),
|
|
151
|
+
]);
|
|
152
|
+
const actions = install(
|
|
153
|
+
{
|
|
154
|
+
harnesses: [
|
|
155
|
+
{
|
|
156
|
+
instance: instance("a", true),
|
|
157
|
+
reading: fakeReading({ list: [info("a", "s1", "/w", "the release"), info("a", "s2", "/v")] }),
|
|
158
|
+
},
|
|
159
|
+
{ instance: instance("b", true), reading: fakeReading({ listFails: true }) },
|
|
160
|
+
{ instance: instance("c", false) },
|
|
161
|
+
],
|
|
162
|
+
},
|
|
163
|
+
journal,
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
const all = await actions["session.list"]!({});
|
|
167
|
+
expect(all.sessions.map((s: { ref: string }) => s.ref)).toEqual(["a s1", "a s2"]);
|
|
168
|
+
// The readable title the reading side gives is listed next to the pointer; none is invented.
|
|
169
|
+
expect(all.sessions[0]).toMatchObject({ ref: "a s1", title: "the release" });
|
|
170
|
+
expect(all.sessions[1]?.title).toBeUndefined();
|
|
171
|
+
// A session niwa started is listed with the id it gave; one only the machine knows has none.
|
|
172
|
+
expect(all.sessions[0]?.id).toBe("s-a1a1a1");
|
|
173
|
+
expect(all.sessions[1]?.id).toBeUndefined();
|
|
174
|
+
// A session that only the reading side knows is unknown, and its cwd is kept for filtering.
|
|
175
|
+
expect(all.sessions[1]).toMatchObject({ state: "unknown", cwd: "/v" });
|
|
176
|
+
// Belonging is a record of its own, with its source; the session carries no relation field.
|
|
177
|
+
expect(all.belongings).toEqual([{ session: "a s1", to: { kind: "agent", id: "x" }, source: "explicit" }]);
|
|
178
|
+
expect(Object.keys(all.sessions[0])).not.toContain("belongs");
|
|
179
|
+
// The failing side is named, not silently dropped.
|
|
180
|
+
expect(all.unreadable).toEqual([{ harness: "b", reason: "the directory is gone" }]);
|
|
181
|
+
|
|
182
|
+
const filtered = await actions["session.list"]!({ cwd: "/v" });
|
|
183
|
+
expect(filtered.sessions.map((s: { ref: string }) => s.ref)).toEqual(["a s2"]);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
test("list pages through sessions of every harness, newest first, each exactly once", async () => {
|
|
187
|
+
const kinds = ["a", "b", "c", "d", "e"];
|
|
188
|
+
const harnesses = kinds.map((kind) => ({
|
|
189
|
+
instance: instance(kind, true),
|
|
190
|
+
reading: fakeReading({
|
|
191
|
+
list: Array.from({ length: 230 }, (_, n) => ({ ...info(kind, `s${n}`, "/w", `session ${n} of ${kind}`), updatedAt: (n % 97) * 1000 + kinds.indexOf(kind) })),
|
|
192
|
+
}),
|
|
193
|
+
}));
|
|
194
|
+
const actions = install({ harnesses });
|
|
195
|
+
const list = actions["session.list"]!;
|
|
196
|
+
|
|
197
|
+
// With no limit said, one page is bounded and says where the rest is.
|
|
198
|
+
const first = await list({});
|
|
199
|
+
expect(first.sessions).toHaveLength(100);
|
|
200
|
+
expect(first.total).toBe(1150);
|
|
201
|
+
expect(first.nextCursor).toBeDefined();
|
|
202
|
+
expect(first.hint).toContain("nextCursor");
|
|
203
|
+
expect(first.belongings).toEqual([]);
|
|
204
|
+
|
|
205
|
+
const seen: string[] = [];
|
|
206
|
+
const times: number[] = [];
|
|
207
|
+
let cursor: string | undefined;
|
|
208
|
+
let pages = 0;
|
|
209
|
+
do {
|
|
210
|
+
const page = await list({ limit: 70, ...(cursor === undefined ? {} : { cursor }) });
|
|
211
|
+
expect(page.sessions.length).toBeLessThanOrEqual(70);
|
|
212
|
+
expect(page.total).toBe(1150);
|
|
213
|
+
for (const entry of page.sessions) {
|
|
214
|
+
seen.push(entry.ref);
|
|
215
|
+
times.push(entry.lastActivityAt ?? 0);
|
|
216
|
+
}
|
|
217
|
+
cursor = page.nextCursor;
|
|
218
|
+
if (cursor === undefined) expect(page.hint).toBeUndefined();
|
|
219
|
+
pages += 1;
|
|
220
|
+
} while (cursor !== undefined);
|
|
221
|
+
expect(pages).toBe(17);
|
|
222
|
+
expect(new Set(seen).size).toBe(1150);
|
|
223
|
+
expect(times).toEqual([...times].sort((a, b) => b - a));
|
|
224
|
+
|
|
225
|
+
// A list that fits one page has no cursor.
|
|
226
|
+
const whole = await list({ harness: "a", limit: 500 });
|
|
227
|
+
expect(whole.sessions).toHaveLength(230);
|
|
228
|
+
expect(whole.nextCursor).toBeUndefined();
|
|
229
|
+
|
|
230
|
+
await expect(list({ cursor: "not-a-cursor" })).rejects.toThrow("cursor");
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
test("managed list reads the journal without listing harness sessions", async () => {
|
|
234
|
+
const managed = sessionRef(sessionId(harnessId("a"), "s1"));
|
|
235
|
+
const excluded = sessionRef(sessionId(harnessId("a"), "s2"));
|
|
236
|
+
const to = { kind: "agent", id: "x" };
|
|
237
|
+
const journal = reader([
|
|
238
|
+
stored(SessionStarted.name, { session: managed, id: "s-a1a1a1", cwd: "/w" }, BEFORE),
|
|
239
|
+
stored(SessionTurnStarted.name, { session: managed, turn: 1 }, BEFORE),
|
|
240
|
+
stored(SessionModel.name, { session: managed, model: "model-actually-running" }, BEFORE),
|
|
241
|
+
stored(SessionBelongs.name, { session: managed, to, source: "explicit" }, BEFORE),
|
|
242
|
+
stored(SessionStarted.name, { session: excluded, id: "s-a2a2a2", cwd: "/v" }, BEFORE),
|
|
243
|
+
stored(SessionBelongs.name, { session: excluded, to, source: "explicit" }, BEFORE),
|
|
244
|
+
]);
|
|
245
|
+
let listed = 0;
|
|
246
|
+
const reading: SessionReading = {
|
|
247
|
+
...fakeReading({}),
|
|
248
|
+
async *list() {
|
|
249
|
+
listed += 1;
|
|
250
|
+
yield info("a", "s1", "/w", "the release");
|
|
251
|
+
yield info("a", "external", "/w");
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
const actions = install({ harnesses: [{ instance: instance("a", true), reading }] }, journal);
|
|
255
|
+
const list = actions["session.list"]!;
|
|
256
|
+
|
|
257
|
+
const own = await list({ managedOnly: true, harness: "a", cwd: "/w" });
|
|
258
|
+
expect(own).toEqual({
|
|
259
|
+
sessions: [{ ref: managed, id: "s-a1a1a1", cwd: "/w", model: "model-actually-running", startedAt: BEFORE, state: "unknown" }],
|
|
260
|
+
total: 1,
|
|
261
|
+
belongings: [{ session: managed, to, source: "explicit" }],
|
|
262
|
+
unreadable: [],
|
|
263
|
+
});
|
|
264
|
+
expect(listed).toBe(0);
|
|
265
|
+
|
|
266
|
+
const all = await list({ managedOnly: false, harness: "a", cwd: "/w" });
|
|
267
|
+
expect(all.sessions).toMatchObject([{ ref: managed, title: "the release" }, { ref: "a external" }]);
|
|
268
|
+
expect(listed).toBe(1);
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
test("read passes the harness's records through and never states ignorance as empty", async () => {
|
|
272
|
+
const records = [text("l1"), text("l2")];
|
|
273
|
+
const actions = install(
|
|
274
|
+
{
|
|
275
|
+
harnesses: [
|
|
276
|
+
{ instance: instance("a", true), reading: fakeReading({ records, coverage: { status: "empty" } }) },
|
|
277
|
+
{ instance: instance("t", true), reading: fakeReading({ records, readFailsAfter: 1 }) },
|
|
278
|
+
{ instance: instance("n", false) },
|
|
279
|
+
],
|
|
280
|
+
},
|
|
281
|
+
undefined,
|
|
282
|
+
);
|
|
283
|
+
|
|
284
|
+
const whole = await actions["session.read"]!({ session: "a s1" });
|
|
285
|
+
expect(whole.records.map((r: { locator: string }) => r.locator)).toEqual(["l1", "l2"]);
|
|
286
|
+
expect(whole.coverage).toEqual({ status: "empty" });
|
|
287
|
+
expect(whole.page).toBeUndefined();
|
|
288
|
+
|
|
289
|
+
const continued = await actions["session.read"]!({ session: "a s1", from: "l1" });
|
|
290
|
+
expect(continued.records.map((r: { locator: string }) => r.locator)).toEqual(["l2"]);
|
|
291
|
+
expect(continued.page).toBeUndefined();
|
|
292
|
+
|
|
293
|
+
const torn = await actions["session.read"]!({ session: { harness: "t", native: "s1" } });
|
|
294
|
+
expect(torn.records).toHaveLength(1);
|
|
295
|
+
expect(torn.coverage).toEqual({ status: "failed", reason: "torn file" });
|
|
296
|
+
|
|
297
|
+
const none = await actions["session.read"]!({ session: "n s1" });
|
|
298
|
+
expect(none.records).toEqual([]);
|
|
299
|
+
expect(none.coverage.status).toBe("unavailable");
|
|
300
|
+
|
|
301
|
+
const missing = await actions["session.read"]!({ session: "zzz s1" });
|
|
302
|
+
expect(missing.coverage.status).toBe("unavailable");
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
test("read windows page back exclusively in harness order", async () => {
|
|
306
|
+
const records = Array.from({ length: 8 }, (_, index) => text(`l${index + 1}`));
|
|
307
|
+
const actions = install({ harnesses: [{ instance: instance("a", true), reading: fakeReading({ records }) }] }, undefined);
|
|
308
|
+
const read = async (before?: string) => actions["session.read"]!({ session: "a s1", window: { limit: 3, before } });
|
|
309
|
+
|
|
310
|
+
const latest = await read();
|
|
311
|
+
expect(latest.records).toEqual(records.slice(5));
|
|
312
|
+
expect(latest.page).toEqual({ hasEarlier: true });
|
|
313
|
+
expect(latest.coverage).toEqual({ status: "not-scanned" });
|
|
314
|
+
|
|
315
|
+
const previous = await read(latest.records[0].locator);
|
|
316
|
+
expect(previous.records).toEqual(records.slice(2, 5));
|
|
317
|
+
expect(previous.page).toEqual({ hasEarlier: true });
|
|
318
|
+
|
|
319
|
+
const first = await read(previous.records[0].locator);
|
|
320
|
+
expect(first.records).toEqual(records.slice(0, 2));
|
|
321
|
+
expect(first.page).toEqual({ hasEarlier: false });
|
|
322
|
+
|
|
323
|
+
const exact = await read("l4");
|
|
324
|
+
expect(exact.records).toEqual(records.slice(0, 3));
|
|
325
|
+
expect(exact.page).toEqual({ hasEarlier: false });
|
|
326
|
+
|
|
327
|
+
const beforeFirst = await read("l1");
|
|
328
|
+
expect(beforeFirst.records).toEqual([]);
|
|
329
|
+
expect(beforeFirst.page).toEqual({ hasEarlier: false });
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
test("read windows distinguish an unknown locator from incomplete and unavailable reads", async () => {
|
|
333
|
+
const records = [text("l1"), text("l2"), text("l3"), text("l4")];
|
|
334
|
+
const actions = install({
|
|
335
|
+
harnesses: [
|
|
336
|
+
{ instance: instance("a", true), reading: fakeReading({ records }) },
|
|
337
|
+
{ instance: instance("t", true), reading: fakeReading({ records, readFailsAfter: 3 }) },
|
|
338
|
+
{ instance: instance("n", false) },
|
|
339
|
+
],
|
|
340
|
+
}, undefined);
|
|
341
|
+
const read = async (session: string, before?: string) => actions["session.read"]!({ session, window: { limit: 2, before } });
|
|
342
|
+
|
|
343
|
+
const unknown = await read("a s1", "stale");
|
|
344
|
+
expect(unknown.records).toEqual([]);
|
|
345
|
+
expect(unknown.coverage).toMatchObject({ status: "failed", reason: expect.stringContaining("before locator") });
|
|
346
|
+
expect(unknown.page).toEqual({ hasEarlier: false });
|
|
347
|
+
|
|
348
|
+
const partial = await read("t s1");
|
|
349
|
+
expect(partial.records).toEqual(records.slice(1, 3));
|
|
350
|
+
expect(partial.coverage).toEqual({ status: "failed", reason: "torn file" });
|
|
351
|
+
expect(partial.page).toEqual({ hasEarlier: true });
|
|
352
|
+
|
|
353
|
+
const unverified = await read("t s1", "l4");
|
|
354
|
+
expect(unverified.records).toEqual([]);
|
|
355
|
+
expect(unverified.coverage).toEqual({ status: "failed", reason: "torn file" });
|
|
356
|
+
expect(unverified.page).toEqual({ hasEarlier: false });
|
|
357
|
+
|
|
358
|
+
const found = await read("t s1", "l3");
|
|
359
|
+
expect(found.records).toEqual(records.slice(0, 2));
|
|
360
|
+
expect(found.coverage).toEqual({ status: "not-scanned" });
|
|
361
|
+
expect(found.page).toEqual({ hasEarlier: false });
|
|
362
|
+
|
|
363
|
+
const unavailable = await read("n s1", "l1");
|
|
364
|
+
expect(unavailable.records).toEqual([]);
|
|
365
|
+
expect(unavailable.coverage.status).toBe("unavailable");
|
|
366
|
+
expect(unavailable.page).toEqual({ hasEarlier: false });
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
test("read rejects invalid windows before accessing the reading side", async () => {
|
|
370
|
+
const actions = install({}, undefined);
|
|
371
|
+
const session = "a s1";
|
|
372
|
+
const read = actions["session.read"]!;
|
|
373
|
+
await expect(read({ session, from: "l1", window: { limit: 1 } })).rejects.toThrow(/cannot be combined/);
|
|
374
|
+
for (const limit of [0, -1, 1.5, 251]) {
|
|
375
|
+
await expect(read({ session, window: { limit } })).rejects.toThrow();
|
|
376
|
+
}
|
|
377
|
+
await expect(read({ session, window: { limit: 1, before: "" } })).rejects.toThrow();
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
test("a digest read gives entries in windows that go on from next, carrying the file index; a brief sums the session up", async () => {
|
|
381
|
+
const records = [
|
|
382
|
+
{ kind: "user", text: "fix it", locator: "l1", incomplete: false },
|
|
383
|
+
{ kind: "tool-call", callId: "c1", name: "Read", category: "read", target: "/r/a.ts", input: { file_path: "/r/a.ts" }, locator: "l2", incomplete: false },
|
|
384
|
+
{ kind: "tool-result", callId: "c1", output: "x".repeat(2_000), ok: true, locator: "l3", incomplete: false },
|
|
385
|
+
{ kind: "tool-call", callId: "c2", name: "Edit", category: "edit", target: "/r/a.ts", input: { file_path: "/r/a.ts" }, locator: "l4", incomplete: false },
|
|
386
|
+
{ kind: "assistant", text: "done", locator: "l5", incomplete: false },
|
|
387
|
+
] as unknown as SessionRecord[];
|
|
388
|
+
const actions = install({ harnesses: [{ instance: instance("a", true), reading: fakeReading({ records }) }] }, undefined);
|
|
389
|
+
const read = actions["session.read"]!;
|
|
390
|
+
|
|
391
|
+
const first = await read({ session: "a s1", mode: "digest", budget: 100 });
|
|
392
|
+
expect(first.records).toEqual([]);
|
|
393
|
+
expect(first.digest.view.entries.map((entry: { kind: string }) => entry.kind)).toEqual(["user", "tool"]);
|
|
394
|
+
expect(first.digest.next).toBe("l2");
|
|
395
|
+
const second = await read({ session: "a s1", mode: "digest", from: first.digest.next, files: first.digest.files });
|
|
396
|
+
expect(second.digest.view.entries.map((entry: { kind: string }) => entry.kind)).toEqual(["result", "tool", "assistant"]);
|
|
397
|
+
expect(second.digest.view.entries[1]).toMatchObject({ category: "edit", target: "[F1]" });
|
|
398
|
+
expect(second.digest.next).toBeNull();
|
|
399
|
+
expect(second.digest.files.files).toEqual([{ id: 1, path: "/r/a.ts", changed: true }]);
|
|
400
|
+
|
|
401
|
+
const brief = await read({ session: "a s1", mode: "brief" });
|
|
402
|
+
expect(brief.digest.view.brief).toMatchObject({ changed: ["/r/a.ts"], calls: { read: 1, edit: 1 }, outcome: "answered" });
|
|
403
|
+
// A full read is the records, as before.
|
|
404
|
+
expect((await read({ session: "a s1", mode: "full" })).records).toHaveLength(5);
|
|
405
|
+
await expect(read({ session: "a s1", mode: "digest", window: { limit: 2 } })).rejects.toThrow(/takes no digest/);
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
test("read refuses an undeclared ability before reading", async () => {
|
|
409
|
+
const silent = { ...instance("a", true), sides: { reading: { list: true, read: false, watch: false } } };
|
|
410
|
+
const actions = install({ harnesses: [{ instance: silent, reading: fakeReading({ records: [text("l1")] }) }] }, undefined);
|
|
411
|
+
await expect(actions["session.read"]!({ session: "a s1" })).rejects.toThrow(/does not support reading.read/);
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
test("read returns the content of the records, each kind with its own fields", async () => {
|
|
415
|
+
const child = sessionId(harnessId("a"), "child-1");
|
|
416
|
+
const records: SessionRecord[] = [
|
|
417
|
+
UserRecordSchema.parse({ kind: "user", text: "what is the plan?", locator: "l1", at: 10, incomplete: false }),
|
|
418
|
+
AssistantRecordSchema.parse({
|
|
419
|
+
kind: "assistant",
|
|
420
|
+
text: "we ship it on friday",
|
|
421
|
+
model: "m",
|
|
422
|
+
locator: "l2",
|
|
423
|
+
at: 20,
|
|
424
|
+
incomplete: false,
|
|
425
|
+
}),
|
|
426
|
+
ToolCallRecordSchema.parse({
|
|
427
|
+
kind: "tool-call",
|
|
428
|
+
callId: "c1",
|
|
429
|
+
name: "read",
|
|
430
|
+
category: "read",
|
|
431
|
+
target: "plan.md",
|
|
432
|
+
input: { path: "plan.md" },
|
|
433
|
+
locator: "l3",
|
|
434
|
+
incomplete: false,
|
|
435
|
+
}),
|
|
436
|
+
ToolResultRecordSchema.parse({
|
|
437
|
+
kind: "tool-result",
|
|
438
|
+
callId: "c1",
|
|
439
|
+
name: "read",
|
|
440
|
+
output: "the plan",
|
|
441
|
+
ok: true,
|
|
442
|
+
locator: "l4",
|
|
443
|
+
incomplete: false,
|
|
444
|
+
}),
|
|
445
|
+
CompactionRecordSchema.parse({ kind: "compaction", summary: "the plan is friday", locator: "l5", incomplete: false }),
|
|
446
|
+
NestedRecordSchema.parse({ kind: "nested", child, locator: "l6", incomplete: false }),
|
|
447
|
+
UnknownRecordSchema.parse({ kind: "unknown", raw: { the: "harness's own shape" }, locator: "l7", incomplete: false }),
|
|
448
|
+
];
|
|
449
|
+
const actions = install(
|
|
450
|
+
{ harnesses: [{ instance: instance("a", true), reading: fakeReading({ records }) }] },
|
|
451
|
+
undefined,
|
|
452
|
+
);
|
|
453
|
+
|
|
454
|
+
const result = await actions["session.read"]!({ session: "a s1" });
|
|
455
|
+
expect(result.records).toEqual([
|
|
456
|
+
{ kind: "user", text: "what is the plan?", locator: "l1", at: 10, incomplete: false },
|
|
457
|
+
{ kind: "assistant", text: "we ship it on friday", model: "m", locator: "l2", at: 20, incomplete: false },
|
|
458
|
+
{ kind: "tool-call", callId: "c1", name: "read", category: "read", target: "plan.md", input: { path: "plan.md" }, locator: "l3", incomplete: false },
|
|
459
|
+
{ kind: "tool-result", callId: "c1", name: "read", output: "the plan", ok: true, locator: "l4", incomplete: false },
|
|
460
|
+
{ kind: "compaction", summary: "the plan is friday", locator: "l5", incomplete: false },
|
|
461
|
+
{ kind: "nested", child: { harness: "a", native: "child-1" }, locator: "l6", incomplete: false },
|
|
462
|
+
{ kind: "unknown", locator: "l7", incomplete: false },
|
|
463
|
+
]);
|
|
464
|
+
// The raw data of an unfamiliar record is not published: it is asked for on demand.
|
|
465
|
+
expect(Object.keys(result.records[6])).not.toContain("raw");
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
test("running separates running from unknown, and never copies content into the journal", async () => {
|
|
469
|
+
const a = sessionRef(sessionId(harnessId("a"), "live"));
|
|
470
|
+
const journal = reader([
|
|
471
|
+
stored(SessionStarted.name, { session: a, id: "s-11fe11" }, BEFORE),
|
|
472
|
+
stored(SessionTurnStarted.name, { session: a, turn: 1 }, BEFORE),
|
|
473
|
+
]);
|
|
474
|
+
const actions = install(
|
|
475
|
+
{ harnesses: [{ instance: instance("a", true), reading: fakeReading({ list: [info("a", "other")] }) }] },
|
|
476
|
+
journal,
|
|
477
|
+
);
|
|
478
|
+
const result = await actions["session.running"]!({});
|
|
479
|
+
// The turn was left open before this process began: unknown, not running and not idle. A session that
|
|
480
|
+
// only the machine knows is not niwa's: it is listed with `all`, and one line each.
|
|
481
|
+
expect(result.running).toEqual([]);
|
|
482
|
+
expect(result.unknown).toEqual(["s-11fe11"]);
|
|
483
|
+
const all = await actions["session.running"]!({ all: true });
|
|
484
|
+
expect(all.unknown.map((line: string) => line.split(" ")[0]).sort()).toEqual(["a other", "s-11fe11"]);
|
|
485
|
+
expect((await actions["session.running"]!({ all: true, limit: 1 })).omitted).toBe(1);
|
|
486
|
+
// A sign of life carries no free text that could hold transcript content.
|
|
487
|
+
expect(SessionActivity.schema.safeParse({ session: a, detail: "secret" }).data).toEqual({ session: a });
|
|
488
|
+
// A tool name survives: a short identifier says what is being done, not what was said.
|
|
489
|
+
expect(SessionActivity.schema.safeParse({ session: a, tool: "mcp__niwa__session.send" }).data).toEqual({ session: a, tool: "mcp__niwa__session.send" });
|
|
490
|
+
expect(SessionActivity.schema.safeParse({ session: a, tool: "ran: cat /etc/passwd" }).success).toBe(false);
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
test("life: a turn open before the restart is unknown, a newer record proves running", () => {
|
|
494
|
+
const ref = sessionRef(sessionId(harnessId("a"), "s"));
|
|
495
|
+
const started = stored(SessionStarted.name, { session: ref, id: "s-5e5e5e" }, BEFORE);
|
|
496
|
+
const turn = stored(SessionTurnStarted.name, { session: ref, turn: 1 }, BEFORE);
|
|
497
|
+
expect(lifeOf([], BOOT)).toBe("unknown");
|
|
498
|
+
expect(lifeOf([started], BOOT)).toBe("idle");
|
|
499
|
+
expect(lifeOf([started, turn], BOOT)).toBe("unknown");
|
|
500
|
+
// Even an activity from before the restart proves nothing about now.
|
|
501
|
+
expect(lifeOf([started, turn, stored(SessionActivity.name, { session: ref }, BEFORE)], BOOT)).toBe("unknown");
|
|
502
|
+
expect(lifeOf([started, turn, stored(SessionActivity.name, { session: ref }, AFTER)], BOOT)).toBe("running");
|
|
503
|
+
const fresh = stored(SessionTurnStarted.name, { session: ref, turn: 2 }, AFTER);
|
|
504
|
+
expect(lifeOf([started, fresh], BOOT)).toBe("running");
|
|
505
|
+
const ended = stored(SessionTurnEnded.name, { session: ref, turn: 1 }, AFTER);
|
|
506
|
+
expect(lifeOf([started, turn, ended], BOOT)).toBe("idle");
|
|
507
|
+
expect(lifeOf([started, turn, stored(SessionEnded.name, { session: ref }, AFTER)], BOOT)).toBe("ended");
|
|
508
|
+
});
|
|
509
|
+
|
|
510
|
+
test("the catalog is built in one pass and keeps what is known when a fact is absent", () => {
|
|
511
|
+
const ref = sessionRef(sessionId(harnessId("a"), "s"));
|
|
512
|
+
const catalog = SessionCatalog.fromRecords(
|
|
513
|
+
[
|
|
514
|
+
stored(SessionStarted.name, { session: ref, id: "s-5e5e5e" }, BEFORE),
|
|
515
|
+
stored(SessionModel.name, { session: ref, model: "m-first" }, BEFORE),
|
|
516
|
+
stored(SessionModel.name, { session: ref, model: "m" }, AFTER),
|
|
517
|
+
stored(SessionActivity.name, { session: ref }, AFTER),
|
|
518
|
+
],
|
|
519
|
+
BOOT,
|
|
520
|
+
);
|
|
521
|
+
catalog.remember({ ref, cwd: "/w", state: "unknown" });
|
|
522
|
+
// The model is the one the harness named last; a start record carries none.
|
|
523
|
+
expect(catalog.get(ref)).toMatchObject({ model: "m", cwd: "/w", startedAt: BEFORE, lastActivityAt: AFTER, state: "idle" });
|
|
524
|
+
});
|
|
525
|
+
|
|
526
|
+
test("a session whose harness has not named its model has none", () => {
|
|
527
|
+
const ref = sessionRef(sessionId(harnessId("a"), "s"));
|
|
528
|
+
const catalog = SessionCatalog.fromRecords([stored(SessionStarted.name, { session: ref, id: "s-5e5e5e", model: "asked" }, BEFORE)], BOOT);
|
|
529
|
+
expect(catalog.get(ref)?.model).toBeUndefined();
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
test("belong: the catalog lists the belonging with its source, and saying it twice writes nothing new", async () => {
|
|
533
|
+
const home = await tempHome();
|
|
534
|
+
const host = createNiwa({ home: home.path });
|
|
535
|
+
host.use(sessions({ harnesses: [{ instance: instance("a", true), reading: fakeReading({ list: [info("a", "s1")] }) }] }));
|
|
536
|
+
await host.serve();
|
|
537
|
+
// A client the host issued a token with no grant: nothing limits it, and it is not the owner.
|
|
538
|
+
const client = await connect({ home: home.path, id: "alice", token: host.issueToken(principalOf("client", "alice")) });
|
|
539
|
+
|
|
540
|
+
try {
|
|
541
|
+
const session = sessionRef(sessionId(harnessId("a"), "s1"));
|
|
542
|
+
const to = { kind: "agent", id: "rin" } as const;
|
|
543
|
+
|
|
544
|
+
const said = await client.call("session.belong" as ActionName, { session, to, source: "explicit" });
|
|
545
|
+
expect(said).toMatchObject({ session, to, source: "explicit", known: false });
|
|
546
|
+
|
|
547
|
+
// The catalog shows the belonging, with the source it was written with.
|
|
548
|
+
const listed = await client.call<unknown, { belongings: unknown[] }>("session.list" as ActionName, {});
|
|
549
|
+
expect(listed.belongings).toEqual([{ session, to, source: "explicit" }]);
|
|
550
|
+
|
|
551
|
+
// Saying the same thing again is one fact, not two: nothing new is written.
|
|
552
|
+
const again = await client.call("session.belong" as ActionName, { session, to, source: "explicit" });
|
|
553
|
+
expect(again).toMatchObject({ known: true });
|
|
554
|
+
const written = await client.records.read({ types: [SessionBelongs.name] });
|
|
555
|
+
expect(written).toHaveLength(1);
|
|
556
|
+
// The actor is the caller: the one who said it, not the host.
|
|
557
|
+
expect(written[0]?.actor).toMatchObject({ kind: "client" });
|
|
558
|
+
expect(JSON.stringify(written[0]?.actor)).toContain("alice");
|
|
559
|
+
|
|
560
|
+
// Another address is another belonging.
|
|
561
|
+
await client.call("session.belong" as ActionName, { session, to: { kind: "task", id: "t1" }, source: "explicit" });
|
|
562
|
+
const both = await client.call<unknown, { belongings: unknown[] }>("session.list" as ActionName, {});
|
|
563
|
+
expect(both.belongings).toEqual([
|
|
564
|
+
{ session, to, source: "explicit" },
|
|
565
|
+
{ session, to: { kind: "task", id: "t1" }, source: "explicit" },
|
|
566
|
+
]);
|
|
567
|
+
} finally {
|
|
568
|
+
await client.close();
|
|
569
|
+
await host.close();
|
|
570
|
+
await home.cleanup();
|
|
571
|
+
}
|
|
572
|
+
});
|
|
573
|
+
|
|
574
|
+
test("belong: identical calls made at once write one record", async () => {
|
|
575
|
+
const home = await tempHome();
|
|
576
|
+
const host = createNiwa({ home: home.path });
|
|
577
|
+
host.use(sessions({ harnesses: [{ instance: instance("a", true), reading: fakeReading({ list: [info("a", "s1")] }) }] }));
|
|
578
|
+
await host.serve();
|
|
579
|
+
|
|
580
|
+
try {
|
|
581
|
+
const session = sessionRef(sessionId(harnessId("a"), "s1"));
|
|
582
|
+
const input = { session, to: { kind: "agent", id: "rin" }, source: "explicit" };
|
|
583
|
+
await Promise.all([
|
|
584
|
+
host.call("session.belong" as ActionName, input),
|
|
585
|
+
host.call("session.belong" as ActionName, input),
|
|
586
|
+
host.call("session.belong" as ActionName, input),
|
|
587
|
+
]);
|
|
588
|
+
expect(await host.records.read({ types: [SessionBelongs.name] })).toHaveLength(1);
|
|
589
|
+
} finally {
|
|
590
|
+
await host.close();
|
|
591
|
+
await home.cleanup();
|
|
592
|
+
}
|
|
593
|
+
});
|
|
594
|
+
|
|
595
|
+
test("search finds the records that hold every word, with their index and a snippet, and states coverage", async () => {
|
|
596
|
+
const records: SessionRecord[] = [
|
|
597
|
+
UserRecordSchema.parse({ kind: "user", text: "what is the plan?", locator: "l1", incomplete: false }),
|
|
598
|
+
AssistantRecordSchema.parse({ kind: "assistant", text: "We ship the PLAN on Friday", locator: "l2", incomplete: false }),
|
|
599
|
+
ToolCallRecordSchema.parse({ kind: "tool-call", callId: "c1", name: "read", category: "read", input: { path: "plan.md" }, locator: "l3", incomplete: false }),
|
|
600
|
+
UnknownRecordSchema.parse({ kind: "unknown", raw: { plan: "friday" }, locator: "l4", incomplete: false }),
|
|
601
|
+
CompactionRecordSchema.parse({ kind: "compaction", summary: "the plan is friday", locator: "l5", incomplete: false }),
|
|
602
|
+
];
|
|
603
|
+
const actions = install(
|
|
604
|
+
{
|
|
605
|
+
harnesses: [
|
|
606
|
+
{ instance: instance("a", true), reading: fakeReading({ records, coverage: { status: "empty" } }) },
|
|
607
|
+
{ instance: instance("t", true), reading: fakeReading({ records, readFailsAfter: 1 }) },
|
|
608
|
+
{ instance: instance("n", false) },
|
|
609
|
+
],
|
|
610
|
+
},
|
|
611
|
+
undefined,
|
|
612
|
+
);
|
|
613
|
+
|
|
614
|
+
// Every word, case aside; the index counts every record, the unknown one too.
|
|
615
|
+
const both = await actions["session.search"]!({ session: "a s1", query: "plan FRIDAY" });
|
|
616
|
+
expect(both.matches.map((m: { index: number }) => m.index)).toEqual([1, 4]);
|
|
617
|
+
expect(both.matches[0]).toEqual({ index: 1, kind: "assistant", locator: "l2", snippet: "We ship the PLAN on Friday" });
|
|
618
|
+
expect(both.more).toBe(false);
|
|
619
|
+
expect(both.coverage).toEqual({ status: "empty" });
|
|
620
|
+
|
|
621
|
+
// A tool call is searched by its name and its input.
|
|
622
|
+
const tool = await actions["session.search"]!({ session: "a s1", query: "plan.md" });
|
|
623
|
+
expect(tool.matches.map((m: { kind: string }) => m.kind)).toEqual(["tool-call"]);
|
|
624
|
+
|
|
625
|
+
// Limit and offset page through the matches.
|
|
626
|
+
const first = await actions["session.search"]!({ session: "a s1", query: "plan", limit: 2 });
|
|
627
|
+
expect(first.matches.map((m: { index: number }) => m.index)).toEqual([0, 1]);
|
|
628
|
+
expect(first.more).toBe(true);
|
|
629
|
+
const rest = await actions["session.search"]!({ session: "a s1", query: "plan", limit: 2, offset: 2 });
|
|
630
|
+
expect(rest.matches.map((m: { index: number }) => m.index)).toEqual([2, 4]);
|
|
631
|
+
expect(rest.more).toBe(false);
|
|
632
|
+
|
|
633
|
+
// A snippet is cut around the first word that matched.
|
|
634
|
+
const long = install(
|
|
635
|
+
{
|
|
636
|
+
harnesses: [
|
|
637
|
+
{
|
|
638
|
+
instance: instance("a", true),
|
|
639
|
+
reading: fakeReading({
|
|
640
|
+
records: [UserRecordSchema.parse({ kind: "user", text: `${"x ".repeat(100)}needle${" y".repeat(100)}`, locator: "l1", incomplete: false })],
|
|
641
|
+
}),
|
|
642
|
+
},
|
|
643
|
+
],
|
|
644
|
+
},
|
|
645
|
+
undefined,
|
|
646
|
+
);
|
|
647
|
+
const cut = await long["session.search"]!({ session: "a s1", query: "needle" });
|
|
648
|
+
expect(cut.matches[0].snippet.startsWith("…")).toBe(true);
|
|
649
|
+
expect(cut.matches[0].snippet.endsWith("…")).toBe(true);
|
|
650
|
+
expect(cut.matches[0].snippet).toContain("needle");
|
|
651
|
+
|
|
652
|
+
// A read that fails is said, never shown as no matches; what matched before it is kept.
|
|
653
|
+
const torn = await actions["session.search"]!({ session: "t s1", query: "plan" });
|
|
654
|
+
expect(torn.matches.map((m: { index: number }) => m.index)).toEqual([0]);
|
|
655
|
+
expect(torn.coverage).toEqual({ status: "failed", reason: "torn file" });
|
|
656
|
+
const none = await actions["session.search"]!({ session: "n s1", query: "plan" });
|
|
657
|
+
expect(none.coverage.status).toBe("unavailable");
|
|
658
|
+
});
|