@ouro.bot/cli 0.1.0-alpha.1627 → 0.1.0-alpha.1629

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,32 @@
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.1629",
6
+ "changes": [
7
+ "`mailbox_deliver` now sends a waiting letter to the person's iMessage chat, as the agent, through the agent's own BlueBubbles settings. The text is the one Ouro renders, never the agent's. It goes to the handle that was set when the letter was filed, and the letter records a `delivered` event saying where it landed. A dry run shows the exact text and sends nothing.",
8
+ "Each letter goes to the chat once. A second deliver is refused with `already-delivered`. A send that fails after it may have reached the chat, or that outlasts its 25-second deadline, counts as delivered (`send-uncertain`), so a retry never sends the person the same letter twice. A send that never reached the chat (`send-failed`) leaves the letter waiting. A letter whose expiry has passed isn't delivered. When the person has never messaged the agent from that handle, the refusal says so."
9
+ ]
10
+ },
11
+ {
12
+ "version": "0.1.0-alpha.1628",
13
+ "changes": [
14
+ "The Butler container's healthcheck checks the Butler under the name its bundle has on disk (`butler.ouro` or `sanctuary.ouro`), whichever Butler name the image passes it. With both bundles present, or neither, it fails as `missing agent` instead of guessing.",
15
+ "The container-spec auditor accepts an image that starts the Butler as `--package-managed-agent butler` as well as `sanctuary`. The entrypoint and arguments must name the same Butler, and any other agent name is still refused."
16
+ ]
17
+ },
4
18
  {
5
19
  "version": "0.1.0-alpha.1627",
6
20
  "changes": [
7
- "The Butler's scheduler now follows the name its bundle has. Its cron proof, its health-check liveness receipt, its crontab and the daemon's package-managed start all work for a bundle named `butler.ouro` as well as `sanctuary.ouro`. A daemon that finds both bundles refuses to start rather than guess which one is the Butler.",
8
21
  "The Butler's root-host tool (owner-approved commands on the Unraid host) is offered to the Butler whose bundle is `butler.ouro` as well as `sanctuary.ouro`. An agent whose name doesn't match its bundle folder still gets no host tool."
9
22
  ]
10
23
  },
24
+ {
25
+ "version": "0.1.0-alpha.1626",
26
+ "changes": [
27
+ "The Butler's scheduler now follows the name its bundle has. Its cron proof, its health-check liveness receipt, its crontab and the daemon's package-managed start all work for a bundle named `butler.ouro` as well as `sanctuary.ouro`. A daemon that finds both bundles refuses to start rather than guess which one is the Butler."
28
+ ]
29
+ },
11
30
  {
12
31
  "version": "0.1.0-alpha.1625",
13
32
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1627",
2
+ "runtimeVersion": "0.1.0-alpha.1629",
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.1627</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1629</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -504,8 +504,38 @@
504
504
  "errors": [
505
505
  {
506
506
  "code": "no-answering-handle",
507
- "means": "The person has no answering handle yet, so Ouro has no chat to send the letter to.",
508
- "fix": "Leave the letter waiting; the person sets the handle with `ouro mailbox handle set` when chat delivery is ready."
507
+ "means": "The letter was filed before the person had an answering handle, so Ouro has no chat to send it to.",
508
+ "fix": "Leave the letter waiting; once the person sets a handle with `ouro mailbox handle set`, letters filed after that can be delivered."
509
+ },
510
+ {
511
+ "code": "not-waiting",
512
+ "means": "The letter is already answered, withdrawn or expired.",
513
+ "fix": "Nothing to deliver; read the letter to see how it closed."
514
+ },
515
+ {
516
+ "code": "already-delivered",
517
+ "means": "The letter is already in the person's chat; each letter goes there once.",
518
+ "fix": "Wait for the answer with mailbox_wait."
519
+ },
520
+ {
521
+ "code": "chat-unavailable",
522
+ "means": "This daemon has no chat to send through.",
523
+ "fix": "Leave the letter waiting; the person reads it in their mailbox."
524
+ },
525
+ {
526
+ "code": "send-failed",
527
+ "means": "The message never reached the chat; the letter stays waiting.",
528
+ "fix": "Deliver it again once the cause the refusal names is fixed."
529
+ },
530
+ {
531
+ "code": "send-uncertain",
532
+ "means": "The send failed after it may have reached the chat, so Ouro counts the letter as delivered and won't send it twice.",
533
+ "fix": "Wait for the answer with mailbox_wait; the letter is in the person's mailbox either way."
534
+ },
535
+ {
536
+ "code": "sent-unrecorded",
537
+ "means": "The letter went to the chat, but writing its delivered event to the letter's file failed, so the mailbox doesn't show it as delivered.",
538
+ "fix": "Leave it; delivering again would send it twice."
509
539
  },
510
540
  {
511
541
  "code": "not-found",
@@ -545,13 +575,23 @@
545
575
  "output": {
546
576
  "outcome": {
547
577
  "label": "Outcome",
548
- "description": "done, when the letter was sent.",
578
+ "description": "done, when the letter was sent; preview on a dry run, which shows the text and sends nothing.",
549
579
  "kind": "string"
550
580
  },
551
581
  "state": {
552
582
  "label": "State",
553
583
  "description": "waiting, answered, withdrawn or expired; Ouro derives it from the letter's events.",
554
584
  "kind": "string"
585
+ },
586
+ "channel": {
587
+ "label": "Channel",
588
+ "description": "The chat the letter went to, such as bluebubbles, when it was sent.",
589
+ "kind": "string"
590
+ },
591
+ "text": {
592
+ "label": "Text",
593
+ "description": "On a dry run, the letter as the person will read it.",
594
+ "kind": "string"
555
595
  }
556
596
  },
557
597
  "cli": "mailbox deliver"
@@ -169,7 +169,7 @@
169
169
  "required": true
170
170
  }
171
171
  ],
172
- "output": "{ outcome, state }"
172
+ "output": "{ outcome, state, channel, text }"
173
173
  }
174
174
  ],
175
175
  "personOnly": {
@@ -408,16 +408,26 @@
408
408
  "properties": {
409
409
  "outcome": {
410
410
  "type": "string",
411
- "description": "done, when the letter was sent."
411
+ "description": "done, when the letter was sent; preview on a dry run, which shows the text and sends nothing."
412
412
  },
413
413
  "state": {
414
414
  "type": "string",
415
415
  "description": "waiting, answered, withdrawn or expired; Ouro derives it from the letter's events."
416
+ },
417
+ "channel": {
418
+ "type": "string",
419
+ "description": "The chat the letter went to, such as bluebubbles, when it was sent."
420
+ },
421
+ "text": {
422
+ "type": "string",
423
+ "description": "On a dry run, the letter as the person will read it."
416
424
  }
417
425
  },
418
426
  "required": [
419
427
  "outcome",
420
- "state"
428
+ "state",
429
+ "channel",
430
+ "text"
421
431
  ],
422
432
  "additionalProperties": false
423
433
  }
@@ -446,8 +446,38 @@
446
446
  "errors": [
447
447
  {
448
448
  "code": "no-answering-handle",
449
- "means": "The person has no answering handle yet, so Ouro has no chat to send the letter to.",
450
- "fix": "Leave the letter waiting; the person sets the handle with `ouro mailbox handle set` when chat delivery is ready."
449
+ "means": "The letter was filed before the person had an answering handle, so Ouro has no chat to send it to.",
450
+ "fix": "Leave the letter waiting; once the person sets a handle with `ouro mailbox handle set`, letters filed after that can be delivered."
451
+ },
452
+ {
453
+ "code": "not-waiting",
454
+ "means": "The letter is already answered, withdrawn or expired.",
455
+ "fix": "Nothing to deliver; read the letter to see how it closed."
456
+ },
457
+ {
458
+ "code": "already-delivered",
459
+ "means": "The letter is already in the person's chat; each letter goes there once.",
460
+ "fix": "Wait for the answer with mailbox_wait."
461
+ },
462
+ {
463
+ "code": "chat-unavailable",
464
+ "means": "This daemon has no chat to send through.",
465
+ "fix": "Leave the letter waiting; the person reads it in their mailbox."
466
+ },
467
+ {
468
+ "code": "send-failed",
469
+ "means": "The message never reached the chat; the letter stays waiting.",
470
+ "fix": "Deliver it again once the cause the refusal names is fixed."
471
+ },
472
+ {
473
+ "code": "send-uncertain",
474
+ "means": "The send failed after it may have reached the chat, so Ouro counts the letter as delivered and won't send it twice.",
475
+ "fix": "Wait for the answer with mailbox_wait; the letter is in the person's mailbox either way."
476
+ },
477
+ {
478
+ "code": "sent-unrecorded",
479
+ "means": "The letter went to the chat, but writing its delivered event to the letter's file failed, so the mailbox doesn't show it as delivered.",
480
+ "fix": "Leave it; delivering again would send it twice."
451
481
  },
452
482
  {
453
483
  "code": "not-found",
@@ -120,7 +120,7 @@ const doors_1 = require("../letters/doors");
120
120
  exports.HANDLE_SET_REFUSAL_CODES = new Set(["bad-handle", "no-person", "which-person", "not-recipient", "answering-unreadable"]);
121
121
  exports.MAILBOX_CLI_REFUSAL_CODES = new Set([
122
122
  "daemon-down", "bad-input", "no-agent", "not-found",
123
- "invalid-letter", "no-person", "not-sender", "not-waiting", "no-answering-handle",
123
+ "invalid-letter", "no-person", "not-sender", "not-waiting", "no-answering-handle", "already-delivered", "chat-unavailable", "send-failed", "send-uncertain", "sent-unrecorded",
124
124
  ]);
125
125
  const plugin_cli_1 = require("./plugin-cli");
126
126
  const cli_desk_1 = require("./cli-desk");
@@ -46,16 +46,23 @@ const container_runtime_1 = require("./container-runtime");
46
46
  const sanctuary_bundle_migration_1 = require("./sanctuary-bundle-migration");
47
47
  const sanctuary_package_management_1 = require("./sanctuary-package-management");
48
48
  const failure_code_1 = require("./cli-commands/failure-code");
49
+ const butler_agent_1 = require("../butler-agent");
49
50
  function fail(reason) {
50
51
  (0, runtime_1.emitNervesEvent)({ level: "error", component: "daemon", event: "daemon.container_healthcheck_error", message: "container healthcheck failed", meta: { reason } });
51
52
  process.exitCode = 1;
52
53
  throw Object.assign(new Error(reason), { code: reason === "missing agent" ? "missing-agent" : "unhealthy" });
53
54
  }
55
+ /** The Butler's name is the one its bundle on disk has; with both bundles, or neither, there is no Butler to check. */
56
+ function butlerOnDisk(bundlesRoot) {
57
+ const present = butler_agent_1.BUTLER_AGENT_NAMES.filter((name) => fs.existsSync(path.join(bundlesRoot, `${name}.ouro`)));
58
+ return present.length === 1 ? present[0] : undefined;
59
+ }
54
60
  function runContainerHealthcheck(options = {}) {
55
61
  const argv = options.argv ?? process.argv;
56
62
  const now = options.now ?? Date.now;
57
63
  const index = argv.indexOf("--agent");
58
- const agent = index >= 0 ? argv[index + 1] : undefined;
64
+ const given = index >= 0 ? argv[index + 1] : undefined;
65
+ const agent = (0, butler_agent_1.isButlerAgent)(given) ? butlerOnDisk((0, identity_1.getAgentBundlesRoot)()) : given;
59
66
  if (!agent)
60
67
  fail("missing agent");
61
68
  const packageManagement = (0, sanctuary_package_management_1.resolveSanctuaryPackageManagementActivation)({ mode: "production", argv, managedAgents: [agent], repoRoot: (0, identity_1.getRepoRoot)(), bundlesRoot: (0, identity_1.getAgentBundlesRoot)(), runtimePackageVersion: (0, bundle_manifest_1.getPackageVersion)() });
@@ -58,8 +58,8 @@ const EXPECTED_TEMPLATE_URLS = new Set([
58
58
  const EXPECTED_ICON = "https://raw.githubusercontent.com/ourostack/ouroboros/main/assets/ouroboros.png";
59
59
  const EXACT_IMAGE = /^sha256:[a-f0-9]{64}$/u;
60
60
  const VERSION_REFERENCE = /^ghcr\.io\/ourostack\/ouroboros-butler:[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/u;
61
- const PACKAGE_DAEMON_ARGS = ["/opt/ouro/dist/heart/daemon/daemon-entry.js", "--package-managed-agent", "sanctuary"];
62
- const PACKAGE_ENTRYPOINT = ["node", ...PACKAGE_DAEMON_ARGS];
61
+ // The image names the Butler `butler` from M2 on; images from before the rename name it `sanctuary`. Either runs its one bundle.
62
+ const PACKAGE_DAEMON_ARGS_BY_NAME = ["butler", "sanctuary"].map((name) => ["/opt/ouro/dist/heart/daemon/daemon-entry.js", "--package-managed-agent", name]);
63
63
  const LEGACY_DAEMON_ARGS = ["/opt/ouro/dist/heart/daemon/daemon-entry.js"];
64
64
  const LEGACY_ENTRYPOINT = ["node", ...LEGACY_DAEMON_ARGS];
65
65
  function record(value) {
@@ -92,8 +92,9 @@ function auditSanctuaryContainerSpec(value, options) {
92
92
  if (mountContract === "legacy-alpha742" && options.expectedImage !== LEGACY_ALPHA742_IMAGE)
93
93
  violations.push("legacy mount exception requires the pinned alpha.742 image ID");
94
94
  const acceptedMounts = mountContract === "legacy-alpha742" ? [LEGACY_ALPHA742_MOUNTS] : mountContract === "canonical-pre-gateway" ? [PRE_GATEWAY_MOUNTS] : gatewayMounts(options.syncEnabled === true);
95
- const expectedArgs = mountContract !== "legacy-alpha742" ? PACKAGE_DAEMON_ARGS : LEGACY_DAEMON_ARGS;
96
- const expectedEntrypoint = mountContract !== "legacy-alpha742" ? PACKAGE_ENTRYPOINT : LEGACY_ENTRYPOINT;
95
+ const packageArgs = PACKAGE_DAEMON_ARGS_BY_NAME.find((args) => JSON.stringify(root.Args) === JSON.stringify(args)) ?? PACKAGE_DAEMON_ARGS_BY_NAME[1];
96
+ const expectedArgs = mountContract !== "legacy-alpha742" ? packageArgs : LEGACY_DAEMON_ARGS;
97
+ const expectedEntrypoint = mountContract !== "legacy-alpha742" ? ["node", ...packageArgs] : LEGACY_ENTRYPOINT;
97
98
  if (root.Image !== options.expectedImage)
98
99
  violations.push("image does not match the reviewed exact local Docker image ID");
99
100
  if (root.Path !== "node")
@@ -2567,7 +2567,11 @@ class OuroDaemon {
2567
2567
  {
2568
2568
  // Loaded on the first mailbox call so a daemon with no letters pays nothing at start.
2569
2569
  const letters = await Promise.resolve().then(() => __importStar(require("../letters/writer")));
2570
- this.lettersWriter ??= new letters.LettersWriter({ bundlesRoot: this.bundlesRoot });
2570
+ this.lettersWriter ??= new letters.LettersWriter({
2571
+ bundlesRoot: this.bundlesRoot,
2572
+ // A letter goes to its person's iMessage chat as the agent, through the agent's own BlueBubbles settings.
2573
+ deliverChat: (await Promise.resolve().then(() => __importStar(require("../../senses/bluebubbles/agent-client")))).letterChatSender(this.bundlesRoot),
2574
+ });
2571
2575
  return letters.answerLettersCommand(this.lettersWriter, command);
2572
2576
  }
2573
2577
  case "mcp.list": {
@@ -219,8 +219,9 @@ async function runMailboxAction(action, input, caller) {
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
221
  const command = { kind: "letters.action", agent: caller.agent, action, input, ...(caller.dryRun ? { dryRun: true } : {}) };
222
- // A wait holds the socket for its own timeout; anything else answers at once.
223
- const waitSeconds = action === "mailbox_wait" ? Number(input.timeout ?? 60) : 0;
222
+ // A wait holds the socket for its own timeout, and a deliver for its chat send (the daemon answers within
223
+ // DELIVER_DEADLINE_MS of starting it, perhaps after another deliver ahead of it); anything else answers at once.
224
+ const waitSeconds = action === "mailbox_wait" ? Number(input.timeout ?? 60) : action === "mailbox_deliver" ? 60 : 0;
224
225
  let response;
225
226
  try {
226
227
  response = await send(socketPath, command, { timeoutMs: (waitSeconds + 30) * 1000 });
@@ -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.LetterRefusal = exports.ownerFriendIds = void 0;
36
+ exports.LettersWriter = exports.ROLL_AFTER_MS = exports.DELIVER_DEADLINE_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,
@@ -45,6 +45,7 @@ const runtime_1 = require("../../nerves/runtime");
45
45
  const letter_1 = require("./letter");
46
46
  const answering_1 = require("./answering");
47
47
  Object.defineProperty(exports, "ownerFriendIds", { enumerable: true, get: function () { return answering_1.ownerFriendIds; } });
48
+ const render_1 = require("./render");
48
49
  const letter_index_1 = require("./letter-index");
49
50
  const store_1 = require("./store");
50
51
  /** A refusal the door answers with its card's code. */
@@ -57,6 +58,8 @@ class LetterRefusal extends Error {
57
58
  }
58
59
  }
59
60
  exports.LetterRefusal = LetterRefusal;
61
+ /** Under the door's own timeout for a deliver (doors.ts), so the daemon always answers before the door gives up. */
62
+ exports.DELIVER_DEADLINE_MS = 25_000;
60
63
  /** Closed letters move to closed/YYYY-MM/ this long after they close (design §3.2); they are never deleted. */
61
64
  exports.ROLL_AFTER_MS = 90 * 24 * 60 * 60 * 1000;
62
65
  const AGENT_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
@@ -120,7 +123,7 @@ class LettersWriter {
120
123
  case "mailbox_read": return Promise.resolve(this.read(letters, input));
121
124
  case "mailbox_wait": return this.wait(letters, input);
122
125
  case "mailbox_withdraw": return this.serial(letters, () => this.withdraw(letters, input, dryRun));
123
- case "mailbox_deliver": return Promise.resolve(this.deliver(letters, input));
126
+ case "mailbox_deliver": return this.serial(letters, () => this.deliver(letters, input, dryRun));
124
127
  default: return Promise.reject(new LetterRefusal("unknown-door", `The mailbox has no action ${action}.`));
125
128
  }
126
129
  }
@@ -290,12 +293,66 @@ class LettersWriter {
290
293
  const after = this.addEvent(letters, entry.letter.id, { t: "withdrawn", at: this.now().toISOString(), reason });
291
294
  return { outcome: "done", state: after.state };
292
295
  }
293
- deliver(letters, input) {
296
+ /**
297
+ * Sends a waiting letter, once, to the chat of the handle frozen into it when it was filed, in the text Ouro renders,
298
+ * and records where it landed. A send that may have reached the chat counts as delivered, so a retry never sends
299
+ * the person the same letter twice; the letter stays in their mailbox either way.
300
+ */
301
+ async deliver(letters, input, dryRun) {
294
302
  const entry = this.find(letters, input);
295
- throw new LetterRefusal("no-answering-handle", `The person has no answering handle yet, so ${entry.letter.code} stays waiting until chat delivery is ready.`);
303
+ const { letter } = entry;
304
+ if (entry.state !== "waiting")
305
+ throw new LetterRefusal("not-waiting", `${letter.code} is already ${entry.state}, so there is nothing to deliver.`);
306
+ if (letter.expiresAt && Date.parse(letter.expiresAt) <= this.now().getTime())
307
+ throw new LetterRefusal("not-waiting", `${letter.code} expired at ${letter.expiresAt}, so there is nothing to deliver.`);
308
+ if (entry.events.some((event) => event.t === "delivered"))
309
+ throw new LetterRefusal("already-delivered", `${letter.code} is already in the person's chat; it stays in their mailbox too.`);
310
+ if (!letter.answeringHandle) {
311
+ throw new LetterRefusal("no-answering-handle", `${letter.code} was filed before the person had an answering handle, so Ouro has no chat to send it to. It stays waiting.`);
312
+ }
313
+ const text = (0, render_1.renderLetter)(letter);
314
+ if (dryRun)
315
+ return { outcome: "preview", state: entry.state, text };
316
+ const deliverChat = this.deps.deliverChat;
317
+ if (!deliverChat)
318
+ throw new LetterRefusal("chat-unavailable", `This daemon has no chat to send ${letter.code} through. It stays waiting.`);
319
+ let receipt;
320
+ try {
321
+ receipt = await withinDeadline(deliverChat({ agent: letters.agent, handle: letter.answeringHandle, text }), this.deps.deliverDeadlineMs ?? exports.DELIVER_DEADLINE_MS);
322
+ }
323
+ catch (error) {
324
+ const reason = error.message;
325
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "daemon", event: "letters.deliver_failed", message: "a letter's chat send failed", meta: { code: letter.code, mayHaveSent: mayHaveSent(error) } });
326
+ if (!mayHaveSent(error))
327
+ throw new LetterRefusal("send-failed", `${letter.code} didn't send: ${reason}. It stays waiting.`);
328
+ this.addEvent(letters, letter.id, { t: "delivered", at: this.now().toISOString(), via: "chat", channel: "unconfirmed", key: "", messageId: "" });
329
+ throw new LetterRefusal("send-uncertain", `${letter.code} may have reached the chat (${reason}), so Ouro counts it as delivered and won't send it again.`);
330
+ }
331
+ try {
332
+ const after = this.addEvent(letters, letter.id, { t: "delivered", at: this.now().toISOString(), via: "chat", ...receipt });
333
+ return { outcome: "done", state: after.state, channel: receipt.channel };
334
+ }
335
+ catch (error) {
336
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "daemon", event: "letters.deliver_unrecorded", message: "a letter was sent but its delivery wasn't recorded", meta: { code: letter.code, channel: receipt.channel, messageId: receipt.messageId } });
337
+ throw new LetterRefusal("sent-unrecorded", `${letter.code} went to the chat, but writing its delivered event failed (${error.message}), so the mailbox doesn't show it as delivered. Don't deliver it again.`);
338
+ }
296
339
  }
297
340
  }
298
341
  exports.LettersWriter = LettersWriter;
342
+ class DeadlinePassed extends Error {
343
+ }
344
+ /** The work's result, or DeadlinePassed once `ms` go by first; the work itself carries on. */
345
+ function withinDeadline(work, ms) {
346
+ let timer;
347
+ const deadline = new Promise((_, reject) => {
348
+ timer = setTimeout(() => reject(new DeadlinePassed(`no answer from the chat within ${Math.round(ms / 1000)} seconds`)), ms);
349
+ });
350
+ return Promise.race([work, deadline]).finally(() => clearTimeout(timer));
351
+ }
352
+ /** Whether a failed send may still have reached the chat: it ran out of time, or it failed after reaching the server. */
353
+ function mayHaveSent(error) {
354
+ return error instanceof DeadlinePassed || error.transportInvoked === true;
355
+ }
299
356
  /** The daemon's answer to a `letters.action` command: the result, or the refusal's code and text. */
300
357
  async function answerLettersCommand(writer, command) {
301
358
  try {
@@ -56,7 +56,7 @@ const doors_1 = require("../letters/doors");
56
56
  /** The codes the mailbox doors answer a refusal with: the doors' own checks and the daemon's letters writer. */
57
57
  exports.MAILBOX_REFUSAL_CODES = new Set([
58
58
  "daemon-down", "unknown-input", "bad-input", "no-agent", "not-found",
59
- "invalid-letter", "no-person", "not-sender", "not-waiting", "no-answering-handle",
59
+ "invalid-letter", "no-person", "not-sender", "not-waiting", "no-answering-handle", "already-delivered", "chat-unavailable", "send-failed", "send-uncertain", "sent-unrecorded",
60
60
  ]);
61
61
  exports.SENSE_TURN_MAX_RETRIES = 3;
62
62
  exports.SENSE_TURN_RETRY_DELAYS_MS = [1000, 2000, 4000];
package/dist/rsvp/cli.js CHANGED
@@ -41,9 +41,9 @@ const path = __importStar(require("node:path"));
41
41
  const doctor_1 = require("../heart/daemon/doctor");
42
42
  const habit_parser_1 = require("../heart/habits/habit-parser");
43
43
  const identity_1 = require("../heart/identity");
44
- const machine_identity_1 = require("../heart/machine-identity");
45
44
  const runtime_credentials_1 = require("../heart/runtime-credentials");
46
45
  const runtime_1 = require("../nerves/runtime");
46
+ const agent_client_1 = require("../senses/bluebubbles/agent-client");
47
47
  const client_1 = require("../senses/bluebubbles/client");
48
48
  const aisleplanner_client_1 = require("./aisleplanner-client");
49
49
  const config_1 = require("./config");
@@ -289,16 +289,12 @@ function resolveLatestSnapshot(agentRoot) {
289
289
  };
290
290
  }
291
291
  }
292
- function machineIdForCli() {
293
- return (0, machine_identity_1.loadOrCreateMachineIdentity)().machineId;
294
- }
295
292
  async function resolveRsvpRuntimeCredentialConfig(agent) {
296
293
  const cached = (0, runtime_credentials_1.readRuntimeCredentialConfig)(agent);
297
294
  return cached.ok ? cached : (0, runtime_credentials_1.refreshRuntimeCredentialConfig)(agent, { preserveCachedOnFailure: true });
298
295
  }
299
296
  async function resolveRsvpMachineRuntimeCredentialConfig(agent) {
300
- const cached = (0, runtime_credentials_1.readMachineRuntimeCredentialConfig)(agent);
301
- return cached.ok ? cached : (0, runtime_credentials_1.refreshMachineRuntimeCredentialConfig)(agent, machineIdForCli(), { preserveCachedOnFailure: true });
297
+ return (0, agent_client_1.agentMachineRuntimeConfig)(agent);
302
298
  }
303
299
  function blueBubblesChatFor(config) {
304
300
  const sendTarget = config.bluebubblesRoute.chatIdentifier
@@ -314,58 +310,12 @@ function blueBubblesChatFor(config) {
314
310
  participantHandles: [],
315
311
  };
316
312
  }
317
- function numberField(record, key, fallback) {
318
- const value = record?.[key];
319
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
320
- }
321
- function stringArrayField(record, key) {
322
- const value = record?.[key];
323
- if (!Array.isArray(value))
324
- return [];
325
- return value.map((entry) => typeof entry === "string" ? entry.trim() : "").filter(Boolean);
326
- }
327
- function recordField(record, key) {
328
- const value = record[key];
329
- return value && typeof value === "object" && !Array.isArray(value)
330
- ? value
331
- : null;
332
- }
333
313
  /** The agent's declared iMessage host account; an unreadable config leaves it unset, so sending fails closed. */
334
314
  function rsvpBlueBubblesHostOptions(agent, agentRoot) {
335
- try {
336
- return { agent, agentRoot, hostUsername: (0, identity_1.loadAgentConfig)({ agentName: agent, agentRoot }).senses?.bluebubbles.hostUsername };
337
- }
338
- catch {
339
- return { agent, agentRoot, hostUsername: undefined };
340
- }
315
+ return (0, agent_client_1.agentHostOptions)(agent, agentRoot);
341
316
  }
342
317
  function rsvpBlueBubblesClientConfig(nativeConfig, machineRuntimeConfig) {
343
- if (!machineRuntimeConfig.ok) {
344
- throw new Error(`BlueBubbles runtime config unavailable at ${machineRuntimeConfig.itemPath}: ${machineRuntimeConfig.error}`);
345
- }
346
- const bluebubbles = recordField(machineRuntimeConfig.config, "bluebubbles");
347
- const bluebubblesChannel = recordField(machineRuntimeConfig.config, "bluebubblesChannel");
348
- const serverUrl = localText(bluebubbles?.serverUrl);
349
- const password = localText(bluebubbles?.password);
350
- if (!serverUrl) {
351
- throw new Error("bluebubbles.serverUrl is required in this machine's agent-vault runtime config. Run `ouro connect bluebubbles --agent <agent>`.");
352
- }
353
- if (!password) {
354
- throw new Error("bluebubbles.password is required in this machine's agent-vault runtime config. Run `ouro connect bluebubbles --agent <agent>`.");
355
- }
356
- return {
357
- config: {
358
- serverUrl,
359
- password,
360
- accountId: localText(bluebubbles?.accountId) || localText(nativeConfig.bluebubblesRoute.accountId) || "default",
361
- ownHandles: stringArrayField(bluebubbles, "ownHandles"),
362
- },
363
- channelConfig: {
364
- port: numberField(bluebubblesChannel, "port", 18790),
365
- webhookPath: localText(bluebubblesChannel?.webhookPath) || "/bluebubbles-webhook",
366
- requestTimeoutMs: numberField(bluebubblesChannel, "requestTimeoutMs", 30_000),
367
- },
368
- };
318
+ return (0, agent_client_1.blueBubblesSettings)(machineRuntimeConfig, localText(nativeConfig.bluebubblesRoute.accountId) || "default");
369
319
  }
370
320
  function normalizeDelivery(value) {
371
321
  const record = value && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -0,0 +1,138 @@
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.agentMachineRuntimeConfig = agentMachineRuntimeConfig;
37
+ exports.blueBubblesSettings = blueBubblesSettings;
38
+ exports.agentHostOptions = agentHostOptions;
39
+ exports.blueBubblesClientForAgent = blueBubblesClientForAgent;
40
+ exports.chatWithHandle = chatWithHandle;
41
+ exports.sendLetterByBlueBubbles = sendLetterByBlueBubbles;
42
+ exports.letterChatSender = letterChatSender;
43
+ // A BlueBubbles client for a named agent, built from outside that agent's sense process: the daemon delivering a
44
+ // letter, or an `ouro rsvp` command. Its settings come from the agent's machine runtime config in the vault (held in
45
+ // process memory once read), and its host check uses the agent's declared iMessage host account.
46
+ const path = __importStar(require("path"));
47
+ const identity_1 = require("../../heart/identity");
48
+ const machine_identity_1 = require("../../heart/machine-identity");
49
+ const runtime_credentials_1 = require("../../heart/runtime-credentials");
50
+ const runtime_1 = require("../../nerves/runtime");
51
+ const client_1 = require("./client");
52
+ function text(value) {
53
+ return typeof value === "string" ? value.trim() : "";
54
+ }
55
+ function record(parent, key) {
56
+ const value = parent[key];
57
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
58
+ }
59
+ function numberField(parent, key, fallback) {
60
+ const value = parent?.[key];
61
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
62
+ }
63
+ function stringList(parent, key) {
64
+ const value = parent?.[key];
65
+ if (!Array.isArray(value))
66
+ return [];
67
+ return value.map((entry) => typeof entry === "string" ? entry.trim() : "").filter(Boolean);
68
+ }
69
+ /** The agent's machine runtime config: the cached copy, or a fresh read from the vault when none is cached. */
70
+ async function agentMachineRuntimeConfig(agent) {
71
+ const cached = (0, runtime_credentials_1.readMachineRuntimeCredentialConfig)(agent);
72
+ return cached.ok ? cached : (0, runtime_credentials_1.refreshMachineRuntimeCredentialConfig)(agent, (0, machine_identity_1.loadOrCreateMachineIdentity)().machineId, { preserveCachedOnFailure: true });
73
+ }
74
+ /** The client and channel settings in a machine runtime config, or an error that names the command that fixes it. */
75
+ function blueBubblesSettings(machineRuntimeConfig, accountIdFallback = "default") {
76
+ if (!machineRuntimeConfig.ok) {
77
+ throw new Error(`BlueBubbles runtime config unavailable at ${machineRuntimeConfig.itemPath}: ${machineRuntimeConfig.error}`);
78
+ }
79
+ const bluebubbles = record(machineRuntimeConfig.config, "bluebubbles");
80
+ const channel = record(machineRuntimeConfig.config, "bluebubblesChannel");
81
+ const serverUrl = text(bluebubbles?.serverUrl);
82
+ const password = text(bluebubbles?.password);
83
+ if (!serverUrl)
84
+ throw new Error("bluebubbles.serverUrl is required in this machine's agent-vault runtime config. Run `ouro connect bluebubbles --agent <agent>`.");
85
+ if (!password)
86
+ throw new Error("bluebubbles.password is required in this machine's agent-vault runtime config. Run `ouro connect bluebubbles --agent <agent>`.");
87
+ return {
88
+ config: { serverUrl, password, accountId: text(bluebubbles?.accountId) || accountIdFallback, ownHandles: stringList(bluebubbles, "ownHandles") },
89
+ channelConfig: {
90
+ port: numberField(channel, "port", 18790),
91
+ webhookPath: text(channel?.webhookPath) || "/bluebubbles-webhook",
92
+ requestTimeoutMs: numberField(channel, "requestTimeoutMs", 30_000),
93
+ },
94
+ };
95
+ }
96
+ /** The host check's inputs for an agent: its name, bundle and declared iMessage host account, when agent.json reads. */
97
+ function agentHostOptions(agent, agentRoot) {
98
+ try {
99
+ return { agent, agentRoot, hostUsername: (0, identity_1.loadAgentConfig)({ agentName: agent, agentRoot }).senses?.bluebubbles.hostUsername };
100
+ }
101
+ catch {
102
+ return { agent, agentRoot, hostUsername: undefined };
103
+ }
104
+ }
105
+ /** A BlueBubbles client acting as the agent's Apple ID, from the agent's own settings. */
106
+ async function blueBubblesClientForAgent(agent, agentRoot) {
107
+ const settings = blueBubblesSettings(await agentMachineRuntimeConfig(agent));
108
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.bluebubbles_agent_client", message: "bluebubbles client built for an agent outside its sense", meta: { agent } });
109
+ return (0, client_1.createBlueBubblesClient)(settings.config, settings.channelConfig, agentHostOptions(agent, agentRoot));
110
+ }
111
+ /** A one-to-one chat with a handle, addressed by the handle alone; the client finds the existing chat for it. */
112
+ function chatWithHandle(handle) {
113
+ return { chatIdentifier: handle, isGroup: false, sessionKey: `chat_identifier:${handle}`, sendTarget: { kind: "chat_identifier", value: handle }, participantHandles: [] };
114
+ }
115
+ /**
116
+ * Sends a letter Ouro rendered to the handle's chat as the agent, and says where it landed. A server that names no
117
+ * chat or message leaves those blank rather than failing a send that went out.
118
+ */
119
+ async function sendLetterByBlueBubbles(request, agentRoot, clientFor = blueBubblesClientForAgent) {
120
+ const client = await clientFor(request.agent, agentRoot);
121
+ let sent;
122
+ try {
123
+ sent = await client.sendText({ chat: chatWithHandle(request.handle), text: request.text });
124
+ }
125
+ catch (error) {
126
+ // A chat that doesn't exist yet can't be found by its handle; say what the person does about it.
127
+ if (error instanceof client_1.BlueBubblesSendError && error.errorCode === "chat_unresolved") {
128
+ throw new client_1.BlueBubblesSendError({ message: `no chat with ${request.handle} exists yet; the person messages the agent once from that handle first`, httpStatus: null, errorCode: "chat_unresolved", transportInvoked: false, cause: error });
129
+ }
130
+ throw error;
131
+ }
132
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.bluebubbles_letter_sent", message: "a letter was sent to its person's chat", meta: { agent: request.agent, hasMessageId: Boolean(sent.messageGuid) } });
133
+ return { channel: "bluebubbles", key: sent.chatGuid ?? "", messageId: sent.messageGuid ?? "" };
134
+ }
135
+ /** The daemon's letter sender: each agent's letters go out through that agent's own bundle and settings. */
136
+ function letterChatSender(bundlesRoot, clientFor) {
137
+ return (request) => sendLetterByBlueBubbles(request, path.join(bundlesRoot, `${request.agent}.ouro`), clientFor);
138
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1627",
3
+ "version": "0.1.0-alpha.1629",
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.1627",
9
+ "version": "0.1.0-alpha.1629",
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.1627",
3
+ "version": "0.1.0-alpha.1629",
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": {