@ouro.bot/cli 0.1.0-alpha.1642 → 0.1.0-alpha.1643

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
@@ -2,11 +2,23 @@
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
4
  {
5
- "version": "0.1.0-alpha.1642",
5
+ "version": "0.1.0-alpha.1643",
6
+ "changes": [
7
+ "Update the Ouro UI files to Ouro UI v1.3.590.",
8
+ "The daemon can now record a person's answer to a letter from their own iMessage. Given only a message's GUID, it reads that message from the agent's BlueBubbles server and records the answer only when every check holds on the server's own fields:",
9
+ "The text is exactly the letter's code and an option number, such as `L7 2`, with an optional note after a dash. The note loses format characters and is capped at 200 characters.",
10
+ "It comes from the letter's answering handle, in that handle's one-to-one iMessage chat. It is not sent by SMS, not by the agent (a message whose direction the server doesn't state counts as the agent's), and not as a threaded reply, an edit or a retraction.",
11
+ "It was sent after the letter, timed by the server's own clock for the letter's sent message when the server has it, otherwise by the daemon's delivery time less five minutes, and before the letter's expiry.",
12
+ "Its GUID hasn't answered before. A ledger in `state/letters/answered-guids.jsonl` keeps replays and recovery passes from answering twice.",
13
+ "Anything else records nothing. The daemon asks only a server on the same Mac, behind TLS, or at a tailnet address, because the fetch carries the server password. It checks the agent's bundle before reading anything for it. Each answer records whether a shell running beside the daemon could send as the person: `separate` only when the daemon runs under the agent's declared BlueBubbles host account (`senses.bluebubbles.hostUsername`), where a shell can at most send as the agent, otherwise `shared-apple-id`. The chat ingress that sends these GUIDs comes in the next change.",
14
+ "A message that already answered its letter gets the same answer when it is checked again, so a retry or a recovery replay is never also run as a chat turn. The asker can set a deadline, and nothing is recorded after it."
15
+ ]
16
+ },
17
+ {
18
+ "version": "0.1.0-alpha.1641",
6
19
  "changes": [
7
20
  "Filing a letter now tells the agent that owns the mailbox. A note such as `letter L7 from the lane \"desk/task\" was filed (decide, today); its sender gave it the subject \"Which name?\"` goes to the agent's private runtime, and a wake has it read the note now, so the agent decides whether and when its person sees the letter. Each letter is told once: refiling the same letter by its dedupeKey, or a repeated wake, adds nothing. If the wake fails, the note waits for the agent's next private turn.",
8
- "The private-runtime policy allows this wake only when it names the letter and comes from the daemon's filing. A wake the policy denies is logged as a failure, with the note still queued. The note quotes the sender's lane and subject as the sender's own words.",
9
- "Update the Ouro UI files to Ouro UI v1.3.590."
21
+ "The private-runtime policy allows this wake only when it names the letter and comes from the daemon's filing. A wake the policy denies is logged as a failure, with the note still queued. The note quotes the sender's lane and subject as the sender's own words."
10
22
  ]
11
23
  },
12
24
  {
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1642",
2
+ "runtimeVersion": "0.1.0-alpha.1643",
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.1642</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1643</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -1377,6 +1377,18 @@ class OuroDaemon {
1377
1377
  hasManagedPrivateRuntime(agent) {
1378
1378
  return this.processManager.listAgentSnapshots().some((snapshot) => snapshot.name === agent && snapshot.channel === "private-runtime");
1379
1379
  }
1380
+ /** The one letters writer, loaded on the first mailbox call so a daemon with no letters pays nothing at start. */
1381
+ letters() {
1382
+ // The promise is kept, not the writer, so two first calls at once share one writer and its one queue.
1383
+ this.lettersWriter ??= (async () => new (await Promise.resolve().then(() => __importStar(require("../letters/writer")))).LettersWriter({
1384
+ bundlesRoot: this.bundlesRoot,
1385
+ // A letter goes to its person's iMessage chat as the agent, through the agent's own BlueBubbles settings.
1386
+ deliverChat: (await Promise.resolve().then(() => __importStar(require("../../senses/bluebubbles/agent-client")))).letterChatSender(this.bundlesRoot),
1387
+ // Filing tells the agent, in its own private runtime, so it decides when its person sees the letter.
1388
+ onFiled: (await Promise.resolve().then(() => __importStar(require("../letters/filed-note")))).letterFiledTeller(this.bundlesRoot, (wake) => this.handlePrivateRuntimeWake(wake)),
1389
+ }))();
1390
+ return this.lettersWriter;
1391
+ }
1380
1392
  buildPrivateRuntimeWakeRequest(command) {
1381
1393
  if (command.kind === "inner.wake") {
1382
1394
  return {
@@ -2566,16 +2578,15 @@ class OuroDaemon {
2566
2578
  }
2567
2579
  case "letters.action":
2568
2580
  {
2569
- // Loaded on the first mailbox call so a daemon with no letters pays nothing at start.
2570
2581
  const letters = await Promise.resolve().then(() => __importStar(require("../letters/writer")));
2571
- this.lettersWriter ??= new letters.LettersWriter({
2572
- bundlesRoot: this.bundlesRoot,
2573
- // A letter goes to its person's iMessage chat as the agent, through the agent's own BlueBubbles settings.
2574
- deliverChat: (await Promise.resolve().then(() => __importStar(require("../../senses/bluebubbles/agent-client")))).letterChatSender(this.bundlesRoot),
2575
- // Filing tells the agent, in its own private runtime, so it decides when its person sees the letter.
2576
- onFiled: (await Promise.resolve().then(() => __importStar(require("../letters/filed-note")))).letterFiledTeller(this.bundlesRoot, (wake) => this.handlePrivateRuntimeWake(wake)),
2577
- });
2578
- return letters.answerLettersCommand(this.lettersWriter, command);
2582
+ return letters.answerLettersCommand(await this.letters(), command);
2583
+ }
2584
+ case "letters.answer":
2585
+ {
2586
+ // The person's own message, named by GUID; the daemon reads it from the agent's BlueBubbles server itself.
2587
+ const { answerLettersAnswerCommand } = await Promise.resolve().then(() => __importStar(require("../letters/answer-command")));
2588
+ const { letterAnswerSource } = await Promise.resolve().then(() => __importStar(require("../../senses/bluebubbles/agent-client")));
2589
+ return answerLettersAnswerCommand(await this.letters(), command, letterAnswerSource(this.bundlesRoot));
2579
2590
  }
2580
2591
  case "mcp.list": {
2581
2592
  return (0, turn_execution_lease_1.withTurnExecutionLease)(async () => {
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.looksLikeAnswer = looksLikeAnswer;
4
+ exports.answerLettersAnswerCommand = answerLettersAnswerCommand;
5
+ // The daemon's `letters.answer` command (design §3.4): the BlueBubbles ingress names a message by GUID, and the
6
+ // daemon reads that message from the agent's own server and records the answer if it is one. The command carries no
7
+ // text, sender or chat, so whoever sends it can only point at a message the server holds.
8
+ const runtime_1 = require("../../nerves/runtime");
9
+ const answer_reader_1 = require("./answer-reader");
10
+ /** A cheap first look at the webhook's text: only text in answer form is worth a fetch from the server. */
11
+ function looksLikeAnswer(text) {
12
+ return (0, answer_reader_1.parseAnswer)(text) !== null;
13
+ }
14
+ async function answerLettersAnswerCommand(writer, command, sourceFor) {
15
+ if (typeof command.agent !== "string" || typeof command.messageGuid !== "string" || !command.messageGuid.trim()) {
16
+ return { ok: false, error: "letters.answer needs an agent and a messageGuid." };
17
+ }
18
+ // Checked before the agent's vault or server is read for it.
19
+ if (!writer.hasAgent(command.agent))
20
+ return { ok: false, error: `No agent bundle ${command.agent}.ouro is on this machine.` };
21
+ try {
22
+ const source = await sourceFor(command.agent);
23
+ // The server password travels in the fetch's query string, so only a server nobody between can read is asked.
24
+ if (source.trust === "untrusted")
25
+ return { ok: true, data: { recorded: false, reason: "untrusted-server-url" } };
26
+ const guid = command.messageGuid.trim();
27
+ const message = await source.getServerMessage(guid);
28
+ if (!message || message.guid !== guid)
29
+ return { ok: true, data: { recorded: false, reason: "unknown-message" } };
30
+ const sentAt = async (sentGuid) => (await source.getServerMessage(sentGuid))?.dateCreated;
31
+ const deadlineAt = typeof command.deadlineAt === "number" ? command.deadlineAt : undefined;
32
+ return { ok: true, data: await writer.recordAnswer(command.agent, message, source.hostTrust, sentAt, deadlineAt) };
33
+ }
34
+ catch (error) {
35
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "daemon", event: "letters.answer_failed", message: "a possible answer couldn't be checked", meta: { reason: error.message } });
36
+ return { ok: false, error: error.message };
37
+ }
38
+ }
@@ -0,0 +1,169 @@
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.DELIVERY_SLACK_MS = exports.ANSWERED_GUIDS_FILE = void 0;
37
+ exports.parseAnswer = parseAnswer;
38
+ exports.readAnsweredGuids = readAnsweredGuids;
39
+ exports.addAnsweredGuid = addAnsweredGuid;
40
+ exports.deliveryFloor = deliveryFloor;
41
+ exports.answerProblem = answerProblem;
42
+ exports.noteAnswerRefused = noteAnswerRefused;
43
+ // How a person's own iMessage answers a letter (design §3.4, "How an answer is recorded"). Only the daemon records
44
+ // an answer, from the BlueBubbles server's own copy of the message: the chat ingress hands it a message GUID and
45
+ // nothing else, so a forged webhook or socket command can at most point at a real message, which must then pass
46
+ // every check below on the server's fields.
47
+ const fs = __importStar(require("fs"));
48
+ const path = __importStar(require("path"));
49
+ const runtime_1 = require("../../nerves/runtime");
50
+ const answering_1 = require("./answering");
51
+ exports.ANSWERED_GUIDS_FILE = "answered-guids.jsonl";
52
+ /** How far before the daemon's delivered time an answer may be dated, when the server's own send time is unknown. */
53
+ exports.DELIVERY_SLACK_MS = 5 * 60_000;
54
+ const NOTE_MAX = 200;
55
+ /**
56
+ * The one form an answer takes: the letter's code, a space, the option's number, and optionally a note after a dash,
57
+ * such as `L7 2` or `L7 2 — after lunch`. A bare number, a label or anything else is not an answer.
58
+ */
59
+ function parseAnswer(text) {
60
+ const match = /^(L[1-9]\d*) ([1-5])(?:\s*[—–-]\s*(\S.*))?$/u.exec(text.trim());
61
+ if (!match)
62
+ return null;
63
+ // The note reaches the agent's turn and the receipt, so format characters (bidi overrides and the like) go, and it is capped.
64
+ const note = (match[3] ?? "").replace(/\p{Cf}/gu, "").trim().slice(0, NOTE_MAX);
65
+ return { code: match[1], option: match[2], ...(note ? { note } : {}) };
66
+ }
67
+ /** The GUIDs that have already answered a letter, each with the id of the letter it answered. */
68
+ function readAnsweredGuids(lettersDir) {
69
+ let raw = "";
70
+ try {
71
+ raw = fs.readFileSync(path.join(lettersDir, exports.ANSWERED_GUIDS_FILE), "utf8");
72
+ }
73
+ catch (error) {
74
+ if (error.code !== "ENOENT")
75
+ throw error;
76
+ }
77
+ const guids = new Map();
78
+ for (const line of raw.split("\n")) {
79
+ try {
80
+ const { guid, letter } = JSON.parse(line);
81
+ if (typeof guid === "string")
82
+ guids.set(guid, typeof letter === "string" ? letter : "");
83
+ }
84
+ catch {
85
+ // A torn last line holds no GUID.
86
+ }
87
+ }
88
+ return guids;
89
+ }
90
+ /** Adds a GUID that answered, synced before the answer is recorded. */
91
+ function addAnsweredGuid(lettersDir, guid, letterId, at) {
92
+ const file = path.join(lettersDir, exports.ANSWERED_GUIDS_FILE);
93
+ const fd = fs.openSync(file, "a+", 0o600);
94
+ try {
95
+ // A line a crash tore is ended first, so it can't swallow this GUID.
96
+ const size = fs.fstatSync(fd).size;
97
+ const last = Buffer.alloc(1);
98
+ const torn = size > 0 && fs.readSync(fd, last, 0, 1, size - 1) === 1 && last[0] !== 0x0a;
99
+ fs.writeSync(fd, `${torn ? "\n" : ""}${JSON.stringify({ guid, letter: letterId, at })}\n`);
100
+ fs.fsyncSync(fd);
101
+ }
102
+ finally {
103
+ fs.closeSync(fd);
104
+ }
105
+ }
106
+ /** The handle a one-to-one chat GUID such as `iMessage;-;+15551234567` names, normalised, or null for any other chat. */
107
+ function directChatHandle(chatGuid) {
108
+ const parts = chatGuid.split(";-;");
109
+ if (parts.length !== 2)
110
+ return null;
111
+ const checked = (0, answering_1.normalizeAnsweringHandle)(parts[1]);
112
+ return checked.ok ? checked.handle : null;
113
+ }
114
+ /**
115
+ * The time an answer must come after, on the server's clock when it can be had: when the server itself dated the
116
+ * letter's sent message. Otherwise the daemon's delivered time less DELIVERY_SLACK_MS, which covers a send that
117
+ * outlasted its deadline (an `unconfirmed` delivery) and clocks that differ. Null when the letter isn't delivered.
118
+ */
119
+ async function deliveryFloor(entry, sentAt) {
120
+ const delivered = entry.events.find((event) => event.t === "delivered");
121
+ if (!delivered)
122
+ return null;
123
+ if (delivered.messageId && sentAt) {
124
+ const serverTime = await sentAt(delivered.messageId).catch(() => undefined);
125
+ if (serverTime !== undefined)
126
+ return serverTime;
127
+ }
128
+ return Date.parse(delivered.at) - exports.DELIVERY_SLACK_MS;
129
+ }
130
+ /**
131
+ * Why the server's message doesn't answer this letter, or null when it does. Each check reads only the server's
132
+ * fields and the letter as filed and delivered; the reasons are for the daemon's log, never shown to the sender.
133
+ * `floor` is the letter's deliveryFloor.
134
+ */
135
+ function answerProblem(entry, message, answer, answered, floor) {
136
+ const letter = entry.letter;
137
+ // Expiry is judged by when the person sent the message, so a pass that reads it late still counts it.
138
+ const sentAfterExpiry = letter.expiresAt !== undefined && (message.dateCreated ?? Number.POSITIVE_INFINITY) >= Date.parse(letter.expiresAt);
139
+ if (entry.state !== "waiting" || sentAfterExpiry)
140
+ return "not-waiting";
141
+ if (!letter.answeringHandle)
142
+ return "no-answering-handle";
143
+ if (message.isFromMe !== false)
144
+ return "from-me";
145
+ if (message.service !== "iMessage")
146
+ return "not-imessage";
147
+ const sender = message.sender ? (0, answering_1.normalizeAnsweringHandle)(message.sender) : null;
148
+ if (!sender?.ok || sender.handle !== letter.answeringHandle)
149
+ return "wrong-sender";
150
+ if (message.chatGuids.length !== 1 || directChatHandle(message.chatGuids[0]) !== letter.answeringHandle)
151
+ return "wrong-chat";
152
+ if (message.threadOriginatorGuid)
153
+ return "threaded";
154
+ if (message.dateEdited || message.dateRetracted)
155
+ return "edited";
156
+ if (floor === null)
157
+ return "not-delivered";
158
+ if (message.dateCreated === undefined || message.dateCreated <= floor)
159
+ return "before-delivery";
160
+ if (answered.has(message.guid))
161
+ return "guid-answered";
162
+ if (!letter.options.some((option) => option.id === answer.option))
163
+ return "no-such-option";
164
+ return null;
165
+ }
166
+ /** Logs a message that looked like an answer and wasn't one, by its reason alone. */
167
+ function noteAnswerRefused(reason) {
168
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.answer_refused", message: "a message in answer form didn't answer its letter", meta: { reason } });
169
+ }
@@ -42,6 +42,7 @@ const fs = __importStar(require("fs"));
42
42
  const path = __importStar(require("path"));
43
43
  const friends_1 = require("@ouro.bot/friends");
44
44
  const runtime_1 = require("../../nerves/runtime");
45
+ const answer_reader_1 = require("./answer-reader");
45
46
  const letter_1 = require("./letter");
46
47
  const answering_1 = require("./answering");
47
48
  Object.defineProperty(exports, "ownerFriendIds", { enumerable: true, get: function () { return answering_1.ownerFriendIds; } });
@@ -237,6 +238,56 @@ class LettersWriter {
237
238
  this.deps.onFiled?.(letters.agent, letter).catch(() => undefined);
238
239
  return { outcome: "needs-human", id: letter.id, code: letter.code, state: "waiting", message: `Filed ${letter.code}, ${letter.subject}. It waits for the person's answer.` };
239
240
  }
241
+ /**
242
+ * Records the person's answer from the BlueBubbles server's own copy of their message. No door reaches this: only
243
+ * the daemon calls it, after fetching the message by GUID. A message that isn't an answer, or doesn't answer its
244
+ * letter, records nothing and says so with the reason, for the log.
245
+ */
246
+ /** Whether the agent's bundle is on this machine, checked before anything is fetched for it. */
247
+ hasAgent(agent) {
248
+ return AGENT_NAME.test(agent) && fs.existsSync(path.join(this.deps.bundlesRoot, `${agent}.ouro`));
249
+ }
250
+ /**
251
+ * Records the person's answer from the server's own copy of their message, when it is one. `sentAt` reads the
252
+ * server's time for the letter's sent message, so the delivery floor is on the server's clock. Past `deadlineAt`
253
+ * (epoch ms) nothing is recorded, so a caller that gave up waiting never has an answer recorded behind its back.
254
+ * A message that already answered this letter answers `already`, so a replay of it is no chat turn either.
255
+ */
256
+ recordAnswer(agent, message, hostTrust, sentAt, deadlineAt) {
257
+ const answer = (0, answer_reader_1.parseAnswer)(message.text);
258
+ if (!answer)
259
+ return Promise.resolve({ recorded: false, reason: "not-answer-form" });
260
+ const letters = this.open(agent, false);
261
+ return this.serial(letters, async () => {
262
+ const entry = letters.index.get(answer.code);
263
+ const answered = (0, answer_reader_1.readAnsweredGuids)(letters.store.dir);
264
+ const recorded = entry?.events.findLast((event) => event.t === "answered");
265
+ if (entry && recorded?.t === "answered" && answered.get(message.guid) === entry.letter.id) {
266
+ const { letter } = entry;
267
+ const label = letter.options.find((option) => option.id === recorded.option).label;
268
+ return { recorded: true, already: true, id: letter.id, code: letter.code, subject: letter.subject, option: recorded.option, label, ...(recorded.note ? { note: recorded.note } : {}) };
269
+ }
270
+ const floor = entry ? await (0, answer_reader_1.deliveryFloor)(entry, sentAt) : null;
271
+ const late = deadlineAt !== undefined && this.now().getTime() > deadlineAt;
272
+ const problem = !entry ? "no-such-letter" : late ? "past-deadline" : (0, answer_reader_1.answerProblem)(entry, message, answer, answered, floor);
273
+ if (problem) {
274
+ (0, answer_reader_1.noteAnswerRefused)(problem);
275
+ return { recorded: false, reason: problem };
276
+ }
277
+ const { letter } = entry;
278
+ const at = this.now().toISOString();
279
+ // The GUID is spent first, so a crash between the two lines can lose this answer but never record it twice.
280
+ (0, answer_reader_1.addAnsweredGuid)(letters.store.dir, message.guid, letter.id, at);
281
+ this.addEvent(letters, letter.id, {
282
+ t: "answered", at, option: answer.option, ...(answer.note ? { note: answer.note } : {}), via: "chat",
283
+ evidence: { friendId: letter.to, channel: "bluebubbles", chatGuid: message.chatGuids[0], messageGuid: message.guid, dateCreated: new Date(message.dateCreated).toISOString() },
284
+ hostTrust,
285
+ });
286
+ const label = letter.options.find((option) => option.id === answer.option).label;
287
+ (0, runtime_1.emitNervesEvent)({ component: "daemon", event: "letters.answer_recorded", message: "a person's answer was recorded", meta: { code: letter.code, hostTrust } });
288
+ return { recorded: true, id: letter.id, code: letter.code, subject: letter.subject, option: answer.option, label, ...(answer.note ? { note: answer.note } : {}) };
289
+ });
290
+ }
240
291
  list(letters, input) {
241
292
  const now = this.now().getTime();
242
293
  const entries = letters.index.list({
@@ -40,9 +40,11 @@ exports.blueBubblesClientForAgent = blueBubblesClientForAgent;
40
40
  exports.chatWithHandle = chatWithHandle;
41
41
  exports.sendLetterByBlueBubbles = sendLetterByBlueBubbles;
42
42
  exports.letterChatSender = letterChatSender;
43
+ exports.letterAnswerSource = letterAnswerSource;
43
44
  // A BlueBubbles client for a named agent, built from outside that agent's sense process: the daemon delivering a
44
45
  // letter, or an `ouro rsvp` command. Its settings come from the agent's machine runtime config in the vault (held in
45
46
  // process memory once read), and its host check uses the agent's declared iMessage host account.
47
+ const os = __importStar(require("os"));
46
48
  const path = __importStar(require("path"));
47
49
  const identity_1 = require("../../heart/identity");
48
50
  const machine_identity_1 = require("../../heart/machine-identity");
@@ -50,6 +52,8 @@ const runtime_credentials_1 = require("../../heart/runtime-credentials");
50
52
  const runtime_1 = require("../../nerves/runtime");
51
53
  const client_1 = require("./client");
52
54
  const letter_guard_1 = require("./letter-guard");
55
+ const host_trust_1 = require("./host-trust");
56
+ const url_trust_1 = require("./url-trust");
53
57
  function text(value) {
54
58
  return typeof value === "string" ? value.trim() : "";
55
59
  }
@@ -137,3 +141,21 @@ async function sendLetterByBlueBubbles(request, agentRoot, clientFor = blueBubbl
137
141
  function letterChatSender(bundlesRoot, clientFor) {
138
142
  return (request) => sendLetterByBlueBubbles(request, path.join(bundlesRoot, `${request.agent}.ouro`), clientFor);
139
143
  }
144
+ function letterAnswerSource(bundlesRoot, deps = {}) {
145
+ return async (agent) => {
146
+ const agentRoot = path.join(bundlesRoot, `${agent}.ouro`);
147
+ const settings = blueBubblesSettings(await agentMachineRuntimeConfig(agent));
148
+ const client = await (deps.clientFor ?? blueBubblesClientForAgent)(agent, agentRoot);
149
+ const daemonUser = (deps.daemonUser ?? (() => os.userInfo().username))();
150
+ const hostUsername = (deps.hostUsername ?? ((name, root) => agentHostOptions(name, root).hostUsername))(agent, agentRoot);
151
+ return {
152
+ trust: (0, url_trust_1.blueBubblesUrlTrust)(settings.config.serverUrl),
153
+ hostTrust: (0, host_trust_1.imessageHostTrust)(hostUsername, daemonUser),
154
+ getServerMessage: async (messageGuid) => {
155
+ if (!client.getServerMessage)
156
+ throw new Error("this BlueBubbles client can't fetch a message's own record");
157
+ return client.getServerMessage(messageGuid);
158
+ },
159
+ };
160
+ };
161
+ }
@@ -7,6 +7,7 @@ const config_1 = require("../../heart/config");
7
7
  const identity_1 = require("../../heart/identity");
8
8
  const bluebubbles_health_diagnostics_1 = require("../../heart/daemon/bluebubbles-health-diagnostics");
9
9
  const runtime_1 = require("../../nerves/runtime");
10
+ const server_message_1 = require("./server-message");
10
11
  const understand_1 = require("../../heart/attachments/understand");
11
12
  const model_1 = require("./model");
12
13
  const media_1 = require("./media");
@@ -829,6 +830,18 @@ function createBlueBubblesClient(config = (0, config_1.getBlueBubblesConfig)(),
829
830
  async getMessageText(messageGuid) {
830
831
  return (await this.getRepliedMessage(messageGuid))?.text ?? null;
831
832
  },
833
+ async getServerMessage(messageGuid) {
834
+ await assertHostAccount();
835
+ const response = await fetch(buildRepairUrl(config.serverUrl, messageGuid, config.password), {
836
+ method: "GET",
837
+ signal: AbortSignal.timeout(channelConfig.requestTimeoutMs),
838
+ });
839
+ if (response.status === 404)
840
+ return null;
841
+ if (!response.ok)
842
+ throw new Error(`the BlueBubbles server answered ${response.status} for that message`);
843
+ return (0, server_message_1.serverMessageFromPayload)(await parseJsonBody(response));
844
+ },
832
845
  async getRepliedMessage(messageGuid) {
833
846
  await assertHostAccount();
834
847
  const url = buildRepairUrl(config.serverUrl, messageGuid, config.password);
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.imessageHostTrust = imessageHostTrust;
4
+ // Whether a shell beside the daemon could send iMessages as the agent's person (design §3.4, the shell boundary).
5
+ // senses.bluebubbles.hostUsername names the macOS account signed in to the agent's own Apple ID, so a daemon running
6
+ // under it can at most send as the agent. Under any other account, the person's own Messages may be signed in.
7
+ const runtime_1 = require("../../nerves/runtime");
8
+ /** `separate` only when the daemon runs under the declared host account; an undeclared one counts as shared. */
9
+ function imessageHostTrust(hostUsername, daemonUser) {
10
+ const trust = hostUsername?.trim() && hostUsername.trim() === daemonUser ? "separate" : "shared-apple-id";
11
+ (0, runtime_1.emitNervesEvent)({ level: "debug", component: "senses", event: "senses.bluebubbles_host_trust", message: "judged whether the daemon could send as the person", meta: { trust } });
12
+ return trust;
13
+ }
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.serverMessageFromPayload = serverMessageFromPayload;
4
+ const runtime_1 = require("../../nerves/runtime");
5
+ const record = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : null);
6
+ const text = (value) => (typeof value === "string" && value.trim() ? value.trim() : undefined);
7
+ const time = (value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined);
8
+ /** The message in a `GET /api/v1/message/:guid` reply, or null when the reply holds no message with a GUID. */
9
+ function serverMessageFromPayload(payload) {
10
+ const outer = record(payload);
11
+ const data = record(outer?.data) ?? outer;
12
+ const guid = text(data?.guid);
13
+ if (!data || !guid) {
14
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.bluebubbles_server_message_missing", message: "the server's reply held no message", meta: {} });
15
+ return null;
16
+ }
17
+ const handle = record(data.handle);
18
+ const chats = Array.isArray(data.chats) ? data.chats : [];
19
+ const sender = text(handle?.address);
20
+ const service = text(handle?.service);
21
+ const dateCreated = time(data.dateCreated);
22
+ const dateEdited = time(data.dateEdited);
23
+ const dateRetracted = time(data.dateRetracted);
24
+ const threadOriginatorGuid = text(data.threadOriginatorGuid);
25
+ return {
26
+ guid,
27
+ text: typeof data.text === "string" ? data.text : "",
28
+ // Kept only as the server states it: a message whose direction isn't stated never counts as the person's.
29
+ ...(typeof data.isFromMe === "boolean" ? { isFromMe: data.isFromMe } : {}),
30
+ ...(sender ? { sender } : {}),
31
+ ...(service ? { service } : {}),
32
+ chatGuids: chats.map((chat) => text(record(chat)?.guid)).filter((chatGuid) => chatGuid !== undefined),
33
+ ...(dateCreated ? { dateCreated } : {}),
34
+ ...(dateEdited ? { dateEdited } : {}),
35
+ ...(dateRetracted ? { dateRetracted } : {}),
36
+ ...(threadOriginatorGuid ? { threadOriginatorGuid } : {}),
37
+ };
38
+ }
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.blueBubblesUrlTrust = blueBubblesUrlTrust;
4
+ // How far the BlueBubbles server's address can be trusted (design §3.4, R3-M3). Fetches put the server password in
5
+ // the query string, so the letter answer reader runs only when nobody between the agent and the server can read or
6
+ // fake that traffic: the same Mac, an authenticated TLS connection, or a tailnet address, whose WireGuard tunnel does both.
7
+ const runtime_1 = require("../../nerves/runtime");
8
+ /**
9
+ * The tailnet's own address ranges: 100.64.0.0/10 and fd7a:115c:a1e0::/48. This trusts Tailscale to be up: when it
10
+ * is down, 100.64.0.0/10 routes like any carrier-grade NAT address. A MagicDNS name isn't trusted over plain http,
11
+ * since whatever resolver answers when Tailscale is down could point it anywhere; over https it counts as TLS.
12
+ */
13
+ function isTailnetHost(host) {
14
+ if (/^fd7a:115c:a1e0:/.test(host))
15
+ return true;
16
+ // new URL() has already written any numeric host as four decimal octets; a name with dots isn't one.
17
+ const octets = host.split(".").map(Number);
18
+ return octets.length === 4 && octets.every(Number.isInteger) && octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127;
19
+ }
20
+ /** Untrusted for anything but an http or https URL, including one that doesn't parse. */
21
+ function blueBubblesUrlTrust(serverUrl) {
22
+ let url = null;
23
+ try {
24
+ url = new URL(serverUrl);
25
+ }
26
+ catch {
27
+ // Judged untrusted below.
28
+ }
29
+ const host = url ? url.hostname.replace(/^\[|\]$/g, "") : "";
30
+ const trust = url === null || (url.protocol !== "http:" && url.protocol !== "https:") ? "untrusted"
31
+ : host === "localhost" || host === "::1" || /^127\.\d+\.\d+\.\d+$/.test(host) ? "loopback"
32
+ : url.protocol === "https:" ? "tls"
33
+ : isTailnetHost(host) ? "tailnet"
34
+ : "untrusted";
35
+ (0, runtime_1.emitNervesEvent)({ level: "debug", component: "senses", event: "senses.bluebubbles_url_trust", message: "judged the BlueBubbles server address", meta: { trust } });
36
+ return trust;
37
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1642",
3
+ "version": "0.1.0-alpha.1643",
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.1642",
9
+ "version": "0.1.0-alpha.1643",
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.1642",
3
+ "version": "0.1.0-alpha.1643",
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": {