@niwa-labs/commitments 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 +27 -2
- package/package.json +32 -4
- package/src/cockpit/actions.ts +37 -0
- package/src/cockpit/cards.ts +45 -0
- package/src/cockpit/index.tsx +19 -0
- package/src/cockpit/page.tsx +68 -0
- package/src/index.ts +478 -0
- package/src/records.ts +232 -0
- package/test/cockpit-actions.test.ts +37 -0
- package/test/cockpit-cards.test.ts +41 -0
- package/test/commitments.test.ts +443 -0
- package/test/queries.test.ts +41 -0
- package/test/replay.test.ts +83 -0
- package/tsconfig.json +15 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The commitments plugin: promises with a deadline, delivered to an agent's inbox when they come due,
|
|
3
|
+
* and done, missed or cancelled.
|
|
4
|
+
*
|
|
5
|
+
* Nothing is kept in memory: where a commitment stands is folded from the journal on every read. A
|
|
6
|
+
* handler decides as of the record that woke it, so a replay decides the same. The deadline is a
|
|
7
|
+
* sleep of the timers, asked through their action; the inbox is the agents plugin's, reached through
|
|
8
|
+
* `agent.notify`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
DeniedError,
|
|
13
|
+
EntityDescription,
|
|
14
|
+
IdIndex,
|
|
15
|
+
UnknownId,
|
|
16
|
+
action,
|
|
17
|
+
confirmOptions,
|
|
18
|
+
isYes,
|
|
19
|
+
recordId,
|
|
20
|
+
seq,
|
|
21
|
+
stableJson,
|
|
22
|
+
} from "@niwa-labs/core";
|
|
23
|
+
import type { ActionContext, Address, JournalReader, RecordId, Seq, Step, StoredRecord } from "@niwa-labs/core";
|
|
24
|
+
import { AGENT_BRIEFING, agentNotify } from "@niwa-labs/agent/records";
|
|
25
|
+
import { COCKPIT_MODULE, bindingOf, plugin } from "@niwa-labs/plugin";
|
|
26
|
+
import type { CallerBinding, MessagesOptions, Plugin } from "@niwa-labs/plugin";
|
|
27
|
+
import { REQUEST_TYPES, RequestCancelled, RequestCreated, RequestExpired, fold as foldRequest, requestAsk, requestCancel } from "@niwa-labs/requests/records";
|
|
28
|
+
import { TimerSlept, timerSleepRequest } from "@niwa-labs/timer/records";
|
|
29
|
+
import { fileURLToPath } from "node:url";
|
|
30
|
+
|
|
31
|
+
import type { z } from "zod";
|
|
32
|
+
|
|
33
|
+
import {
|
|
34
|
+
COMMITMENT_TYPES,
|
|
35
|
+
CONFIRM_QUESTION,
|
|
36
|
+
CommitmentCancelled,
|
|
37
|
+
CommitmentDeclined,
|
|
38
|
+
CommitmentDelivered,
|
|
39
|
+
CommitmentKept,
|
|
40
|
+
CommitmentMade,
|
|
41
|
+
CommitmentMissed,
|
|
42
|
+
CommitmentProposed,
|
|
43
|
+
ENDED,
|
|
44
|
+
MAX_MOMENT,
|
|
45
|
+
commitmentBriefing,
|
|
46
|
+
commitmentCancel,
|
|
47
|
+
commitmentDone,
|
|
48
|
+
commitmentGet,
|
|
49
|
+
commitmentList,
|
|
50
|
+
commitmentMake,
|
|
51
|
+
} from "./records.ts";
|
|
52
|
+
import type { CommitmentBasis, CommitmentEntity, CommitmentId, CommitmentStatus } from "./records.ts";
|
|
53
|
+
|
|
54
|
+
export * from "./records.ts";
|
|
55
|
+
|
|
56
|
+
/** The grace after a deadline before an open commitment is missed, by default: an hour. */
|
|
57
|
+
export const DEFAULT_GRACE_MS = 3_600_000;
|
|
58
|
+
|
|
59
|
+
export interface CommitmentsOptions {
|
|
60
|
+
/** What address a caller speaks as: the same binding the messages module uses. */
|
|
61
|
+
readonly messages?: MessagesOptions;
|
|
62
|
+
/** How long after its deadline a commitment that is not done is missed. */
|
|
63
|
+
readonly graceMs?: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A commitment was asked to do what its status does not allow: it ended, or it is still proposed. */
|
|
67
|
+
export class CommitmentClosed extends Error {
|
|
68
|
+
override name = "CommitmentClosed";
|
|
69
|
+
readonly code = "CommitmentClosed";
|
|
70
|
+
constructor(
|
|
71
|
+
readonly id: CommitmentId,
|
|
72
|
+
readonly status: CommitmentStatus,
|
|
73
|
+
) {
|
|
74
|
+
super(`the commitment "${id}" is ${status}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
type Terms = z.infer<typeof CommitmentProposed.schema>;
|
|
79
|
+
|
|
80
|
+
/** One commitment as the journal says it stands. */
|
|
81
|
+
interface Folded {
|
|
82
|
+
terms: Terms;
|
|
83
|
+
status: CommitmentStatus;
|
|
84
|
+
basis?: CommitmentBasis;
|
|
85
|
+
/** The record it was proposed in: the cause of the question put to the owner. */
|
|
86
|
+
proposal?: RecordId;
|
|
87
|
+
endedBy?: Address;
|
|
88
|
+
note?: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Where each commitment stands, from its records in the order they were written.
|
|
93
|
+
*
|
|
94
|
+
* An ended commitment stays as it ended: an answer of the owner that comes after a proposal was
|
|
95
|
+
* cancelled, or a wake after it was done, changes nothing.
|
|
96
|
+
*/
|
|
97
|
+
function fold(rows: readonly StoredRecord[]): Map<string, Folded> {
|
|
98
|
+
const all = new Map<string, Folded>();
|
|
99
|
+
for (const row of rows) {
|
|
100
|
+
if (row.type === CommitmentProposed.name) {
|
|
101
|
+
const terms = CommitmentProposed.schema.parse(row.data);
|
|
102
|
+
all.set(terms.id, { terms, status: "proposed", proposal: row.id });
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (row.type === CommitmentMade.name) {
|
|
106
|
+
const { basis, ...terms } = CommitmentMade.schema.parse(row.data);
|
|
107
|
+
const known = all.get(terms.id);
|
|
108
|
+
if (known === undefined) all.set(terms.id, { terms, status: "open", basis });
|
|
109
|
+
else if (known.status === "proposed") Object.assign(known, { terms, status: "open", basis });
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
const id = (row.data as { id?: string }).id;
|
|
113
|
+
const known = id === undefined ? undefined : all.get(id);
|
|
114
|
+
if (known === undefined) continue;
|
|
115
|
+
if (row.type === CommitmentDelivered.name && known.status === "open") known.status = "due";
|
|
116
|
+
else if (row.type === CommitmentMissed.name && (known.status === "due" || known.status === "open")) known.status = "missed";
|
|
117
|
+
else if (row.type === CommitmentDeclined.name && known.status === "proposed") known.status = "declined";
|
|
118
|
+
else if (row.type === CommitmentKept.name && (known.status === "open" || known.status === "due" || known.status === "missed")) {
|
|
119
|
+
const kept = CommitmentKept.schema.parse(row.data);
|
|
120
|
+
Object.assign(known, { status: known.status === "missed" ? "kept-late" : "kept", endedBy: kept.by, note: kept.note });
|
|
121
|
+
} else if (row.type === CommitmentCancelled.name && !ENDED.includes(known.status)) {
|
|
122
|
+
const cancelled = CommitmentCancelled.schema.parse(row.data);
|
|
123
|
+
Object.assign(known, { status: "cancelled", endedBy: cancelled.by, note: cancelled.reason });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return all;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function mayCancel(one: Folded, by: Address | undefined): boolean {
|
|
130
|
+
return by !== undefined && !ENDED.includes(one.status) && (same(by, OWNER) ||
|
|
131
|
+
(same(by, one.terms.by) && (one.terms.party === "self" || one.status === "proposed")));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The records of commitments, up to a position when one is given. */
|
|
135
|
+
function rowsOf(journal: JournalReader | undefined, upto?: Seq): StoredRecord[] {
|
|
136
|
+
const rows = journal?.since(seq(0), COMMITMENT_TYPES.map((type) => type.name)) ?? [];
|
|
137
|
+
return upto === undefined ? rows : rows.filter((row) => row.seq <= upto);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The record an action writes first: the one a commitment is born in, and the seed of its id. */
|
|
141
|
+
function birthOf(ctx: ActionContext): RecordId {
|
|
142
|
+
return recordId(`${ctx.operationId}/emit/1`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** A description a person reads in a list, made from the text when none was given. */
|
|
146
|
+
function describe(text: string): EntityDescription {
|
|
147
|
+
const line = (text.split("\n")[0] ?? "").trim();
|
|
148
|
+
const short = line.length > 60 ? `${line.slice(0, 59).trimEnd()}…` : line;
|
|
149
|
+
return EntityDescription.parse(short.length >= 3 ? short : "Commitment");
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Whether two addresses are the same. */
|
|
153
|
+
function same(a: Address | undefined, b: Address | undefined): boolean {
|
|
154
|
+
return a !== undefined && b !== undefined && stableJson(a) === stableJson(b);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const OWNER: Address = { kind: "owner" };
|
|
158
|
+
|
|
159
|
+
/** The key of a sleep of a commitment: its deadline, or the end of the grace after it. */
|
|
160
|
+
function sleepKeyOf(id: string, which: "due" | "grace"): string {
|
|
161
|
+
return `commitment:${id}:${which}`;
|
|
162
|
+
}
|
|
163
|
+
const SLEEP_KEY = /^commitment:(com-[0-9a-f]+):(due|grace)$/;
|
|
164
|
+
|
|
165
|
+
/** What a record says in words, and who it says wrote them, by the shape of the record that holds them. */
|
|
166
|
+
function wordsOf(row: StoredRecord | undefined): { text: string; author: { kind?: unknown } | undefined } | undefined {
|
|
167
|
+
const data = row?.data as
|
|
168
|
+
| { text?: unknown; body?: { text?: unknown }; from?: { kind?: unknown }; author?: { kind?: unknown } }
|
|
169
|
+
| null
|
|
170
|
+
| undefined;
|
|
171
|
+
if (data === null || data === undefined || typeof data !== "object") return undefined;
|
|
172
|
+
// A message, sent or received, holds its words in its body and its sender in `from`; a turn or a
|
|
173
|
+
// sentence a plugin relays holds them in `text`, with the author it names.
|
|
174
|
+
const text = typeof data.body?.text === "string" ? data.body.text : data.text;
|
|
175
|
+
if (typeof text !== "string" || text.trim().length === 0) return undefined;
|
|
176
|
+
return { text, author: typeof data.body?.text === "string" ? data.from : (data.author ?? data.from) };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* The owner's own words in a record, or nothing when it is not his: it has words, and he wrote it, or
|
|
181
|
+
* the plugin that wrote it says he is its author. What a client wrote names its author by the client
|
|
182
|
+
* alone: a client that may write a record could write any author into it.
|
|
183
|
+
*/
|
|
184
|
+
function ownersWords(row: StoredRecord | undefined): string | undefined {
|
|
185
|
+
const words = wordsOf(row);
|
|
186
|
+
if (row === undefined || words === undefined) return undefined;
|
|
187
|
+
if (row.actor.kind === "client") return row.actor.principal?.kind === "owner" && (words.author === undefined || words.author.kind === "owner") ? words.text : undefined;
|
|
188
|
+
return words.author?.kind === "owner" ? words.text : undefined;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** A text as it is compared when one is said to quote another: no case, one space between words, no closing mark. */
|
|
192
|
+
function plain(text: string): string {
|
|
193
|
+
return text.toLowerCase().replace(/\s+/g, " ").replace(/[\s.!?,;:]+$/, "").trim();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** When a moment is, as a person reads it. */
|
|
197
|
+
function when(at: number): string {
|
|
198
|
+
return new Date(at).toISOString().replace(/:\d\d\.\d{3}Z$/, "Z");
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** The commitments plugin. */
|
|
202
|
+
export function commitments(opts: CommitmentsOptions = {}): Plugin {
|
|
203
|
+
const bind: CallerBinding = bindingOf(opts.messages);
|
|
204
|
+
const grace = opts.graceMs ?? DEFAULT_GRACE_MS;
|
|
205
|
+
if (!Number.isSafeInteger(grace) || grace < 0) throw new RangeError(`graceMs is a number of milliseconds, not negative: ${String(grace)}`);
|
|
206
|
+
return plugin("commitments", (api) => {
|
|
207
|
+
api.declare(...COMMITMENT_TYPES);
|
|
208
|
+
// The cards of the commitments in the cockpit: a client module, offered by the path of its source.
|
|
209
|
+
api.offer(COCKPIT_MODULE, { id: "commitments", entry: fileURLToPath(new URL("./cockpit/index.tsx", import.meta.url)) });
|
|
210
|
+
const journal = () => api.journal?.();
|
|
211
|
+
const ids = new IdIndex("commitment", () =>
|
|
212
|
+
rowsOf(journal())
|
|
213
|
+
.filter((row) => row.type === CommitmentProposed.name || (row.type === CommitmentMade.name && (row.data as { basis: CommitmentBasis }).basis.kind !== "owner-confirmed"))
|
|
214
|
+
.map((row) => ({ id: (row.data as { id: string }).id, seed: String(row.id) })),
|
|
215
|
+
);
|
|
216
|
+
const current = () => fold(rowsOf(journal()));
|
|
217
|
+
const require = (text: string): Folded & { id: CommitmentId } => {
|
|
218
|
+
const id = ids.require(text);
|
|
219
|
+
const found = current().get(id);
|
|
220
|
+
if (found === undefined) throw new UnknownId(text, "commitment");
|
|
221
|
+
return { ...found, id };
|
|
222
|
+
};
|
|
223
|
+
/** Whether this very operation already wrote the record that ends the commitment: a call made again after it was cut off. */
|
|
224
|
+
const wrote = (ctx: ActionContext, type: typeof CommitmentKept | typeof CommitmentCancelled, id: CommitmentId): boolean => {
|
|
225
|
+
const born = journal()?.get(birthOf(ctx));
|
|
226
|
+
return born !== undefined && born.type === type.name && (born.data as { id?: string }).id === id;
|
|
227
|
+
};
|
|
228
|
+
const speaker = (ctx: ActionContext): Address => {
|
|
229
|
+
const address = bind(ctx.caller);
|
|
230
|
+
if (address === undefined) throw new DeniedError("a commitment is made and ended by someone who speaks as an address; this caller speaks as none");
|
|
231
|
+
return address;
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
api.action(
|
|
235
|
+
action(commitmentMake, {
|
|
236
|
+
recovery: "do-not-repeat",
|
|
237
|
+
effect: "record",
|
|
238
|
+
world: "niwa",
|
|
239
|
+
run: async (input, ctx) => {
|
|
240
|
+
const by = speaker(ctx);
|
|
241
|
+
if (input.due !== undefined && input.due + grace > MAX_MOMENT) {
|
|
242
|
+
throw new RangeError(`the deadline ${input.due} and the grace after it reach past the last moment a date holds`);
|
|
243
|
+
}
|
|
244
|
+
const terms: Terms = {
|
|
245
|
+
id: ids.issue(birthOf(ctx)),
|
|
246
|
+
text: input.text,
|
|
247
|
+
description: input.description ?? describe(input.text),
|
|
248
|
+
by,
|
|
249
|
+
to: input.to,
|
|
250
|
+
party: input.party,
|
|
251
|
+
...(input.due === undefined ? {} : { due: input.due }),
|
|
252
|
+
};
|
|
253
|
+
let basis: CommitmentBasis | undefined;
|
|
254
|
+
if (same(by, OWNER)) basis = { kind: "owner" };
|
|
255
|
+
else if (input.party === "self") basis = { kind: "own" };
|
|
256
|
+
else if (input.basis !== undefined) {
|
|
257
|
+
const said = ownersWords(journal()?.get(recordId(input.basis.record)));
|
|
258
|
+
if (said === undefined) {
|
|
259
|
+
throw new DeniedError(`"${input.basis.record}" is not a record of the owner's words: a promise for the owner stands only on his word`);
|
|
260
|
+
}
|
|
261
|
+
// His words carry the promise as he worded it. What an agent rewords, or a deadline it
|
|
262
|
+
// reads into them, is its own: it stands once he confirms the terms as they are now.
|
|
263
|
+
if (input.due === undefined && plain(said).includes(plain(input.text))) basis = input.basis;
|
|
264
|
+
}
|
|
265
|
+
if (basis === undefined) {
|
|
266
|
+
await ctx.emit(CommitmentProposed, terms);
|
|
267
|
+
return { id: terms.id, status: "proposed" as const };
|
|
268
|
+
}
|
|
269
|
+
await ctx.emit(CommitmentMade, { ...terms, basis });
|
|
270
|
+
return { id: terms.id, status: "open" as const };
|
|
271
|
+
},
|
|
272
|
+
}),
|
|
273
|
+
);
|
|
274
|
+
|
|
275
|
+
api.action(
|
|
276
|
+
action(commitmentDone, {
|
|
277
|
+
recovery: "repeat",
|
|
278
|
+
effect: "record",
|
|
279
|
+
world: "niwa",
|
|
280
|
+
run: async (input, ctx) => {
|
|
281
|
+
const found = require(input.id);
|
|
282
|
+
// Made again under the operation that already did it, it answers as it did.
|
|
283
|
+
if (wrote(ctx, CommitmentKept, found.id)) return { id: found.id, status: found.status };
|
|
284
|
+
if (found.status !== "open" && found.status !== "due" && found.status !== "missed") throw new CommitmentClosed(found.id, found.status);
|
|
285
|
+
const by = speaker(ctx);
|
|
286
|
+
if (!same(by, OWNER) && !same(by, found.terms.by)) throw new DeniedError("only the one who made a commitment, or the owner, may say it is done");
|
|
287
|
+
await ctx.emit(CommitmentKept, { id: found.id, basedOn: found.status, by, ...(input.note === undefined ? {} : { note: input.note }) });
|
|
288
|
+
return { id: found.id, status: found.status === "missed" ? "kept-late" as const : "kept" as const };
|
|
289
|
+
},
|
|
290
|
+
}),
|
|
291
|
+
);
|
|
292
|
+
|
|
293
|
+
api.action(
|
|
294
|
+
action(commitmentCancel, {
|
|
295
|
+
recovery: "repeat",
|
|
296
|
+
effect: "record",
|
|
297
|
+
world: "niwa",
|
|
298
|
+
run: async (input, ctx) => {
|
|
299
|
+
const found = require(input.id);
|
|
300
|
+
if (wrote(ctx, CommitmentCancelled, found.id)) return { id: found.id, status: "cancelled" as const };
|
|
301
|
+
if (found.status !== "open" && found.status !== "due" && found.status !== "proposed") throw new CommitmentClosed(found.id, found.status);
|
|
302
|
+
const by = speaker(ctx);
|
|
303
|
+
if (!mayCancel(found, by)) {
|
|
304
|
+
throw new DeniedError(
|
|
305
|
+
found.terms.party === "owner"
|
|
306
|
+
? "only the owner may cancel a commitment made for him"
|
|
307
|
+
: "only the one who made a commitment, or the owner, may cancel it",
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
await ctx.emit(CommitmentCancelled, { id: found.id, basedOn: found.status, by, ...(input.reason === undefined ? {} : { reason: input.reason }) });
|
|
311
|
+
return { id: found.id, status: "cancelled" as const };
|
|
312
|
+
},
|
|
313
|
+
}),
|
|
314
|
+
);
|
|
315
|
+
|
|
316
|
+
const entityOf = (found: Folded): CommitmentEntity => ({
|
|
317
|
+
...found.terms,
|
|
318
|
+
id: found.terms.id,
|
|
319
|
+
status: found.status,
|
|
320
|
+
...(found.basis === undefined ? {} : { basis: found.basis }),
|
|
321
|
+
...(found.endedBy === undefined ? {} : { endedBy: found.endedBy }),
|
|
322
|
+
...(found.note === undefined ? {} : { note: found.note }),
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
api.action(
|
|
326
|
+
action(commitmentList, {
|
|
327
|
+
recovery: "repeat",
|
|
328
|
+
effect: "read",
|
|
329
|
+
world: "niwa",
|
|
330
|
+
run: async (input, ctx) => ({
|
|
331
|
+
items: [...current().values()]
|
|
332
|
+
.filter((one) => (input.status === undefined || one.status === input.status) && (input.to === undefined || one.terms.to === input.to))
|
|
333
|
+
.map((one) => ({
|
|
334
|
+
id: one.terms.id,
|
|
335
|
+
description: one.terms.description,
|
|
336
|
+
by: one.terms.by,
|
|
337
|
+
canCancel: mayCancel(one, bind(ctx.caller)),
|
|
338
|
+
status: one.status,
|
|
339
|
+
party: one.terms.party,
|
|
340
|
+
to: one.terms.to,
|
|
341
|
+
...(one.terms.due === undefined ? {} : { due: one.terms.due }),
|
|
342
|
+
})),
|
|
343
|
+
}),
|
|
344
|
+
}),
|
|
345
|
+
);
|
|
346
|
+
|
|
347
|
+
api.action(
|
|
348
|
+
action(commitmentGet, {
|
|
349
|
+
recovery: "repeat",
|
|
350
|
+
effect: "read",
|
|
351
|
+
world: "niwa",
|
|
352
|
+
run: async (input) => {
|
|
353
|
+
const found = require(input.id);
|
|
354
|
+
return entityOf(found);
|
|
355
|
+
},
|
|
356
|
+
}),
|
|
357
|
+
);
|
|
358
|
+
|
|
359
|
+
// The section of an agent's briefing: what it is to deliver and what it promised, not yet ended.
|
|
360
|
+
api.offer(AGENT_BRIEFING, { title: "Commitments", action: commitmentBriefing.name });
|
|
361
|
+
api.action(
|
|
362
|
+
action(commitmentBriefing, {
|
|
363
|
+
recovery: "repeat",
|
|
364
|
+
effect: "read",
|
|
365
|
+
world: "niwa",
|
|
366
|
+
run: async ({ agent }) => {
|
|
367
|
+
const self: Address = { kind: "agent", id: agent };
|
|
368
|
+
const lines = [...current().values()]
|
|
369
|
+
.filter((one) => !ENDED.includes(one.status) && (one.terms.to === agent || same(one.terms.by, self)))
|
|
370
|
+
.map((one) => `${one.terms.id} ${one.status} ${one.terms.due === undefined ? "no deadline" : `due ${when(one.terms.due)}`} ${one.terms.description}`);
|
|
371
|
+
return { text: lines.join("\n") };
|
|
372
|
+
},
|
|
373
|
+
}),
|
|
374
|
+
);
|
|
375
|
+
|
|
376
|
+
/** Whether a proposal still waits for the owner, as the journal says now: an answer to one that ended decides nothing. */
|
|
377
|
+
const stillProposed = (id: CommitmentId): boolean => current().get(id)?.status === "proposed";
|
|
378
|
+
// A proposal is put to the owner. The asks wait side by side: one he leaves open holds no other.
|
|
379
|
+
api.on(CommitmentProposed, { id: "commitment-confirm", concurrency: Infinity }, async (terms, step) => {
|
|
380
|
+
const due = terms.due === undefined ? "" : ` by ${when(terms.due)}`;
|
|
381
|
+
try {
|
|
382
|
+
const asked = await step(requestAsk, {
|
|
383
|
+
to: OWNER,
|
|
384
|
+
answerPolicy: "owner-only",
|
|
385
|
+
question: CONFIRM_QUESTION,
|
|
386
|
+
input: {
|
|
387
|
+
kind: "confirm",
|
|
388
|
+
title: `Promise for you${due}: ${terms.text}`,
|
|
389
|
+
detail: `Proposed by ${terms.by.kind === "agent" ? `agent ${terms.by.id}` : terms.by.kind} as ${terms.id}. It stands only if you confirm it.`,
|
|
390
|
+
options: confirmOptions(),
|
|
391
|
+
allowOther: false,
|
|
392
|
+
},
|
|
393
|
+
from: terms.by,
|
|
394
|
+
});
|
|
395
|
+
if (!("answer" in asked)) return;
|
|
396
|
+
// The owner's confirmation is his own answer: a resolver that found one for him did not ask him.
|
|
397
|
+
if (!stillProposed(terms.id)) return;
|
|
398
|
+
if (isYes(asked.answer)) await step.emit(CommitmentMade, { ...terms, basis: { kind: "owner-confirmed", request: asked.id } });
|
|
399
|
+
else await step.emit(CommitmentDeclined, { id: terms.id, request: asked.id });
|
|
400
|
+
} catch (error) {
|
|
401
|
+
if (!(error instanceof RequestCancelled) && !(error instanceof RequestExpired)) throw error;
|
|
402
|
+
// A proposal its author withdrew is not one the owner refused.
|
|
403
|
+
if (stillProposed(terms.id)) await step.emit(CommitmentDeclined, { id: terms.id, request: error.request });
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
/** The question that confirms a proposal, when it was asked before `at` and is still open then. */
|
|
408
|
+
const openConfirmation = (proposal: RecordId, at: Seq): z.infer<typeof RequestCreated.schema> | undefined => {
|
|
409
|
+
const reader = journal();
|
|
410
|
+
const asked = reader?.since(seq(0), [RequestCreated.name]).find((row) => row.seq <= at && row.cause === proposal);
|
|
411
|
+
if (reader === undefined || asked === undefined) return undefined;
|
|
412
|
+
const created = RequestCreated.schema.parse(asked.data);
|
|
413
|
+
const ended = reader.since(asked.seq, REQUEST_TYPES.map((type) => type.name)).filter((row) => row.seq <= at && (row.data as { id?: string }).id === created.id);
|
|
414
|
+
return foldRequest([asked, ...ended], bind).get(created.id)?.status === "open" ? created : undefined;
|
|
415
|
+
};
|
|
416
|
+
const withdraw = async (step: Step, request: z.infer<typeof RequestCreated.schema>, by: Address) => {
|
|
417
|
+
await step.outcome(requestCancel, { id: request.id, reason: "the proposed commitment was cancelled", by });
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
// A cancelled proposal takes its question with it, whether it was asked before the cancel ...
|
|
421
|
+
api.on(CommitmentCancelled, { id: "commitment-withdraw" }, async (data, step, at) => {
|
|
422
|
+
const found = fold(rowsOf(journal(), at.seq)).get(data.id);
|
|
423
|
+
if (found?.proposal === undefined || found.basis !== undefined) return;
|
|
424
|
+
const open = openConfirmation(found.proposal, at.seq);
|
|
425
|
+
if (open !== undefined) await withdraw(step, open, found.terms.by);
|
|
426
|
+
});
|
|
427
|
+
// ... or asked after it.
|
|
428
|
+
api.on(RequestCreated, { id: "commitment-withdraw-late", filter: { question: CONFIRM_QUESTION } }, async (created, step, at) => {
|
|
429
|
+
if (at.cause === null) return;
|
|
430
|
+
const proposal = journal()?.get(at.cause);
|
|
431
|
+
if (proposal?.type !== CommitmentProposed.name) return;
|
|
432
|
+
const found = fold(rowsOf(journal(), at.seq)).get(CommitmentProposed.schema.parse(proposal.data).id);
|
|
433
|
+
if (found?.status === "cancelled") await withdraw(step, created, found.terms.by);
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
// A commitment with a deadline sleeps until it.
|
|
437
|
+
api.on(CommitmentMade, { id: "commitment-due" }, async (made, step) => {
|
|
438
|
+
if (made.due === undefined) return;
|
|
439
|
+
await step(timerSleepRequest, { at: made.due, key: sleepKeyOf(made.id, "due") });
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
// At the deadline an open commitment is told to its agent; after the grace one that is not done is
|
|
443
|
+
// missed, delivered or not. Each is decided as of its own wake, so the wakes run side by side, and
|
|
444
|
+
// an inbox that cannot be reached is a failed outcome that stops no other wake: the commitment
|
|
445
|
+
// is not delivered, and the grace still ends it.
|
|
446
|
+
api.on(TimerSlept, { id: "commitment-wake", requires: [TimerSlept], concurrency: Infinity }, async (wake, step, at) => {
|
|
447
|
+
const matched = SLEEP_KEY.exec(wake.key);
|
|
448
|
+
if (matched === null) return;
|
|
449
|
+
const [, id, which] = matched;
|
|
450
|
+
const found = id === undefined ? undefined : fold(rowsOf(journal(), at.seq)).get(id);
|
|
451
|
+
const due = found?.terms.due;
|
|
452
|
+
if (id === undefined || found === undefined || due === undefined) return;
|
|
453
|
+
// Done or cancelled after the wake was recorded, before this ran: that came first, and nothing
|
|
454
|
+
// the wake would say is true any more.
|
|
455
|
+
const outrun = (): boolean => {
|
|
456
|
+
const status = current().get(id)?.status;
|
|
457
|
+
return status === "kept" || status === "cancelled";
|
|
458
|
+
};
|
|
459
|
+
if (which === "due" && found.status === "open") {
|
|
460
|
+
if (outrun()) return;
|
|
461
|
+
const told = await step.outcome(agentNotify, { agent: found.terms.to, text: `Commitment ${found.terms.id} is due now: ${found.terms.text}` });
|
|
462
|
+
if (outrun()) return;
|
|
463
|
+
if (told.status === "completed") await step.emit(CommitmentDelivered, { id: found.terms.id, due, at: at.at });
|
|
464
|
+
await step(timerSleepRequest, { at: due + grace, key: sleepKeyOf(found.terms.id, "grace") });
|
|
465
|
+
} else if (which === "grace" && (found.status === "due" || found.status === "open")) {
|
|
466
|
+
if (outrun()) return;
|
|
467
|
+
await step.emit(CommitmentMissed, { id: found.terms.id, due, at: at.at });
|
|
468
|
+
await step.outcome(agentNotify, { agent: found.terms.to, text: `Commitment ${found.terms.id} was missed: ${found.terms.text}` });
|
|
469
|
+
}
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
api.summarize(() => {
|
|
473
|
+
const counts: Record<string, number> = {};
|
|
474
|
+
for (const one of current().values()) counts[one.status] = (counts[one.status] ?? 0) + 1;
|
|
475
|
+
return counts;
|
|
476
|
+
});
|
|
477
|
+
});
|
|
478
|
+
}
|