@niwa-labs/delegate 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,622 @@
1
+ // Delegate on a real host: a request put to the agent is answered from the owner's decisions,
2
+ // decided within bounds, judged, or forwarded to the owner, and what was forwarded never outlives
3
+ // the request it was forwarded for.
4
+
5
+ import { afterEach, expect, test } from "bun:test";
6
+
7
+ import { action, grant, principalOf, record, stableJson } from "@niwa-labs/core";
8
+ import type { Address, Caller, Question, StoredRecord } from "@niwa-labs/core";
9
+ import { plugin } from "@niwa-labs/plugin";
10
+ import type { Plugin } from "@niwa-labs/plugin";
11
+ import { RequestCreated, RequestId, requestAnswer, requestAsk, requestCancel, requestGet, requestResolve } from "@niwa-labs/requests/records";
12
+ import { baseStack, connect, connectAsOwner, createNiwa, eventually, requests, tempHome, testClock } from "@niwa-labs/testing";
13
+ import type { NiwaApi, TestClock } from "@niwa-labs/testing";
14
+ import { z } from "zod";
15
+
16
+ import { delegate } from "../src/index.ts";
17
+ import { contextSource, delegateDecide, delegateDecisionList, delegateRecall, delegateRevoke } from "../src/records.ts";
18
+ import type { ContextRequest } from "../src/records.ts";
19
+
20
+ const START = 1_700_000_000_000;
21
+ const RIN: Address = { kind: "agent", id: "rin" };
22
+ // The requests module of the base stack binds a session to a client address of its own, not to an
23
+ // agent, so in these tests the owner gives the answer in the judge's place.
24
+ const JUDGE: Address = { kind: "agent", id: "judge" };
25
+ const LEAD: Address = { kind: "agent", id: "lead" };
26
+ const JUDGE_WAIT = 30 * 60_000;
27
+
28
+ /** The owner is the owner; a session speaks as the agent of its name. */
29
+ function bind(caller: Caller): Address | undefined {
30
+ if (caller.kind !== "client") return undefined;
31
+ if (caller.principal?.kind === "owner") return { kind: "owner" };
32
+ if (caller.principal?.kind === "session") return { kind: "agent", id: String(caller.principal.id) };
33
+ return { kind: "client", id: caller.id };
34
+ }
35
+
36
+ /** A question in an area, with a choice of two options. */
37
+ function choice(title: string, area?: string): Question {
38
+ return {
39
+ kind: "choice",
40
+ title,
41
+ ...(area === undefined ? {} : { area }),
42
+ options: [
43
+ { id: "tabs", label: "Tabs", flavor: "plain" },
44
+ { id: "spaces", label: "Spaces", flavor: "plain" },
45
+ ],
46
+ allowOther: false,
47
+ } as Question;
48
+ }
49
+
50
+ const memoryContext = contextSource("memory.context");
51
+ const contextAsked: ContextRequest[] = [];
52
+ /** A memory as delegate sees it: it answers a request for context with one conclusion and keeps two back. */
53
+ const memory = plugin("memory", (api) => {
54
+ api.action(
55
+ action(memoryContext, {
56
+ recovery: "repeat",
57
+ effect: "read",
58
+ world: "niwa",
59
+ run: async (input) => {
60
+ contextAsked.push(input);
61
+ const at = input.at ?? 0;
62
+ return {
63
+ at,
64
+ items: [{ text: "The owner indents Go with tabs.", project: "/work/go", source: { owner: { kind: "agent" as const, id: input.memory }, note: "note-5e1f0a2b", seq: at } }],
65
+ withheld: [{ note: "note-00000001" }, { note: "note-00000002" }],
66
+ };
67
+ },
68
+ }),
69
+ );
70
+ });
71
+
72
+ interface World {
73
+ readonly host: ReturnType<typeof createNiwa>;
74
+ readonly home: string;
75
+ readonly clock: TestClock;
76
+ readonly owner: NiwaApi;
77
+ /** A session that speaks as an agent, held to a grant. */
78
+ readonly session: (name: string, rules: readonly string[]) => Promise<NiwaApi>;
79
+ readonly records: (type: string) => Promise<StoredRecord[]>;
80
+ /** The lead asks rin a question, as a request of its own. */
81
+ readonly ask: (question: Question, deadline?: number) => Promise<string>;
82
+ /** The requests addressed to someone, as they were created. */
83
+ readonly to: (address: Address) => Promise<Array<{ id: string; question: string; input: Question; from?: Address }>>;
84
+ readonly status: (id: string) => Promise<string>;
85
+ }
86
+
87
+ const cleanups: Array<() => Promise<void>> = [];
88
+ afterEach(async () => {
89
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
90
+ });
91
+
92
+ async function world(opts: { judges?: Record<string, Address>; extra?: readonly Plugin[] } = {}): Promise<World> {
93
+ const home = await tempHome();
94
+ const clock = testClock(START);
95
+ const host = createNiwa({ home: home.path, clock });
96
+ cleanups.push(() => home.cleanup());
97
+ cleanups.push(() => host.close());
98
+ host.use(
99
+ ...baseStack().plugins,
100
+ ...(opts.extra ?? []),
101
+ memory,
102
+ delegate({ agent: "rin", messages: { bind }, judgeWaitMs: JUDGE_WAIT, ...(opts.judges === undefined ? {} : { judges: opts.judges, context: ["memory.context"] }) }),
103
+ );
104
+ await host.serve();
105
+ const owner = await connectAsOwner(home.path);
106
+ cleanups.push(() => owner.close());
107
+ const records = async (type: string) => (await host.records.read()).filter((row) => row.type === type);
108
+ const session = async (name: string, rules: readonly string[]) => {
109
+ const token = host.issueToken(principalOf("session", name), { grant: grant([...rules]) });
110
+ const client = await connect({ home: home.path, id: `session:${name}`, token });
111
+ cleanups.push(() => client.close());
112
+ return client;
113
+ };
114
+ const ask = async (question: Question, deadline?: number) => {
115
+ const asked = await host.call(requestAsk, {
116
+ to: RIN,
117
+ question: "style.indent" as never,
118
+ input: question,
119
+ from: LEAD,
120
+ ...(deadline === undefined ? {} : { deadline }),
121
+ } as never);
122
+ return (asked as { id: string }).id;
123
+ };
124
+ const to = async (address: Address) =>
125
+ (await records("request.created"))
126
+ .map((row) => row.data as { id: string; to: Address; question: string; input: Question; from?: Address })
127
+ .filter((one) => stableJson(one.to) === stableJson(address));
128
+ const status = async (id: string) => (await host.call(requestGet, { id: id as never })).status;
129
+ return { host, home: home.path, clock, owner, session, records, ask, to, status };
130
+ }
131
+
132
+ /** The answer of a request, once it has one. */
133
+ async function answerOf(w: World, id: string): Promise<unknown> {
134
+ return (await w.host.call(requestGet, { id: id as never })).answer;
135
+ }
136
+
137
+ test("a request the owner has not decided is forwarded to him, and his answer is recalled the next time", async () => {
138
+ const w = await world();
139
+ const first = await w.ask(choice("Tabs or spaces in Go?", "style"));
140
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
141
+ const [forward] = await w.to({ kind: "owner" });
142
+ expect(forward?.from).toEqual(RIN);
143
+ expect(forward?.input.title).toBe("Tabs or spaces in Go?");
144
+
145
+ await w.owner.call(requestAnswer, { id: forward?.id as never, answer: { ids: ["tabs"] } });
146
+ await eventually(async () => (await w.status(first)) === "answered");
147
+ expect(await answerOf(w, first)).toEqual({ ids: ["tabs"] });
148
+ await eventually(async () => (await w.records("delegate.decided")).length === 1);
149
+ expect((await w.records("delegate.decided"))[0]?.data).toMatchObject({ area: "style", kind: "owner", answer: { ids: ["tabs"] } });
150
+
151
+ const second = await w.ask(choice("Tabs or spaces in Go?", "style"));
152
+ await eventually(async () => (await w.status(second)) === "answered");
153
+ expect(await answerOf(w, second)).toEqual({ ids: ["tabs"] });
154
+ const answered = (await w.records("request.answered")).map((row) => row.data as { id: string; how?: string; area?: string; source?: string });
155
+ expect(answered.find((one) => one.id === second)).toMatchObject({ how: "recalled", area: "style" });
156
+ expect(await w.to({ kind: "owner" })).toHaveLength(1);
157
+ });
158
+
159
+ for (const route of ["forward", "judge"] as const) {
160
+ test(`an authenticated ${route} answer reaches the original request and keeps its scope on restart`, async () => {
161
+ const home = await tempHome();
162
+ cleanups.push(() => home.cleanup());
163
+ const pick = record("surface.picked", z.object({ id: RequestId }));
164
+ const address: Address = route === "judge" ? JUDGE : { kind: "owner" };
165
+ const surface = plugin("surface", api => {
166
+ api.declare(pick);
167
+ api.on(pick, async ({ id }, step) => { await step(requestAnswer, { id, answer: { ids: ["tabs"] } }); });
168
+ });
169
+ const addressing = (caller: Caller) => caller.kind === "handler" && caller.handler.startsWith("surface/") ? address : bind(caller);
170
+ const start = async () => {
171
+ const host = createNiwa({ home: home.path });
172
+ host.use(requests({ bind: addressing }), surface, delegate({
173
+ agent: "rin", messages: { bind: addressing }, judges: route === "forward" ? {} : { style: JUDGE }, context: [],
174
+ }));
175
+ await host.serve();
176
+ return host;
177
+ };
178
+ let host = await start();
179
+ cleanups.push(() => host.close());
180
+ const input = choice("Tabs or spaces?", "style");
181
+ const ask = () => host.call(requestAsk, { to: RIN, question: "style.indent" as never, input, from: LEAD });
182
+ const original = await ask();
183
+ const copies = async () => (await host.records.read()).filter(row =>
184
+ row.type === RequestCreated.name && stableJson(RequestCreated.schema.parse(row.data).from ?? null) === stableJson(RIN));
185
+ await eventually(async () => (await copies()).length === 1);
186
+ const copy = RequestCreated.schema.parse((await copies())[0]!.data);
187
+ expect(copy.answerPolicy).toBe(route === "forward" ? "owner-only" : undefined);
188
+ await host.emit(pick, { id: copy.id });
189
+ await eventually(async () => (await host.records.read()).some(row => row.type === "delegate.decided"));
190
+ expect(await host.call(requestGet, { id: original.id })).toMatchObject({ status: "answered", answer: { ids: ["tabs"] } });
191
+ await host.close();
192
+ host = await start();
193
+ const second = await ask();
194
+ if (route === "judge") {
195
+ await eventually(async () => (await copies()).length === 2);
196
+ expect((await host.call(requestGet, { id: second.id })).status).toBe("open");
197
+ } else {
198
+ await eventually(async () => (await host.call(requestGet, { id: second.id })).status === "answered");
199
+ expect(await host.call(requestGet, { id: second.id })).toMatchObject({ answer: { ids: ["tabs"] } });
200
+ expect(await copies()).toHaveLength(1);
201
+ }
202
+ const decisions = (await host.records.read()).filter(row => row.type === "delegate.decided");
203
+ expect(decisions.map(row => row.data)).toMatchObject([{ kind: route === "judge" ? "judge" : "owner", by: address }]);
204
+ });
205
+ }
206
+
207
+ test("a decision holds in its own area, and a question without an area is never recalled", async () => {
208
+ const w = await world();
209
+ const first = await w.ask(choice("Tabs or spaces?", "style"));
210
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
211
+ await w.owner.call(requestAnswer, { id: (await w.to({ kind: "owner" }))[0]?.id as never, answer: { ids: ["tabs"] } });
212
+ await eventually(async () => (await w.status(first)) === "answered");
213
+
214
+ await w.ask(choice("Tabs or spaces?", "docs"));
215
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 2);
216
+ await w.ask(choice("Tabs or spaces?"));
217
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 3);
218
+ const recall = await w.host.call(delegateRecall, { question: "style.indent" as never, input: choice("Tabs or spaces?") });
219
+ expect(recall).toEqual({ found: false });
220
+ });
221
+
222
+ test("a revoked decision is no longer recalled, but a recall as of before the revocation still finds it", async () => {
223
+ const w = await world();
224
+ const first = await w.ask(choice("Tabs or spaces?", "style"));
225
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
226
+ await w.owner.call(requestAnswer, { id: (await w.to({ kind: "owner" }))[0]?.id as never, answer: { ids: ["spaces"] } });
227
+ await eventually(async () => (await w.records("delegate.decided")).length === 1);
228
+ const decision = ((await w.records("delegate.decided"))[0]?.data as { id: string }).id;
229
+ const before = (await w.host.records.read()).at(-1)?.seq ?? 0;
230
+
231
+ const rin = await w.session("rin", ["delegate.*"]);
232
+ await expect(rin.call(delegateRevoke, { decision: decision as never })).rejects.toThrow(/owner/);
233
+ await w.owner.call(delegateRevoke, { decision: decision as never, reason: "changed my mind" });
234
+
235
+ const input = choice("Tabs or spaces?", "style");
236
+ expect(await w.host.call(delegateRecall, { question: "style.indent" as never, input })).toEqual({ found: false });
237
+ expect(await w.host.call(delegateRecall, { question: "style.indent" as never, input, asOf: before })).toMatchObject({ found: true, decision, answer: { ids: ["spaces"] } });
238
+ expect(await answerOf(w, first)).toEqual({ ids: ["spaces"] });
239
+
240
+ await w.ask(input);
241
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 2);
242
+ const listed = await w.owner.call(delegateDecisionList, {});
243
+ expect(listed.items).toEqual([expect.objectContaining({ id: decision, area: "style", kind: "owner", revoked: true })]);
244
+ });
245
+
246
+ test("requests waiting for the owner wait side by side", async () => {
247
+ const w = await world();
248
+ const indent = await w.ask(choice("Tabs or spaces?", "style"));
249
+ const width = await w.ask(choice("80 or 100 columns?", "style"));
250
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 2);
251
+ const forwards = await w.to({ kind: "owner" });
252
+ const widthForward = forwards.find((one) => one.input.title.startsWith("80"));
253
+ await w.owner.call(requestAnswer, { id: widthForward?.id as never, answer: { ids: ["spaces"] } });
254
+ await eventually(async () => (await w.status(width)) === "answered");
255
+ expect(await w.status(indent)).toBe("open");
256
+ });
257
+
258
+ test("the owner cancelling a forward cancels the request it was forwarded for", async () => {
259
+ const w = await world();
260
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
261
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
262
+ await w.owner.call(requestCancel, { id: (await w.to({ kind: "owner" }))[0]?.id as never, reason: "not now" });
263
+ await eventually(async () => (await w.status(asked)) === "cancelled");
264
+ });
265
+
266
+ test("a forward is withdrawn when its request is cancelled by the asker", async () => {
267
+ const w = await world();
268
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
269
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
270
+ await w.host.call(requestCancel, { id: asked as never, by: LEAD });
271
+ const forward = (await w.to({ kind: "owner" }))[0]?.id ?? "";
272
+ await eventually(async () => (await w.status(forward)) === "cancelled");
273
+ });
274
+
275
+ test("a forward is withdrawn when its request expires", async () => {
276
+ const w = await world();
277
+ const asked = await w.ask(choice("Tabs or spaces?", "style"), START + 60_000);
278
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
279
+ await w.clock.advance(60_000);
280
+ await eventually(async () => (await w.status(asked)) === "expired");
281
+ const forward = (await w.to({ kind: "owner" }))[0]?.id ?? "";
282
+ await eventually(async () => (await w.status(forward)) === "cancelled");
283
+ });
284
+
285
+ test("a forward asked after its request was over is withdrawn at once", async () => {
286
+ let release = () => {};
287
+ const held = new Promise<void>((resolve) => (release = resolve));
288
+ let asking = false;
289
+ const hold = plugin("hold", (api) => {
290
+ api.adjust(requestAsk, async (input) => {
291
+ if (input.to.kind === "owner") {
292
+ asking = true;
293
+ await held;
294
+ }
295
+ return input;
296
+ });
297
+ });
298
+ const w = await world({ extra: [hold] });
299
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
300
+ await eventually(() => asking);
301
+ await w.host.call(requestCancel, { id: asked as never, by: LEAD });
302
+ release();
303
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
304
+ const forward = (await w.to({ kind: "owner" }))[0]?.id ?? "";
305
+ await eventually(async () => (await w.status(forward)) === "cancelled");
306
+ });
307
+
308
+ test("the agent decides within its bounds: the request is answered and the forward withdrawn", async () => {
309
+ const w = await world();
310
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
311
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
312
+ const rin = await w.session("rin", ["delegate.decide@style"]);
313
+
314
+ const decided = await rin.call(delegateDecide, { request: asked as never, area: "style", answer: { ids: ["spaces"] } });
315
+ await eventually(async () => (await w.status(asked)) === "answered");
316
+ expect(await answerOf(w, asked)).toEqual({ ids: ["spaces"] });
317
+ expect((await w.records("delegate.decided")).map((row) => row.data)).toEqual([
318
+ expect.objectContaining({ id: decided.decision, kind: "agent", area: "style", by: RIN, request: asked }),
319
+ ]);
320
+ const forward = (await w.to({ kind: "owner" }))[0]?.id ?? "";
321
+ await eventually(async () => (await w.status(forward)) === "cancelled");
322
+
323
+ // An agent's decision answers its request; it is not the owner's, so it is not recalled.
324
+ expect(await w.host.call(delegateRecall, { question: "style.indent" as never, input: choice("Tabs or spaces?", "style") })).toEqual({ found: false });
325
+ });
326
+
327
+ test("a decision outside the request's own area is refused, whatever the grant allows", async () => {
328
+ const w = await world();
329
+ const asked = await w.ask(choice("Pay the invoice?", "money"));
330
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
331
+ const rin = await w.session("rin", ["delegate.decide@style"]);
332
+ await expect(rin.call(delegateDecide, { request: asked as never, area: "style", answer: { ids: ["tabs"] } })).rejects.toThrow(/area/);
333
+ await expect(rin.call(delegateDecide, { request: asked as never, area: "money", answer: { ids: ["tabs"] } })).rejects.toThrow();
334
+ expect(await w.records("delegate.decided")).toHaveLength(0);
335
+ expect(await w.status(asked)).toBe("open");
336
+ });
337
+
338
+ test("only a request put to the agent, and still open, is decided", async () => {
339
+ const w = await world();
340
+ const rin = await w.session("rin", ["delegate.decide@style"]);
341
+ const elsewhere = (await w.host.call(requestAsk, { to: JUDGE, question: "style.indent" as never, input: choice("Tabs?", "style") })) as { id: string };
342
+ await expect(rin.call(delegateDecide, { request: elsewhere.id as never, area: "style", answer: { ids: ["tabs"] } })).rejects.toThrow(/rin/);
343
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
344
+ await w.host.call(requestCancel, { id: asked as never, by: LEAD });
345
+ await expect(rin.call(delegateDecide, { request: asked as never, area: "style", answer: { ids: ["tabs"] } })).rejects.toThrow(/cancelled/);
346
+ });
347
+
348
+ test("a request of an area with a judge goes to the judge, with the context the data owner gives", async () => {
349
+ const w = await world({ judges: { style: JUDGE } });
350
+ const before = contextAsked.length;
351
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
352
+ await eventually(async () => (await w.to(JUDGE)).length === 1);
353
+ const [judged] = await w.to(JUDGE);
354
+ expect(judged?.from).toEqual(RIN);
355
+ expect(judged?.input.detail).toContain("The owner indents Go with tabs.");
356
+ expect(judged?.input.detail).toContain("note-5e1f0a2b of agent rin");
357
+ expect(judged?.input.detail).toContain("2 more");
358
+ expect(judged?.input.detail).toContain("/work/go");
359
+ const created = (await w.records("request.created")).find((row) => (row.data as { id: string }).id === asked);
360
+ expect(contextAsked.slice(before)).toEqual([
361
+ expect.objectContaining({ memory: "rin", for: JUDGE, at: created?.seq, query: "Tabs or spaces?", purpose: expect.stringContaining("style") }),
362
+ ]);
363
+ expect(await w.to({ kind: "owner" })).toHaveLength(0);
364
+
365
+ await w.owner.call(requestResolve, { id: judged?.id as never, answer: { ids: ["tabs"] } });
366
+ await eventually(async () => (await w.status(asked)) === "answered");
367
+ await eventually(async () => (await w.records("delegate.decided")).length === 1);
368
+ // The owner answered in the judge's place: the decision is his, not the judge's.
369
+ expect((await w.records("delegate.decided"))[0]?.data).toMatchObject({ kind: "owner", area: "style", by: { kind: "owner" } });
370
+ expect(await w.host.call(delegateRecall, { question: "style.indent" as never, input: choice("Tabs or spaces?", "style") })).toMatchObject({ found: true, answer: { ids: ["tabs"] } });
371
+ const next = await w.ask(choice("Tabs or spaces?", "style"));
372
+ await eventually(async () => (await w.status(next)) === "answered");
373
+ expect(await answerOf(w, next)).toEqual({ ids: ["tabs"] });
374
+ expect(await w.to(JUDGE)).toHaveLength(1);
375
+ });
376
+
377
+ test("a request the judge does not answer in time goes on to the owner", async () => {
378
+ const w = await world({ judges: { style: JUDGE } });
379
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
380
+ await eventually(async () => (await w.to(JUDGE)).length === 1);
381
+ const judged = (await w.to(JUDGE))[0]?.id ?? "";
382
+ await w.clock.advance(JUDGE_WAIT - 1);
383
+ await Bun.sleep(50);
384
+ expect(await w.status(judged)).toBe("open");
385
+ await w.clock.advance(1);
386
+ await eventually(async () => (await w.status(judged)) === "expired");
387
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
388
+ await w.owner.call(requestAnswer, { id: (await w.to({ kind: "owner" }))[0]?.id as never, answer: { ids: ["spaces"] } });
389
+ await eventually(async () => (await w.status(asked)) === "answered");
390
+ expect(await answerOf(w, asked)).toEqual({ ids: ["spaces"] });
391
+ });
392
+
393
+ test("a judge's question is withdrawn with its request, and nothing goes on to the owner", async () => {
394
+ const w = await world({ judges: { style: JUDGE } });
395
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
396
+ await eventually(async () => (await w.to(JUDGE)).length === 1);
397
+ await w.host.call(requestCancel, { id: asked as never, by: LEAD });
398
+ const judged = (await w.to(JUDGE))[0]?.id ?? "";
399
+ await eventually(async () => (await w.status(judged)) === "cancelled");
400
+ await Bun.sleep(50);
401
+ expect(await w.to({ kind: "owner" })).toHaveLength(0);
402
+ });
403
+
404
+ const hasDecision = async (w: World, kind: string) => (await w.records("delegate.decided")).some((row) => (row.data as { kind: string }).kind === kind);
405
+
406
+ /** A permission question with a one-time, a standing and a refusing option. */
407
+ function permission(title: string, area?: string): Question {
408
+ return {
409
+ kind: "permission",
410
+ title,
411
+ ...(area === undefined ? {} : { area }),
412
+ options: [
413
+ { id: "once", label: "Allow this once", flavor: "allow_once" },
414
+ { id: "always", label: "Always allow", flavor: "allow_always" },
415
+ { id: "no", label: "Refuse", flavor: "reject_once" },
416
+ ],
417
+ subject: { kind: "execute", target: "make test" },
418
+ } as Question;
419
+ }
420
+
421
+ test("a one-time permission answer is not recalled: the next request goes to the owner again", async () => {
422
+ const w = await world();
423
+ const question = permission("Run make test?", "shell");
424
+ const first = await w.ask(question);
425
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
426
+ await w.owner.call(requestAnswer, { id: (await w.to({ kind: "owner" }))[0]?.id as never, answer: { ids: ["once"] } });
427
+ await eventually(async () => (await w.status(first)) === "answered");
428
+ await eventually(async () => (await w.records("delegate.decided")).length === 1);
429
+ expect(await w.host.call(delegateRecall, { question: "style.indent" as never, input: question })).toEqual({ found: false });
430
+
431
+ const second = await w.ask(question);
432
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 2);
433
+ expect(await w.status(second)).toBe("open");
434
+
435
+ // A standing permission is recalled, as any other decision.
436
+ await w.owner.call(requestAnswer, { id: (await w.to({ kind: "owner" }))[1]?.id as never, answer: { ids: ["always"] } });
437
+ await eventually(async () => (await w.status(second)) === "answered");
438
+ await eventually(async () => (await w.records("delegate.decided")).length === 2);
439
+ const third = await w.ask(question);
440
+ await eventually(async () => (await w.status(third)) === "answered");
441
+ expect(await w.to({ kind: "owner" })).toHaveLength(2);
442
+ });
443
+
444
+ test("a refusal for this time only is not recalled either", async () => {
445
+ const w = await world();
446
+ const question = permission("Run make test?", "shell");
447
+ await w.ask(question);
448
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
449
+ await w.owner.call(requestAnswer, { id: (await w.to({ kind: "owner" }))[0]?.id as never, answer: { ids: ["no"] } });
450
+ await eventually(async () => (await w.records("delegate.decided")).length === 1);
451
+ await w.ask(question);
452
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 2);
453
+ });
454
+
455
+ test("an answer the request's question does not take is refused and nothing is decided", async () => {
456
+ const w = await world();
457
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
458
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
459
+ const rin = await w.session("rin", ["delegate.decide@style"]);
460
+ await expect(rin.call(delegateDecide, { request: asked as never, area: "style", answer: { text: "either" } })).rejects.toThrow(/not valid|not answered/);
461
+ await expect(rin.call(delegateDecide, { request: asked as never, area: "style", answer: { ids: ["elastic"] } })).rejects.toThrow();
462
+ expect(await w.records("delegate.decided")).toHaveLength(0);
463
+ expect(await w.status(asked)).toBe("open");
464
+ });
465
+
466
+ /** A plugin that holds the answer of the agent's decisions where it reaches the request. */
467
+ function holdDecided(): { hold: Plugin; release: () => void } {
468
+ let release = () => {};
469
+ const held = new Promise<void>((resolve) => (release = resolve));
470
+ const hold = plugin("hold-decided", (api) => {
471
+ api.adjust(requestResolve, async (input) => {
472
+ if (input.info?.how === "decided") await held;
473
+ return input;
474
+ });
475
+ });
476
+ return { hold, release };
477
+ }
478
+
479
+ test("a request is decided once: a competing answer is refused and the same one gives the first decision back", async () => {
480
+ const { hold, release } = holdDecided();
481
+ const w = await world({ extra: [hold] });
482
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
483
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
484
+ const rin = await w.session("rin", ["delegate.decide@style"]);
485
+ const first = await rin.call(delegateDecide, { request: asked as never, area: "style", answer: { ids: ["spaces"] } });
486
+ await expect(rin.call(delegateDecide, { request: asked as never, area: "style", answer: { ids: ["tabs"] } })).rejects.toThrow(/decided/);
487
+ const again = await rin.call(delegateDecide, { request: asked as never, area: "style", answer: { ids: ["spaces"] } });
488
+ expect(again.decision).toBe(first.decision);
489
+ expect(await w.records("delegate.decided")).toHaveLength(1);
490
+ release();
491
+ await eventually(async () => (await w.status(asked)) === "answered");
492
+ expect(await answerOf(w, asked)).toEqual({ ids: ["spaces"] });
493
+ });
494
+
495
+ test("concurrent delegates choosing the same answer receive one decision", async () => {
496
+ const { hold, release } = holdDecided();
497
+ const w = await world({ extra: [hold] });
498
+ try {
499
+ const request = await w.ask(choice("Tabs or spaces?", "style"));
500
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
501
+ const rin = await w.session("rin", ["delegate.decide@style"]);
502
+ const input = { request: request as never, area: "style", answer: { ids: ["tabs"] } };
503
+ const [one, two] = await Promise.all([rin.call(delegateDecide, input), rin.call(delegateDecide, input)]);
504
+ expect(one).toEqual(two);
505
+ expect(await w.records("delegate.decided")).toHaveLength(1);
506
+ expect(await w.records("delegate.handling.started")).toHaveLength(1);
507
+ } finally {
508
+ release();
509
+ }
510
+ });
511
+
512
+ test("a decision the request did not take is revoked, not left standing", async () => {
513
+ const { hold, release } = holdDecided();
514
+ const w = await world({ extra: [hold] });
515
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
516
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
517
+ const rin = await w.session("rin", ["delegate.decide@style"]);
518
+ const decided = await rin.call(delegateDecide, { request: asked as never, area: "style", answer: { ids: ["spaces"] } });
519
+ await w.host.call(requestCancel, { id: asked as never, by: LEAD });
520
+ release();
521
+ await eventually(async () => (await w.records("delegate.revoked")).length === 1);
522
+ expect((await w.records("delegate.revoked"))[0]?.data).toMatchObject({ decision: decided.decision });
523
+ expect(await w.status(asked)).toBe("cancelled");
524
+ const listed = await w.owner.call(delegateDecisionList, {});
525
+ expect(listed.items).toEqual([expect.objectContaining({ id: decided.decision, revoked: true })]);
526
+ });
527
+
528
+ test("a short id of a request names it for a decision", async () => {
529
+ const w = await world();
530
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
531
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
532
+ const rin = await w.session("rin", ["delegate.decide@style"]);
533
+ await rin.call(delegateDecide, { request: asked.slice(-6) as never, area: "style", answer: { ids: ["tabs"] } });
534
+ await eventually(async () => (await w.status(asked)) === "answered");
535
+ });
536
+
537
+ const STARTER: Address = { kind: "agent", id: "starter" };
538
+ const OTHER: Address = { kind: "agent", id: "other" };
539
+
540
+ /** A handler of the agent that asks rin a form of its own, whose value must also pass a refinement. */
541
+ function formAsker(): Plugin {
542
+ return plugin("form-asker", (api) => {
543
+ api.on(RequestCreated, { id: "start", filter: { "to.kind": "agent", "to.id": "starter" } }, async (_created, step) => {
544
+ await step(requestAsk, {
545
+ to: RIN,
546
+ question: "size.pick" as never,
547
+ input: { kind: "form", title: "How many?", schema: { type: "object", properties: { n: { type: "number" } }, required: ["n"] } } as Question,
548
+ from: LEAD,
549
+ check: z.object({ n: z.number().min(0) }),
550
+ });
551
+ });
552
+ });
553
+ }
554
+
555
+ test("an owner's answer the original form refuses is asked for again, and the corrected one answers the request", async () => {
556
+ const w = await world({ extra: [formAsker()] });
557
+ await w.host.call(requestAsk, { to: STARTER, question: "size.start" as never, input: choice("Go?"), from: LEAD } as never);
558
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
559
+ const original = (await w.to(RIN))[0]?.id ?? "";
560
+ await w.owner.call(requestAnswer, { id: (await w.to({ kind: "owner" }))[0]?.id as never, answer: { form: { n: -1 } } });
561
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 2);
562
+ const [, again] = await w.to({ kind: "owner" });
563
+ expect(again?.input.detail).toContain("not accepted");
564
+ expect(await w.status(original)).toBe("open");
565
+ await w.owner.call(requestAnswer, { id: again?.id as never, answer: { form: { n: 3 } } });
566
+ await eventually(async () => (await w.status(original)) === "answered");
567
+ expect(await answerOf(w, original)).toEqual({ form: { n: 3 } });
568
+ });
569
+
570
+ test("an owner who keeps giving an answer the form refuses ends the request", async () => {
571
+ const w = await world({ extra: [formAsker()] });
572
+ await w.host.call(requestAsk, { to: STARTER, question: "size.start" as never, input: choice("Go?"), from: LEAD } as never);
573
+ const original = async () => (await w.to(RIN))[0]?.id ?? "";
574
+ for (let round = 1; round <= 3; round++) {
575
+ await eventually(async () => (await w.to({ kind: "owner" })).length === round);
576
+ await w.owner.call(requestAnswer, { id: (await w.to({ kind: "owner" }))[round - 1]?.id as never, answer: { form: { n: -round } } });
577
+ }
578
+ await eventually(async () => (await w.status(await original())) === "cancelled");
579
+ expect(await w.to({ kind: "owner" })).toHaveLength(3);
580
+ });
581
+
582
+ test("a question another handler of the agent asked for the same request is not withdrawn with the forward", async () => {
583
+ const rival = plugin("rival", (api) => {
584
+ api.on(RequestCreated, { id: "rival-ask", filter: { "to.kind": "agent", "to.id": "rin" } }, async (_created, step) => {
585
+ await step(requestAsk, { to: OTHER, question: "style.other" as never, input: choice("Which editor?"), from: RIN });
586
+ });
587
+ });
588
+ const w = await world({ extra: [rival] });
589
+ const asked = await w.ask(choice("Tabs or spaces?", "style"));
590
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1 && (await w.to(OTHER)).length === 1);
591
+ await w.host.call(requestCancel, { id: asked as never, by: LEAD });
592
+ const forward = (await w.to({ kind: "owner" }))[0]?.id ?? "";
593
+ await eventually(async () => (await w.status(forward)) === "cancelled");
594
+ await Bun.sleep(50);
595
+ expect(await w.status((await w.to(OTHER))[0]?.id ?? "")).toBe("open");
596
+ });
597
+
598
+ test("an area named like a property of every object goes to the owner", async () => {
599
+ const w = await world();
600
+ const asked = await w.ask(choice("Tabs or spaces?", "constructor"));
601
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
602
+ expect(await w.status(asked)).toBe("open");
603
+ });
604
+
605
+ test("a title on several lines is kept as a decision", async () => {
606
+ const w = await world();
607
+ const asked = await w.ask(choice("Tabs\nor spaces in Go, whatever the editor says about it later?", "style"));
608
+ await eventually(async () => (await w.to({ kind: "owner" })).length === 1);
609
+ await w.owner.call(requestAnswer, { id: (await w.to({ kind: "owner" }))[0]?.id as never, answer: { ids: ["tabs"] } });
610
+ await eventually(async () => (await w.status(asked)) === "answered");
611
+ await eventually(async () => await hasDecision(w, "owner"));
612
+ expect((await w.records("delegate.decided"))[0]?.data).toMatchObject({ description: "Tabs or spaces in Go, whatever the editor says about it lat…" });
613
+ });
614
+
615
+ test("a host without the requests module does not start", async () => {
616
+ const home = await tempHome();
617
+ cleanups.push(() => home.cleanup());
618
+ const host = createNiwa({ home: home.path, clock: testClock(START) });
619
+ cleanups.push(() => host.close());
620
+ host.use(delegate({ agent: "rin" }));
621
+ await expect(host.serve()).rejects.toThrow(/request/);
622
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "include": [
4
+ "src"
5
+ ]
6
+ }