@ouro.bot/cli 0.1.0-alpha.1644 → 0.1.0-alpha.1646

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/changelog.json CHANGED
@@ -1,6 +1,17 @@
1
1
  {
2
2
  "_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1646",
6
+ "changes": [
7
+ "A person can now answer a letter by texting its code and an option number, such as `L7 2`, in the iMessage chat the letter went to. When a one-to-one message in answer form arrives, the BlueBubbles sense hands the daemon only its GUID, and the daemon decides from the server's own copy. A recorded answer is not a chat turn. A message that already answered is handled the same when it is replayed. Anything else stays an ordinary chat turn, and so does a message the daemon doesn't answer for within 30 seconds: the daemon records nothing after 27 seconds, so a message is never both.",
8
+ "Once an answer is recorded, the person gets a one-line receipt in the same chat, naming the letter as its heading does, such as `Recorded L7 · Slugger asks: Which name? → 2 Ouro`, so a misread answer shows at once. The agent is told in its private runtime and woken; the private-runtime policy allows that wake only when it names the letter and comes from the daemon's answer command. A receipt or wake that fails is logged and never undoes the answer.",
9
+ "A letter now closes as expired once its `expiresAt` has passed with no answer. The daemon checks every minute and waits ten minutes past the expiry before closing a letter, so an answer the person sent in time still counts when it is read late. It then releases anyone waiting on the letter and wakes the agent that owns it with a note in its private runtime: \"letter L7 expired at … with no answer from my person\". An expired letter can't be answered or delivered. A new private-runtime policy rule allows that wake only when it names the letter and comes from the expiry pass.",
10
+ "A `now` letter whose sender sets no `expiresAt` now expires 24 hours after it is filed. Other letters still never expire unless their sender says so. Refiling a letter with the same `dedupeKey` doesn't extend its expiry, and once a letter is past its expiry the same `dedupeKey` files a new letter.",
11
+ "`mailbox_send` refuses an `expiresAt` that has already passed.",
12
+ "A daemon with no letters loads none of the mailbox's code for the expiry pass."
13
+ ]
14
+ },
4
15
  {
5
16
  "version": "0.1.0-alpha.1644",
6
17
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1644",
2
+ "runtimeVersion": "0.1.0-alpha.1646",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1644</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1646</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -626,6 +626,10 @@ function defaultUpdaterAgentWatch() {
626
626
  }
627
627
  /* v8 ignore stop */
628
628
  const STATE_RETENTION_FIRST_DELAY_MS = 10 * 60_000;
629
+ /** How often the daemon closes letters past their expiresAt. */
630
+ const LETTER_EXPIRY_TICK_MS = 60_000;
631
+ /** Matches EXPIRY_GRACE_MS in the letters writer, which daemon.ts doesn't load at start. */
632
+ const LETTER_EXPIRY_GRACE_MS = 10 * 60_000;
629
633
  const STATE_RETENTION_INTERVAL_MS = 24 * 60 * 60_000;
630
634
  const UPDATER_AGENT_WATCH_FIRST_DELAY_MS = 5 * 60_000;
631
635
  const UPDATER_AGENT_WATCH_INTERVAL_MS = 60 * 60_000;
@@ -661,6 +665,7 @@ class OuroDaemon {
661
665
  socketIdentity = null;
662
666
  senseAutostartTimer = null;
663
667
  externalEventReconcileTimer = null;
668
+ letterExpiryTimer = null;
664
669
  stateRetentionTimer = null;
665
670
  stateRetention;
666
671
  updaterAgentWatchTimer = null;
@@ -894,6 +899,14 @@ class OuroDaemon {
894
899
  void this.reconcileExternalEvents();
895
900
  }, 1_000);
896
901
  this.externalEventReconcileTimer.unref?.();
902
+ // The first pass waits out the grace after start, so the senses' catch-up over messages missed while the daemon
903
+ // was down records any answer sent before a letter expired, before the sweep can close that letter.
904
+ const expiryFrom = Date.now() + LETTER_EXPIRY_GRACE_MS;
905
+ this.letterExpiryTimer = setInterval(() => {
906
+ if (Date.now() >= expiryFrom)
907
+ void this.expireLetters();
908
+ }, LETTER_EXPIRY_TICK_MS);
909
+ this.letterExpiryTimer.unref?.();
897
910
  this.scheduleStateRetention(STATE_RETENTION_FIRST_DELAY_MS);
898
911
  this.scheduleUpdaterAgentWatch(UPDATER_AGENT_WATCH_FIRST_DELAY_MS);
899
912
  // Write all managed PIDs to disk so the next daemon can clean up
@@ -1218,6 +1231,23 @@ class OuroDaemon {
1218
1231
  }
1219
1232
  }
1220
1233
  }
1234
+ /**
1235
+ * One expiry pass. It reads no letters code until some bundle has letters, so a daemon without them loads nothing.
1236
+ * Answers how many letters it closed.
1237
+ */
1238
+ async expireLetters() {
1239
+ try {
1240
+ const any = !!this.lettersWriter || fs.readdirSync(this.bundlesRoot).some((name) => fs.existsSync(path.join(this.bundlesRoot, name, "state", "letters")));
1241
+ return any ? await (await this.letters()).expireDue() : 0;
1242
+ }
1243
+ catch (error) {
1244
+ // No bundles folder yet means no letters, not a failure worth a warning every minute.
1245
+ if (error.code === "ENOENT")
1246
+ return 0;
1247
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "daemon.letter_expiry_error", message: "the letter expiry pass failed", meta: { error: error.message } });
1248
+ return 0;
1249
+ }
1250
+ }
1221
1251
  async stop() {
1222
1252
  // Must be named `_end` (not `_stop`) to satisfy the nerves audit's
1223
1253
  // start/end pairing rule — see src/nerves/coverage/audit-rules.ts.
@@ -1241,6 +1271,10 @@ class OuroDaemon {
1241
1271
  clearTimeout(this.senseAutostartTimer);
1242
1272
  this.senseAutostartTimer = null;
1243
1273
  }
1274
+ if (this.letterExpiryTimer) {
1275
+ clearInterval(this.letterExpiryTimer);
1276
+ this.letterExpiryTimer = null;
1277
+ }
1244
1278
  if (this.externalEventReconcileTimer) {
1245
1279
  clearInterval(this.externalEventReconcileTimer);
1246
1280
  this.externalEventReconcileTimer = null;
@@ -1386,6 +1420,10 @@ class OuroDaemon {
1386
1420
  deliverChat: (await Promise.resolve().then(() => __importStar(require("../../senses/bluebubbles/agent-client")))).letterChatSender(this.bundlesRoot),
1387
1421
  // Filing tells the agent, in its own private runtime, so it decides when its person sees the letter.
1388
1422
  onFiled: (await Promise.resolve().then(() => __importStar(require("../letters/filed-note")))).letterFiledTeller(this.bundlesRoot, (wake) => this.handlePrivateRuntimeWake(wake)),
1423
+ // So does a letter that expires with no answer.
1424
+ onExpired: (await Promise.resolve().then(() => __importStar(require("../letters/expired-note")))).letterExpiredTeller(this.bundlesRoot, (wake) => this.handlePrivateRuntimeWake(wake)),
1425
+ // A recorded answer sends the person a receipt in the same chat and tells the agent.
1426
+ onAnswered: (await Promise.resolve().then(() => __importStar(require("../letters/answered-note")))).letterAnsweredTeller(this.bundlesRoot, (await Promise.resolve().then(() => __importStar(require("../../senses/bluebubbles/agent-client")))).letterChatSender(this.bundlesRoot), (wake) => this.handlePrivateRuntimeWake(wake)),
1389
1427
  }))();
1390
1428
  return this.lettersWriter;
1391
1429
  }
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.answerReceipt = answerReceipt;
37
+ exports.letterAnsweredNote = letterAnsweredNote;
38
+ exports.letterAnsweredWake = letterAnsweredWake;
39
+ exports.tellLetterAnswered = tellLetterAnswered;
40
+ exports.letterAnsweredTeller = letterAnsweredTeller;
41
+ // What happens once a person's answer is recorded (design §3.4, "Visibility"): the harness sends them a one-line
42
+ // receipt in the letters chat, so a misread answer shows at once, and tells the owning agent in its private runtime.
43
+ // Both run after the answer is recorded and never undo it; a failure is logged.
44
+ const path = __importStar(require("path"));
45
+ const pending_1 = require("../../mind/pending");
46
+ const runtime_1 = require("../../nerves/runtime");
47
+ const render_1 = require("./render");
48
+ /**
49
+ * The receipt the person sees, naming the letter as its heading does: "Recorded L7 · Slugger asks: Which name? → 2
50
+ * Ouro", so a paraphrase of another letter can't pass for it. Only Ouro writes it, so it may name the code.
51
+ */
52
+ function answerReceipt(letter, answer) {
53
+ return `Recorded ${(0, render_1.letterHeading)(letter)} → ${answer.option} ${answer.label}`;
54
+ }
55
+ /** The agent's note; the subject, label and note are other people's words, so they are quoted as theirs. */
56
+ function letterAnsweredNote(letter, answer) {
57
+ const note = answer.note ? `, with the note ${JSON.stringify(answer.note)}` : "";
58
+ return `my person answered letter ${letter.code} (its sender's subject: ${JSON.stringify(letter.subject)}) with option ${answer.option}, ${JSON.stringify(answer.label)}${note}. mailbox_read shows it.`;
59
+ }
60
+ function letterAnsweredWake(agent, letter) {
61
+ return {
62
+ kind: "private.wake",
63
+ agent,
64
+ reason: `letter ${letter.code} answered`,
65
+ triggerSource: "letter-answered",
66
+ budgetClass: "interactive",
67
+ idempotencyKey: `letter-answered:${agent}:${letter.id}`,
68
+ originRefs: [{ kind: "letter", id: letter.id }, { kind: "daemon-command", id: "letters.answer" }],
69
+ };
70
+ }
71
+ async function tellLetterAnswered(agent, agentRoot, letter, answer, sendReceipt, wake) {
72
+ if (sendReceipt && letter.answeringHandle) {
73
+ try {
74
+ await sendReceipt({ agent, handle: letter.answeringHandle, text: answerReceipt(letter, answer) });
75
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.receipt_sent", message: "the person was sent a receipt for their answer", meta: { code: letter.code } });
76
+ }
77
+ catch (error) {
78
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.receipt_failed", message: "the receipt for an answer didn't send; the answer stands", meta: { code: letter.code, error: error.message } });
79
+ }
80
+ }
81
+ (0, pending_1.queuePendingMessageOnce)((0, pending_1.getPrivateRuntimePendingDir)(agent, agentRoot), {
82
+ from: agent,
83
+ friendId: "self",
84
+ channel: "inner",
85
+ key: "dialog",
86
+ content: letterAnsweredNote(letter, answer),
87
+ timestamp: Date.parse(answer.at),
88
+ packetId: `letter-answered:${letter.id}`,
89
+ });
90
+ try {
91
+ const woke = await wake(letterAnsweredWake(agent, letter));
92
+ if (!woke.ok)
93
+ throw new Error(woke.error ?? "the wake was refused");
94
+ if (woke.data?.decision?.executable === false)
95
+ throw new Error(woke.message ?? "the wake was denied");
96
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.answered_told", message: "the agent was told its letter was answered", meta: { code: letter.code } });
97
+ }
98
+ catch (error) {
99
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.answered_wake_failed", message: "an answered letter's note waits for the agent's next private turn", meta: { code: letter.code, error: error.message } });
100
+ }
101
+ }
102
+ /** The daemon's onAnswered, over each agent's own bundle. */
103
+ function letterAnsweredTeller(bundlesRoot, sendReceipt, wake) {
104
+ return (agent, letter, answer) => tellLetterAnswered(agent, path.join(bundlesRoot, `${agent}.ouro`), letter, answer, sendReceipt, wake);
105
+ }
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.letterExpiredNote = letterExpiredNote;
37
+ exports.letterExpiredWake = letterExpiredWake;
38
+ exports.letterExpiredTeller = letterExpiredTeller;
39
+ // A letter that reaches its expiresAt with no answer closes as expired, and the agent that owns it is woken with
40
+ // "expired, no answer" (design §3.4, "Expiry"), so it can decide what its lane does without the person's answer.
41
+ const path = __importStar(require("path"));
42
+ const runtime_1 = require("../../nerves/runtime");
43
+ const tell_agent_1 = require("./tell-agent");
44
+ /** The note in the agent's own words; the subject is the sender's, quoted as theirs. */
45
+ function letterExpiredNote(letter) {
46
+ return `letter ${letter.code} expired at ${letter.expiresAt} with no answer from my person; its sender gave it the subject ${JSON.stringify(letter.subject)}. it is closed, so it can't be answered or delivered now; mailbox_read shows it.`;
47
+ }
48
+ /** The private-runtime wake for one expired letter; its idempotency key makes a repeat a duplicate. */
49
+ function letterExpiredWake(agent, letter) {
50
+ return {
51
+ kind: "private.wake",
52
+ agent,
53
+ reason: `letter ${letter.code} expired`,
54
+ triggerSource: "letter-expired",
55
+ budgetClass: "interactive",
56
+ idempotencyKey: `letter-expired:${agent}:${letter.id}`,
57
+ originRefs: [{ kind: "letter", id: letter.id }, { kind: "scheduler", id: "letters-expiry" }],
58
+ };
59
+ }
60
+ /** The daemon's onExpired: the note is dated by the expiry, so telling twice is one note. */
61
+ function letterExpiredTeller(bundlesRoot, wake) {
62
+ return async (agent, letter) => {
63
+ const note = { content: letterExpiredNote(letter), timestamp: Date.parse(letter.expiresAt), packetId: `letter-expired:${letter.id}` };
64
+ const problem = await (0, tell_agent_1.queueNoteAndWake)(agent, path.join(bundlesRoot, `${agent}.ouro`), note, () => wake(letterExpiredWake(agent, letter)));
65
+ if (problem === null) {
66
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.expired_told", message: "the agent was told a letter expired", meta: { code: letter.code } });
67
+ }
68
+ else {
69
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.expired_wake_failed", message: "an expired letter's note waits for the agent's next private turn", meta: { code: letter.code, error: problem } });
70
+ }
71
+ };
72
+ }
@@ -41,8 +41,8 @@ exports.letterFiledTeller = letterFiledTeller;
41
41
  // decide whether and when its person sees the letter. The note goes to the agent's own private runtime, the way a
42
42
  // habit that can't run tells it, and a wake has the agent read it now. It is the harness speaking, never the person.
43
43
  const path = __importStar(require("path"));
44
- const pending_1 = require("../../mind/pending");
45
44
  const runtime_1 = require("../../nerves/runtime");
45
+ const tell_agent_1 = require("./tell-agent");
46
46
  /** The note in the agent's own words, the way its private runtime notes read. */
47
47
  function letterFiledNote(letter) {
48
48
  // The lane and subject are the sender's words, quoted as theirs, so they can't read as the agent's own thought.
@@ -71,26 +71,13 @@ function letterFiledWake(agent, letter) {
71
71
  */
72
72
  async function tellAgentLetterFiled(agent, agentRoot, letter, wake) {
73
73
  // The queue names a note by its timestamp and packet id, so the letter's own filing time makes a repeat one note.
74
- (0, pending_1.queuePendingMessageOnce)((0, pending_1.getPrivateRuntimePendingDir)(agent, agentRoot), {
75
- from: agent,
76
- friendId: "self",
77
- channel: "inner",
78
- key: "dialog",
79
- content: letterFiledNote(letter),
80
- timestamp: Date.parse(letter.createdAt),
81
- packetId: `letter-filed:${letter.id}`,
82
- });
83
- try {
84
- const answer = await wake(letterFiledWake(agent, letter));
85
- if (!answer.ok)
86
- throw new Error(answer.error ?? "the wake was refused");
87
- // A wake policy denies still answers ok; only an executable decision woke the agent.
88
- if (answer.data?.decision?.executable === false)
89
- throw new Error(answer.message ?? "the wake was denied");
74
+ const note = { content: letterFiledNote(letter), timestamp: Date.parse(letter.createdAt), packetId: `letter-filed:${letter.id}` };
75
+ const problem = await (0, tell_agent_1.queueNoteAndWake)(agent, agentRoot, note, () => wake(letterFiledWake(agent, letter)));
76
+ if (problem === null) {
90
77
  (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.filed_told", message: "the agent was told a letter was filed", meta: { code: letter.code } });
91
78
  }
92
- catch (error) {
93
- (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.filed_wake_failed", message: "a filed letter's note waits for the agent's next private turn", meta: { code: letter.code, error: error.message } });
79
+ else {
80
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.filed_wake_failed", message: "a filed letter's note waits for the agent's next private turn", meta: { code: letter.code, error: problem } });
94
81
  }
95
82
  }
96
83
  /** The daemon's onFiled: each agent hears through its own bundle's private runtime. */
@@ -69,7 +69,8 @@ class LetterIndex {
69
69
  for (const entry of this.byId.values()) {
70
70
  if (dedupeScope(entry.letter) !== scope)
71
71
  continue;
72
- if (entry.state === "waiting")
72
+ // A letter past its expiry is as good as expired, though the sweep hasn't closed it yet, so a new one is filed.
73
+ if (entry.state === "waiting" && !(entry.letter.expiresAt && Date.parse(entry.letter.expiresAt) <= now))
73
74
  return { entry, why: "open" };
74
75
  const answer = entry.events.find((event) => event.t === "answered");
75
76
  if (answer && now - Date.parse(answer.at) <= exports.ANSWERED_DEDUPE_MS)
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.OPTIONS_LINE = void 0;
4
+ exports.letterHeading = letterHeading;
4
5
  exports.renderLetter = renderLetter;
5
6
  // How a letter reads in chat (design §3.4): plain text the harness writes, never the agent. The sender's fields
6
7
  // were checked and collapsed to one line each when the letter was filed, so nothing here can fake the option block.
@@ -19,12 +20,16 @@ function replyLine(letter) {
19
20
  const spoken = answers.length === 1 ? answers[0] : `${answers.slice(0, -1).join(", ")} or ${answers.at(-1)}`;
20
21
  return `Reply ${spoken}.`;
21
22
  }
23
+ /** The letter's first line, which names its code, its sender and its subject: `L7 · Slugger asks: Which name?`. */
24
+ function letterHeading(letter) {
25
+ return `${letter.code} · ${agentName(letter.from.agent)} ${VERB[letter.kind]}: ${letter.subject}`;
26
+ }
22
27
  /**
23
28
  * The letter as the person reads it. A link shows its label and address; a line anchor is dropped from the
24
29
  * address, so the chat never shows a code-shaped `#L12` beside the letter's own code.
25
30
  */
26
31
  function renderLetter(letter) {
27
- const lines = [`${letter.code} · ${agentName(letter.from.agent)} ${VERB[letter.kind]}: ${letter.subject}`];
32
+ const lines = [letterHeading(letter)];
28
33
  if (letter.whyOnlyYou)
29
34
  lines.push(letter.whyOnlyYou);
30
35
  if (letter.body)
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.queueNoteAndWake = queueNoteAndWake;
4
+ // How the mailbox tells the agent that owns it about a letter: a note in its own private runtime, then a wake so it
5
+ // reads the note now. A wake that fails leaves the note queued for the agent's next private turn, so it is never lost.
6
+ const pending_1 = require("../../mind/pending");
7
+ const runtime_1 = require("../../nerves/runtime");
8
+ /** Queues the note and wakes the agent: null once it is woken, or why the wake failed. A failed queue throws. */
9
+ async function queueNoteAndWake(agent, agentRoot, note, wake) {
10
+ (0, pending_1.queuePendingMessageOnce)((0, pending_1.getPrivateRuntimePendingDir)(agent, agentRoot), {
11
+ from: agent, friendId: "self", channel: "inner", key: "dialog", content: note.content, timestamp: note.timestamp, packetId: note.packetId,
12
+ });
13
+ let problem = null;
14
+ try {
15
+ const answer = await wake();
16
+ // A wake policy denies still answers ok; only an executable decision woke the agent.
17
+ if (!answer.ok)
18
+ problem = answer.error ?? "the wake was refused";
19
+ else if (answer.data?.decision?.executable === false)
20
+ problem = answer.message ?? "the wake was denied";
21
+ }
22
+ catch (error) {
23
+ problem = error.message;
24
+ }
25
+ (0, runtime_1.emitNervesEvent)({ level: "debug", component: "daemon", event: "letters.agent_note_queued", message: "a mailbox note was queued for the agent", meta: { packetId: note.packetId, woken: problem === null } });
26
+ return problem;
27
+ }
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.LettersWriter = exports.ROLL_AFTER_MS = exports.DELIVER_DEADLINE_MS = exports.LetterRefusal = exports.ownerFriendIds = void 0;
36
+ exports.LettersWriter = exports.ROLL_AFTER_MS = exports.DELIVER_DEADLINE_MS = exports.EXPIRY_GRACE_MS = exports.NOW_LETTER_EXPIRY_MS = exports.LetterRefusal = exports.ownerFriendIds = void 0;
37
37
  exports.answerLettersCommand = answerLettersCommand;
38
38
  // The letters' single writer (design §3.2): the daemon holds one of these, and every door (CLI, MCP, in-turn tools)
39
39
  // reaches it over the daemon's socket with a `letters.action` command. Each agent's letters live in its own bundle,
@@ -59,6 +59,14 @@ class LetterRefusal extends Error {
59
59
  }
60
60
  }
61
61
  exports.LetterRefusal = LetterRefusal;
62
+ /** How long a `now` letter waits when its sender sets no expiresAt (design §3.4, "Expiry"); other letters never expire. */
63
+ exports.NOW_LETTER_EXPIRY_MS = 24 * 60 * 60_000;
64
+ /**
65
+ * How long past its expiresAt a letter stays open before the sweep closes it. An answer the person sent before the
66
+ * expiry still counts when it is read late (by a webhook that lags, or a catch-up pass after a restart), and that
67
+ * needs the letter still waiting when it is read.
68
+ */
69
+ exports.EXPIRY_GRACE_MS = 10 * 60_000;
62
70
  /** Under the door's own timeout for a deliver (doors.ts), so the daemon always answers before the door gives up. */
63
71
  exports.DELIVER_DEADLINE_MS = 25_000;
64
72
  /** Closed letters move to closed/YYYY-MM/ this long after they close (design §3.2); they are never deleted. */
@@ -128,6 +136,39 @@ class LettersWriter {
128
136
  default: return Promise.reject(new LetterRefusal("unknown-door", `The mailbox has no action ${action}.`));
129
137
  }
130
138
  }
139
+ /**
140
+ * Closes every waiting letter more than EXPIRY_GRACE_MS past its expiresAt, in each agent's bundle that has letters,
141
+ * and tells its agent.
142
+ * The daemon runs it on a timer; it answers how many letters it closed.
143
+ */
144
+ async expireDue() {
145
+ let closed = 0;
146
+ for (const name of fs.readdirSync(this.deps.bundlesRoot)) {
147
+ const agent = name.endsWith(".ouro") ? name.slice(0, -".ouro".length) : "";
148
+ if (!AGENT_NAME.test(agent) || !fs.existsSync(path.join(this.deps.bundlesRoot, name, "state", "letters")))
149
+ continue;
150
+ try {
151
+ const letters = this.open(agent, false);
152
+ closed += await this.serial(letters, async () => {
153
+ const now = this.now();
154
+ const due = letters.index.list({}).filter((entry) => entry.letter.expiresAt && Date.parse(entry.letter.expiresAt) + exports.EXPIRY_GRACE_MS <= now.getTime());
155
+ for (const entry of due) {
156
+ this.addEvent(letters, entry.letter.id, { t: "expired", at: now.toISOString() });
157
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.letter_expired", message: "a letter expired with no answer", meta: { code: entry.letter.code } });
158
+ this.deps.onExpired?.(agent, entry.letter).catch((error) => {
159
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.expired_tell_failed", message: "the agent could not be told a letter expired", meta: { code: entry.letter.code, reason: error.message } });
160
+ });
161
+ }
162
+ return due.length;
163
+ });
164
+ }
165
+ catch (error) {
166
+ // One agent's letters that don't read leave the others' expiry alone.
167
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.expiry_failed", message: "an agent's letters could not be checked for expiry", meta: { agent, reason: error.message } });
168
+ }
169
+ }
170
+ return closed;
171
+ }
131
172
  /** The agent's letters, read from its bundle the first time; letters closed long enough are rolled then, unless that first call is a dry run, which writes nothing. */
132
173
  open(agent, dryRun) {
133
174
  const bundle = path.join(this.deps.bundlesRoot, `${agent}.ouro`);
@@ -195,6 +236,9 @@ class LettersWriter {
195
236
  const { lane, ...draft } = checked.letter;
196
237
  const from = { agent: letters.agent, ...(lane ? { lane } : {}) };
197
238
  const now = this.now();
239
+ if (draft.expiresAt && Date.parse(draft.expiresAt) <= now.getTime()) {
240
+ throw new LetterRefusal("invalid-letter", `expiresAt ${draft.expiresAt} has already passed. Fix: give a time in the future, or leave it out.`);
241
+ }
198
242
  const duplicate = letters.index.findDuplicate({ from, dedupeKey: draft.dedupeKey }, now.getTime());
199
243
  if (duplicate) {
200
244
  const { letter } = duplicate.entry;
@@ -216,8 +260,10 @@ class LettersWriter {
216
260
  letters.index.reserve(number + 1);
217
261
  // The person's answering handle is frozen into the letter now, so a later change leaves this letter alone.
218
262
  const answeringHandle = (0, answering_1.readAnsweringHandles)(letters.store.dir)[to];
263
+ const expiresAt = draft.expiresAt ?? (draft.urgency === "now" ? new Date(now.getTime() + exports.NOW_LETTER_EXPIRY_MS).toISOString() : undefined);
219
264
  const letter = {
220
- v: 1, id: (this.deps.newId ?? letter_1.newLetterId)(now.getTime()), code: `L${number}`, ...(answeringHandle ? { answeringHandle } : {}), to, from, ...draft, createdAt: now.toISOString(),
265
+ v: 1, id: (this.deps.newId ?? letter_1.newLetterId)(now.getTime()), code: `L${number}`, ...(answeringHandle ? { answeringHandle } : {}), to, from, ...draft,
266
+ ...(expiresAt ? { expiresAt } : {}), createdAt: now.toISOString(),
221
267
  };
222
268
  try {
223
269
  letters.store.create(letter);
@@ -285,6 +331,7 @@ class LettersWriter {
285
331
  });
286
332
  const label = letter.options.find((option) => option.id === answer.option).label;
287
333
  (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.answer_recorded", message: "a person's answer was recorded", meta: { code: letter.code, hostTrust } });
334
+ this.deps.onAnswered?.(letters.agent, letter, { option: answer.option, label, ...(answer.note ? { note: answer.note } : {}), messageGuid: message.guid, at }).catch(() => undefined);
288
335
  return { recorded: true, id: letter.id, code: letter.code, subject: letter.subject, option: answer.option, label, ...(answer.note ? { note: answer.note } : {}) };
289
336
  });
290
337
  }
@@ -201,6 +201,22 @@ async function evaluatePolicy(request, context, deps) {
201
201
  reason: "a letter was filed for the agent's person",
202
202
  };
203
203
  }
204
+ if (request.triggerSource === "letter-expired"
205
+ && hasNonEmptyOriginRef(originRefs, "letter")
206
+ && hasOriginRef(originRefs, "scheduler", "letters-expiry")) {
207
+ return {
208
+ result: "allow",
209
+ reason: "a letter expired with no answer",
210
+ };
211
+ }
212
+ if (request.triggerSource === "letter-answered"
213
+ && hasNonEmptyOriginRef(originRefs, "letter")
214
+ && hasOriginRef(originRefs, "daemon-command", "letters.answer")) {
215
+ return {
216
+ result: "allow",
217
+ reason: "the agent's person answered a letter",
218
+ };
219
+ }
204
220
  if (isVerifiedHabitWake(request.triggerSource, originRefs)) {
205
221
  return {
206
222
  result: "allow",
@@ -86,6 +86,8 @@ const model_1 = require("./model");
86
86
  const client_1 = require("./client");
87
87
  const letter_guard_1 = require("./letter-guard");
88
88
  const chat_interaction_1 = require("../../heart/chat-interaction");
89
+ const answer_command_1 = require("../../heart/letters/answer-command");
90
+ const letter_answer_ingress_1 = require("./letter-answer-ingress");
89
91
  const reactions_1 = require("./reactions");
90
92
  const send_file_1 = require("./send-file");
91
93
  const chat_file_1 = require("../chat-file");
@@ -440,6 +442,7 @@ const defaultDeps = {
440
442
  },
441
443
  recordProcessed: processed_log_1.recordProcessedBlueBubblesMessage,
442
444
  withSessionTurnLease: session_transaction_1.withSessionTurnLease,
445
+ answerLetter: (agent, messageGuid) => (0, letter_answer_ingress_1.askDaemonToAnswerLetter)(agent, messageGuid),
443
446
  // Incoming events recheck every time, like sends, so a server that takes over
444
447
  // the same URL under another account is refused immediately.
445
448
  verifyHostAccount: (options) => (0, host_account_verifier_1.verifyBlueBubblesServerAccount)({
@@ -1820,6 +1823,20 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1820
1823
  return { handled: true, notifiedAgent: false, kind: event.kind, reason: "from_me" };
1821
1824
  }
1822
1825
  options.lifecycleSignal?.throwIfAborted();
1826
+ // A message in answer form ("L7 2") from a one-to-one chat may answer a letter. The daemon decides from the
1827
+ // server's copy; a recorded answer is the harness's, so it doesn't become a chat turn, and the daemon tells
1828
+ // the agent. Anything else, or a daemon that can't be asked, runs the turn as usual.
1829
+ if (event.eventType === "new-message" && !event.chat.isGroup && event.fromMe !== true && (0, answer_command_1.looksLikeAnswer)(event.text)) {
1830
+ try {
1831
+ if (await resolvedDeps.answerLetter(agentName, event.messageGuid)) {
1832
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.bluebubbles_letter_answered", message: "a message answered a letter, so it is not a chat turn", meta: { messageGuid: event.messageGuid } });
1833
+ return { handled: true, notifiedAgent: false, kind: event.kind, reason: "letter_answered" };
1834
+ }
1835
+ }
1836
+ catch (error) {
1837
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.bluebubbles_letter_answer_unchecked", message: "couldn't ask the daemon whether a message answers a letter; it is a chat turn", meta: { messageGuid: event.messageGuid, reason: error.message } });
1838
+ }
1839
+ }
1823
1840
  // ── Adapter setup: friend, session, content, callbacks ────────
1824
1841
  const store = resolvedDeps.createFriendStore();
1825
1842
  const resolver = resolvedDeps.createFriendResolver(store, resolveFriendParams(event));
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.askDaemonToAnswerLetter = askDaemonToAnswerLetter;
4
+ // The chat side of a letter's answer (design §3.4): the sense names a message by GUID and the daemon decides from the
5
+ // server's own copy, so nothing this process saw in the webhook decides the answer.
6
+ const socket_client_1 = require("../../heart/daemon/socket-client");
7
+ const runtime_1 = require("../../nerves/runtime");
8
+ /** How long the sense waits for the daemon. A deliver can hold the daemon's letter queue for up to 25 s. */
9
+ const ANSWER_TIMEOUT_MS = 30_000;
10
+ /** The daemon records nothing after this much of the wait, so an answer is never recorded once the sense gives up on it. */
11
+ const ANSWER_DEADLINE_MS = 27_000;
12
+ /**
13
+ * Asks the daemon whether a message answers one of the agent's letters; true when it recorded an answer now or
14
+ * before (a replay). Past the deadline the daemon records nothing, so a timed-out ask leaves the message a chat turn.
15
+ */
16
+ async function askDaemonToAnswerLetter(agent, messageGuid, send = socket_client_1.sendDaemonCommand, now = Date.now) {
17
+ const answer = await send(socket_client_1.DEFAULT_DAEMON_SOCKET_PATH, { kind: "letters.answer", agent, messageGuid, deadlineAt: now() + ANSWER_DEADLINE_MS }, { timeoutMs: ANSWER_TIMEOUT_MS });
18
+ if (!answer.ok)
19
+ throw new Error(answer.error ?? "the daemon refused the letters.answer command");
20
+ const recorded = answer.data?.recorded === true;
21
+ (0, runtime_1.emitNervesEvent)({ level: "debug", component: "senses", event: "senses.bluebubbles_letter_answer_checked", message: "asked the daemon whether a message answers a letter", meta: { messageGuid, recorded } });
22
+ return recorded;
23
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1644",
3
+ "version": "0.1.0-alpha.1646",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1644",
9
+ "version": "0.1.0-alpha.1646",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1644",
3
+ "version": "0.1.0-alpha.1646",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {