@ouro.bot/cli 0.1.0-alpha.1393 → 0.1.0-alpha.1396

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/changelog.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1396",
6
+ "changes": [
7
+ "A BlueBubbles listener that stops proving itself now reads as an error and is restarted, timed on the daemon's own clock so sleep never triggers it, and slow syncs, failed syncs and recoveries are logged."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1394",
12
+ "changes": [
13
+ "Groundwork for relaying Ari's approval answers: the relay token, the trust-folder switch and a store method for a relayed deny. Nothing uses them yet."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1393",
6
18
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1393",
2
+ "runtimeVersion": "0.1.0-alpha.1396",
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.1393</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1396</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MIN_RELAY_KEY_LENGTH = exports.APPROVAL_RELAY_FILE = void 0;
4
+ exports.approvalRelayToken = approvalRelayToken;
5
+ exports.relayTokensEqual = relayTokensEqual;
6
+ exports.checkRelayedDecision = checkRelayedDecision;
7
+ exports.readApprovalRelaySwitch = readApprovalRelaySwitch;
8
+ /**
9
+ * The approval relay: Ari answers a tool approval by replying to his primary agent (the owner route's peer) instead of
10
+ * tapping the Telegram card, and that agent's harness sends the answer back as a signed `approvalAnswer`.
11
+ *
12
+ * This file holds the pieces that do no I/O beyond reading the operator's switch:
13
+ * - the relay token, which binds an answer to one approval and one route DID;
14
+ * - the trust-folder switch, which turns the relay on;
15
+ * - the v1 rule that only `deny` is relayed.
16
+ *
17
+ * Design: desk sanctuary-server/butler-productionization/ouroboros/2026-11-23-signed-relay-design-v3.md.
18
+ */
19
+ const node_crypto_1 = require("node:crypto");
20
+ const runtime_1 = require("../nerves/runtime");
21
+ const operator_trust_1 = require("./operator-trust");
22
+ const trusted_files_1 = require("./trusted-files");
23
+ /** The Butler's switch, in its operator trust folder. Root-owned, so neither the agent nor its shell can turn it on. */
24
+ exports.APPROVAL_RELAY_FILE = "approval-relay.json";
25
+ const DOMAIN = "ouro.approval-relay.v1\0";
26
+ /** A decision token is 32 random bytes in base64url (43 characters); anything under 32 characters isn't one. */
27
+ exports.MIN_RELAY_KEY_LENGTH = 32;
28
+ const DID = /^did:[a-z0-9]+:[A-Za-z0-9._:%-]{1,512}$/;
29
+ const ISO = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z$/;
30
+ /**
31
+ * `HMAC-SHA256(decisionToken, "ouro.approval-relay.v1\0" || approvalId || "\0" || routeDid)`, base64url. The decision
32
+ * token is the approval's own secret, so only the Butler can compute it, and the route DID means an outstanding token
33
+ * stops matching once the route rotates. It refuses to compute with an empty or short key (a settled approval has no
34
+ * token, and a short one isn't a decision token).
35
+ * Never log it.
36
+ */
37
+ function approvalRelayToken(input) {
38
+ const parts = [input.decisionToken, input.approvalId, input.routeDid];
39
+ if (parts.some((part) => typeof part !== "string" || part.length === 0 || part.includes("\0"))
40
+ || input.decisionToken.length < exports.MIN_RELAY_KEY_LENGTH) {
41
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.approval_relay_token_refused", message: "refused to compute an approval relay token without a decision token, approval id and route DID", meta: { reason: "missing_input" } });
42
+ throw new Error("approval relay token needs a decision token, an approval id and a route DID");
43
+ }
44
+ return (0, node_crypto_1.createHmac)("sha256", input.decisionToken).update(`${DOMAIN}${input.approvalId}\0${input.routeDid}`).digest("base64url");
45
+ }
46
+ /** Constant-time comparison of two relay tokens. Empty or non-string never matches. */
47
+ function relayTokensEqual(a, b) {
48
+ if (typeof a !== "string" || typeof b !== "string" || a.length === 0)
49
+ return false;
50
+ const left = Buffer.from(a);
51
+ const right = Buffer.from(b);
52
+ return left.length === right.length && (0, node_crypto_1.timingSafeEqual)(left, right);
53
+ }
54
+ /**
55
+ * v1 relays `deny` only. Approve is refused here in code, before any switch or list is read, so allowing it later means
56
+ * changing code (and friends, whose `approvalAnswer` also takes deny only), not editing a file.
57
+ */
58
+ function checkRelayedDecision(decision) {
59
+ if (decision === "deny")
60
+ return { ok: true, decision: "deny" };
61
+ const reason = decision === "approve" ? "approve_not_in_v1" : "unknown_decision";
62
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.approval_relay_decision_refused", message: "refused a relayed approval decision v1 does not relay", meta: { reason } });
63
+ return { ok: false, reason };
64
+ }
65
+ /**
66
+ * Reads `{ schemaVersion: 1, did, expiresAt, approveTools, source }` from the operator trust folder. Missing,
67
+ * untrusted, malformed or expired is off. `approveTools` must be a list of names but is never returned: v1 relays deny
68
+ * only, whatever it lists. A copy anywhere under the bundle is never read.
69
+ */
70
+ function readApprovalRelaySwitch(agentRoot, now = new Date()) {
71
+ const raw = (0, trusted_files_1.inspectTrustedJson)((0, operator_trust_1.operatorTrustFile)(agentRoot, exports.APPROVAL_RELAY_FILE));
72
+ if (raw.state === "missing")
73
+ return { on: false, reason: "missing" };
74
+ if (raw.state === "untrusted")
75
+ return off("untrusted", raw.reason);
76
+ const value = raw.value;
77
+ if (!value || typeof value !== "object" || Array.isArray(value))
78
+ return off("malformed");
79
+ const v = value;
80
+ const valid = Object.keys(v).sort().join(",") === "approveTools,did,expiresAt,schemaVersion,source"
81
+ && v.schemaVersion === 1
82
+ && typeof v.did === "string" && DID.test(v.did)
83
+ && typeof v.expiresAt === "string" && ISO.test(v.expiresAt) && Number.isFinite(Date.parse(v.expiresAt))
84
+ && Array.isArray(v.approveTools) && v.approveTools.every((tool) => typeof tool === "string")
85
+ && typeof v.source === "string" && v.source.trim().length > 0;
86
+ if (!valid)
87
+ return off("malformed");
88
+ if (now.getTime() >= Date.parse(v.expiresAt))
89
+ return off("expired");
90
+ return { on: true, did: v.did, expiresAt: v.expiresAt, source: v.source };
91
+ }
92
+ function off(reason, detail) {
93
+ (0, runtime_1.emitNervesEvent)({ level: "warn", component: "senses", event: "senses.approval_relay_switch_off", message: "the approval relay switch is off because its trust-folder file can't be used", meta: { reason, ...(detail ? { detail } : {}) } });
94
+ return { on: false, reason, ...(detail ? { detail } : {}) };
95
+ }
@@ -123,7 +123,9 @@ function canonicalApprovalArguments(value) {
123
123
  }
124
124
  function hasExactKeys(value) {
125
125
  const actual = Object.keys(value).sort();
126
- const expected = [...RECORD_KEYS, ...("ownerBinding" in value ? ["ownerBinding"] : [])].sort();
126
+ const expected = [
127
+ ...RECORD_KEYS, ...("ownerBinding" in value ? ["ownerBinding"] : []), ...("relayDecision" in value ? ["relayDecision"] : []),
128
+ ].sort();
127
129
  return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
128
130
  }
129
131
  function validOwnerBinding(value) {
@@ -131,6 +133,10 @@ function validOwnerBinding(value) {
131
133
  && ["friendId", "requestId", "sessionEventId", "sessionKey"].every((key) => isNonEmpty(value[key]) && value[key] === value[key].trim())
132
134
  && typeof value.profileVersion === "number" && Number.isSafeInteger(value.profileVersion) && value.profileVersion > 0;
133
135
  }
136
+ function validRelayDecision(value) {
137
+ return isObject(value) && Object.keys(value).sort().join(",") === "actor,decidedAt,envelopeBindingId,senderDid"
138
+ && value.actor === "owner-via-relay" && isNonEmpty(value.senderDid) && isNonEmpty(value.envelopeBindingId) && isTimestamp(value.decidedAt);
139
+ }
134
140
  function validStateShape(record) {
135
141
  const hasOwner = isNonEmpty(record.ownerId);
136
142
  const hasAttempt = isTimestamp(record.attemptedAt);
@@ -200,6 +206,8 @@ function parseApprovalRecord(value) {
200
206
  fail("corrupt_record");
201
207
  if ("ownerBinding" in value && !validOwnerBinding(value.ownerBinding))
202
208
  fail("corrupt_record");
209
+ if ("relayDecision" in value && (!validRelayDecision(value.relayDecision) || value.state !== "denied"))
210
+ fail("corrupt_record");
203
211
  const record = value;
204
212
  if (!UUID.test(record.approvalId))
205
213
  fail("corrupt_record");
@@ -325,6 +333,17 @@ function observeDecide(operation) {
325
333
  throw error;
326
334
  }
327
335
  }
336
+ function observeDecideRelayed(operation) {
337
+ try {
338
+ const result = operation();
339
+ (0, runtime_1.emitNervesEvent)({ component: "heart", event: "approval.store_decide_relayed", message: "relayed approval decision completed", meta: { operation: "decide_relayed", outcome: "success" } });
340
+ return result;
341
+ }
342
+ catch (error) {
343
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "heart", event: "approval.store_decide_relayed", message: "relayed approval decision failed", meta: operationErrorMeta("decide_relayed", error) });
344
+ throw error;
345
+ }
346
+ }
328
347
  function observeExpire(operation) {
329
348
  try {
330
349
  const result = operation();
@@ -691,6 +710,30 @@ function openApprovalStore(options) {
691
710
  return cas(previous, { ...previous, state: "claimed", ownerId: input.ownerId, epoch: previous.epoch + 1, updatedAt: timestamp() });
692
711
  });
693
712
  },
713
+ decideRelayed(input) {
714
+ return observeDecideRelayed(() => {
715
+ if (input.decision !== "deny")
716
+ fail("relay_decision_not_allowed");
717
+ if (!isNonEmpty(input.senderDid) || !isNonEmpty(input.envelopeBindingId))
718
+ fail("invalid_relay_decision");
719
+ const previous = requireRecord(input.approvalId);
720
+ const decisionAt = now().getTime();
721
+ if (!tokenMatches(input.decisionToken, previous.decisionTokenDigest))
722
+ fail("decision_binding_mismatch");
723
+ if (previous.state === "denied" && previous.relayDecision?.envelopeBindingId === input.envelopeBindingId
724
+ && previous.relayDecision.senderDid === input.senderDid)
725
+ return previous;
726
+ if (previous.state !== "proposed")
727
+ fail("decision_not_eligible");
728
+ if (decisionAt >= Date.parse(previous.expiresAt)) {
729
+ return cas(previous, { ...previous, state: "expired", updatedAt: timestamp() });
730
+ }
731
+ const relayDecision = {
732
+ actor: "owner-via-relay", senderDid: input.senderDid, envelopeBindingId: input.envelopeBindingId, decidedAt: timestamp(),
733
+ };
734
+ return cas(previous, { ...previous, state: "denied", relayDecision, updatedAt: timestamp() });
735
+ });
736
+ },
694
737
  expire(input) {
695
738
  return observeExpire(() => {
696
739
  const previous = requireRecord(input.approvalId);
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.DaemonSenseManager = void 0;
36
+ exports.DaemonSenseManager = exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS = void 0;
37
37
  const fs = __importStar(require("fs"));
38
38
  const bluebubbles_host_account_1 = require("../bluebubbles-host-account");
39
39
  const os = __importStar(require("os"));
@@ -54,6 +54,14 @@ const DEFAULT_TEAMS_PORT = 3978;
54
54
  const DEFAULT_BLUEBUBBLES_PORT = 18790;
55
55
  const DEFAULT_BLUEBUBBLES_WEBHOOK_PATH = "/bluebubbles-webhook";
56
56
  const BLUEBUBBLES_RUNTIME_FRESHNESS_WINDOW_MS = 90_000;
57
+ /**
58
+ * The listener's 30 s sync loop refreshes its proof on every tick, even while a slow pass runs, and a pass that
59
+ * hangs is abandoned after two minutes without progress. So a proof this daemon has watched stay unchanged this long means the loop
60
+ * itself has stopped. Busy turns never hold it back.
61
+ */
62
+ exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS = 10 * 60_000;
63
+ /** Each restart that brings no fresh proof doubles the wait before the next, up to this many doublings. */
64
+ const BLUEBUBBLES_STALE_PROOF_MAX_DOUBLINGS = 3;
57
65
  const SENSE_CONFIG_RETRY_DELAYS_MS = [1_000, 2_000, 5_000, 10_000, 30_000, 60_000];
58
66
  const WORKBENCH_RUNTIME_INJECTION_DETAIL = "runtime-injected by Workbench app; no agent.json entry required";
59
67
  const WORKBENCH_STALE_BUNDLE_DETAIL = "stale agent.json Workbench entry; run 'ouro connect workbench' to clean it and use runtime injection";
@@ -490,6 +498,7 @@ function readBlueBubblesRuntimeJson(runtimePath) {
490
498
  ? parsed.detail
491
499
  : "startup health probe pending",
492
500
  lastCheckedAt: typeof parsed.lastCheckedAt === "string" ? parsed.lastCheckedAt : undefined,
501
+ lastHeartbeatAt: typeof parsed.lastHeartbeatAt === "string" ? parsed.lastHeartbeatAt : undefined,
493
502
  proofMethod: typeof parsed.proofMethod === "string" && parsed.proofMethod.trim()
494
503
  ? parsed.proofMethod
495
504
  : undefined,
@@ -518,10 +527,19 @@ function readBlueBubblesRuntimeJson(runtimePath) {
518
527
  /* v8 ignore start -- defensive: catch for missing/corrupt BB runtime state file @preserve */
519
528
  }
520
529
  catch {
521
- return { upstreamStatus: "unknown", detail: "startup health probe pending", pendingRecoveryCount: 0, failedRecoveryCount: 0 };
530
+ return { upstreamStatus: "unknown", detail: "startup health probe pending", pendingRecoveryCount: 0, failedRecoveryCount: 0, unreadable: true };
522
531
  }
523
532
  /* v8 ignore stop */
524
533
  }
534
+ /** The listener's latest sign of life: its last health check, or a sync heartbeat written since. */
535
+ function blueBubblesLatestProof(state) {
536
+ const checkedMs = state.lastCheckedAt ? Date.parse(state.lastCheckedAt) : Number.NaN;
537
+ const heartbeatMs = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : Number.NaN;
538
+ if (!Number.isFinite(heartbeatMs) || checkedMs >= heartbeatMs)
539
+ return { at: state.lastCheckedAt, method: state.proofMethod };
540
+ // Every write stamps a heartbeat a moment after its check, so the heartbeat is named the proof only once the check is old.
541
+ return { at: state.lastHeartbeatAt, method: blueBubblesRuntimeStateIsFresh(state.lastCheckedAt) ? state.proofMethod : "bluebubbles.syncHeartbeat" };
542
+ }
525
543
  function readBlueBubblesRuntimeFacts(agent, bundlesRoot, snapshot) {
526
544
  const agentRoot = path.join(bundlesRoot, `${agent}.ouro`);
527
545
  const runtimePath = path.join(agentRoot, "state", "senses", "bluebubbles", "runtime.json");
@@ -529,11 +547,12 @@ function readBlueBubblesRuntimeFacts(agent, bundlesRoot, snapshot) {
529
547
  return { runtime: snapshot?.runtime };
530
548
  }
531
549
  const state = readBlueBubblesRuntimeJson(runtimePath);
532
- const checkedAtMs = state.lastCheckedAt ? Date.parse(state.lastCheckedAt) : Number.NaN;
550
+ const proof = blueBubblesLatestProof(state);
551
+ const proofAtMs = proof.at ? Date.parse(proof.at) : Number.NaN;
533
552
  const proofFacts = {
534
- proofMethod: state.proofMethod ?? "bluebubbles.checkHealth",
535
- lastProofAt: state.lastCheckedAt,
536
- proofAgeMs: Number.isFinite(checkedAtMs) ? Math.max(0, Date.now() - checkedAtMs) : undefined,
553
+ proofMethod: proof.method ?? "bluebubbles.checkHealth",
554
+ lastProofAt: proof.at,
555
+ proofAgeMs: Number.isFinite(proofAtMs) ? Math.max(0, Date.now() - proofAtMs) : undefined,
537
556
  pendingRecoveryCount: state.pendingRecoveryCount,
538
557
  failedRecoveryCount: state.failedRecoveryCount,
539
558
  oldestPendingRecoveryAt: state.oldestPendingRecoveryAt,
@@ -543,11 +562,21 @@ function readBlueBubblesRuntimeFacts(agent, bundlesRoot, snapshot) {
543
562
  oldestActiveTurnStartedAt: state.oldestActiveTurnStartedAt,
544
563
  oldestActiveTurnAgeMs: state.oldestActiveTurnAgeMs,
545
564
  };
546
- if (!blueBubblesRuntimeStateIsFresh(state.lastCheckedAt)) {
565
+ if (!blueBubblesRuntimeStateIsFresh(proof.at)) {
566
+ // A running listener that has stopped proving itself is not healthy, whatever its process state says.
567
+ if (proof.at && snapshot?.runtime === "running") {
568
+ return {
569
+ runtime: "error",
570
+ ...proofFacts,
571
+ lastFailure: "BlueBubbles proof is stale",
572
+ failureLayer: "proof_freshness",
573
+ recoveryAction: `the daemon restarts the BlueBubbles listener once its proof has not changed for ${Math.round(exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS / 60_000)}m`,
574
+ };
575
+ }
547
576
  return {
548
577
  runtime: snapshot?.runtime,
549
- lastFailure: state.lastCheckedAt ? "BlueBubbles proof is stale" : undefined,
550
- failureLayer: state.lastCheckedAt ? "proof_freshness" : undefined,
578
+ lastFailure: proof.at ? "BlueBubbles proof is stale" : undefined,
579
+ failureLayer: proof.at ? "proof_freshness" : undefined,
551
580
  };
552
581
  }
553
582
  if (snapshot?.runtime !== "running") {
@@ -617,9 +646,14 @@ class DaemonSenseManager {
617
646
  presenceFlagOn;
618
647
  /** Shared senses skipped because another machine owns them; started here when ownership arrives. */
619
648
  notOwnerSkipped = new Set();
649
+ monotonicNow;
650
+ /** Per agent: the listener process and proof last seen, since when (monotonic), and restarts that brought no new proof. */
651
+ blueBubblesProofWatch = new Map();
620
652
  constructor(options) {
621
653
  const bundlesRoot = options.bundlesRoot ?? path.join(os.homedir(), "AgentBundles");
622
654
  this.bundlesRoot = bundlesRoot;
655
+ /* v8 ignore next -- production default; tests inject the clock @preserve */
656
+ this.monotonicNow = options.monotonicNow ?? (() => performance.now());
623
657
  /* v8 ignore start -- production default reads the real roster and machine identity; tests inject presenceOwner @preserve */
624
658
  this.presenceOwner = options.presenceOwner ?? ((agent, sense) => {
625
659
  if (!(0, presence_1.isSharedSense)(sense))
@@ -977,9 +1011,69 @@ class DaemonSenseManager {
977
1011
  // something else triggers a tight respawn cycle for any reason, the
978
1012
  // guard fires and refuses further restarts after N attempts in M
979
1013
  // minutes, so we can never re-enter the 2026-05-11 spiral.
1014
+ //
1015
+ // What we do watch is the listener's own proof. Its sync loop rewrites
1016
+ // runtime.json every 30 s on a timer that turns never block, so a proof
1017
+ // ten minutes old means that loop has stopped, not that it is busy. The
1018
+ // probe only reads the file; it never calls into the listener.
1019
+ probes.push(this.blueBubblesProofProbe(agent));
980
1020
  }
981
1021
  return probes;
982
1022
  }
1023
+ blueBubblesProofProbe(agent) {
1024
+ const managedName = `${agent}:bluebubbles`;
1025
+ return {
1026
+ name: `bluebubbles-proof:${agent}`,
1027
+ managedName,
1028
+ check: async () => {
1029
+ const snapshot = this.processManager.listAgentSnapshots().find((row) => row.name === managedName);
1030
+ if (snapshot?.status !== "running")
1031
+ return { ok: true };
1032
+ const runtimePath = path.join(this.bundlesRoot, `${agent}.ouro`, "state", "senses", "bluebubbles", "runtime.json");
1033
+ const state = fs.existsSync(runtimePath) ? readBlueBubblesRuntimeJson(runtimePath) : null;
1034
+ // A file caught mid-write says nothing either way.
1035
+ if (state?.unreadable)
1036
+ return { ok: true };
1037
+ const proofAt = (state && blueBubblesLatestProof(state).at) ?? null;
1038
+ const processKey = `${snapshot.pid ?? ""}:${snapshot.startedAt ?? ""}`;
1039
+ // Timed on this daemon's own clock, which stops while the machine sleeps just as the listener's timers do,
1040
+ // so waking from sleep or a wall-clock correction never makes a proof look stale.
1041
+ const now = this.monotonicNow();
1042
+ const watch = this.blueBubblesProofWatch.get(agent);
1043
+ if (!watch || watch.process !== processKey || watch.proofAt !== proofAt) {
1044
+ const restarts = watch && watch.proofAt === proofAt ? watch.restarts : 0;
1045
+ this.blueBubblesProofWatch.set(agent, { process: processKey, proofAt, sinceMs: now, restarts });
1046
+ return { ok: true };
1047
+ }
1048
+ const stalledMs = now - watch.sinceMs;
1049
+ if (stalledMs < exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS * 2 ** Math.min(watch.restarts, BLUEBUBBLES_STALE_PROOF_MAX_DOUBLINGS))
1050
+ return { ok: true };
1051
+ // If the restart brings no new proof either, wait longer before the next one.
1052
+ watch.restarts += 1;
1053
+ watch.sinceMs = now;
1054
+ const stalledMinutes = Math.round(stalledMs / 60_000);
1055
+ (0, runtime_1.emitNervesEvent)({
1056
+ level: "warn",
1057
+ component: "daemon",
1058
+ event: "daemon.bluebubbles_stale_proof_restart",
1059
+ message: "restarting a BlueBubbles listener whose proof stopped updating",
1060
+ meta: {
1061
+ agent,
1062
+ stalledMs,
1063
+ lastProofAt: proofAt,
1064
+ restarts: watch.restarts,
1065
+ nextRestartAfterMs: exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS * 2 ** Math.min(watch.restarts, BLUEBUBBLES_STALE_PROOF_MAX_DOUBLINGS),
1066
+ },
1067
+ });
1068
+ return {
1069
+ ok: false,
1070
+ detail: proofAt === null
1071
+ ? `the BlueBubbles listener has written no BlueBubbles proof in ${stalledMinutes}m; restarting it`
1072
+ : `BlueBubbles proof has not changed in ${stalledMinutes}m; restarting the listener`,
1073
+ };
1074
+ },
1075
+ };
1076
+ }
983
1077
  async restartSense(managedName) {
984
1078
  const parsed = parseSenseSnapshotName(managedName);
985
1079
  if (parsed?.sense === "shepherd" && this.quiescedShepherdOwners.has(parsed.agent))
@@ -429,6 +429,13 @@ const defaultDeps = {
429
429
  }),
430
430
  };
431
431
  const BLUEBUBBLES_RUNTIME_SYNC_INTERVAL_MS = 30_000;
432
+ /** After a failed sync, the next one comes sooner than the interval: 5 s, then 10 s, then 20 s. */
433
+ const BLUEBUBBLES_RUNTIME_SYNC_RETRY_BASE_MS = 5_000;
434
+ /**
435
+ * A sync that makes no progress (no probe answer, catch-up page or capture) for this long is abandoned so the next
436
+ * one can start. Every request times out in 30 s, so only a hang gets here; a slow catch-up that keeps going finishes.
437
+ */
438
+ const BLUEBUBBLES_RUNTIME_SYNC_STALL_MS = 2 * 60_000;
432
439
  const BLUEBUBBLES_RECOVERY_PASS_DELAY_MS = 1_000;
433
440
  const BLUEBUBBLES_RECOVERY_PASS_INTERVAL_MS = 30_000;
434
441
  // A turn that is still thinking after this long is treated as hung. It is generous on purpose: a slow reply that
@@ -3082,7 +3089,8 @@ function resolveBlueBubblesCatchUpSince(previousState, nowMs = Date.now()) {
3082
3089
  if (previousState.upstreamStatus === "error") {
3083
3090
  return nowMs - BLUEBUBBLES_RECOVERY_CATCHUP_LOOKBACK_MS;
3084
3091
  }
3085
- const lastCheckedAt = parseTimestampMs(previousState.lastCheckedAt);
3092
+ // A sync abandoned partway through catch-up has moved lastCheckedAt but not the cursor.
3093
+ const lastCheckedAt = parseTimestampMs(previousState.catchUpThrough ?? previousState.lastCheckedAt);
3086
3094
  if (lastCheckedAt !== null) {
3087
3095
  return Math.max(0, lastCheckedAt - BLUEBUBBLES_HEALTHY_CATCHUP_OVERLAP_MS);
3088
3096
  }
@@ -3124,16 +3132,32 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
3124
3132
  options.lifecycleSignal?.throwIfAborted();
3125
3133
  const resolvedDeps = { ...defaultDeps, ...deps };
3126
3134
  const agentName = resolvedDeps.getAgentName();
3127
- // Allocate before the first health-probe await. Any live webhook accepted
3128
- // while that probe is pending must remain causally newer than this pass.
3129
- const catchUpObservationBatch = options.catchUpObservationBatch ?? (0, latest_turn_1.beginObservationBatch)(BLUEBUBBLES_CATCHUP_PAGE_SIZE * BLUEBUBBLES_CATCHUP_MAX_PAGES);
3130
- pruneBlueBubblesSemanticObservationGenerations(Date.now(), new Set((0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName).map((capture) => capture.keyHash)));
3131
- const client = resolvedDeps.createClient();
3132
3135
  const checkedAt = new Date().toISOString();
3133
3136
  const previousState = (0, runtime_state_1.readBlueBubblesRuntimeState)(agentName);
3137
+ let probeStarted = false;
3138
+ let probePassed = false;
3134
3139
  try {
3140
+ // Setup failures land in the catch below too, so they write an error proof like any failed sync.
3141
+ // Allocate before the first health-probe await. Any live webhook accepted
3142
+ // while that probe is pending must remain causally newer than this pass.
3143
+ const catchUpObservationBatch = options.catchUpObservationBatch ?? (0, latest_turn_1.beginObservationBatch)(BLUEBUBBLES_CATCHUP_PAGE_SIZE * BLUEBUBBLES_CATCHUP_MAX_PAGES);
3144
+ pruneBlueBubblesSemanticObservationGenerations(Date.now(), new Set((0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName).map((capture) => capture.keyHash)));
3145
+ const client = resolvedDeps.createClient();
3146
+ probeStarted = true;
3135
3147
  await client.checkHealth();
3136
3148
  options.lifecycleSignal?.throwIfAborted();
3149
+ probePassed = true;
3150
+ options.onProgress?.();
3151
+ // The listener logs at warn, so a healthy pass is silent; a recovery must not be.
3152
+ if (previousState.upstreamStatus === "error") {
3153
+ (0, runtime_1.emitNervesEvent)({
3154
+ level: "warn",
3155
+ component: "senses",
3156
+ event: "senses.bluebubbles_upstream_recovered",
3157
+ message: "bluebubbles upstream answered again after a failed sync",
3158
+ meta: { previousDetail: previousState.detail, previousCheckedAt: previousState.lastCheckedAt },
3159
+ });
3160
+ }
3137
3161
  const pendingBeforeCatchup = blueBubblesPendingRecoverySnapshot(agentName);
3138
3162
  const activeBeforeCatchup = (0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS);
3139
3163
  (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
@@ -3150,6 +3174,7 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
3150
3174
  processTurns: false,
3151
3175
  observationBatch: catchUpObservationBatch,
3152
3176
  lifecycleSignal: options.lifecycleSignal,
3177
+ onProgress: options.onProgress,
3153
3178
  });
3154
3179
  options.lifecycleSignal?.throwIfAborted();
3155
3180
  const failed = catchUp.failed;
@@ -3164,6 +3189,7 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
3164
3189
  upstreamStatus: "ok",
3165
3190
  detail: formatBlueBubblesRuntimeDetail(pendingAfterCatchup, failed, activeAfterCatchup),
3166
3191
  lastCheckedAt: checkedAt,
3192
+ catchUpThrough: checkedAt,
3167
3193
  proofMethod: "bluebubbles.checkHealth",
3168
3194
  ...pendingAfterCatchup,
3169
3195
  ...activeAfterCatchup,
@@ -3172,19 +3198,32 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
3172
3198
  lastRecoveredAt: previousState.lastRecoveredAt,
3173
3199
  lastRecoveredMessageGuid: previousState.lastRecoveredMessageGuid,
3174
3200
  });
3201
+ return "ok";
3175
3202
  }
3176
3203
  catch (error) {
3177
3204
  if (options.lifecycleSignal?.aborted)
3178
- return;
3205
+ return "aborted";
3206
+ const detail = error instanceof Error ? error.message : String(error);
3207
+ // A failed probe logs itself, so a streak of them adds only the line that starts it. Anything else logs here.
3208
+ if (!probeStarted || probePassed || previousState.upstreamStatus !== "error") {
3209
+ (0, runtime_1.emitNervesEvent)({
3210
+ level: "warn",
3211
+ component: "senses",
3212
+ event: "senses.bluebubbles_runtime_sync_failed",
3213
+ message: "bluebubbles runtime sync failed; recorded upstream error",
3214
+ meta: { reason: detail, probePassed },
3215
+ });
3216
+ }
3179
3217
  (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
3180
3218
  upstreamStatus: "error",
3181
- detail: error instanceof Error ? error.message : String(error),
3219
+ detail,
3182
3220
  lastCheckedAt: checkedAt,
3183
3221
  proofMethod: "bluebubbles.checkHealth",
3184
3222
  ...blueBubblesPendingRecoverySnapshot(agentName),
3185
3223
  ...(0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS),
3186
3224
  failedRecoveryCount: 0,
3187
3225
  });
3226
+ return "error";
3188
3227
  }
3189
3228
  }
3190
3229
  async function recoverQueuedBlueBubblesMessages(deps = {}, options = {}) {
@@ -3315,6 +3354,7 @@ async function catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousStat
3315
3354
  break;
3316
3355
  }
3317
3356
  options.lifecycleSignal?.throwIfAborted();
3357
+ options.onProgress?.();
3318
3358
  const pageMessages = pageEvents
3319
3359
  .filter((event) => event.kind === "message")
3320
3360
  .sort((left, right) => right.timestamp - left.timestamp);
@@ -3375,6 +3415,7 @@ async function catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousStat
3375
3415
  try {
3376
3416
  options.lifecycleSignal?.throwIfAborted();
3377
3417
  const captured = await captureBlueBubblesSemanticEvent(event, resolvedDeps, "upstream-catchup", observationReservation);
3418
+ options.onProgress?.();
3378
3419
  if (captured.status === "audit_only") {
3379
3420
  result.skipped++;
3380
3421
  continue;
@@ -4233,7 +4274,9 @@ function startBlueBubblesApp(deps = {}) {
4233
4274
  lifecycleSignal: lifecycleController.signal,
4234
4275
  }));
4235
4276
  let recoveryPassRunning = false;
4236
- let runtimeSyncRunning = false;
4277
+ let runtimeSync = null;
4278
+ let runtimeSyncFailures = 0;
4279
+ let runtimeSyncRetryTimer = null;
4237
4280
  let recoveryDelayTimer = null;
4238
4281
  let webhookReconciler = null;
4239
4282
  let closed = false;
@@ -4276,16 +4319,65 @@ function startBlueBubblesApp(deps = {}) {
4276
4319
  triggerRecoveryPass();
4277
4320
  }, BLUEBUBBLES_RECOVERY_PASS_DELAY_MS);
4278
4321
  }
4322
+ function scheduleRuntimeSyncRetry() {
4323
+ runtimeSyncFailures += 1;
4324
+ const delayMs = BLUEBUBBLES_RUNTIME_SYNC_RETRY_BASE_MS * 2 ** (runtimeSyncFailures - 1);
4325
+ // From here the 30 s interval retries soon enough.
4326
+ if (closed || delayMs >= BLUEBUBBLES_RUNTIME_SYNC_INTERVAL_MS)
4327
+ return;
4328
+ runtimeSyncRetryTimer = setTimeout(() => {
4329
+ runtimeSyncRetryTimer = null;
4330
+ triggerRuntimeSync();
4331
+ }, delayMs);
4332
+ }
4279
4333
  function triggerRuntimeSync(catchUpObservationBatch) {
4280
- if (closed || runtimeSyncRunning)
4334
+ /* v8 ignore next -- close clears the interval and the retry timer; guard covers an already-queued host callback @preserve */
4335
+ if (closed)
4281
4336
  return;
4282
- runtimeSyncRunning = true;
4337
+ if (runtimeSync) {
4338
+ const runningMs = Date.now() - runtimeSync.startedAt;
4339
+ const idleMs = Date.now() - runtimeSync.lastProgressAt;
4340
+ if (idleMs < BLUEBUBBLES_RUNTIME_SYNC_STALL_MS) {
4341
+ // A slow pass is still a live loop; say so, so the daemon does not take it for a stopped one.
4342
+ (0, runtime_state_1.touchBlueBubblesRuntimeHeartbeat)(resolvedDeps.getAgentName());
4343
+ return;
4344
+ }
4345
+ // A sync that never finishes must not stop every later one, which would leave the proof to go stale.
4346
+ (0, runtime_1.emitNervesEvent)({
4347
+ level: "warn",
4348
+ component: "senses",
4349
+ event: "senses.bluebubbles_runtime_sync_timeout",
4350
+ message: "abandoned a bluebubbles runtime sync that did not finish",
4351
+ meta: { runningMs, idleMs },
4352
+ });
4353
+ runtimeSync.controller.abort(new Error("bluebubbles_runtime_sync_timeout"));
4354
+ runtimeSync = null;
4355
+ }
4356
+ if (runtimeSyncRetryTimer !== null) {
4357
+ clearTimeout(runtimeSyncRetryTimer);
4358
+ runtimeSyncRetryTimer = null;
4359
+ }
4360
+ const sync = { startedAt: Date.now(), lastProgressAt: Date.now(), controller: new AbortController() };
4361
+ runtimeSync = sync;
4283
4362
  void syncBlueBubblesRuntime(resolvedDeps, {
4284
4363
  ...(catchUpObservationBatch ? { catchUpObservationBatch } : {}),
4285
- lifecycleSignal: lifecycleController.signal,
4364
+ lifecycleSignal: AbortSignal.any([lifecycleController.signal, sync.controller.signal]),
4365
+ onProgress: () => { sync.lastProgressAt = Date.now(); },
4366
+ })
4367
+ .then((outcome) => {
4368
+ if (runtimeSync !== sync)
4369
+ return;
4370
+ runtimeSync = null;
4371
+ if (outcome === "error")
4372
+ scheduleRuntimeSyncRetry();
4373
+ else
4374
+ runtimeSyncFailures = 0;
4375
+ scheduleRecoveryPass();
4286
4376
  })
4287
- .then(scheduleRecoveryPass)
4377
+ /* v8 ignore start -- defensive: every failure of the sync itself is caught inside it and written as an error proof @preserve */
4288
4378
  .catch((error) => {
4379
+ if (runtimeSync === sync)
4380
+ runtimeSync = null;
4289
4381
  if (closed)
4290
4382
  return;
4291
4383
  (0, runtime_1.emitNervesEvent)({
@@ -4295,10 +4387,9 @@ function startBlueBubblesApp(deps = {}) {
4295
4387
  message: "bluebubbles runtime sync failed",
4296
4388
  meta: { reason: error instanceof Error ? error.message : String(error) },
4297
4389
  });
4298
- })
4299
- .finally(() => {
4300
- runtimeSyncRunning = false;
4390
+ scheduleRuntimeSyncRetry();
4301
4391
  });
4392
+ /* v8 ignore stop */
4302
4393
  }
4303
4394
  const runtimeTimer = setInterval(() => {
4304
4395
  /* v8 ignore next -- close clears this interval; guard covers an already-queued host callback @preserve */
@@ -4316,6 +4407,10 @@ function startBlueBubblesApp(deps = {}) {
4316
4407
  lifecycleController.abort(new Error("bluebubbles_runtime_shutdown"));
4317
4408
  clearInterval(runtimeTimer);
4318
4409
  clearInterval(recoveryTimer);
4410
+ if (runtimeSyncRetryTimer !== null) {
4411
+ clearTimeout(runtimeSyncRetryTimer);
4412
+ runtimeSyncRetryTimer = null;
4413
+ }
4319
4414
  if (recoveryDelayTimer !== null) {
4320
4415
  clearTimeout(recoveryDelayTimer);
4321
4416
  recoveryDelayTimer = null;
@@ -36,8 +36,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.getBlueBubblesRuntimeStatePath = getBlueBubblesRuntimeStatePath;
37
37
  exports.readBlueBubblesRuntimeState = readBlueBubblesRuntimeState;
38
38
  exports.writeBlueBubblesRuntimeState = writeBlueBubblesRuntimeState;
39
+ exports.touchBlueBubblesRuntimeHeartbeat = touchBlueBubblesRuntimeHeartbeat;
39
40
  const fs = __importStar(require("node:fs"));
40
41
  const path = __importStar(require("node:path"));
42
+ const atomic_file_1 = require("../../heart/atomic-file");
41
43
  const identity_1 = require("../../heart/identity");
42
44
  const runtime_1 = require("../../nerves/runtime");
43
45
  const DEFAULT_RUNTIME_STATE = {
@@ -64,6 +66,8 @@ function readBlueBubblesRuntimeState(agentName, agentRoot) {
64
66
  ? parsed.detail
65
67
  : DEFAULT_RUNTIME_STATE.detail,
66
68
  lastCheckedAt: typeof parsed.lastCheckedAt === "string" ? parsed.lastCheckedAt : undefined,
69
+ lastHeartbeatAt: typeof parsed.lastHeartbeatAt === "string" ? parsed.lastHeartbeatAt : undefined,
70
+ catchUpThrough: typeof parsed.catchUpThrough === "string" ? parsed.catchUpThrough : undefined,
67
71
  proofMethod: typeof parsed.proofMethod === "string" && parsed.proofMethod.trim()
68
72
  ? parsed.proofMethod
69
73
  : undefined,
@@ -102,8 +106,13 @@ function readBlueBubblesRuntimeState(agentName, agentRoot) {
102
106
  function writeBlueBubblesRuntimeState(agentName, state, agentRoot) {
103
107
  const filePath = getBlueBubblesRuntimeStatePath(agentName, agentRoot);
104
108
  try {
105
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
106
- fs.writeFileSync(filePath, JSON.stringify(state, null, 2) + "\n", "utf-8");
109
+ const catchUpThrough = state.catchUpThrough ?? readBlueBubblesRuntimeState(agentName, agentRoot).catchUpThrough;
110
+ // Replaced whole, so the daemon reading it mid-write never sees half a file.
111
+ (0, atomic_file_1.writeJsonAtomicSync)(filePath, {
112
+ ...state,
113
+ ...(catchUpThrough === undefined ? {} : { catchUpThrough }),
114
+ lastHeartbeatAt: new Date(Date.now()).toISOString(),
115
+ });
107
116
  }
108
117
  catch (error) {
109
118
  (0, runtime_1.emitNervesEvent)({
@@ -135,3 +144,9 @@ function writeBlueBubblesRuntimeState(agentName, state, agentRoot) {
135
144
  });
136
145
  return filePath;
137
146
  }
147
+ /** Refresh the heartbeat of the state on disk, while a sync that has not written yet is still running. */
148
+ function touchBlueBubblesRuntimeHeartbeat(agentName, agentRoot) {
149
+ if (!fs.existsSync(getBlueBubblesRuntimeStatePath(agentName, agentRoot)))
150
+ return;
151
+ writeBlueBubblesRuntimeState(agentName, readBlueBubblesRuntimeState(agentName, agentRoot), agentRoot);
152
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1393",
3
+ "version": "0.1.0-alpha.1396",
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.1393",
9
+ "version": "0.1.0-alpha.1396",
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.1393",
3
+ "version": "0.1.0-alpha.1396",
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": {