@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.
package/src/index.ts ADDED
@@ -0,0 +1,572 @@
1
+ /**
2
+ * The delegate plugin: it answers for the owner the requests put to one agent.
3
+ *
4
+ * A request addressed to the agent is answered from the owner's decision about the same question in
5
+ * the same area, when one stands. A request of an area that has a judge goes to the judge, with the
6
+ * context the data owners give for it. The agent, or anyone a grant lets decide the area, may decide
7
+ * it within that bound. What is left goes to the owner, and his answer is his decision from then on,
8
+ * unless it was given for this time only. Whatever was passed on for a request is withdrawn when the
9
+ * request is over without it.
10
+ *
11
+ * Nothing is kept in memory: decisions are folded from the journal. A handler reads the journal as
12
+ * of the record that woke it, so a replay decides the same.
13
+ */
14
+
15
+ import {
16
+ DeniedError,
17
+ EntityDescription,
18
+ IdIndex,
19
+ RecordRefused,
20
+ UnknownId,
21
+ ValidationError,
22
+ action,
23
+ answerMismatch,
24
+ issueId,
25
+ pickedOptions,
26
+ recordId,
27
+ seq,
28
+ stableJson,
29
+ timestamp,
30
+ } from "@niwa-labs/core";
31
+ import type { Address, Answer, JournalReader, OptionFlavor, Question, Seq, Step, StoredRecord } from "@niwa-labs/core";
32
+ import { bindingOf, plugin } from "@niwa-labs/plugin";
33
+ import type { CallerBinding, MessagesOptions, Plugin } from "@niwa-labs/plugin";
34
+ import {
35
+ REQUEST_TYPES,
36
+ RequestAnswered,
37
+ RequestCancelled,
38
+ RequestCancelledRecord,
39
+ RequestCreated,
40
+ RequestExpired,
41
+ RequestExpiredRecord,
42
+ RequestId,
43
+ fold as foldRequests,
44
+ operatorAnswered,
45
+ requestAsk,
46
+ requestCancel,
47
+ requestResolve,
48
+ } from "@niwa-labs/requests/records";
49
+ import type { RequestState } from "@niwa-labs/requests/records";
50
+ import type { z } from "zod";
51
+
52
+ import {
53
+ ContextAnswer,
54
+ DELEGATE_TYPES,
55
+ HandlingStarted,
56
+ DecisionMade,
57
+ DecisionRevoked,
58
+ RequestForwarded,
59
+ contextSource,
60
+ delegateDecide,
61
+ delegateDecisionList,
62
+ delegateRecall,
63
+ delegateRevoke,
64
+ } from "./records.ts";
65
+ import type { ContextItem, ContextRequest, DecisionId, DecisionKind } from "./records.ts";
66
+
67
+ export * from "./records.ts";
68
+
69
+ export interface DelegateOptions {
70
+ /** The agent the requests are addressed to: delegate answers what is put to it. */
71
+ readonly agent: string;
72
+ /** The judge of an area: the address a request of that area is passed to before the owner. */
73
+ readonly judges?: Readonly<Record<string, Address>>;
74
+ /**
75
+ * The actions that answer a request for context (`contextSource`), asked before a request goes to
76
+ * a judge. A memory serves one; delegate knows it only by name.
77
+ */
78
+ readonly context?: readonly string[];
79
+ /** How long a judge has to answer before the request goes on to the owner. Default: an hour. */
80
+ readonly judgeWaitMs?: number;
81
+ /** What address a caller speaks as: the same binding the messages module uses. */
82
+ readonly messages?: MessagesOptions;
83
+ }
84
+
85
+ /** How long a judge has to answer, by default. */
86
+ export const DEFAULT_JUDGE_WAIT_MS = 3_600_000;
87
+
88
+ /** How many times the owner is asked again for an answer the request's own question refuses. */
89
+ const MAX_OWNER_ROUNDS = 3;
90
+
91
+ /** The longest description a list shows, and the shortest. */
92
+ const DESCRIPTION_MAX_CHARS = 60;
93
+ const DESCRIPTION_MIN_CHARS = 3;
94
+
95
+ type Created = z.infer<typeof RequestCreated.schema>;
96
+ type Decision = z.infer<typeof DecisionMade.schema>;
97
+
98
+ /** How an answer given to a request was found, as `request.resolve` keeps it. */
99
+ interface Found {
100
+ readonly how: string;
101
+ readonly area: string;
102
+ readonly source: string;
103
+ }
104
+
105
+ /** What became of an answer handed to its request. */
106
+ type Taken =
107
+ /** The request is answered by it. */
108
+ | { readonly status: "answered" }
109
+ /** The request was over before it came. */
110
+ | { readonly status: "over" }
111
+ /** The request's own question refuses it. */
112
+ | { readonly status: "refused"; readonly reason: string };
113
+
114
+ /** The key of a question: its name and what was asked, without the area. */
115
+ export function questionKey(question: string, input: Question): string {
116
+ const { area: _area, ...rest } = input;
117
+ return `${question}|${stableJson(rest)}`;
118
+ }
119
+
120
+ /** The decisions in the order they were made, each with whether it was revoked. */
121
+ function decisionsOf(rows: readonly StoredRecord[]): Array<{ decision: Decision; revoked: boolean }> {
122
+ const revoked = new Set(rows.filter((row) => row.type === DecisionRevoked.name).map((row) => DecisionRevoked.schema.parse(row.data).decision));
123
+ return rows
124
+ .filter((row) => row.type === DecisionMade.name)
125
+ .map((row) => {
126
+ const decision = DecisionMade.schema.parse(row.data);
127
+ return { decision, revoked: revoked.has(decision.id) };
128
+ });
129
+ }
130
+
131
+ /** What choosing an option is worth for one time only. */
132
+ const ONE_TIME: ReadonlySet<OptionFlavor> = new Set(["allow_once", "reject_once"]);
133
+
134
+ /** Whether an answer holds for this one request only: it picks an option that allows or refuses once. */
135
+ export function isOneTime(input: Question, answer: Answer): boolean {
136
+ return pickedOptions(input, answer).some((option) => ONE_TIME.has(option.flavor));
137
+ }
138
+
139
+ /**
140
+ * The owner's decision that answers a question, when one stands: the last one made for the same key
141
+ * in the same area and not revoked. A question without an area names no decision, and neither does
142
+ * a decision that was good for one time only: the next request is put to the owner again.
143
+ */
144
+ export function recallOf(rows: readonly StoredRecord[], question: string, input: Question): Decision | undefined {
145
+ const area = input.area;
146
+ if (area === undefined) return undefined;
147
+ const key = questionKey(question, input);
148
+ const last = decisionsOf(rows)
149
+ .filter((one) => !one.revoked && one.decision.kind === "owner" && one.decision.question === key && one.decision.area === area)
150
+ .at(-1)?.decision;
151
+ return last === undefined || isOneTime(input, last.answer) ? undefined : last;
152
+ }
153
+
154
+ /** A description a person reads in a list, from the title of a question: one line, cut to what a list shows. */
155
+ function describe(title: string): EntityDescription {
156
+ const line = title.replace(/\s+/g, " ").trim();
157
+ let short = "";
158
+ if (line.length <= DESCRIPTION_MAX_CHARS) short = line;
159
+ else {
160
+ for (const character of line) {
161
+ if (short.length + character.length > DESCRIPTION_MAX_CHARS - 1) break;
162
+ short += character;
163
+ }
164
+ short = `${short.trimEnd()}…`;
165
+ }
166
+ return EntityDescription.parse(short.length >= DESCRIPTION_MIN_CHARS ? short : "Decision");
167
+ }
168
+
169
+ /** Whether two addresses are the same. */
170
+ function same(a: Address | undefined, b: Address | undefined): boolean {
171
+ return a !== undefined && b !== undefined && stableJson(a) === stableJson(b);
172
+ }
173
+
174
+ /** The context the data owners gave, as lines a judge reads under the question. */
175
+ function withContext(detail: string | undefined, items: readonly ContextItem[], withheld: number): string | undefined {
176
+ if (items.length === 0 && withheld === 0) return detail;
177
+ const lines = items.map(({ text, project, source }) => {
178
+ const owner = "id" in source.owner ? `${source.owner.kind} ${source.owner.id}` : source.owner.kind;
179
+ const holds = project === undefined ? "" : `holds in ${project}; `;
180
+ return `- ${text} (${holds}${source.note} of ${owner} at ${String(source.seq)})`;
181
+ });
182
+ if (withheld > 0) lines.push(`- ${String(withheld)} more not shown: this reader may not have them.`);
183
+ return [detail, "Context:", ...lines].filter((line) => line !== undefined).join("\n");
184
+ }
185
+
186
+ /** The request types delegate needs the host to declare: it answers, withdraws and waits on them. */
187
+ const REQUIRED = [RequestCreated, RequestAnswered, RequestCancelledRecord, RequestExpiredRecord] as const;
188
+
189
+ /** The delegate plugin. */
190
+ export function delegate(opts: DelegateOptions): Plugin {
191
+ const self: Address = { kind: "agent", id: opts.agent };
192
+ // A map, not the object it was given: an area named like a property of every object is not a judge.
193
+ const judges = new Map(Object.entries(opts.judges ?? {}));
194
+ const judgeWait = opts.judgeWaitMs ?? DEFAULT_JUDGE_WAIT_MS;
195
+ for (const [area, judge] of judges) {
196
+ if (same(judge, self)) throw new TypeError(`the judge of "${area}" is the agent delegate answers for: it would be asked its own question`);
197
+ }
198
+ const sources = (opts.context ?? []).map((name) => contextSource(name));
199
+ const bind: CallerBinding = bindingOf(opts.messages);
200
+
201
+ return plugin("delegate", (api) => {
202
+ api.declare(...DELEGATE_TYPES);
203
+ const journal = (): JournalReader | undefined => api.journal?.();
204
+ /** The records of delegate, up to a position when one is given. */
205
+ const rowsOf = (upto?: Seq): StoredRecord[] => {
206
+ const rows = journal()?.since(seq(0), DELEGATE_TYPES.map((type) => type.name)) ?? [];
207
+ return upto === undefined ? rows : rows.filter((row) => row.seq <= upto);
208
+ };
209
+ const ids = new IdIndex("decision", () =>
210
+ rowsOf()
211
+ .filter((row) => row.type === DecisionMade.name)
212
+ .map((row) => ({ id: DecisionMade.schema.parse(row.data).id, seed: String(row.id) })),
213
+ );
214
+ /** The id a decision of a request gets: one request is decided once by each kind of decider. */
215
+ const decisionIdOf = (request: RequestId, kind: DecisionKind): DecisionId =>
216
+ issueId(
217
+ "decision",
218
+ recordId(`decision:${request}:${kind}`),
219
+ rowsOf()
220
+ .filter((row) => row.type === DecisionMade.name)
221
+ .map((row) => {
222
+ const made = DecisionMade.schema.parse(row.data);
223
+ return { id: made.id, seed: `decision:${made.request}:${made.kind}` };
224
+ }),
225
+ );
226
+ /** The ids of the requests put to the agent, to name one by a short text. */
227
+ const requestIds = new IdIndex("request", () =>
228
+ (journal()?.find({ type: RequestCreated.name }) ?? [])
229
+ .map((row) => ({ created: RequestCreated.schema.parse(row.data), seed: String(row.id) }))
230
+ .filter(({ created }) => same(created.to, self))
231
+ .map(({ created, seed }) => ({ id: created.id, seed })),
232
+ );
233
+
234
+ /** The request with this id as it was created, and the record that created it. */
235
+ const createdOf = (id: string): { created: Created; row: StoredRecord } | undefined => {
236
+ const row = journal()?.find({ type: RequestCreated.name, field: "id", equals: id }).at(0);
237
+ return row === undefined ? undefined : { created: RequestCreated.schema.parse(row.data), row };
238
+ };
239
+ /** The request a text names among those put to the agent: its id, or a unique start or end of it. */
240
+ const requestNamed = (text: string): { created: Created; row: StoredRecord } => {
241
+ const found = createdOf(text) ?? createdOf(requestIds.require(text));
242
+ if (found === undefined) throw new UnknownId(text, "request");
243
+ return found;
244
+ };
245
+ /** The records about one request, in the order they were written. */
246
+ const recordsAbout = (id: string, types: readonly { readonly name: string }[]): StoredRecord[] =>
247
+ types
248
+ .flatMap((type) => journal()?.find({ type: type.name as StoredRecord["type"], field: "id", equals: id }) ?? [])
249
+ .sort((a, b) => a.seq - b.seq);
250
+ /** Where a request stands as of a position: the records about it written up to then. */
251
+ const stateAt = (id: string, at: Seq): RequestState | undefined =>
252
+ foldRequests(recordsAbout(id, REQUEST_TYPES).filter((row) => row.seq <= at), bind).get(id as RequestId);
253
+ /**
254
+ * The invocations of delegate-answer that passed a request on: the forwards they wrote name
255
+ * them, and what they asked is what was passed on. Another handler's question, asked for the
256
+ * same request, is its own.
257
+ */
258
+ const forwardersOf = (request: RequestId): ReadonlySet<string> =>
259
+ new Set(
260
+ (journal()?.find({ type: RequestForwarded.name, field: "request", equals: request }) ?? []).flatMap((row) =>
261
+ row.actor.kind === "handler" ? [String(row.actor.invocation)] : [],
262
+ ),
263
+ );
264
+ const askedBy = (row: StoredRecord, invocations: ReadonlySet<string>): boolean => row.actor.kind === "handler" && invocations.has(String(row.actor.invocation));
265
+ /** The requests delegate passed on for a request, as of a position. */
266
+ const passedOn = (request: RequestId, created: Seq, at: Seq): Created[] => {
267
+ const invocations = forwardersOf(request);
268
+ if (invocations.size === 0) return [];
269
+ return (journal()?.query({ types: [RequestCreated.name], filter: { "from.kind": "agent", "from.id": opts.agent }, from: created }) ?? [])
270
+ .filter((row) => row.seq <= at && askedBy(row, invocations))
271
+ .map((row) => RequestCreated.schema.parse(row.data));
272
+ };
273
+ const withdraw = async (step: Step, request: RequestId) => {
274
+ // The one it was passed to may end it at the same moment: then there is nothing to withdraw.
275
+ await step.outcome(requestCancel, { id: request, reason: "the request it was passed on for is over", by: self });
276
+ };
277
+
278
+ /** The decision of a request, written once, as the request is answered. */
279
+ const decided = (created: Created, kind: DecisionKind, answer: Answer, grounds: readonly string[], by: Address | undefined): Decision | undefined => {
280
+ const area = created.input.area;
281
+ if (area === undefined) return undefined;
282
+ return {
283
+ id: decisionIdOf(created.id, kind),
284
+ description: describe(created.input.title),
285
+ question: questionKey(created.question, created.input),
286
+ area,
287
+ kind,
288
+ answer,
289
+ request: created.id,
290
+ grounds: [...grounds],
291
+ ...(by === undefined ? {} : { by }),
292
+ };
293
+ };
294
+
295
+ /** Ask the data owners for the context a judge needs, as the journal stood when the request was made. */
296
+ const contextFor = async (step: Step, created: Created, judge: Address, at: Seq) => {
297
+ const asked: ContextRequest = {
298
+ memory: opts.agent,
299
+ query: created.input.title.slice(0, 500),
300
+ purpose: `judge a request${created.input.area === undefined ? "" : ` about ${created.input.area}`} put to ${opts.agent} for the owner`,
301
+ for: judge,
302
+ at,
303
+ };
304
+ const items: ContextItem[] = [];
305
+ let withheld = 0;
306
+ for (const source of sources) {
307
+ const outcome = await step.outcome(source, asked);
308
+ if (outcome.status !== "completed") continue;
309
+ // The owner of the action checked its own answer; delegate reads the part it knows.
310
+ const answer = ContextAnswer.safeParse(outcome.value);
311
+ if (!answer.success) continue;
312
+ items.push(...answer.data.items);
313
+ withheld += answer.data.withheld.length;
314
+ }
315
+ return { items, withheld };
316
+ };
317
+
318
+ /** Pass a request on to an address, and give back what it answers. Undefined when it ended unanswered. */
319
+ const passOn = async (step: Step, created: Created, to: Address, input: Question, key: string, deadline?: number) => {
320
+ await step.emit(RequestForwarded, { request: created.id, to }, { key });
321
+ try {
322
+ const asked = await step(requestAsk, {
323
+ to, question: created.question, input, from: self,
324
+ ...(to.kind === "owner" ? { answerPolicy: "owner-only" as const } : {}),
325
+ ...(deadline === undefined ? {} : { deadline: timestamp(deadline) }),
326
+ });
327
+ return "answer" in asked ? asked : undefined;
328
+ } catch (error) {
329
+ if (error instanceof RequestCancelled || error instanceof RequestExpired) return { ended: error.request };
330
+ throw error;
331
+ }
332
+ };
333
+
334
+ /**
335
+ * Hand an answer to its request. The question of the request may refuse it (a form held to more
336
+ * than its schema says), and then the request stays open and the answer is not taken.
337
+ */
338
+ const take = async (step: Step, created: Created, answer: Answer, found?: Found): Promise<Taken> => {
339
+ const outcome = await step.outcome(requestResolve, { id: created.id, answer, ...(found === undefined ? {} : { info: found }) });
340
+ if (outcome.status === "completed") return outcome.value.answered ? { status: "answered" } : { status: "over" };
341
+ return outcome.status === "failed" ? { status: "refused", reason: outcome.error } : { status: "over" };
342
+ };
343
+
344
+ /** Where the record that ended a request is. */
345
+ const endOf = (request: RequestId): Seq | undefined => recordsAbout(request, [RequestAnswered, RequestCancelledRecord, RequestExpiredRecord]).at(0)?.seq;
346
+
347
+ // The owner-only ask identifies its accepted request even when its surface binding lives in requests.
348
+ const ownerGrounds = (id: RequestId): string[] => {
349
+ const request = createdOf(id);
350
+ return request === undefined ? [] : [String(request.row.id)];
351
+ };
352
+
353
+ const judgeDecision = (created: Created, judged: { id: RequestId; answer: Answer }, judge: Address) => {
354
+ const birth = createdOf(judged.id);
355
+ if (birth === undefined) return undefined;
356
+ // The ordinary judge ask returns the first answer after its creation, including on replay.
357
+ const row = journal()?.query({ types: [RequestAnswered.name], filter: { id: judged.id }, from: birth.row.seq }, 1)[0];
358
+ if (row === undefined) return undefined;
359
+ const receipt = RequestAnswered.schema.parse(row.data);
360
+ if (stableJson(receipt.answer) !== stableJson(judged.answer)) return undefined;
361
+ const grounds = [String(row.id)];
362
+ if (receipt.how === undefined && receipt.by?.kind === "owner" && operatorAnswered(row, bind)) {
363
+ return decided(created, "owner", judged.answer, grounds, { kind: "owner" });
364
+ }
365
+ const author = bind(row.actor);
366
+ return decided(created, "judge", judged.answer, grounds, author !== undefined && same(author, judge) ? judge : undefined);
367
+ };
368
+
369
+ // A request put to the agent: recalled, judged, or forwarded to the owner. Each waits for its own
370
+ // answer, side by side with the others.
371
+ api.on(
372
+ RequestCreated,
373
+ { id: "delegate-answer", filter: { "to.kind": "agent", "to.id": opts.agent }, concurrency: { by: data => data.id }, requires: REQUIRED },
374
+ async (created, step, at) => {
375
+ await step.emit(HandlingStarted, { request: created.id }, { key: "claim" });
376
+ const recalled = recallOf(rowsOf(at.seq), created.question, created.input);
377
+ if (recalled !== undefined) {
378
+ // An answer the question refuses today is not an answer: the request goes on as if nothing was recalled.
379
+ const taken = await take(step, created, recalled.answer, { how: "recalled", area: recalled.area, source: recalled.id });
380
+ if (taken.status !== "refused") return;
381
+ }
382
+ const area = created.input.area;
383
+ const judge = area === undefined ? undefined : judges.get(area);
384
+ if (area !== undefined && judge !== undefined) {
385
+ const context = await contextFor(step, created, judge, at.seq);
386
+ const input = { ...created.input, detail: withContext(created.input.detail, context.items, context.withheld) } as Question;
387
+ const deadline = (await step.now({ key: "judge-asked" })) + judgeWait;
388
+ const judged = await passOn(step, created, judge, input, "judge", deadline);
389
+ if (judged !== undefined && "answer" in judged) {
390
+ const taken = await take(step, created, judged.answer, { how: "judged", area, source: judged.id });
391
+ if (taken.status === "over") return;
392
+ if (taken.status === "answered") {
393
+ // Whoever answered the judge's question decided: the judge, or the owner in its place.
394
+ const decision = judge.kind === "owner"
395
+ ? decided(created, "owner", judged.answer, ownerGrounds(judged.id), judge)
396
+ : judgeDecision(created, judged, judge);
397
+ if (decision !== undefined) await step.emit(DecisionMade, decision, { key: "decided" });
398
+ return;
399
+ }
400
+ // The question refused the judge's answer: the owner is asked.
401
+ } else {
402
+ // The judge's question ended unanswered. When the request ended first, it was withdrawn
403
+ // with it and nothing goes on; otherwise the owner is asked.
404
+ const ended = judged === undefined ? undefined : endOf(judged.ended);
405
+ if (ended !== undefined && stateAt(created.id, ended)?.status !== "open") return;
406
+ }
407
+ }
408
+ let asking: Question = created.input;
409
+ for (let round = 1; round <= MAX_OWNER_ROUNDS; round++) {
410
+ const forwarded = await passOn(step, created, { kind: "owner" }, asking, round === 1 ? "owner" : `owner-${String(round)}`);
411
+ if (forwarded === undefined) return;
412
+ if (!("answer" in forwarded)) {
413
+ // The owner cancelled the forward, so nobody is left to answer the request. One that ended
414
+ // by itself cannot be cancelled, and that is not a failure.
415
+ const ended = endOf(forwarded.ended);
416
+ if (ended !== undefined && stateAt(created.id, ended)?.status === "open") {
417
+ await step.outcome(requestCancel, { id: created.id, reason: "the owner cancelled the forward", by: self });
418
+ }
419
+ return;
420
+ }
421
+ const taken = await take(step, created, forwarded.answer);
422
+ if (taken.status === "refused") {
423
+ // The owner answered the copy; the question of the original refuses the answer. He is asked again, with why.
424
+ const why = `Your answer was not accepted: ${taken.reason}`;
425
+ asking = { ...created.input, detail: [created.input.detail, why].filter((line) => line !== undefined).join("\n") } as Question;
426
+ continue;
427
+ }
428
+ // What the owner answered is his decision in the area, whether or not the request still waited.
429
+ const decision = decided(created, "owner", forwarded.answer, ownerGrounds(forwarded.id), { kind: "owner" });
430
+ if (decision !== undefined) await step.emit(DecisionMade, decision, { key: "decided" });
431
+ return;
432
+ }
433
+ await step.outcome(requestCancel, { id: created.id, reason: "the answers of the owner did not fit the question", by: self });
434
+ },
435
+ );
436
+
437
+ // A request put to the agent that is over takes with it what was passed on for it and still waits:
438
+ // nothing stale is left for the owner or the judge. Decided as of the record that ended it.
439
+ const closePassedOn = async (ended: { id: RequestId }, step: Step, at: StoredRecord) => {
440
+ const found = createdOf(ended.id);
441
+ if (found === undefined || !same(found.created.to, self)) return;
442
+ for (const passed of passedOn(found.created.id, found.row.seq, at.seq)) {
443
+ if (stateAt(passed.id, at.seq)?.status === "open") await withdraw(step, passed.id);
444
+ }
445
+ };
446
+ api.on(RequestAnswered, { id: "delegate-close-answered", requires: REQUIRED }, closePassedOn);
447
+ api.on(RequestCancelledRecord, { id: "delegate-close-cancelled", requires: REQUIRED }, closePassedOn);
448
+ api.on(RequestExpiredRecord, { id: "delegate-close-expired", requires: REQUIRED }, closePassedOn);
449
+
450
+ // What was passed on after its request was already over is withdrawn as soon as it is created.
451
+ api.on(
452
+ RequestCreated,
453
+ { id: "delegate-close-late", filter: { "from.kind": "agent", "from.id": opts.agent }, requires: REQUIRED },
454
+ async (passed, step, at) => {
455
+ const cause = at.cause === null ? undefined : journal()?.get(at.cause);
456
+ if (cause?.type !== RequestCreated.name) return;
457
+ const original = RequestCreated.schema.parse(cause.data);
458
+ if (!same(original.to, self) || !askedBy(at, forwardersOf(original.id))) return;
459
+ if (stateAt(original.id, at.seq)?.status !== "open") await withdraw(step, passed.id);
460
+ },
461
+ );
462
+
463
+ // A decision of the agent answers the request it decided. When the request does not take it,
464
+ // because it ended otherwise first or its question refuses the answer, the decision is revoked.
465
+ api.on(DecisionMade, { id: "delegate-decided", filter: { kind: "agent" }, requires: REQUIRED }, async (decision, step) => {
466
+ const outcome = await step.outcome(requestResolve, { id: decision.request, answer: decision.answer, info: { how: "decided", area: decision.area, source: decision.id } });
467
+ if (outcome.status === "completed" && outcome.value.answered) return;
468
+ const reason = outcome.status === "failed" ? outcome.error : "the request did not take the answer";
469
+ await step.emit(DecisionRevoked, { decision: decision.id, reason }, { key: "revoked" });
470
+ });
471
+
472
+ /** The decision the agent made of a request, revoked or not. */
473
+ const agentDecisionOf = (request: RequestId): { decision: Decision; revoked: boolean } | undefined => {
474
+ const reader = journal();
475
+ const made = reader?.find({ type: DecisionMade.name, field: "request", equals: request }).map((row) => DecisionMade.schema.parse(row.data)).find((one) => one.kind === "agent");
476
+ if (reader === undefined || made === undefined) return undefined;
477
+ return { decision: made, revoked: reader.find({ type: DecisionRevoked.name, field: "decision", equals: made.id }).length > 0 };
478
+ };
479
+
480
+ api.action(
481
+ action(delegateDecide, {
482
+ recovery: "repeat",
483
+ effect: "record",
484
+ world: "niwa",
485
+ run: async (input, ctx) => {
486
+ const { created } = requestNamed(input.request);
487
+ if (!same(created.to, self)) throw new DeniedError(`the request "${created.id}" is not put to ${opts.agent}`);
488
+ // The grant was checked against the area the caller named; it must be the request's own.
489
+ if (created.input.area !== input.area) {
490
+ throw new DeniedError(`the request "${created.id}" is about the area "${created.input.area ?? "(none)"}", not "${input.area}"`);
491
+ }
492
+ // A request is decided once. The same answer again, as a call made again, is the decision it made.
493
+ const prior = agentDecisionOf(created.id);
494
+ if (prior !== undefined) {
495
+ if (prior.revoked) throw new DeniedError(`the decision of the request "${created.id}" was revoked: the request did not take it`);
496
+ if (stableJson(prior.decision.answer) !== stableJson(input.answer)) throw new DeniedError(`the request "${created.id}" is already decided otherwise`);
497
+ return { decision: prior.decision.id };
498
+ }
499
+ const mismatch = answerMismatch(created.input, input.answer);
500
+ if (mismatch !== undefined) throw new ValidationError(`the answer is not one the question of "${created.id}" takes: ${mismatch}`);
501
+ const state = journal() === undefined ? undefined : stateAt(created.id, journal()!.last());
502
+ if (state?.status !== "open") throw new DeniedError(`the request "${created.id}" is ${state?.status ?? "unknown"}`);
503
+ const decision = decided(created, "agent", input.answer, input.grounds, bind(ctx.caller));
504
+ if (decision === undefined) throw new DeniedError(`the request "${created.id}" names no area to decide in`);
505
+ try {
506
+ await ctx.emit(DecisionMade, decision);
507
+ return { decision: decision.id };
508
+ } catch (error) {
509
+ if (!(error instanceof RecordRefused) || error.code !== "decided") throw error;
510
+ const winner = agentDecisionOf(created.id);
511
+ if (winner !== undefined && !winner.revoked && stableJson(winner.decision.answer) === stableJson(input.answer)) {
512
+ return { decision: winner.decision.id };
513
+ }
514
+ throw error;
515
+ }
516
+ },
517
+ }),
518
+ );
519
+
520
+ api.action(
521
+ action(delegateRecall, {
522
+ recovery: "repeat",
523
+ effect: "read",
524
+ world: "niwa",
525
+ run: async (input) => {
526
+ const found = recallOf(rowsOf(input.asOf === undefined ? undefined : seq(input.asOf)), input.question, input.input);
527
+ return found === undefined ? { found: false as const } : { found: true as const, answer: found.answer, area: found.area, decision: found.id };
528
+ },
529
+ }),
530
+ );
531
+
532
+ api.action(
533
+ action(delegateRevoke, {
534
+ recovery: "repeat",
535
+ effect: "record",
536
+ world: "niwa",
537
+ run: async (input, ctx) => {
538
+ const by = bind(ctx.caller);
539
+ if (by?.kind !== "owner") throw new DeniedError("only the owner may revoke a decision");
540
+ const id = ids.require(input.decision);
541
+ await ctx.emit(DecisionRevoked, { decision: id, by, ...(input.reason === undefined ? {} : { reason: input.reason }) });
542
+ return { decision: id };
543
+ },
544
+ }),
545
+ );
546
+
547
+ api.action(
548
+ action(delegateDecisionList, {
549
+ recovery: "repeat",
550
+ effect: "read",
551
+ world: "niwa",
552
+ run: async (input) => ({
553
+ items: decisionsOf(rowsOf())
554
+ .filter(({ decision }) => (input.area === undefined || decision.area === input.area) && (input.kind === undefined || decision.kind === input.kind))
555
+ .map(({ decision, revoked }) => ({
556
+ id: decision.id,
557
+ description: decision.description,
558
+ area: decision.area,
559
+ kind: decision.kind,
560
+ request: decision.request,
561
+ revoked,
562
+ })),
563
+ }),
564
+ }),
565
+ );
566
+
567
+ api.summarize(() => {
568
+ const all = decisionsOf(rowsOf());
569
+ return { decisions: all.filter((one) => !one.revoked).length, revoked: all.filter((one) => one.revoked).length };
570
+ });
571
+ });
572
+ }