@ouro.bot/cli 0.1.0-alpha.1647 → 0.1.0-alpha.1649

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,13 +1,20 @@
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.1649",
6
+ "changes": [
7
+ "A letter filed from an agent's turn now remembers that turn's session. Once the person's answer is recorded, the daemon queues \"Ari answered L7: 2 Ouro — after lunch\" in that session, so the conversation that asked reads the answer on its next turn. A letter filed from the private runtime, the CLI or an MCP client has no session to return to. The agent's private runtime is told of every answer as before, and anyone waiting with `mailbox_wait` is released as before.",
8
+ "Each try to return an answer writes a `returned` event. A try that fails is tried again after a minute, then after a doubling wait of at most an hour, until it succeeds.",
9
+ "The session must be one the agent has really had turns in. A voice session gets no returned note, because a voice call drops notes older than a few minutes. The note comes from the mailbox, so Telegram's rule that drops an agent's own stale outreach doesn't remove it.",
10
+ "The agent's private runtime note about an answer now names the session that asked, so the agent can raise the answer there sooner than that session's next turn.",
11
+ "When another caller refiles a letter, the reply says the answer returns to the session that first filed it.",
12
+ "When the person reads a letter in iMessage, the mailbox now records it as seen. The sense tells the daemon about the read receipt, and the daemon checks the BlueBubbles server's own copy of the message: Ouro sent it, into the chat the letter was delivered to, and the server has a read time. `mailbox_list` then shows `waiting, seen 2h ago` and `mailbox_read` returns `seen: \"seen 2h ago, not answered\"`, so an agent can tell its person has read the letter and doesn't ask again. A read receipt that arrives while the sense is down is not replayed, so a letter can be read without being marked seen."
13
+ ]
14
+ },
4
15
  {
5
16
  "version": "0.1.0-alpha.1647",
6
17
  "changes": [
7
- "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.",
8
- "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.",
9
- "`mailbox_send` refuses an `expiresAt` that has already passed.",
10
- "A daemon with no letters loads none of the mailbox's code for the expiry pass.",
11
18
  "The Butler's host upgrade tells the bundle migration which Butler name the new image runs (`--butler-name`), so the bundle's own files (agent.json, the replay-client provisioning record, recent attachments, skills and HOUSE.md) name the container path that image mounts.",
12
19
  "An await filed from an external event still resolves after the Butler's events folder moves to its other name, in either direction.",
13
20
  "When the Butler starts and finds events saved under its other name, it merges them into its own folder even when both folders exist. It combines the privileged spool's replay manifests first, so no accepted envelope is accepted twice. A record both folders have keeps the running Butler's copy, and the other copy moves to `external-events/.adoption-conflicts/<other name>/<time>/`, with a warning; nothing is deleted and the start goes on. Only a move that fails stops the daemon from starting, with guidance naming the container and Unraid host paths. An other-name entry that is a symlink is left alone, with a warning.",
@@ -16,6 +23,15 @@
16
23
  "The health acceptance probe runs as the Butler whose bundle is on disk, and the privileged spool scan files envelopes under the Butler the daemon start set, so neither recreates the other name's events folder after the rename."
17
24
  ]
18
25
  },
26
+ {
27
+ "version": "0.1.0-alpha.1646",
28
+ "changes": [
29
+ "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.",
30
+ "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.",
31
+ "`mailbox_send` refuses an `expiresAt` that has already passed.",
32
+ "A daemon with no letters loads none of the mailbox's code for the expiry pass."
33
+ ]
34
+ },
19
35
  {
20
36
  "version": "0.1.0-alpha.1645",
21
37
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1647",
2
+ "runtimeVersion": "0.1.0-alpha.1649",
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.1647</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1649</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -330,6 +330,12 @@
330
330
  "description": "waiting, answered, withdrawn or expired; Ouro derives it from the letter's events.",
331
331
  "kind": "string"
332
332
  },
333
+ "seen": {
334
+ "label": "Seen",
335
+ "description": "When the person read a waiting letter, such as \"seen 2h ago, not answered\", so it isn't asked again.",
336
+ "optional": true,
337
+ "kind": "string"
338
+ },
333
339
  "letter": {
334
340
  "label": "Letter",
335
341
  "description": "The letter as filed, as JSON.",
@@ -108,7 +108,7 @@
108
108
  "required": true
109
109
  }
110
110
  ],
111
- "output": "{ outcome, state, letter, events }"
111
+ "output": "{ outcome, state, seen, letter, events }"
112
112
  },
113
113
  {
114
114
  "name": "mailbox wait",
@@ -255,6 +255,10 @@
255
255
  "type": "string",
256
256
  "description": "waiting, answered, withdrawn or expired; Ouro derives it from the letter's events."
257
257
  },
258
+ "seen": {
259
+ "type": "string",
260
+ "description": "When the person read a waiting letter, such as \"seen 2h ago, not answered\", so it isn't asked again."
261
+ },
258
262
  "letter": {
259
263
  "type": "string",
260
264
  "description": "The letter as filed, as JSON."
@@ -1232,13 +1232,18 @@ class OuroDaemon {
1232
1232
  }
1233
1233
  }
1234
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.
1235
+ * One expiry pass, which also retries returning answers to the sessions that asked. It reads no letters code until
1236
+ * some bundle has letters, so a daemon without them loads nothing. Answers how many letters it closed.
1237
1237
  */
1238
1238
  async expireLetters() {
1239
1239
  try {
1240
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;
1241
+ if (!any)
1242
+ return 0;
1243
+ const writer = await this.letters();
1244
+ const expired = await writer.expireDue();
1245
+ await writer.returnAnswers();
1246
+ return expired;
1242
1247
  }
1243
1248
  catch (error) {
1244
1249
  // No bundles folder yet means no letters, not a failure worth a warning every minute.
@@ -2627,6 +2632,13 @@ class OuroDaemon {
2627
2632
  const { letterAnswerSource } = await Promise.resolve().then(() => __importStar(require("../../senses/bluebubbles/agent-client")));
2628
2633
  return answerLettersAnswerCommand(await this.letters(), command, letterAnswerSource(this.bundlesRoot));
2629
2634
  }
2635
+ case "letters.seen":
2636
+ {
2637
+ // A read receipt, named by the GUID of the message Ouro delivered; the server's copy decides.
2638
+ const { answerLettersSeenCommand } = await Promise.resolve().then(() => __importStar(require("../letters/seen-command")));
2639
+ const { letterAnswerSource } = await Promise.resolve().then(() => __importStar(require("../../senses/bluebubbles/agent-client")));
2640
+ return answerLettersSeenCommand(await this.letters(), command, letterAnswerSource(this.bundlesRoot));
2641
+ }
2630
2642
  case "mcp.list": {
2631
2643
  return (0, turn_execution_lease_1.withTurnExecutionLease)(async () => {
2632
2644
  const agentName = command.agent ?? "default";
@@ -55,7 +55,10 @@ function answerReceipt(letter, answer) {
55
55
  /** The agent's note; the subject, label and note are other people's words, so they are quoted as theirs. */
56
56
  function letterAnsweredNote(letter, answer) {
57
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.`;
58
+ const session = letter.from.session;
59
+ // The session that asked reads the answer on its next turn; naming it lets me raise the answer there sooner.
60
+ const asked = session ? ` it was asked from my ${session.channel} session with ${session.friendId} (${JSON.stringify(session.key)}), where the answer is left too.` : "";
61
+ return `my person answered letter ${letter.code} (its sender's subject: ${JSON.stringify(letter.subject)}) with option ${answer.option}, ${JSON.stringify(answer.label)}${note}.${asked} mailbox_read shows it.`;
59
62
  }
60
63
  function letterAnsweredWake(agent, letter) {
61
64
  return {
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.ANSWERING_FILE = void 0;
36
+ exports.listBundleFriends = exports.ANSWERING_FILE = void 0;
37
37
  exports.ownerFriendIds = ownerFriendIds;
38
38
  exports.normalizeAnsweringHandle = normalizeAnsweringHandle;
39
39
  exports.readAnsweringHandles = readAnsweringHandles;
@@ -52,8 +52,9 @@ const friends_1 = require("@ouro.bot/friends");
52
52
  const runtime_1 = require("../../nerves/runtime");
53
53
  exports.ANSWERING_FILE = "answering.json";
54
54
  const listBundleFriends = (root) => new friends_1.FileFriendStore(path.join(root, "friends")).listAll();
55
+ exports.listBundleFriends = listBundleFriends;
55
56
  /** The family records in a bundle's friends folder that name this machine's owner, the rule `ouro friend link-code` uses. */
56
- async function ownerFriendIds(bundleRoot, owner, list = listBundleFriends) {
57
+ async function ownerFriendIds(bundleRoot, owner, list = exports.listBundleFriends) {
57
58
  const friends = await list(bundleRoot);
58
59
  return friends
59
60
  .filter((record) => record.trustLevel === "family" && record.externalIds.some((id) => (0, friends_1.isLocalMachineOwnerIdentity)(id.provider, id.externalId, owner)))
@@ -164,7 +165,7 @@ async function setAnsweringHandle(bundleRoot, person, rawHandle, deps = {}) {
164
165
  const checked = normalizeAnsweringHandle(rawHandle);
165
166
  if (!checked.ok)
166
167
  throw refusal("bad-handle", checked.problem);
167
- const list = deps.list ?? listBundleFriends;
168
+ const list = deps.list ?? exports.listBundleFriends;
168
169
  const friends = await list(bundleRoot);
169
170
  const byId = friends.find((record) => record.id === person);
170
171
  const byName = friends.filter((record) => record.name.toLowerCase() === person.toLowerCase());
@@ -35,6 +35,7 @@ async function runMailboxTool(name, args, ctx) {
35
35
  try {
36
36
  return JSON.stringify(await (0, doors_1.runMailboxAction)(name, input, {
37
37
  agent: ctx?.agentName ?? (0, identity_1.getAgentName)(),
38
+ ...(ctx?.currentSession ? { session: { friendId: ctx.currentSession.friendId, channel: ctx.currentSession.channel, key: ctx.currentSession.key } } : {}),
38
39
  ...(ctx?.daemonSocketPath ? { socketPath: ctx.daemonSocketPath } : {}),
39
40
  }));
40
41
  }
@@ -218,7 +218,10 @@ async function runMailboxAction(action, input, caller) {
218
218
  }
219
219
  const send = caller.send ?? (await Promise.resolve().then(() => __importStar(require("../daemon/socket-client")))).sendDaemonCommand;
220
220
  const socketPath = caller.socketPath ?? (await Promise.resolve().then(() => __importStar(require("../daemon/socket-client")))).DEFAULT_DAEMON_SOCKET_PATH;
221
- const command = { kind: "letters.action", agent: caller.agent, action, input, ...(caller.dryRun ? { dryRun: true } : {}) };
221
+ const command = {
222
+ kind: "letters.action", agent: caller.agent, action, input, ...(caller.dryRun ? { dryRun: true } : {}),
223
+ ...(caller.session && action === "mailbox_send" ? { session: caller.session } : {}),
224
+ };
222
225
  // A wait holds the socket for its own timeout, and a deliver for its chat send (the daemon answers within
223
226
  // DELIVER_DEADLINE_MS of starting it, perhaps after another deliver ahead of it); anything else answers at once.
224
227
  const waitSeconds = action === "mailbox_wait" ? Number(input.timeout ?? 60) : action === "mailbox_deliver" ? 60 : 0;
@@ -0,0 +1,99 @@
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.RETURN_BACKOFF_MAX_MS = void 0;
37
+ exports.returnSession = returnSession;
38
+ exports.answerReturnText = answerReturnText;
39
+ exports.queueAnswerReturn = queueAnswerReturn;
40
+ exports.returnDue = returnDue;
41
+ // Returning a person's answer to the session that asked (design §3.4, "Answer return"). A letter filed from an
42
+ // agent's turn remembers that turn's session; once the answer is recorded, the daemon queues a note in that session,
43
+ // so its next turn reads "Ari answered L7: Ouro". The agent's private runtime is told separately (answered-note.ts).
44
+ const fs = __importStar(require("fs"));
45
+ const config_1 = require("../config");
46
+ const pending_1 = require("../../mind/pending");
47
+ const runtime_1 = require("../../nerves/runtime");
48
+ /**
49
+ * Channels a returned note can't serve: the private runtime is told of every answer anyway, and a voice session drops
50
+ * any note older than a few minutes unread.
51
+ */
52
+ const NO_RETURN_CHANNELS = new Set(["inner", "voice"]);
53
+ /**
54
+ * The session a letter returns its answer to, or null when there is none to return to: a caller with no session
55
+ * (the CLI, an MCP client), a channel in NO_RETURN_CHANNELS, coordinates that would name a folder outside the
56
+ * agent's own, or a session the agent has never had. With `agentRoot`, the session must have its session file.
57
+ */
58
+ function returnSession(value, agentRoot) {
59
+ if (typeof value !== "object" || value === null)
60
+ return null;
61
+ const { friendId, channel, key } = value;
62
+ if (![friendId, channel, key].every((part) => (0, config_1.isValidSessionCoordinate)(part) && part.length <= 300))
63
+ return null;
64
+ const session = { friendId: friendId, channel: channel, key: key };
65
+ if (NO_RETURN_CHANNELS.has(session.channel))
66
+ return null;
67
+ if (agentRoot !== undefined && !fs.existsSync((0, config_1.resolveSessionPath)(session.friendId, session.channel, session.key, { agentRoot })))
68
+ return null;
69
+ return session;
70
+ }
71
+ /** The note the asking session reads; the label and note are the person's words. */
72
+ function answerReturnText(person, letter, answer) {
73
+ return `${person} answered ${letter.code}: ${answer.option} ${answer.label}${answer.note ? ` — ${answer.note}` : ""}`;
74
+ }
75
+ /** Queues the note in the session's pending folder, once per letter. A failed write throws. */
76
+ function queueAnswerReturn(agent, agentRoot, session, text, letter, at) {
77
+ (0, pending_1.queuePendingMessageOnce)((0, pending_1.getPendingDir)(agent, session.friendId, session.channel, session.key, agentRoot), {
78
+ // From the mailbox, not the agent: a Telegram session drops the agent's own stale notes unread.
79
+ from: "mailbox", friendId: session.friendId, channel: session.channel, key: session.key, content: text, timestamp: Date.parse(at), packetId: `letter-returned:${letter.id}`,
80
+ });
81
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.answer_returned", message: "an answer was returned to the session that asked", meta: { code: letter.code, channel: session.channel } });
82
+ }
83
+ /** The longest wait between tries, so a session that can't be written is still tried every hour. */
84
+ exports.RETURN_BACKOFF_MAX_MS = 60 * 60_000;
85
+ /**
86
+ * Whether an answered letter's return is due now: it has a session, no try has succeeded, and the wait after the last
87
+ * failed try (one minute, doubling, at most an hour) has passed.
88
+ */
89
+ function returnDue(letter, events, now) {
90
+ if (!returnSession(letter.from.session) || !events.some((event) => event.t === "answered"))
91
+ return false;
92
+ const tries = events.filter((event) => event.t === "returned" && event.to === "session");
93
+ if (tries.some((event) => event.ok))
94
+ return false;
95
+ if (tries.length === 0)
96
+ return true;
97
+ const wait = Math.min(60_000 * 2 ** (tries.length - 1), exports.RETURN_BACKOFF_MAX_MS);
98
+ return now >= Date.parse(tries[tries.length - 1].at) + wait;
99
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.answerLettersSeenCommand = answerLettersSeenCommand;
4
+ // The daemon's `letters.seen` command: the BlueBubbles ingress names a message whose read receipt it saw, and the
5
+ // daemon reads that message from the agent's own server and records that the person read the letter it delivered.
6
+ // Like `letters.answer`, the command carries only a GUID, so whoever sends it can only point at a real message.
7
+ const runtime_1 = require("../../nerves/runtime");
8
+ async function answerLettersSeenCommand(writer, command, sourceFor) {
9
+ if (typeof command.agent !== "string" || typeof command.messageGuid !== "string" || !command.messageGuid.trim()) {
10
+ return { ok: false, error: "letters.seen needs an agent and a messageGuid." };
11
+ }
12
+ if (!writer.hasAgent(command.agent))
13
+ return { ok: false, error: `No agent bundle ${command.agent}.ouro is on this machine.` };
14
+ try {
15
+ const guid = command.messageGuid.trim();
16
+ // Most read receipts are for ordinary chat messages, so the index is asked before the server is.
17
+ if (!writer.hasWaitingDelivery(command.agent, guid))
18
+ return { ok: true, data: { recorded: false, reason: "no-letter" } };
19
+ const source = await sourceFor(command.agent);
20
+ // The server password travels in the fetch's query string, so only a server nobody between can read is asked.
21
+ if (source.trust === "untrusted")
22
+ return { ok: true, data: { recorded: false, reason: "untrusted-server-url" } };
23
+ const message = await source.getServerMessage(guid);
24
+ if (!message || message.guid !== guid)
25
+ return { ok: true, data: { recorded: false, reason: "unknown-message" } };
26
+ return { ok: true, data: await writer.recordSeen(command.agent, message) };
27
+ }
28
+ catch (error) {
29
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.seen_failed", message: "a read receipt couldn't be checked", meta: { reason: error.message } });
30
+ return { ok: false, error: error.message };
31
+ }
32
+ }
@@ -46,6 +46,7 @@ const answer_reader_1 = require("./answer-reader");
46
46
  const letter_1 = require("./letter");
47
47
  const answering_1 = require("./answering");
48
48
  Object.defineProperty(exports, "ownerFriendIds", { enumerable: true, get: function () { return answering_1.ownerFriendIds; } });
49
+ const return_to_session_1 = require("./return-to-session");
49
50
  const render_1 = require("./render");
50
51
  const letter_index_1 = require("./letter-index");
51
52
  const store_1 = require("./store");
@@ -74,6 +75,11 @@ exports.ROLL_AFTER_MS = 90 * 24 * 60 * 60 * 1000;
74
75
  const AGENT_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
75
76
  const WAIT_DEFAULT_S = 60;
76
77
  const WAIT_MAX_S = 300;
78
+ /** How long ago the person read a waiting letter, such as "2h", which tells an agent not to ask again; null when unread. */
79
+ function seenAgo(entry, now) {
80
+ const seen = entry.state === "waiting" ? entry.events.find((event) => event.t === "seen") : undefined;
81
+ return seen ? ageOf(seen.at, now) : null;
82
+ }
77
83
  function ageOf(createdAt, now) {
78
84
  const minutes = Math.max(0, Math.floor((now - Date.parse(createdAt)) / 60000));
79
85
  if (minutes < 60)
@@ -115,18 +121,19 @@ class LettersWriter {
115
121
  if (typeof input !== "object" || input === null || Array.isArray(input))
116
122
  throw new LetterRefusal("bad-input", "The action's input must be an object.");
117
123
  const letters = this.open(agent, options.dryRun === true);
118
- const result = await this.dispatch(letters, action, input, options.dryRun === true);
124
+ const session = action === "mailbox_send" ? (0, return_to_session_1.returnSession)(options.session, path.join(this.deps.bundlesRoot, `${agent}.ouro`)) : null;
125
+ const result = await this.dispatch(letters, action, input, options.dryRun === true, session);
119
126
  (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.action_done", message: "letters action done", meta: { action, outcome: result.outcome } });
120
127
  return result;
121
128
  }
122
- dispatch(letters, action, input, dryRun) {
129
+ dispatch(letters, action, input, dryRun, session) {
123
130
  switch (action) {
124
131
  case "mailbox_send": return this.serial(letters, () => {
125
132
  // Each send first rolls the letters closed long enough, so a daemon that runs for months still rolls them; a
126
133
  // dry run writes nothing, so it doesn't roll.
127
134
  if (!dryRun)
128
135
  this.rollClosed(letters);
129
- return this.send(letters, input, dryRun);
136
+ return this.send(letters, input, dryRun, session);
130
137
  });
131
138
  case "mailbox_list": return Promise.resolve(this.list(letters, input));
132
139
  case "mailbox_read": return Promise.resolve(this.read(letters, input));
@@ -229,12 +236,12 @@ class LettersWriter {
229
236
  ? "No family friend record names this machine's owner, so Ouro can't tell who the letter is to."
230
237
  : `${ids.length} family records name this machine's owner, so Ouro can't tell which one the letter is to.`);
231
238
  }
232
- async send(letters, input, dryRun) {
239
+ async send(letters, input, dryRun, session) {
233
240
  const checked = (0, letter_1.checkLetterInput)(input);
234
241
  if (!checked.ok)
235
242
  throw new LetterRefusal("invalid-letter", checked.problem);
236
243
  const { lane, ...draft } = checked.letter;
237
- const from = { agent: letters.agent, ...(lane ? { lane } : {}) };
244
+ const from = { agent: letters.agent, ...(session ? { session } : {}), ...(lane ? { lane } : {}) };
238
245
  const now = this.now();
239
246
  if (draft.expiresAt && Date.parse(draft.expiresAt) <= now.getTime()) {
240
247
  throw new LetterRefusal("invalid-letter", `expiresAt ${draft.expiresAt} has already passed. Fix: give a time in the future, or leave it out.`);
@@ -249,7 +256,8 @@ class LettersWriter {
249
256
  return { outcome: "done", id: letter.id, code: letter.code, state: "answered", message: `${letter.code} was answered ${optionText(letter, answer.option)} in the last day, so the answer stands.` };
250
257
  }
251
258
  this.addEvent(letters, letter.id, { t: "refiled", at: now.toISOString(), by: letters.agent });
252
- return { outcome: "done", id: letter.id, code: letter.code, state: "waiting", message: `${letter.code} is already waiting with this dedupeKey, so it was refiled, not filed again.` };
259
+ const elsewhere = letter.from.session && JSON.stringify(letter.from.session) !== JSON.stringify(session) ? " Its answer returns to the session that first filed it." : "";
260
+ return { outcome: "done", id: letter.id, code: letter.code, state: "waiting", message: `${letter.code} is already waiting with this dedupeKey, so it was refiled, not filed again.${elsewhere}` };
253
261
  }
254
262
  const to = await this.person(letters.agent);
255
263
  if (dryRun)
@@ -332,9 +340,121 @@ class LettersWriter {
332
340
  const label = letter.options.find((option) => option.id === answer.option).label;
333
341
  (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.answer_recorded", message: "a person's answer was recorded", meta: { code: letter.code, hostTrust } });
334
342
  this.deps.onAnswered?.(letters.agent, letter, { option: answer.option, label, ...(answer.note ? { note: answer.note } : {}), messageGuid: message.guid, at }).catch(() => undefined);
343
+ // Its own step on the queue, so the person's answer is recorded and answered on whatever the return does.
344
+ void this.serial(letters, () => this.returnAnswer(letters, letter.id)).catch((error) => {
345
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.return_step_failed", message: "an answer's return step failed; the retry pass tries it again", meta: { code: letter.code, reason: error.message } });
346
+ });
335
347
  return { recorded: true, id: letter.id, code: letter.code, subject: letter.subject, option: answer.option, label, ...(answer.note ? { note: answer.note } : {}) };
336
348
  });
337
349
  }
350
+ /**
351
+ * Records that the person read a waiting letter, from the server's own copy of the message Ouro delivered it as:
352
+ * sent by this side, into the chat it was delivered to, with the server's read time. Once per letter.
353
+ */
354
+ recordSeen(agent, message) {
355
+ const letters = this.open(agent, false);
356
+ return this.serial(letters, async () => {
357
+ const found = this.waitingDelivery(letters, message.guid);
358
+ if (!found)
359
+ return { recorded: false, reason: "no-letter" };
360
+ const { entry, delivered } = found;
361
+ let problem = null;
362
+ if (message.isFromMe !== true)
363
+ problem = "not-from-me";
364
+ else if (message.chatGuids.length !== 1 || message.chatGuids[0] !== delivered.key)
365
+ problem = "wrong-chat";
366
+ else if (message.dateRead === undefined)
367
+ problem = "not-read";
368
+ else if (entry.events.some((event) => event.t === "seen"))
369
+ problem = "already-seen";
370
+ if (problem)
371
+ return { recorded: false, reason: problem };
372
+ this.addEvent(letters, entry.letter.id, { t: "seen", at: new Date(message.dateRead).toISOString(), via: "chat" });
373
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.letter_seen", message: "the person read a letter", meta: { code: entry.letter.code } });
374
+ return { recorded: true, code: entry.letter.code };
375
+ });
376
+ }
377
+ /**
378
+ * Whether a waiting letter was delivered as this message, read from the index alone. The daemon asks it before it
379
+ * fetches anything from the server, since most read receipts are for ordinary chat messages.
380
+ */
381
+ hasWaitingDelivery(agent, messageGuid) {
382
+ return this.waitingDelivery(this.open(agent, false), messageGuid) !== null;
383
+ }
384
+ /** The waiting letter delivered as this message, with its delivered event; a send that wasn't confirmed has no GUID. */
385
+ waitingDelivery(letters, messageGuid) {
386
+ if (!messageGuid)
387
+ return null;
388
+ for (const entry of letters.index.list({})) {
389
+ const delivered = entry.events.find((event) => event.t === "delivered" && event.messageId === messageGuid);
390
+ if (delivered)
391
+ return { entry, delivered: delivered };
392
+ }
393
+ return null;
394
+ }
395
+ /**
396
+ * Returns an answered letter's answer to the session that asked, when that is due, and records the try as a
397
+ * `returned` event. A failed try is retried by returnAnswers; the answer stands either way.
398
+ */
399
+ async returnAnswer(letters, id) {
400
+ const entry = letters.index.get(id);
401
+ const { letter } = entry;
402
+ if (!(0, return_to_session_1.returnDue)(letter, entry.events, this.now().getTime()))
403
+ return false;
404
+ const answer = entry.events.findLast((event) => event.t === "answered");
405
+ const label = letter.options.find((option) => option.id === answer.option).label;
406
+ const at = this.now().toISOString();
407
+ try {
408
+ const bundle = path.join(this.deps.bundlesRoot, `${letters.agent}.ouro`);
409
+ const friends = await (this.deps.listFriends ?? answering_1.listBundleFriends)(bundle).catch(() => []);
410
+ const person = friends.find((friend) => friend.id === letter.to)?.name || "my person";
411
+ (0, return_to_session_1.queueAnswerReturn)(letters.agent, bundle, letter.from.session, (0, return_to_session_1.answerReturnText)(person, letter, { option: answer.option, label, ...(answer.note ? { note: answer.note } : {}) }), letter, answer.at);
412
+ this.addEvent(letters, id, { t: "returned", at, to: "session", ok: true });
413
+ }
414
+ catch (error) {
415
+ const detail = error.message;
416
+ this.addEvent(letters, id, { t: "returned", at, to: "session", ok: false, detail });
417
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.return_failed", message: "an answer couldn't be returned to the session that asked; it will be tried again", meta: { code: letter.code, detail } });
418
+ }
419
+ return true;
420
+ }
421
+ /**
422
+ * Tries again every answer whose return to its session failed and is due, across the bundles that have letters.
423
+ * The daemon runs it on a timer; it answers how many it tried.
424
+ */
425
+ async returnAnswers() {
426
+ let tried = 0;
427
+ let names = [];
428
+ try {
429
+ names = fs.readdirSync(this.deps.bundlesRoot);
430
+ }
431
+ catch (error) {
432
+ if (error.code !== "ENOENT")
433
+ throw error;
434
+ }
435
+ for (const name of names) {
436
+ const agent = name.endsWith(".ouro") ? name.slice(0, -".ouro".length) : "";
437
+ if (!AGENT_NAME.test(agent) || !fs.existsSync(path.join(this.deps.bundlesRoot, name, "state", "letters")))
438
+ continue;
439
+ try {
440
+ const letters = this.open(agent, false);
441
+ tried += await this.serial(letters, async () => {
442
+ const now = this.now().getTime();
443
+ let count = 0;
444
+ for (const entry of letters.index.list({ all: true }).filter((entry) => entry.state === "answered")) {
445
+ if ((0, return_to_session_1.returnDue)(entry.letter, entry.events, now) && await this.returnAnswer(letters, entry.letter.id))
446
+ count += 1;
447
+ }
448
+ return count;
449
+ });
450
+ }
451
+ catch (error) {
452
+ // One agent's letters that don't read leave the others' returns alone.
453
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.returns_failed", message: "an agent's answers could not be checked for return", meta: { agent, reason: error.message } });
454
+ }
455
+ }
456
+ return tried;
457
+ }
338
458
  list(letters, input) {
339
459
  const now = this.now().getTime();
340
460
  const entries = letters.index.list({
@@ -342,12 +462,16 @@ class LettersWriter {
342
462
  ...(typeof input.kind === "string" ? { kind: input.kind } : {}),
343
463
  ...(input.mine === true ? { from: letters.agent } : {}),
344
464
  });
345
- const listing = entries.map((entry) => `${entry.letter.code} ${entry.state} ${ageOf(entry.letter.createdAt, now)} ${entry.letter.subject}`).join("\n");
465
+ const listing = entries.map((entry) => {
466
+ const seen = seenAgo(entry, now);
467
+ return `${entry.letter.code} ${seen ? `waiting, seen ${seen} ago` : entry.state} ${ageOf(entry.letter.createdAt, now)} ${entry.letter.subject}`;
468
+ }).join("\n");
346
469
  return { outcome: "done", count: entries.length, listing };
347
470
  }
348
471
  read(letters, input) {
349
472
  const entry = this.find(letters, input);
350
- return { outcome: "done", state: entry.state, letter: JSON.stringify(entry.letter), events: entry.events.map((event) => eventLine(entry.letter, event)).join("\n") };
473
+ const seen = seenAgo(entry, this.now().getTime());
474
+ return { outcome: "done", state: entry.state, ...(seen ? { seen: `seen ${seen} ago, not answered` } : {}), letter: JSON.stringify(entry.letter), events: entry.events.map((event) => eventLine(entry.letter, event)).join("\n") };
351
475
  }
352
476
  /** Blocks until the letter leaves waiting, or has an event past the cursor, or the timeout ends. */
353
477
  async wait(letters, input) {
@@ -456,7 +580,7 @@ function mayHaveSent(error) {
456
580
  /** The daemon's answer to a `letters.action` command: the result, or the refusal's code and text. */
457
581
  async function answerLettersCommand(writer, command) {
458
582
  try {
459
- return { ok: true, data: await writer.run(command.agent, command.action, command.input, { dryRun: command.dryRun === true }) };
583
+ return { ok: true, data: await writer.run(command.agent, command.action, command.input, { dryRun: command.dryRun === true, session: command.session }) };
460
584
  }
461
585
  catch (error) {
462
586
  if (error instanceof LetterRefusal)
@@ -443,6 +443,7 @@ const defaultDeps = {
443
443
  recordProcessed: processed_log_1.recordProcessedBlueBubblesMessage,
444
444
  withSessionTurnLease: session_transaction_1.withSessionTurnLease,
445
445
  answerLetter: (agent, messageGuid) => (0, letter_answer_ingress_1.askDaemonToAnswerLetter)(agent, messageGuid),
446
+ letterSeen: (agent, messageGuid) => (0, letter_answer_ingress_1.tellDaemonLetterSeen)(agent, messageGuid),
446
447
  // Incoming events recheck every time, like sends, so a server that takes over
447
448
  // the same URL under another account is refused immediately.
448
449
  verifyHostAccount: (options) => (0, host_account_verifier_1.verifyBlueBubblesServerAccount)({
@@ -2953,6 +2954,14 @@ async function handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, so
2953
2954
  if (captured.normalized.chat.isGroup) {
2954
2955
  recordDiscoveredOwnHandle(captured.normalized.sender.externalId);
2955
2956
  }
2957
+ // The person read a message this side sent in a one-to-one chat; if it delivered a letter, the daemon records
2958
+ // that they've seen it, from the server's copy. Nothing waits on it, and a failure only loses the "seen".
2959
+ if (captured.capture.event.kind === "read" && !captured.normalized.chat.isGroup) {
2960
+ const messageGuid = captured.normalized.messageGuid;
2961
+ resolvedDeps.letterSeen(agentName, messageGuid).catch((error) => {
2962
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.bluebubbles_letter_seen_unchecked", message: "couldn't tell the daemon a message was read", meta: { messageGuid, reason: error.message } });
2963
+ });
2964
+ }
2956
2965
  const result = {
2957
2966
  handled: true,
2958
2967
  notifiedAgent: false,
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tellDaemonLetterSeen = tellDaemonLetterSeen;
3
4
  exports.askDaemonToAnswerLetter = askDaemonToAnswerLetter;
4
5
  // 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
6
  // server's own copy, so nothing this process saw in the webhook decides the answer.
@@ -9,10 +10,21 @@ const runtime_1 = require("../../nerves/runtime");
9
10
  const ANSWER_TIMEOUT_MS = 30_000;
10
11
  /** The daemon records nothing after this much of the wait, so an answer is never recorded once the sense gives up on it. */
11
12
  const ANSWER_DEADLINE_MS = 27_000;
13
+ /** How long the sense waits for the daemon to check a read receipt; nothing waits on the answer. */
14
+ const SEEN_TIMEOUT_MS = 30_000;
12
15
  /**
13
16
  * Asks the daemon whether a message answers one of the agent's letters; true when it recorded an answer now or
14
17
  * before (a replay). Past the deadline the daemon records nothing, so a timed-out ask leaves the message a chat turn.
15
18
  */
19
+ /** Tells the daemon the server reported a message read; it records `seen` if that message delivered a letter. */
20
+ async function tellDaemonLetterSeen(agent, messageGuid, send = socket_client_1.sendDaemonCommand) {
21
+ const answer = await send(socket_client_1.DEFAULT_DAEMON_SOCKET_PATH, { kind: "letters.seen", agent, messageGuid }, { timeoutMs: SEEN_TIMEOUT_MS });
22
+ if (!answer.ok)
23
+ throw new Error(answer.error ?? "the daemon refused the letters.seen command");
24
+ const recorded = answer.data?.recorded === true;
25
+ (0, runtime_1.emitNervesEvent)({ level: "debug", component: "senses", event: "senses.bluebubbles_letter_seen_checked", message: "told the daemon a message was read", meta: { messageGuid, recorded } });
26
+ return recorded;
27
+ }
16
28
  async function askDaemonToAnswerLetter(agent, messageGuid, send = socket_client_1.sendDaemonCommand, now = Date.now) {
17
29
  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
30
  if (!answer.ok)
@@ -21,6 +21,7 @@ function serverMessageFromPayload(payload) {
21
21
  const dateCreated = time(data.dateCreated);
22
22
  const dateEdited = time(data.dateEdited);
23
23
  const dateRetracted = time(data.dateRetracted);
24
+ const dateRead = time(data.dateRead);
24
25
  const threadOriginatorGuid = text(data.threadOriginatorGuid);
25
26
  return {
26
27
  guid,
@@ -33,6 +34,7 @@ function serverMessageFromPayload(payload) {
33
34
  ...(dateCreated ? { dateCreated } : {}),
34
35
  ...(dateEdited ? { dateEdited } : {}),
35
36
  ...(dateRetracted ? { dateRetracted } : {}),
37
+ ...(dateRead ? { dateRead } : {}),
36
38
  ...(threadOriginatorGuid ? { threadOriginatorGuid } : {}),
37
39
  };
38
40
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1647",
3
+ "version": "0.1.0-alpha.1649",
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.1647",
9
+ "version": "0.1.0-alpha.1649",
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.1647",
3
+ "version": "0.1.0-alpha.1649",
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": {