@niwa-labs/rin 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/plugin.ts ADDED
@@ -0,0 +1,1071 @@
1
+ /**
2
+ * The Rin plugin: her definition, her attention, the corrections she learns from and her charter, on a host.
3
+ *
4
+ * Rin is an agent of the agents module (`agent:rin`); this plugin offers her definition and adds what makes her
5
+ * Rin. Something that happened reaches her as an occasion (`rin.notice`, and the occasions she follows herself:
6
+ * a stuck agent, a run she started that finished); she decides in her main session what to do about it
7
+ * (`rin.attend`), and the plugin carries the decision out: it holds what waits for the owner's next contact or
8
+ * for the end of his quiet hours, tells him now through the configured delivery action, and brings up
9
+ * what waits when he writes to her or attaches a session.
10
+ *
11
+ * His corrections are written down (`rin.corrected`), whether he says them, she writes them from his words, or he
12
+ * acts them out: changes a note of hers, cancels what she promised or decided, turns down or leaves unanswered
13
+ * what she asked, waves away what she told him. Corrections about one thing that repeat ask her for a rule; the
14
+ * rule she words is put to him, and only his yes makes it part of her charter.
15
+ *
16
+ * What she does reaches nobody with the rights of whoever told her something: the plugin's handlers carry her
17
+ * decisions out, and her own actions check that it is she, or the owner, who calls them.
18
+ */
19
+
20
+ import { createHash } from "node:crypto";
21
+ import { readFile } from "node:fs/promises";
22
+ import { isAbsolute } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+
25
+ import { CORE_TYPES, OptionIdSchema, RecordRefused, action, actionName, agent as agentAddress, owner, recordId, seq } from "@niwa-labs/core";
26
+ import type { Address, Caller, JournalReader, Outcome, RecordType, Step, StoredRecord } from "@niwa-labs/core";
27
+ import { AGENT, COCKPIT_MODULE, plugin, trigger } from "@niwa-labs/plugin";
28
+ import type { CallerBinding, Plugin, PluginApi } from "@niwa-labs/plugin";
29
+ import { AGENT_BRIEFING, AGENT_PROMPT_SECTION, AgentAttached, AgentTurnDelivered, AgentTurnFailed, AgentTurnQueued, AgentTurnReplied, agentNotify, agentReply, agentTell } from "@niwa-labs/agent/records";
30
+ import type { TurnAuthor } from "@niwa-labs/agent/records";
31
+ import { CommitmentCancelled, CommitmentMade } from "@niwa-labs/commitments/records";
32
+ import { DecisionMade, DecisionRevoked } from "@niwa-labs/delegate/records";
33
+ import { NoteCorrected, NoteErased, NoteRetracted, NoteWritten, memoryConsolidate } from "@niwa-labs/memory/records";
34
+ import { Message as MessageEnvelope, MessageReceived, MessageSent, contentText } from "@niwa-labs/messages/records";
35
+ import type { Message } from "@niwa-labs/messages/records";
36
+ import { RequestAnswered, RequestCancelled, RequestCancelledRecord, RequestCreated, RequestExpired, RequestExpiredRecord, answeredBy, question, requestAsk } from "@niwa-labs/requests/records";
37
+ import { timer } from "@niwa-labs/timer";
38
+ import { RunFinished, RunRequested } from "@niwa-labs/workflow/records";
39
+
40
+ import {
41
+ DEFAULT_CEILING,
42
+ DEFAULT_QUIET,
43
+ briefingText,
44
+ ceilingLeft,
45
+ foldAttention,
46
+ heldItems,
47
+ inQuietHours,
48
+ insistRefusal,
49
+ itemView,
50
+ noticeOf,
51
+ openOccasions,
52
+ pendingAbout,
53
+ repeatRefusal,
54
+ quietEnds,
55
+ routeOf,
56
+ sayNow,
57
+ ATTACHED,
58
+ } from "./attention.ts";
59
+ import type { AttentionState, Ceiling, Item, QuietHours, Row } from "./attention.ts";
60
+ import { DEFAULT_RULE_AFTER, charterText, correctionView, dueFor, foldCharter, ruleView, ruledRules } from "./charter.ts";
61
+ import type { CharterState, Correction } from "./charter.ts";
62
+ import { RIN_AGENT, rinDefinition } from "./character.ts";
63
+ import type { Core } from "./character.ts";
64
+ import { PRESENCE_TYPES, workingNow } from "./presence.ts";
65
+ import {
66
+ AttentionBrought,
67
+ AttentionDecided,
68
+ AttentionDismissed,
69
+ AttentionDropped,
70
+ AttentionHeld,
71
+ AttentionSaid,
72
+ AttentionSending,
73
+ AttentionUnsure,
74
+ CharterDeclined,
75
+ CharterDue,
76
+ CharterProposed,
77
+ CharterRetired,
78
+ CharterRuled,
79
+ Corrected,
80
+ OccasionClaimed,
81
+ OccasionEnded,
82
+ OccasionIgnored,
83
+ OccasionNotified,
84
+ OccasionOpened,
85
+ OccasionRepeated,
86
+ RIN_TYPES,
87
+ SelfEditClaimed,
88
+ SelfEditMode,
89
+ SelfEditProposed,
90
+ SelfEditSettled,
91
+ pluginInstall,
92
+ rinAttend,
93
+ rinAttention,
94
+ rinBriefing,
95
+ rinCharter,
96
+ rinCharterPropose,
97
+ rinCharterRetire,
98
+ rinContext,
99
+ rinConversation,
100
+ rinCorrect,
101
+ rinDismiss,
102
+ rinInbox,
103
+ rinNotice,
104
+ rinPromptCharter,
105
+ rinSelfHistory,
106
+ rinSelfInstall,
107
+ } from "./records.ts";
108
+ import type { Contact, Delivery, NoteChange, OccasionId, Subject, Topic } from "./records.ts";
109
+
110
+ /** What the Rin plugin is made with. */
111
+ export interface RinOptions {
112
+ /**
113
+ * The address a caller speaks as: the binding the composition gives the messages module, so a session of Rin
114
+ * speaks as `agent:rin` and the owner's client as the owner.
115
+ */
116
+ readonly bind: CallerBinding;
117
+ /** The harness installation her sessions run on, or the role the composition maps to one: exactly one. */
118
+ readonly harness?: string;
119
+ readonly role?: string;
120
+ /** Policy for module installs proposed by Rin. Default: off. */
121
+ readonly selfEdit?: SelfEditMode;
122
+ /** The core of her character; the one of this package unless the owner gives his own. */
123
+ readonly core?: Core;
124
+ /** The owner's quiet hours, local time. Default 23:00 to 08:00. */
125
+ readonly quietHours?: QuietHours;
126
+ /** The safety ceiling on what she says now. Default: twelve in any 24 hours. */
127
+ readonly ceiling?: Ceiling;
128
+ /** Enable Telegram delivery and require telegram.send at host startup. */
129
+ readonly telegram?: boolean;
130
+ /** Action for proactive messages, given `{ text }`. Uses Telegram when enabled. */
131
+ readonly say?: string;
132
+ /** How many corrections about one thing, not covered by a rule, ask her for one. Default: two. */
133
+ readonly ruleAfter?: number;
134
+ }
135
+
136
+ /** A refusal of Rin's: a caller that is neither she nor the owner, or a decision that does not hold. */
137
+ export class RinRefusal extends Error {
138
+ override name = "RinRefusal";
139
+ constructor(
140
+ readonly code: "not-rin" | "not-owner" | "unknown" | "no-text" | "already-said" | "insist" | "open-proposal" | "not-his-words" | "self-edit-off" | "not-her-group" | "unreachable",
141
+ message: string,
142
+ ) {
143
+ super(message);
144
+ }
145
+ }
146
+
147
+ /** An id of a kind, cut from what makes it unique, so a repeat makes the same id. */
148
+ function idOf<P extends string>(prefix: P, seed: string): `${P}-${string}` {
149
+ return `${prefix}-${createHash("sha256").update(seed).digest("hex").slice(0, 10)}`;
150
+ }
151
+
152
+ /** The first line of a text, cut to fit a line of a list. */
153
+ function firstLine(text: string, max = 160): string {
154
+ const line = text.split(/\r?\n/, 1)[0]?.trim() ?? "";
155
+ return line.length <= max ? line : `${line.slice(0, max - 1).trimEnd()}…`;
156
+ }
157
+
158
+ /** The record types her attention is folded from. */
159
+ const ATTENTION_TYPES = [OccasionOpened, OccasionRepeated, OccasionEnded, AttentionDecided, AttentionHeld, AttentionSending, AttentionSaid, AttentionUnsure, AttentionBrought, AttentionDropped, AttentionDismissed].map((type) => type.name as string);
160
+ const CHARTER_TYPES = [Corrected, CharterDue, CharterProposed, CharterRuled, CharterDeclined, CharterRetired].map((type) => type.name as string);
161
+
162
+ /** The choices of a question to the owner that only his yes settles. */
163
+ const CONFIRM = OptionIdSchema.parse("confirm");
164
+ const DECLINE = OptionIdSchema.parse("decline");
165
+ function confirmQuestion(name: string, title: string) {
166
+ return question(name, {
167
+ kind: "choice",
168
+ title,
169
+ options: [
170
+ { id: CONFIRM, label: "confirm", flavor: "plain" },
171
+ { id: DECLINE, label: "decline", flavor: "plain" },
172
+ ],
173
+ });
174
+ }
175
+ /** The question that puts a rule of the charter to the owner. */
176
+ const ruleQuestion = (text: string, about: string) => confirmQuestion("rin.charter.confirm", `Rin proposes a rule for her charter (${about}): ${text}`);
177
+
178
+ /** How a question that only the owner's yes settles ended. */
179
+ type Verdict = "confirmed" | "declined" | "cancelled" | "expired";
180
+
181
+ /** Recover this handler's exact install without running module code again. */
182
+ function recordedInstall(log: JournalReader, actor: Extract<Caller, { kind: "handler" }>, input: { plugin: string; module: string; hash: string }): Outcome<unknown> | undefined {
183
+ const own = (row: StoredRecord) => row.actor.kind === "handler" && row.actor.handler === actor.handler && row.actor.invocation === actor.invocation;
184
+ const intents = log.find({ type: CORE_TYPES.stepIntent, field: "invocation", equals: actor.invocation });
185
+ const intent = intents.findLast((row) => own(row) && (row.data as { key: string }).key === "install");
186
+ if (intent === undefined) return undefined;
187
+ const call = intent.data as { action: string; operationId: string; input: typeof input };
188
+ if (call.action !== pluginInstall.name || call.input.plugin !== input.plugin || call.input.module !== input.module || call.input.hash !== input.hash) {
189
+ return { status: "unknown" };
190
+ }
191
+ const receipt = log.get(recordId(`${call.operationId}/installed`));
192
+ if (receipt?.type === CORE_TYPES.pluginInstalled && own(receipt)) {
193
+ const saved = receipt.data as typeof input;
194
+ if (saved.plugin === input.plugin && saved.module === input.module && saved.hash === input.hash) return { status: "completed", value: undefined };
195
+ return { status: "unknown" };
196
+ }
197
+ const ended = log.find({ type: CORE_TYPES.stepOutcome, field: "invocation", equals: actor.invocation })
198
+ .findLast((row) => own(row) && row.seq > intent.seq && (row.data as { key: string }).key === "install");
199
+ const result = (ended?.data as { outcome: Outcome<unknown> } | undefined)?.outcome;
200
+ return result === undefined || result.status === "completed" ? { status: "unknown" } : result;
201
+ }
202
+
203
+ /** A message the owner wrote to Rin: a contact, and his own words. */
204
+ const ToRin = { "to.kind": "agent", "to.id": RIN_AGENT, "from.kind": "owner" } as const;
205
+ const OwnerWroteToRin = trigger(MessageSent, { name: "message.sent:owner-to-rin", filter: ToRin });
206
+ const OwnerWroteInToRin = trigger(MessageReceived, { name: "message.received:owner-to-rin", filter: ToRin });
207
+
208
+ /** The Rin plugin. Install it after the agents module, which serves her, and with the plugins whose records she follows. */
209
+ export function rinPlugin(options: RinOptions): Plugin {
210
+ const selfEdit = SelfEditMode.parse(options.selfEdit ?? "off");
211
+ const definition = rinDefinition({
212
+ ...(options.harness === undefined ? {} : { harness: options.harness }),
213
+ ...(options.role === undefined ? {} : { role: options.role }),
214
+ selfEdit,
215
+ ...(options.core === undefined ? {} : { core: options.core }),
216
+ });
217
+ const quiet = options.quietHours ?? DEFAULT_QUIET;
218
+ const ceiling = options.ceiling ?? DEFAULT_CEILING;
219
+ const sendAction = options.say ?? (options.telegram ? "telegram.send" : undefined);
220
+ const say = sendAction === undefined ? undefined : actionName(sendAction);
221
+ const ruleAfter = options.ruleAfter ?? DEFAULT_RULE_AFTER;
222
+ const bind = options.bind;
223
+ const quietEnd = timer.daily(quiet.to, { id: "rin-quiet-end", description: "The end of the owner's quiet hours" });
224
+
225
+ return plugin("rin", (api: PluginApi) => {
226
+ api.declare(...RIN_TYPES);
227
+ api.needs({
228
+ actions: [
229
+ agentNotify, agentTell, agentReply, requestAsk, memoryConsolidate,
230
+ ...(say === undefined ? [] : [say]),
231
+ ...(options.telegram ? ["telegram.send"] : []),
232
+ ...(selfEdit === "off" ? [] : [pluginInstall]),
233
+ ],
234
+ types: [AgentTurnReplied],
235
+ });
236
+ api.offer(AGENT, definition);
237
+ api.offer(AGENT_BRIEFING, { title: "What Rin holds for you", action: rinBriefing.name });
238
+ // Her charter is part of the prompt of her sessions, read when each one starts: a rule confirmed since reaches the next.
239
+ api.offer(AGENT_PROMPT_SECTION, { id: "charter", agent: RIN_AGENT, action: rinPromptCharter.name });
240
+ // Her page in the cockpit: a client module, offered by the path of its source.
241
+ api.offer(COCKPIT_MODULE, { id: "rin", entry: fileURLToPath(new URL("./cockpit/index.tsx", import.meta.url)) });
242
+
243
+ const journal = (): JournalReader | undefined => api.journal?.();
244
+ const rowsOf = (types: readonly string[]): Row[] =>
245
+ (journal()?.since(seq(0), types as never) ?? []).map((stored) => ({ type: stored.type, data: stored.data, at: stored.at, seq: stored.seq }));
246
+ const attention = (): AttentionState => foldAttention(rowsOf([...ATTENTION_TYPES, ATTACHED]), RIN_AGENT);
247
+ const charter = (): CharterState => foldCharter(rowsOf(CHARTER_TYPES));
248
+ const ruledIds = () => new Set<string>(ruledRules(charter()).map((rule) => rule.rule));
249
+
250
+ /** Wait for the answer requests accepts through an authenticated owner connection. */
251
+ const askOwner = async (step: Step, asking: ReturnType<typeof confirmQuestion>, key: string): Promise<Verdict> => {
252
+ try {
253
+ const { answer } = answeredBy(await step(requestAsk, { to: owner, answerPolicy: "owner-only", ...asking }, { key }));
254
+ return "ids" in answer && answer.ids[0] === CONFIRM ? "confirmed" : "declined";
255
+ } catch (error) {
256
+ if (error instanceof RequestCancelled) return "cancelled";
257
+ if (error instanceof RequestExpired) return "expired";
258
+ throw error;
259
+ }
260
+ };
261
+
262
+ // The clock of the host, once it serves.
263
+ let clock: (() => number) | undefined;
264
+ api.service((ctx) => {
265
+ clock = () => ctx.now();
266
+ return () => {
267
+ clock = undefined;
268
+ };
269
+ });
270
+ const now = (): number => {
271
+ if (clock === undefined) throw new Error("rin: the host is not serving");
272
+ return clock();
273
+ };
274
+
275
+ /** Who a caller is to Rin: she, the owner, or anybody else. */
276
+ const whoIs = (caller: Caller): "rin" | "owner" | "other" => {
277
+ const address = bind(caller);
278
+ if (address?.kind === "owner") return "owner";
279
+ if (address?.kind === "agent" && address.id === RIN_AGENT) return "rin";
280
+ return "other";
281
+ };
282
+ /** The author a record of hers names: the caller's address, or niwa's own. */
283
+ const authorOf = (caller: Caller): TurnAuthor => {
284
+ if (caller.kind === "handler") return { kind: "niwa", by: String(caller.handler) };
285
+ if (caller.kind === "host") return { kind: "niwa", by: "host" };
286
+ return bind(caller) ?? { kind: "niwa", by: String(caller.id) };
287
+ };
288
+
289
+ /** What she weighs before she speaks, as text that goes with every occasion she is told. */
290
+ const contextText = (at: number): string => {
291
+ const lines: string[] = [];
292
+ const working = workingNow(rowsOf(PRESENCE_TYPES));
293
+ lines.push(
294
+ working.length === 0
295
+ ? "The owner is not working in an attached session now."
296
+ : `The owner is working now: ${working.map((one) => `${one.session} in ${one.cwd}`).join("; ")}.`,
297
+ );
298
+ const ends = quietEnds(at, quiet);
299
+ if (ends !== undefined) lines.push(`These are his quiet hours, until ${quiet.to}: what you say now waits until then.`);
300
+ const left = ceilingLeft(attention().said, at, ceiling);
301
+ if (left === 0) lines.push("The safety ceiling is reached: what you say now waits for his next contact.");
302
+ const rules = charterText(ruledRules(charter()));
303
+ lines.push(rules === "" ? "Your charter has no rules yet." : `Your charter:\n${rules}`);
304
+ return lines.join("\n");
305
+ };
306
+
307
+ // Serialize attention routing for the shared ceiling and for items brought at owner contact.
308
+ // Occasion and charter transitions are admitted by the journal.
309
+ let tail: Promise<unknown> = Promise.resolve();
310
+ const serially = <T>(work: () => Promise<T>): Promise<T> => {
311
+ const run = tail.then(work, work);
312
+ tail = run.catch(() => undefined);
313
+ return run;
314
+ };
315
+
316
+ // ---- occasions -----------------------------------------------------------------------------------------
317
+
318
+ /** Write a notice against the open occurrence of its key. On replay it keeps its first outcome. */
319
+ const notice = async (
320
+ emit: <T>(type: RecordType<T>, data: T, key: string) => Promise<StoredRecord>,
321
+ input: { key: string; kind: string; text: string; ends?: boolean },
322
+ from: TurnAuthor,
323
+ seed: string,
324
+ ): Promise<{ occasion?: OccasionId; status: "opened" | "repeated" | "ended" | "none" }> => {
325
+ const committed = [
326
+ [OccasionOpened, "opened"], [OccasionRepeated, "repeated"],
327
+ [OccasionEnded, "ended"], [OccasionIgnored, "none"],
328
+ ] as const;
329
+ for (const [type, status] of committed) {
330
+ const row = journal()?.find({ type: type.name, field: "notice", equals: seed })[0];
331
+ if (row === undefined) continue;
332
+ const data = type.schema.parse(row.data);
333
+ return { status, ...("occasion" in data && typeof data.occasion === "string" ? { occasion: data.occasion } : {}) };
334
+ }
335
+
336
+ const found = noticeOf(attention(), input);
337
+ const data = { key: input.key, notice: seed, text: input.text, from };
338
+ switch (found.kind) {
339
+ case "open": {
340
+ const occasion = idOf("occ", seed);
341
+ await emit(OccasionOpened, { ...data, occasion, kind: input.kind }, `open-${occasion}`);
342
+ return { occasion, status: "opened" };
343
+ }
344
+ case "repeat":
345
+ await emit(OccasionRepeated, { ...data, occasion: found.occasion }, `repeat-${found.occasion}`);
346
+ return { occasion: found.occasion, status: "repeated" };
347
+ case "end":
348
+ await emit(OccasionEnded, { ...data, occasion: found.occasion }, `end-${found.occasion}`);
349
+ return { occasion: found.occasion, status: "ended" };
350
+ case "none":
351
+ await emit(OccasionIgnored, { key: input.key, notice: seed }, "ignore");
352
+ return { status: "none" };
353
+ }
354
+ };
355
+
356
+ api.action(
357
+ action(rinNotice, {
358
+ // The occasion's id is cut from the operation, and each record it writes follows the operation.
359
+ recovery: "repeat",
360
+ effect: "record",
361
+ world: "niwa",
362
+ run: (input, ctx) => notice((type, data) => ctx.emit(type, data), input, authorOf(ctx.caller), String(ctx.operationId)),
363
+ }),
364
+ );
365
+
366
+ // A new occasion reaches her inbox as a fact, with what she weighs before she decides. The plugin tells her,
367
+ // not whoever noticed it: telling an agent is no right of theirs.
368
+ api.on(OccasionOpened, { concurrency: { by: (data) => data.key } }, async (data, step, stored) => {
369
+ const occurrence = { key: data.key, occasion: data.occasion };
370
+ const previous = journal()?.find({ type: OccasionClaimed.name, field: "occasion", equals: data.occasion })[0];
371
+ const text = previous === undefined ? [
372
+ `Something happened (occasion ${data.occasion}, ${data.kind}): ${data.text}`,
373
+ "",
374
+ contextText(stored.at),
375
+ "",
376
+ `Decide with rin.attend on { kind: "occasion", occasion: "${data.occasion}" }.`,
377
+ ].join("\n") : OccasionClaimed.schema.parse(previous.data).text;
378
+ try {
379
+ await step.emit(OccasionClaimed, { ...occurrence, text }, { key: "claim" });
380
+ } catch (error) {
381
+ if (error instanceof RecordRefused && (error.code === "occasion-changed" || error.code === "occasion-already-claimed")) return;
382
+ throw error;
383
+ }
384
+ await step(agentNotify, { agent: RIN_AGENT, text }, { key: "notify" });
385
+ await step.emit(OccasionNotified, occurrence, { key: "notified" });
386
+ });
387
+
388
+ // An agent she leads that cannot be reached is an occasion; it ends when a turn reaches it again.
389
+ api.on(AgentTurnFailed, { id: "stuck-agent" }, async (data, step, stored) => {
390
+ if (data.agent === RIN_AGENT) return;
391
+ const text = `A turn did not reach agent ${data.agent} (${data.status}): ${firstLine(data.reason)}`;
392
+ await notice((type, value, key) => step.emit(type, value, { key }), { key: `agent:${data.agent}:unreachable`, kind: "agent", text }, { kind: "niwa", by: "agents" }, String(stored.id));
393
+ });
394
+ api.on(AgentTurnDelivered, { id: "agent-reachable" }, async (data, step, stored) => {
395
+ if (data.agent === RIN_AGENT) return;
396
+ const text = `A turn reached agent ${data.agent} again.`;
397
+ await notice((type, value, key) => step.emit(type, value, { key }), { key: `agent:${data.agent}:unreachable`, kind: "agent", text, ends: true }, { kind: "niwa", by: "agents" }, String(stored.id));
398
+ });
399
+
400
+ // A workflow run she started that finished is an occasion: she learns its outcome without asking. Who started it
401
+ // is who asked for it (the record of the request); the run's own start is written by the workflow module.
402
+ api.on(RunFinished, { id: "run-finished", requires: [RunFinished] }, async (data, step, stored) => {
403
+ const requested = journal()?.find({ type: RunRequested.name, field: "run", equals: data.run })[0];
404
+ if (requested === undefined || whoIs(requested.actor) !== "rin") return;
405
+ const asked = RunRequested.schema.safeParse(requested.data);
406
+ if (!asked.success) return;
407
+ const label = asked.data.label ?? asked.data.file;
408
+ const how = data.outcome.status === "failed" ? `failed: ${firstLine(data.outcome.error.message)}` : data.outcome.status;
409
+ const text = `The workflow run ${data.run}${label === "" ? "" : ` (${label})`} you started ended: ${how}.`;
410
+ await notice((type, value, key) => step.emit(type, value, { key }), { key: `run:${data.run}`, kind: "workflow", text }, { kind: "niwa", by: "workflow" }, String(stored.id));
411
+ });
412
+
413
+ // ---- her decisions --------------------------------------------------------------------------------------
414
+
415
+ /** Is the subject one she can decide about: an occasion of hers that still holds, or a turn of her inbox? */
416
+ const known = (subject: Subject, state: AttentionState): boolean => {
417
+ if (subject.kind === "occasion") {
418
+ const occasion = state.occasions.get(subject.occasion);
419
+ return occasion !== undefined && state.open.get(occasion.key) === occasion.occasion;
420
+ }
421
+ return (journal()?.find({ type: AgentTurnQueued.name, field: "turn", equals: subject.turn }) ?? []).some((stored) => {
422
+ const turn = stored.data as { agent?: unknown; turn?: unknown };
423
+ return turn.agent === RIN_AGENT && turn.turn === subject.turn;
424
+ });
425
+ };
426
+
427
+ api.action(
428
+ action(rinAttend, {
429
+ // Every record follows the operation: a repeat finds what the first call wrote.
430
+ recovery: "repeat",
431
+ effect: "record",
432
+ world: "niwa",
433
+ run: (input, ctx) =>
434
+ serially(async () => {
435
+ if (whoIs(ctx.caller) !== "rin") throw new RinRefusal("not-rin", "only Rin decides what to do about what reaches her");
436
+ const state = attention();
437
+ if (!known(input.subject, state)) throw new RinRefusal("unknown", "there is no such occasion that holds, or turn of hers");
438
+ const telling = input.decision === "next-contact" || input.decision === "now" || input.decision === "insist";
439
+ if (telling && input.text === undefined) throw new RinRefusal("no-text", `"${input.decision}" needs the text the owner is to read`);
440
+ if ((input.decision === "now" || input.decision === "insist") && say === undefined) throw new RinRefusal("unreachable", "No channel is configured for proactive messages; hold it for the owner’s next contact");
441
+ if (input.decision === "now" || input.decision === "next-contact") {
442
+ const refused = repeatRefusal(state, input.subject);
443
+ if (refused !== undefined) throw new RinRefusal("already-said", refused);
444
+ }
445
+ if (input.decision === "insist") {
446
+ const refused = insistRefusal(state, input.subject, input.rule, ruledIds());
447
+ if (refused !== undefined) throw new RinRefusal("insist", refused);
448
+ }
449
+ const decided = await ctx.emit(AttentionDecided, {
450
+ subject: input.subject,
451
+ decision: input.decision,
452
+ ...(input.text === undefined ? {} : { text: input.text }),
453
+ ...(input.rule === undefined ? {} : { rule: input.rule }),
454
+ });
455
+ const route = routeOf(input.decision, { at: decided.at, quiet, ceiling, said: state.said });
456
+ if (route.kind === "keep" || input.text === undefined) return { decision: input.decision, outcome: "kept" as const };
457
+ // A decision about what already waits takes the place of the one that waits: one thing, one message.
458
+ const item = pendingAbout(state, input.subject)?.item ?? idOf("att", String(ctx.operationId));
459
+ const rule = input.decision === "insist" && input.rule !== undefined ? { rule: input.rule } : {};
460
+ if (route.kind === "say") {
461
+ await ctx.emit(AttentionSending, { item, subject: input.subject, text: input.text, ...rule });
462
+ return { decision: input.decision, outcome: "sending" as const, item };
463
+ }
464
+ await ctx.emit(AttentionHeld, { item, subject: input.subject, text: input.text, until: route.until, why: route.why, ...rule });
465
+ return { decision: input.decision, outcome: "held" as const, item, why: route.why, ...(route.until === "quiet-end" ? { until: route.at } : {}) };
466
+ }),
467
+ }),
468
+ );
469
+
470
+ // What she says now goes out through the action of the composition, called by this plugin. What cannot reach
471
+ // the owner waits for his next contact, and she is told.
472
+ api.on(AttentionSending, { id: "say" }, async (data, step) => {
473
+ if (say === undefined) {
474
+ await step.emit(AttentionHeld, { ...data, until: "contact", why: "undelivered" }, { key: "hold" });
475
+ return;
476
+ }
477
+ const sent = await step.outcome<{ text: string }, unknown>(say, { text: data.text }, { key: "say" });
478
+ const rule = data.rule === undefined ? {} : { rule: data.rule };
479
+ if (sent.status === "completed") {
480
+ await step.emit(AttentionSaid, { item: data.item, subject: data.subject, text: data.text, channel: String(say), ...rule });
481
+ return;
482
+ }
483
+ // Only what surely did not go waits for the next contact; what may have gone is not sent again.
484
+ const nothingSent = sent.status === "denied" || (sent.status === "failed" && !sent.effectPossible);
485
+ const why = sent.status === "failed" ? sent.error : sent.status === "denied" || sent.status === "cancelled" ? sent.reason : "the outcome is not known";
486
+ if (!nothingSent) {
487
+ await step.emit(AttentionUnsure, { item: data.item, subject: data.subject, text: data.text, why, ...rule });
488
+ await step(agentNotify, { agent: RIN_AGENT, text: `What you meant to tell the owner now may or may not have reached him (${firstLine(why)}); it is not sent again, and does not wait: ask him if it matters: ${firstLine(data.text)}` });
489
+ return;
490
+ }
491
+ const state = attention();
492
+ const occasion = data.subject.kind === "occasion" ? state.occasions.get(data.subject.occasion) : undefined;
493
+ if (occasion !== undefined && state.open.get(occasion.key) !== occasion.occasion) {
494
+ // Its occasion ended meanwhile: there is nothing left to tell him.
495
+ await step.emit(AttentionDropped, { item: data.item, occasion: occasion.occasion });
496
+ return;
497
+ }
498
+ await step.emit(AttentionHeld, { item: data.item, subject: data.subject, text: data.text, until: "contact", why: "undelivered", ...rule });
499
+ await step(agentNotify, { agent: RIN_AGENT, text: `What you meant to tell the owner now did not reach him (${firstLine(why)}); it waits for his next contact: ${firstLine(data.text)}` });
500
+ });
501
+
502
+ // At the end of his quiet hours what waited for it is said, as far as the ceiling allows.
503
+ api.on(quietEnd, { id: "quiet-end" }, (_firing, step, stored) =>
504
+ serially(async () => {
505
+ const state = attention();
506
+ const said = [...state.said];
507
+ for (const item of heldItems(state, "quiet-end")) {
508
+ const route = say === undefined ? { kind: "hold", why: "undelivered" } as const : sayNow({ at: stored.at, quiet, ceiling, said });
509
+ const rule = item.rule === undefined ? {} : { rule: item.rule };
510
+ if (route.kind === "say") {
511
+ said.push(stored.at);
512
+ await step.emit(AttentionSending, { item: item.item, subject: item.subject, text: item.text, ...rule }, { key: `send-${item.item}` });
513
+ } else {
514
+ await step.emit(AttentionHeld, { item: item.item, subject: item.subject, text: item.text, until: "contact", why: route.kind === "hold" ? route.why : "ceiling", ...rule }, { key: `hold-${item.item}` });
515
+ }
516
+ }
517
+ }),
518
+ );
519
+
520
+ // Rin's nightly quiet period ends at this firing. The durable step makes one consolidation per firing.
521
+ api.on(quietEnd, { id: "wake-memory" }, async (_firing, step) => {
522
+ await step(memoryConsolidate, { memory: RIN_AGENT }, { key: "consolidate" });
523
+ });
524
+
525
+ // ---- the owner in touch ---------------------------------------------------------------------------------
526
+
527
+ /** What waits is brought up at a contact: what was held before it. */
528
+ const bring = (step: Step, contact: Contact, before: number): Promise<void> =>
529
+ serially(async () => {
530
+ const items = heldItems(attention()).filter((item) => item.seq < before);
531
+ if (items.length > 0) await step.emit(AttentionBrought, { items: items.map((item) => item.item), contact });
532
+ });
533
+
534
+ for (const source of [OwnerWroteToRin, OwnerWroteInToRin]) {
535
+ api.on(source, { requires: [source.type] }, async (message: Message, step, stored) => {
536
+ await bring(step, { kind: "message", message: message.id }, stored.seq);
537
+ });
538
+ }
539
+
540
+ // She is told what was brought up when he wrote to her, from the record that says so: a restart between that
541
+ // record and her being told finds the record. An attach needs no telling: it answers with the briefing.
542
+ api.on(AttentionBrought, { id: "brought-told" }, async (data, step) => {
543
+ if (data.contact.kind !== "message") return;
544
+ const state = attention();
545
+ const lines = data.items.flatMap((id) => {
546
+ const item = state.items.get(id);
547
+ return item === undefined ? [] : [`- ${item.text}${countText(state, item)}`];
548
+ });
549
+ if (lines.length === 0) return;
550
+ await step(agentNotify, { agent: RIN_AGENT, text: ["The owner is in touch now. What you held for him, to bring up as it fits:", ...lines].join("\n") });
551
+ });
552
+
553
+ // An attach of his session to her answers with her briefing, which shows what waited: it is brought up.
554
+ api.on(AgentAttached, { id: "attached", filter: { agent: RIN_AGENT } }, async (data, step, stored) => {
555
+ await bring(step, { kind: "attach", session: data.session }, stored.seq);
556
+ });
557
+
558
+ // ---- reading --------------------------------------------------------------------------------------------
559
+
560
+ api.action(
561
+ action(rinInbox, {
562
+ recovery: "repeat",
563
+ effect: "read",
564
+ world: "niwa",
565
+ run: async (input) => {
566
+ const decided = new Set((journal()?.since(seq(0), [AttentionDecided.name]) ?? []).flatMap((stored) => {
567
+ const parsed = AttentionDecided.schema.safeParse(stored.data);
568
+ return parsed.success && parsed.data.subject.kind === "turn" ? [parsed.data.subject.turn] : [];
569
+ }));
570
+ const turns = (journal()?.find({ type: AgentTurnQueued.name, field: "agent", equals: RIN_AGENT }) ?? []).flatMap((stored) => {
571
+ const turn = AgentTurnQueued.schema.safeParse(stored.data);
572
+ return turn.success ? [{ turn: turn.data.turn, kind: turn.data.kind, from: turn.data.author, text: firstLine(turn.data.text, 300), decided: decided.has(turn.data.turn) }] : [];
573
+ });
574
+ return { turns: turns.filter((one) => input.decided === undefined ? !one.decided : one.decided === input.decided).reverse().slice(0, input.limit) };
575
+ },
576
+ }),
577
+ );
578
+
579
+ api.action(
580
+ action(rinConversation, {
581
+ recovery: "repeat",
582
+ effect: "read",
583
+ world: "niwa",
584
+ run: async (input, ctx) => {
585
+ if (whoIs(ctx.caller) !== "owner") throw new RinRefusal("not-owner", "Only the owner can read this conversation");
586
+ const rows = journal()?.since(seq(0), [MessageSent.name, AgentTurnDelivered.name, AgentTurnFailed.name, AgentTurnReplied.name]) ?? [];
587
+ type Entry = { id: string; turn: string; from: "owner" | "rin"; text: string; at: number; delivery?: Delivery };
588
+ const messages: Entry[] = [];
589
+ const incoming = new Map<string, Entry>();
590
+ for (const stored of rows) {
591
+ if (stored.type === MessageSent.name) {
592
+ const data = MessageEnvelope.parse(stored.data);
593
+ if (data.from.kind !== "owner" || data.to.kind !== "agent" || data.to.id !== RIN_AGENT ||
594
+ data.replyTo?.channel !== "cockpit" || data.replyTo.conversation !== input.conversation) continue;
595
+ const message: Entry = { id: data.id, turn: data.id, from: "owner", text: contentText(data), at: stored.at, delivery: "waiting" };
596
+ incoming.set(data.id, message);
597
+ messages.push(message);
598
+ } else if (stored.type === AgentTurnReplied.name) {
599
+ const data = AgentTurnReplied.schema.parse(stored.data);
600
+ if (data.agent !== RIN_AGENT || data.replyTo.channel !== "cockpit" ||
601
+ data.replyTo.conversation !== input.conversation || !incoming.has(data.turn)) continue;
602
+ messages.push({ id: String(stored.id), turn: data.turn, from: "rin", text: data.text, at: stored.at });
603
+ } else if (stored.type === AgentTurnDelivered.name) {
604
+ const data = AgentTurnDelivered.schema.parse(stored.data);
605
+ const entry = data.agent === RIN_AGENT ? incoming.get(data.turn) : undefined;
606
+ if (entry !== undefined) entry.delivery = "delivered";
607
+ } else {
608
+ const data = AgentTurnFailed.schema.parse(stored.data);
609
+ const entry = data.agent === RIN_AGENT ? incoming.get(data.turn) : undefined;
610
+ if (entry !== undefined && entry.delivery !== "delivered") entry.delivery = data.status;
611
+ }
612
+ }
613
+ return { messages: messages.slice(-input.limit) };
614
+ },
615
+ }),
616
+ );
617
+
618
+ api.action(
619
+ action(rinContext, {
620
+ recovery: "repeat",
621
+ effect: "read",
622
+ world: "niwa",
623
+ run: async () => {
624
+ const at = now();
625
+ const state = attention();
626
+ const ends = quietEnds(at, quiet);
627
+ return {
628
+ at,
629
+ working: workingNow(rowsOf(PRESENCE_TYPES)),
630
+ quiet: { now: inQuietHours(at, quiet), from: quiet.from, to: quiet.to, ...(ends === undefined ? {} : { ends }) },
631
+ ceiling: { count: ceiling.count, windowMs: ceiling.windowMs, left: ceilingLeft(state.said, at, ceiling) },
632
+ charter: [...charter().rules.values()].filter((rule) => rule.status === "ruled" || rule.status === "proposed").map(ruleView),
633
+ occasions: openOccasions(state),
634
+ held: heldItems(state).map((item) => itemView(state, item)),
635
+ };
636
+ },
637
+ }),
638
+ );
639
+
640
+ api.action(
641
+ action(rinAttention, {
642
+ recovery: "repeat",
643
+ effect: "read",
644
+ world: "niwa",
645
+ run: async (input) => {
646
+ const state = attention();
647
+ const items = [...state.items.values()]
648
+ .filter((item) => input.status === undefined || item.status === input.status)
649
+ .sort((a, b) => b.at - a.at || b.seq - a.seq)
650
+ .map((item) => itemView(state, item));
651
+ return { items, occasions: openOccasions(state) };
652
+ },
653
+ }),
654
+ );
655
+
656
+ api.action(
657
+ action(rinBriefing, {
658
+ recovery: "repeat",
659
+ effect: "read",
660
+ world: "niwa",
661
+ run: async (input) => {
662
+ if (input.agent !== RIN_AGENT) return { text: "" };
663
+ const sections: string[] = [];
664
+ const held = briefingText(attention());
665
+ if (held !== "") sections.push(held);
666
+ const waiting = [...charter().rules.values()].filter((rule) => rule.status === "proposed");
667
+ if (waiting.length > 0) sections.push(["Rules of her charter that wait for your word:", ...waiting.map((rule) => `- ${rule.text}`)].join("\n"));
668
+ return { text: sections.join("\n\n") };
669
+ },
670
+ }),
671
+ );
672
+
673
+ api.action(
674
+ action(rinPromptCharter, {
675
+ recovery: "repeat",
676
+ effect: "read",
677
+ world: "niwa",
678
+ run: async (input) => {
679
+ if (input.agent !== RIN_AGENT) return { text: "" };
680
+ const rules = charterText(ruledRules(charter()));
681
+ return { text: rules === "" ? "Your charter has no rules yet." : `Your charter, the rules the owner confirmed:\n${rules}` };
682
+ },
683
+ }),
684
+ );
685
+
686
+ api.action(
687
+ action(rinCharter, {
688
+ recovery: "repeat",
689
+ effect: "read",
690
+ world: "niwa",
691
+ run: async () => {
692
+ const state = charter();
693
+ return { rules: [...state.rules.values()].map(ruleView), corrections: state.corrections.map((one) => correctionView(one, whatOf(one))) };
694
+ },
695
+ }),
696
+ );
697
+
698
+ // ---- corrections ----------------------------------------------------------------------------------------
699
+
700
+ /** Are these the owner's own words: a message he wrote, or a turn he wrote that holds a message? */
701
+ const wordsOf = (stored: StoredRecord): boolean => {
702
+ if (stored.type === MessageSent.name || stored.type === MessageReceived.name) {
703
+ const message = MessageEnvelope.safeParse(stored.data);
704
+ return message.success && message.data.from.kind === "owner" && message.data.body.text.trim() !== "";
705
+ }
706
+ if (stored.type === AgentTurnQueued.name) {
707
+ const turn = AgentTurnQueued.schema.safeParse(stored.data);
708
+ return turn.success && turn.data.kind === "message" && turn.data.author.kind === "owner" && turn.data.text.trim() !== "";
709
+ }
710
+ return false;
711
+ };
712
+ /**
713
+ * Does this id name a record that holds words the owner wrote: a record of the journal by its id (an emitted
714
+ * record's id has slashes in it), or a message by its own id (`msg-…`)? A record he merely wrote, an answer or a
715
+ * correction, holds no words of his to rest a correction on.
716
+ */
717
+ const isHisWords = (id: string): boolean => {
718
+ let byRecord: StoredRecord | undefined;
719
+ try {
720
+ byRecord = journal()?.get(recordId(id));
721
+ } catch {
722
+ byRecord = undefined; // not the shape of a record id
723
+ }
724
+ const byMessage = (journal()?.since(seq(0), [MessageSent.name, MessageReceived.name]) ?? []).filter((stored) => (stored.data as { id?: unknown }).id === id);
725
+ return [...(byRecord === undefined ? [] : [byRecord]), ...byMessage].some(wordsOf);
726
+ };
727
+
728
+ api.action(
729
+ action(rinCorrect, {
730
+ recovery: "repeat",
731
+ effect: "record",
732
+ world: "niwa",
733
+ run: async (input, ctx) => {
734
+ const who = whoIs(ctx.caller);
735
+ if (who === "other") throw new RinRefusal("not-owner", "a correction is the owner's: only he, or Rin from his words, writes one");
736
+ if (who === "rin" && (input.source === undefined || !isHisWords(input.source))) {
737
+ throw new RinRefusal("not-his-words", "Rin writes a correction only from the owner's own words: give the id of the record that holds them");
738
+ }
739
+ const correction = idOf("cor", String(ctx.operationId));
740
+ await ctx.emit(Corrected, {
741
+ correction,
742
+ about: input.about,
743
+ what: input.what,
744
+ by: who === "owner" ? owner : agentAddress(RIN_AGENT),
745
+ ...(input.source === undefined ? {} : { source: input.source }),
746
+ });
747
+ return { correction };
748
+ },
749
+ }),
750
+ );
751
+
752
+ api.action(
753
+ action(rinDismiss, {
754
+ recovery: "repeat",
755
+ effect: "record",
756
+ world: "niwa",
757
+ run: async (input, ctx) => {
758
+ if (whoIs(ctx.caller) !== "owner") throw new RinRefusal("not-owner", "only the owner waves away what Rin tells him");
759
+ const state = attention();
760
+ const item = state.items.get(input.item);
761
+ if (item === undefined) throw new RinRefusal("unknown", `there is no item "${input.item}"`);
762
+ const dismissed = await ctx.emit(AttentionDismissed, { item: input.item, ...(input.reason === undefined ? {} : { reason: input.reason }) });
763
+ const kind = item.subject.kind === "occasion" ? state.occasions.get(item.subject.occasion)?.kind : undefined;
764
+ const correction = idOf("cor", String(ctx.operationId));
765
+ await ctx.emit(Corrected, {
766
+ correction,
767
+ about: kind === undefined ? "attention" : `attention.${kind}`,
768
+ what: `The owner waved away what you told him: "${firstLine(item.text)}"${input.reason === undefined ? "" : `, saying: ${input.reason}`}`,
769
+ by: { kind: "niwa", by: "rin.attention.dismiss" },
770
+ source: String(dismissed.id),
771
+ });
772
+ return { item: input.item, correction };
773
+ },
774
+ }),
775
+ );
776
+
777
+ /** Write a correction the owner acted out, from the record of what he did. */
778
+ const actedOut = (step: Step, stored: StoredRecord, about: Topic, what: string, note?: NoteChange) =>
779
+ step.emit(Corrected, { correction: idOf("cor", String(stored.id)), about, what, by: { kind: "niwa", by: "rin" }, source: String(stored.id), ...(note === undefined ? {} : { note }) });
780
+
781
+ /** Did Rin write this note of her memory? */
782
+ const herNote = (memory: string, note: string) =>
783
+ memory === RIN_AGENT &&
784
+ (journal()?.find({ type: NoteWritten.name, field: "note", equals: note }) ?? []).some((stored) => {
785
+ const written = stored.data as { memory?: unknown; by?: Address | TurnAuthor };
786
+ return written.memory === memory && written.by?.kind === "agent" && written.by.id === RIN_AGENT;
787
+ });
788
+
789
+ /** The words of a note as they stood before a position of the journal: its text when written, or as last corrected. */
790
+ const noteBefore = (memory: string, note: string, before: number): string | undefined => {
791
+ const rows = [...(journal()?.find({ type: NoteWritten.name, field: "note", equals: note }) ?? []), ...(journal()?.find({ type: NoteCorrected.name, field: "note", equals: note }) ?? [])]
792
+ .filter((stored) => stored.seq < before && (stored.data as { memory?: unknown }).memory === memory)
793
+ .sort((a, b) => a.seq - b.seq);
794
+ return (rows.at(-1)?.data as { text?: string } | undefined)?.text;
795
+ };
796
+ const noteErasedSince = (memory: string, note: string): boolean =>
797
+ (journal()?.find({ type: NoteErased.name, field: "note", equals: note }) ?? []).some((stored) => (stored.data as { memory?: unknown }).memory === memory);
798
+
799
+ /**
800
+ * What a correction says as it is shown. A correction about a note of hers keeps no words of the note: they are
801
+ * read from memory's records now, and left out once the note was erased, so erasing it leaves no copy here.
802
+ */
803
+ const whatOf = (correction: Correction): string => {
804
+ const note = correction.note;
805
+ if (note === undefined || note.change === "erased" || noteErasedSince(note.memory, note.note)) return correction.what;
806
+ const source = correction.source === undefined ? undefined : journal()?.get(recordId(correction.source));
807
+ const data = source?.data as { text?: string; reason?: string } | undefined;
808
+ const was = source === undefined ? undefined : noteBefore(note.memory, note.note, source.seq);
809
+ if (note.change === "corrected") return data?.text === undefined || was === undefined ? correction.what : `${correction.what}: "${firstLine(was)}" became "${firstLine(data.text)}"`;
810
+ return `${correction.what}${was === undefined ? "" : `: "${firstLine(was)}"`}${data?.reason === undefined ? "" : `, saying: ${firstLine(data.reason)}`}`;
811
+ };
812
+
813
+ api.on(NoteCorrected, { id: "note-corrected", filter: { "by.kind": "owner" } }, async (data, step, stored) => {
814
+ if (!herNote(data.memory, data.note)) return;
815
+ await actedOut(step, stored, "memory", "The owner changed a note of yours", { memory: data.memory, note: data.note, change: "corrected" });
816
+ });
817
+ api.on(NoteRetracted, { id: "note-retracted", filter: { "by.kind": "owner" } }, async (data, step, stored) => {
818
+ if (!herNote(data.memory, data.note)) return;
819
+ await actedOut(step, stored, "memory", "The owner took back a note of yours", { memory: data.memory, note: data.note, change: "retracted" });
820
+ });
821
+ api.on(NoteErased, { id: "note-erased", filter: { "by.kind": "owner" } }, async (data, step, stored) => {
822
+ if (!herNote(data.memory, data.note)) return;
823
+ await actedOut(step, stored, "memory", "The owner erased a note of yours: what it held should not have been kept", { memory: data.memory, note: data.note, change: "erased" });
824
+ });
825
+
826
+ api.on(CommitmentCancelled, { id: "commitment-cancelled", filter: { "by.kind": "owner" } }, async (data, step, stored) => {
827
+ const made = journal()?.find({ type: CommitmentMade.name, field: "id", equals: data.id })[0];
828
+ const by = (made?.data as { by?: Address; text?: string } | undefined)?.by;
829
+ if (by?.kind !== "agent" || by.id !== RIN_AGENT) return;
830
+ const text = (made?.data as { text?: string }).text ?? data.id;
831
+ await actedOut(step, stored, "commitments", `The owner cancelled your promise "${firstLine(text)}"${data.reason === undefined ? "" : `: ${data.reason}`}`);
832
+ });
833
+
834
+ api.on(DecisionRevoked, { id: "decision-revoked", filter: { "by.kind": "owner" } }, async (data, step, stored) => {
835
+ const made = journal()?.find({ type: DecisionMade.name, field: "id", equals: data.decision })[0];
836
+ const decided = made?.data as { by?: Address; description?: string; area?: string } | undefined;
837
+ if (decided?.by?.kind !== "agent" || decided.by.id !== RIN_AGENT) return;
838
+ await actedOut(step, stored, "decisions", `The owner revoked your decision on "${firstLine(decided.description ?? data.decision)}" in ${decided.area ?? "its area"}${data.reason === undefined ? "" : `: ${data.reason}`}`);
839
+ });
840
+
841
+ /** What she asked the owner, when it was she who asked. */
842
+ const herQuestion = (request: string): string | undefined => {
843
+ const created = journal()?.find({ type: RequestCreated.name, field: "id", equals: request })[0];
844
+ const data = created?.data as { from?: Address; to?: Address; input?: { title?: string } } | undefined;
845
+ if (data?.to?.kind !== "owner" || data.from?.kind !== "agent" || data.from.id !== RIN_AGENT) return undefined;
846
+ return data.input?.title ?? request;
847
+ };
848
+ // What the owner answered reaches her as a fact that names the request: she asked, and learns the answer
849
+ // without polling. An answer that was not his (a resolver's) is told as such.
850
+ api.on(RequestAnswered, { id: "question-answered" }, async (data, step) => {
851
+ const title = herQuestion(data.id);
852
+ if (title === undefined) return;
853
+ const answer = "ids" in data.answer ? `chose ${data.answer.ids.join(", ")}` : "text" in data.answer ? `said: ${data.answer.text}` : "form" in data.answer ? `filled in: ${JSON.stringify(data.answer.form)}` : "withdrew the question";
854
+ const who = data.by?.kind === "owner" ? "The owner" : `Not the owner but a resolver${data.how === undefined ? "" : ` (${data.how})`}`;
855
+ await step(agentNotify, { agent: RIN_AGENT, text: `Request ${data.id}, your question "${firstLine(title)}": ${who} ${answer}.` });
856
+ });
857
+ api.on(RequestCancelledRecord, { id: "question-turned-down", filter: { "by.kind": "owner" } }, async (data, step, stored) => {
858
+ const title = herQuestion(data.id);
859
+ if (title === undefined) return;
860
+ await actedOut(step, stored, "questions", `The owner turned down your question "${firstLine(title)}"${data.reason === undefined ? "" : `: ${data.reason}`}`);
861
+ });
862
+ api.on(RequestExpiredRecord, { id: "question-unanswered" }, async (data, step, stored) => {
863
+ const title = herQuestion(data.id);
864
+ if (title === undefined) return;
865
+ await actedOut(step, stored, "questions", `The owner left your question "${firstLine(title)}" unanswered until it expired`);
866
+ });
867
+
868
+ // ---- the charter ----------------------------------------------------------------------------------------
869
+
870
+ // Corrections about one thing that repeat make a rule due; the record, not this handler, tells her.
871
+ api.on(Corrected, { id: "consolidate", concurrency: { by: (data) => data.about } }, async (data, step) => {
872
+ const due = dueFor(charter(), data.about, ruleAfter);
873
+ if (due === undefined) return;
874
+ try {
875
+ await step.emit(CharterDue, { about: data.about, corrections: due });
876
+ } catch (error) {
877
+ if (!(error instanceof RecordRefused) || error.code !== "corrections-changed") throw error;
878
+ }
879
+ });
880
+
881
+ // She is asked for a rule from the record of what is due, so that a restart between the two does not lose the ask.
882
+ api.on(CharterDue, { id: "rule-due" }, async (data, step) => {
883
+ const lines = charter().corrections.filter((one) => data.corrections.includes(one.correction)).map((one) => `- ${one.correction}: ${one.what}${one.note === undefined ? "" : " (what he changed is in rin.charter)"}`);
884
+ await step(agentNotify, {
885
+ agent: RIN_AGENT,
886
+ text: [
887
+ `The owner's corrections about ${data.about} repeat:`,
888
+ ...lines,
889
+ "",
890
+ "If one rule covers them, word it in one sentence and propose it with rin.charter.propose, naming these corrections. If none does, leave it.",
891
+ ].join("\n"),
892
+ });
893
+ });
894
+
895
+ api.action(
896
+ action(rinCharterPropose, {
897
+ recovery: "repeat",
898
+ effect: "record",
899
+ world: "niwa",
900
+ run: async (input, ctx) => {
901
+ const who = whoIs(ctx.caller);
902
+ if (who === "other") throw new RinRefusal("not-owner", "only Rin or the owner proposes a rule of her charter");
903
+ const rule = idOf("rule", String(ctx.operationId));
904
+ const proposal = { rule, about: input.about, text: input.text, corrections: input.corrections, by: who === "owner" ? owner : agentAddress(RIN_AGENT) };
905
+ if (who === "owner") {
906
+ await ctx.emitAll([
907
+ { type: CharterProposed, data: proposal },
908
+ { type: CharterRuled, data: { rule, about: input.about, by: owner } },
909
+ ]);
910
+ return { rule, status: "ruled" as const };
911
+ }
912
+ await ctx.emit(CharterProposed, proposal);
913
+ return { rule, status: "proposed" as const };
914
+ },
915
+ }),
916
+ );
917
+
918
+ // A rule she proposed is put to the owner, and only his yes makes it part of the charter. She is told either way.
919
+ api.on(CharterProposed, { id: "confirm-rule", filter: { "by.kind": "agent" }, concurrency: Number.POSITIVE_INFINITY }, async (data, step) => {
920
+ const verdict = await askOwner(step, ruleQuestion(data.text, data.about), "ask");
921
+ try {
922
+ if (verdict === "confirmed") await step.emit(CharterRuled, { rule: data.rule, about: data.about, by: owner }, { key: "ruled" });
923
+ else await step.emit(CharterDeclined, { rule: data.rule, about: data.about, why: verdict }, { key: "declined" });
924
+ } catch (error) {
925
+ if (error instanceof RecordRefused && error.code === "rule-closed") return;
926
+ throw error;
927
+ }
928
+ const told: Record<Verdict, string> = {
929
+ confirmed: `The owner confirmed a rule of your charter, ${data.rule}: ${data.text}`,
930
+ declined: `The owner declined the rule you proposed: ${data.text}`,
931
+ cancelled: `The rule you proposed was not confirmed (the question was cancelled): ${data.text}`,
932
+ expired: `The rule you proposed was not confirmed (the question was left to expire): ${data.text}`,
933
+ };
934
+ await step(agentNotify, { agent: RIN_AGENT, text: told[verdict] }, { key: "told" });
935
+ });
936
+
937
+ // ---- changing herself -----------------------------------------------------------------------------------
938
+
939
+ api.action(
940
+ action(rinSelfInstall, {
941
+ // The edit is cut from the operation: a repeat finds the proposal the first call wrote.
942
+ recovery: "repeat",
943
+ effect: "record",
944
+ world: "niwa",
945
+ run: async (input, ctx) => {
946
+ if (whoIs(ctx.caller) !== "rin") throw new RinRefusal("not-rin", "only Rin proposes to change herself");
947
+ if (selfEdit === "off") throw new RinRefusal("self-edit-off", "changing herself by code is turned off");
948
+ if (!input.plugin.startsWith("rin/")) throw new RinRefusal("not-her-group", `a plugin of hers has a name that begins with rin/, not "${input.plugin}"`);
949
+ if (!isAbsolute(input.module)) throw new RinRefusal("unknown", "give the module as an absolute path");
950
+ const edit = idOf("edit", String(ctx.operationId));
951
+ const existing = journal()?.find({ type: SelfEditProposed.name, field: "edit", equals: edit })[0];
952
+ if (existing !== undefined) return { edit, hash: SelfEditProposed.schema.parse(existing.data).hash };
953
+ const bytes = await readFile(input.module).catch(() => undefined);
954
+ if (bytes === undefined) throw new RinRefusal("unknown", `cannot read the module ${input.module}`);
955
+ const hash = createHash("sha256").update(bytes).digest("hex");
956
+ await ctx.emit(SelfEditProposed, { edit, plugin: input.plugin, module: input.module, hash, why: input.why, mode: selfEdit });
957
+ return { edit, hash };
958
+ },
959
+ }),
960
+ );
961
+
962
+ api.on(SelfEditProposed, { id: "confirm-self-edit", concurrency: { by: (data) => data.plugin } }, async (data, step, proposal) => {
963
+ const { edit, plugin: name, module, hash } = data;
964
+ const log = journal();
965
+ if (log === undefined) throw new Error("Self-edit recovery needs the host journal");
966
+ const ownRecord = (row: StoredRecord) => row.cause === proposal.id && row.actor.kind === "handler" && row.actor.handler === "rin/confirm-self-edit";
967
+ const previous = log.find({ type: SelfEditSettled.name, field: "edit", equals: edit }).find(ownRecord);
968
+ if (previous !== undefined) {
969
+ const saved = SelfEditSettled.schema.parse(previous.data);
970
+ return tellEdit(step, { name, hash, ...saved });
971
+ }
972
+ const claim = log.find({ type: SelfEditClaimed.name, field: "edit", equals: edit }).find(ownRecord);
973
+ let installed = claim?.actor.kind === "handler" ? recordedInstall(log, claim.actor, { plugin: name, module, hash }) : undefined;
974
+ const settle = async (outcome: Exclude<Verdict, "confirmed"> | "installed" | "failed" | "unknown", detail?: string) => {
975
+ await step.emit(SelfEditSettled, { edit, plugin: name, outcome, ...(detail === undefined ? {} : { detail }) }, { key: "settled" });
976
+ await tellEdit(step, { name, hash, outcome, detail });
977
+ };
978
+ if (installed === undefined) {
979
+ if (selfEdit === "off") return settle("cancelled", "Self-editing is disabled on this host");
980
+ if (data.mode === "ask" || selfEdit === "ask") {
981
+ const title = `Rin asks to install ${name} from ${module} (sha256 ${hash}): ${data.why}`;
982
+ const verdict = await askOwner(step, confirmQuestion("rin.self-edit.confirm", title), "ask");
983
+ if (verdict !== "confirmed") return settle(verdict);
984
+ }
985
+ await step.emit(SelfEditClaimed, { edit, plugin: name, hash }, { key: "claim" });
986
+ installed = await step.outcome(pluginInstall, { plugin: name, module, hash }, { key: "install" });
987
+ }
988
+ switch (installed.status) {
989
+ case "completed": return settle("installed");
990
+ case "failed": return settle(installed.effectPossible ? "unknown" : "failed", installed.error);
991
+ case "denied":
992
+ case "cancelled": return settle("failed", installed.reason);
993
+ case "unknown": return settle("unknown", "The outcome is not known");
994
+ }
995
+ });
996
+
997
+ async function tellEdit(step: Step, edit: { name: string; hash: string; outcome: string; detail?: string | undefined }) {
998
+ await step(agentNotify, {
999
+ agent: RIN_AGENT,
1000
+ text: `Installation of ${edit.name} (${edit.hash}): ${edit.outcome}${edit.detail === undefined ? "." : `. ${firstLine(edit.detail)}`}`,
1001
+ }, { key: "told" });
1002
+ }
1003
+
1004
+ api.action(action(rinSelfHistory, {
1005
+ recovery: "repeat",
1006
+ effect: "read",
1007
+ world: "niwa",
1008
+ run: async (_input, ctx) => {
1009
+ if (whoIs(ctx.caller) !== "owner") throw new RinRefusal("not-owner", "Only the owner can read the self-edit history");
1010
+ const rows = journal()?.since(seq(0), [
1011
+ SelfEditProposed.name, SelfEditClaimed.name, SelfEditSettled.name, CORE_TYPES.pluginInstalled, CORE_TYPES.pluginUninstalled,
1012
+ ]) ?? [];
1013
+ type Result = ReturnType<typeof rinSelfHistory.output.parse>;
1014
+ const edits = new Map<string, Result["edits"][number]>();
1015
+ const installed = new Map<string, Result["installed"][number]>();
1016
+ const proposed = new Set<string>();
1017
+ for (const row of rows) {
1018
+ if (row.type === SelfEditProposed.name) {
1019
+ const data = SelfEditProposed.schema.parse(row.data);
1020
+ edits.set(data.edit, { ...data, at: row.at, status: "pending" });
1021
+ proposed.add(`${data.plugin}:${data.hash}`);
1022
+ } else if (row.type === SelfEditClaimed.name) {
1023
+ const edit = edits.get(SelfEditClaimed.schema.parse(row.data).edit);
1024
+ if (edit !== undefined) edit.status = "installing";
1025
+ } else if (row.type === SelfEditSettled.name) {
1026
+ const data = SelfEditSettled.schema.parse(row.data);
1027
+ const edit = edits.get(data.edit);
1028
+ if (edit !== undefined) {
1029
+ edit.status = data.outcome;
1030
+ if (data.detail !== undefined) edit.detail = data.detail;
1031
+ }
1032
+ } else if (row.type === CORE_TYPES.pluginInstalled) {
1033
+ const data = pluginInstall.output.parse(row.data);
1034
+ if (proposed.has(`${data.plugin}:${data.hash}`)) installed.set(data.plugin, data);
1035
+ else installed.delete(data.plugin);
1036
+ } else {
1037
+ const data = row.data as { plugin: string };
1038
+ installed.delete(data.plugin);
1039
+ }
1040
+ }
1041
+ return { mode: selfEdit, edits: [...edits.values()].reverse(), installed: [...installed.values()] };
1042
+ },
1043
+ }));
1044
+
1045
+ api.action(
1046
+ action(rinCharterRetire, {
1047
+ recovery: "repeat",
1048
+ effect: "record",
1049
+ world: "niwa",
1050
+ run: async (input, ctx) => {
1051
+ if (whoIs(ctx.caller) !== "owner") throw new RinRefusal("not-owner", "only the owner takes a rule out of Rin's charter");
1052
+ const rule = charter().rules.get(input.rule);
1053
+ if (rule === undefined) throw new RinRefusal("unknown", `"${input.rule}" is not a rule of the charter`);
1054
+ await ctx.emit(CharterRetired, { rule: input.rule, about: rule.about, ...(input.reason === undefined ? {} : { reason: input.reason }) });
1055
+ return { rule: input.rule };
1056
+ },
1057
+ }),
1058
+ );
1059
+
1060
+ api.summarize(() => {
1061
+ const state = attention();
1062
+ return { held: heldItems(state).length, occasions: state.open.size, rules: ruledRules(charter()).length };
1063
+ });
1064
+
1065
+ /** How often the occasion of an item came up, as a few words after it. */
1066
+ function countText(state: AttentionState, item: Item): string {
1067
+ const count = item.subject.kind === "occasion" ? state.occasions.get(item.subject.occasion)?.count : undefined;
1068
+ return count !== undefined && count > 1 ? ` (came up ${count} times)` : "";
1069
+ }
1070
+ });
1071
+ }