@ouro.bot/cli 0.1.0-alpha.1374 → 0.1.0-alpha.1376

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.1376",
6
+ "changes": [
7
+ "iMessage: a reply whose send timed out but arrived is recorded within a recovery pass instead of after 10 minutes, so status stops reporting it as not caught up."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1375",
12
+ "changes": [
13
+ "Senses: an iMessage turn can no longer wait forever to send; an iMessage turn that ends without a reply stays pending for replay or records a visible failure, and one the friend already heard from is never replayed; SIGTERM stops iMessage and Shepherd within 3 s; ouro status shows a reply stuck waiting to send."
14
+ ]
15
+ },
4
16
  {
5
17
  "version": "0.1.0-alpha.1374",
6
18
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1374",
2
+ "runtimeVersion": "0.1.0-alpha.1376",
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.1374</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1376</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -5,15 +5,63 @@ const node_async_hooks_1 = require("node:async_hooks");
5
5
  const runtime_1 = require("../nerves/runtime");
6
6
  const leaseContext = new node_async_hooks_1.AsyncLocalStorage();
7
7
  let queueTail = Promise.resolve();
8
- async function withTurnExecutionLease(work) {
8
+ /** Turns holding or waiting for the lease. */
9
+ let queuedTurns = 0;
10
+ function untilReadyOrAborted(previous, signal) {
11
+ return new Promise((resolve, reject) => {
12
+ if (signal.aborted) {
13
+ reject(signal.reason);
14
+ return;
15
+ }
16
+ const onAbort = () => reject(signal.reason);
17
+ signal.addEventListener("abort", onAbort, { once: true });
18
+ void previous.then(() => {
19
+ signal.removeEventListener("abort", onAbort);
20
+ resolve();
21
+ });
22
+ });
23
+ }
24
+ /**
25
+ * Run `work` once every turn queued ahead of it has finished. With a signal,
26
+ * an abort (turn deadline, supersession, shutdown) ends the wait instead of
27
+ * leaving the turn queued behind one that may never finish. A turn that finds
28
+ * the lease free runs as before, whatever its signal says.
29
+ */
30
+ async function withTurnExecutionLease(work, signal) {
9
31
  if (leaseContext.getStore())
10
32
  return work();
11
- let release;
33
+ let resolveTail;
12
34
  const previous = queueTail;
35
+ const mustWait = queuedTurns > 0;
36
+ queuedTurns += 1;
13
37
  queueTail = new Promise((resolve) => {
14
- release = resolve;
38
+ resolveTail = resolve;
15
39
  });
16
- await previous;
40
+ const release = () => {
41
+ queuedTurns -= 1;
42
+ resolveTail();
43
+ };
44
+ if (signal && mustWait) {
45
+ try {
46
+ await untilReadyOrAborted(previous, signal);
47
+ }
48
+ catch (error) {
49
+ // Give up this place in line only when the turn ahead ends, so the turn
50
+ // behind still runs after it rather than alongside it.
51
+ void previous.then(release);
52
+ (0, runtime_1.emitNervesEvent)({
53
+ level: "warn",
54
+ component: "heart",
55
+ event: "heart.turn_execution_lease_abandoned",
56
+ message: "turn stopped waiting for the turn ahead of it",
57
+ meta: { reason: error instanceof Error ? error.message : String(error) },
58
+ });
59
+ throw error;
60
+ }
61
+ }
62
+ else {
63
+ await previous;
64
+ }
17
65
  (0, runtime_1.emitNervesEvent)({
18
66
  component: "heart",
19
67
  event: "heart.turn_execution_lease_acquired",
@@ -33,8 +33,10 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.BLUEBUBBLES_DELIVERY_ADMISSION_STALLED_MS = void 0;
36
37
  exports.beginBlueBubblesActiveTurn = beginBlueBubblesActiveTurn;
37
38
  exports.noteBlueBubblesActiveTurnVisibleActivity = noteBlueBubblesActiveTurnVisibleActivity;
39
+ exports.noteBlueBubblesActiveTurnAdmissionWait = noteBlueBubblesActiveTurnAdmissionWait;
38
40
  exports.finishBlueBubblesActiveTurn = finishBlueBubblesActiveTurn;
39
41
  exports.listBlueBubblesActiveTurns = listBlueBubblesActiveTurns;
40
42
  exports.snapshotBlueBubblesActiveTurns = snapshotBlueBubblesActiveTurns;
@@ -43,6 +45,8 @@ const path = __importStar(require("node:path"));
43
45
  const config_1 = require("../../heart/config");
44
46
  const identity_1 = require("../../heart/identity");
45
47
  const runtime_1 = require("../../nerves/runtime");
48
+ /** A reply waiting this long for permission to send counts as a stalled turn. */
49
+ exports.BLUEBUBBLES_DELIVERY_ADMISSION_STALLED_MS = 60_000;
46
50
  function activeTurnsDir(agentName) {
47
51
  return path.join((0, identity_1.getAgentRoot)(agentName), "state", "senses", "bluebubbles", "active-turns");
48
52
  }
@@ -72,6 +76,9 @@ function parseActiveTurn(raw) {
72
76
  lastVisibleActivityAt: typeof parsed.lastVisibleActivityAt === "string"
73
77
  ? parsed.lastVisibleActivityAt
74
78
  : undefined,
79
+ admissionWaitingSince: typeof parsed.admissionWaitingSince === "string"
80
+ ? parsed.admissionWaitingSince
81
+ : undefined,
75
82
  messageGuid: parsed.messageGuid,
76
83
  sessionKey: parsed.sessionKey,
77
84
  chatGuid: parsed.chatGuid ?? null,
@@ -116,6 +123,13 @@ function beginBlueBubblesActiveTurn(agentName, event) {
116
123
  return turnId;
117
124
  }
118
125
  function noteBlueBubblesActiveTurnVisibleActivity(agentName, turnId) {
126
+ updateActiveTurn(agentName, turnId, (entry) => ({ ...entry, lastVisibleActivityAt: new Date().toISOString() }));
127
+ }
128
+ /** Marks (or, with null, clears) a turn whose reply is stuck waiting for permission to send. */
129
+ function noteBlueBubblesActiveTurnAdmissionWait(agentName, turnId, waitingSince) {
130
+ updateActiveTurn(agentName, turnId, ({ admissionWaitingSince: _cleared, ...entry }) => (waitingSince ? { ...entry, admissionWaitingSince: waitingSince } : entry));
131
+ }
132
+ function updateActiveTurn(agentName, turnId, update) {
119
133
  const filePath = activeTurnPath(agentName, turnId);
120
134
  let entry = null;
121
135
  try {
@@ -127,7 +141,7 @@ function noteBlueBubblesActiveTurnVisibleActivity(agentName, turnId) {
127
141
  if (!entry)
128
142
  return;
129
143
  try {
130
- fs.writeFileSync(filePath, JSON.stringify({ ...entry, lastVisibleActivityAt: new Date().toISOString() }, null, 2) + "\n", "utf-8");
144
+ fs.writeFileSync(filePath, JSON.stringify(update(entry), null, 2) + "\n", "utf-8");
131
145
  }
132
146
  catch (error) {
133
147
  (0, runtime_1.emitNervesEvent)({
@@ -207,9 +221,20 @@ function snapshotBlueBubblesActiveTurns(agentName, stalledAfterMs, nowMs = Date.
207
221
  .filter((entry) => Number.isFinite(entry.ms))
208
222
  .sort((left, right) => left.ms - right.ms);
209
223
  const oldest = started[0];
224
+ const admissionWaitAges = entries
225
+ .map((entry) => nowMs - Date.parse(entry.admissionWaitingSince ?? ""))
226
+ .filter((ageMs) => Number.isFinite(ageMs) && ageMs >= exports.BLUEBUBBLES_DELIVERY_ADMISSION_STALLED_MS);
227
+ const stalledTurns = entries.filter((entry) => {
228
+ const startedMs = Date.parse(entry.startedAt);
229
+ const waitingMs = Date.parse(entry.admissionWaitingSince ?? "");
230
+ return (Number.isFinite(startedMs) && nowMs - startedMs >= stalledAfterMs)
231
+ || (Number.isFinite(waitingMs) && nowMs - waitingMs >= exports.BLUEBUBBLES_DELIVERY_ADMISSION_STALLED_MS);
232
+ });
210
233
  return {
211
234
  activeTurnCount: entries.length,
212
- stalledTurnCount: started.filter((entry) => nowMs - entry.ms >= stalledAfterMs).length,
235
+ stalledTurnCount: stalledTurns.length,
236
+ admissionStalledTurnCount: admissionWaitAges.length,
237
+ ...(admissionWaitAges.length > 0 ? { oldestAdmissionWaitAgeMs: Math.max(...admissionWaitAges) } : {}),
213
238
  oldestActiveTurnStartedAt: oldest?.value,
214
239
  oldestActiveTurnAgeMs: oldest ? Math.max(0, nowMs - oldest.ms) : undefined,
215
240
  };
@@ -60,21 +60,10 @@ Promise.resolve().then(() => __importStar(require("../../heart/runtime-credentia
60
60
  if (!machineConfig.ok) {
61
61
  await refreshMachineRuntimeCredentialConfig(agentName, machine.machineId, { preserveCachedOnFailure: true }).catch(() => undefined);
62
62
  }
63
- const { startBlueBubblesApp } = await Promise.resolve().then(() => __importStar(require("./index")));
64
- const server = await startBlueBubblesApp();
65
- let shutdownStarted = false;
66
- const closeOnSignal = () => {
67
- if (shutdownStarted)
68
- return;
69
- shutdownStarted = true;
70
- server.close();
71
- };
72
- process.once("SIGTERM", closeOnSignal);
73
- process.once("SIGINT", closeOnSignal);
74
- server.once("close", () => {
75
- process.removeListener("SIGTERM", closeOnSignal);
76
- process.removeListener("SIGINT", closeOnSignal);
77
- });
63
+ const { startBlueBubblesApp, stopBlueBubblesApp } = await Promise.resolve().then(() => __importStar(require("./index")));
64
+ const { installSenseShutdown } = await Promise.resolve().then(() => __importStar(require("../sense-shutdown")));
65
+ const server = startBlueBubblesApp();
66
+ installSenseShutdown({ sense: "bluebubbles", stop: () => stopBlueBubblesApp(server) });
78
67
  void refreshRuntimeCredentialConfig(agentName, { preserveCachedOnFailure: true }).catch(() => undefined);
79
68
  })
80
69
  .catch((error) => {
@@ -34,7 +34,9 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.BB_IN_FLIGHT_MAX_AGE_MS = exports.BLUEBUBBLES_SEMANTIC_GENERATION_RETENTION_MS = void 0;
37
+ exports.drainBlueBubblesTurns = drainBlueBubblesTurns;
37
38
  exports.pruneBlueBubblesSemanticObservationGenerations = pruneBlueBubblesSemanticObservationGenerations;
39
+ exports.auditBlueBubblesObservationOwnership = auditBlueBubblesObservationOwnership;
38
40
  exports.tokenizeForDedupe = tokenizeForDedupe;
39
41
  exports.jaccardSimilarity = jaccardSimilarity;
40
42
  exports.isBlueBubblesMessageInFlight = isBlueBubblesMessageInFlight;
@@ -55,6 +57,7 @@ exports.recoverMissedBlueBubblesMessages = recoverMissedBlueBubblesMessages;
55
57
  exports.createBlueBubblesWebhookHandler = createBlueBubblesWebhookHandler;
56
58
  exports.sendProactiveBlueBubblesMessageToSession = sendProactiveBlueBubblesMessageToSession;
57
59
  exports.drainAndSendPendingBlueBubbles = drainAndSendPendingBlueBubbles;
60
+ exports.stopBlueBubblesApp = stopBlueBubblesApp;
58
61
  exports.startBlueBubblesApp = startBlueBubblesApp;
59
62
  const fs = __importStar(require("node:fs"));
60
63
  const http = __importStar(require("node:http"));
@@ -100,7 +103,22 @@ const context_packet_1 = require("./context-packet");
100
103
  const autonomy_budget_1 = require("../../heart/autonomy-budget");
101
104
  const outbound_state_1 = require("./outbound-state");
102
105
  const bbFailoverStates = new Map();
106
+ const inFlightBlueBubblesWork = new Set();
107
+ function trackBlueBubblesTurn(work) {
108
+ inFlightBlueBubblesWork.add(work);
109
+ const forget = () => { inFlightBlueBubblesWork.delete(work); };
110
+ void work.then(forget, forget);
111
+ }
112
+ /** Resolves once every queued webhook turn and recovery pass this process started has ended. */
113
+ async function drainBlueBubblesTurns() {
114
+ const work = [...inFlightBlueBubblesWork];
115
+ await Promise.allSettled(work);
116
+ return work.length;
117
+ }
103
118
  const activeSemanticHandlingSlots = new Map();
119
+ // Turns that timed out without a reply, per capture, in this process. Each one
120
+ // stays pending for replay until it reaches the delivery attempt cap.
121
+ const unfinishedTurnAttempts = new Map();
104
122
  const semanticObservationGenerations = new Map();
105
123
  const BLUEBUBBLES_VISIBLE_OUTBOUND_STATUSES = new Set([
106
124
  "accepted",
@@ -114,11 +132,19 @@ const BLUEBUBBLES_REPLY_DELIVERY_MAX_ATTEMPTS = 3;
114
132
  // A timed-out send may still land, so wait before checking the chat and retrying.
115
133
  const BLUEBUBBLES_REPLY_RETRY_DELAY_MS = 10 * 60_000;
116
134
  exports.BLUEBUBBLES_SEMANTIC_GENERATION_RETENTION_MS = 15 * 60_000;
117
- function pruneBlueBubblesSemanticObservationGenerations(nowMs = Date.now()) {
135
+ /**
136
+ * A retained generation fences older replies in its chat only while its capture
137
+ * still waits for recovery. Once the capture has an outcome (or after the
138
+ * retention window), nothing owns the fence, so release it.
139
+ */
140
+ function pruneBlueBubblesSemanticObservationGenerations(nowMs = Date.now(), pendingKeyHashes) {
118
141
  let pruned = 0;
119
142
  for (const [keyHash, generation] of semanticObservationGenerations) {
120
- if (generation.retainedAtMs === null
121
- || nowMs - generation.retainedAtMs < exports.BLUEBUBBLES_SEMANTIC_GENERATION_RETENTION_MS)
143
+ if (generation.retainedAtMs === null)
144
+ continue;
145
+ const expired = nowMs - generation.retainedAtMs >= exports.BLUEBUBBLES_SEMANTIC_GENERATION_RETENTION_MS;
146
+ const resolved = pendingKeyHashes !== undefined && !pendingKeyHashes.has(keyHash);
147
+ if (!expired && !resolved)
122
148
  continue;
123
149
  (0, latest_turn_1.clearPending)(generation.reservation);
124
150
  semanticObservationGenerations.delete(keyHash);
@@ -126,6 +152,69 @@ function pruneBlueBubblesSemanticObservationGenerations(nowMs = Date.now()) {
126
152
  }
127
153
  return pruned;
128
154
  }
155
+ /**
156
+ * Owns the observation reservations one call makes. Every reservation is
157
+ * settled when the scope closes unless a live semantic generation has taken it
158
+ * over, so no code path can leave a fence behind by returning or throwing early.
159
+ */
160
+ class BlueBubblesObservationScope {
161
+ owned = [];
162
+ constructor() {
163
+ openObservationScopes.add(this);
164
+ }
165
+ own(reservation) {
166
+ this.owned.push(reservation);
167
+ return reservation;
168
+ }
169
+ owns(reservation) {
170
+ return this.owned.includes(reservation);
171
+ }
172
+ close() {
173
+ openObservationScopes.delete(this);
174
+ for (const reservation of this.owned.splice(0)) {
175
+ if (!isGenerationReservation(reservation))
176
+ (0, latest_turn_1.clearPending)(reservation);
177
+ }
178
+ }
179
+ }
180
+ const openObservationScopes = new Set();
181
+ /**
182
+ * Runs `work` with a scope that settles its reservations once `work` ends.
183
+ * Returns `work`'s own promise so callers see no extra await.
184
+ */
185
+ function withObservationScope(work) {
186
+ const scope = new BlueBubblesObservationScope();
187
+ const running = work(scope);
188
+ const close = () => scope.close();
189
+ void running.then(close, close);
190
+ return running;
191
+ }
192
+ function isGenerationReservation(reservation) {
193
+ for (const generation of semanticObservationGenerations.values()) {
194
+ if (generation.reservation === reservation)
195
+ return true;
196
+ }
197
+ return false;
198
+ }
199
+ /**
200
+ * Test and diagnostics audit: pending observations that nothing owns. A
201
+ * reservation is owned while its scope is open, or while it is the reservation
202
+ * of a generation that is in flight or whose capture still waits for recovery.
203
+ */
204
+ function auditBlueBubblesObservationOwnership(pendingKeyHashes) {
205
+ const owners = new Map();
206
+ for (const [keyHash, generation] of semanticObservationGenerations) {
207
+ owners.set(generation.reservation, keyHash);
208
+ }
209
+ return (0, latest_turn_1.listPendingObservationsForAudit)().filter((reservation) => {
210
+ if ([...openObservationScopes].some((scope) => scope.owns(reservation)))
211
+ return false;
212
+ const keyHash = owners.get(reservation);
213
+ if (keyHash === undefined)
214
+ return true;
215
+ return !activeSemanticHandlingSlots.has(keyHash) && !pendingKeyHashes.has(keyHash);
216
+ });
217
+ }
129
218
  function adoptBlueBubblesSemanticObservation(keyHash, observedReservation, activate) {
130
219
  pruneBlueBubblesSemanticObservationGenerations();
131
220
  const existing = semanticObservationGenerations.get(keyHash);
@@ -158,6 +247,7 @@ function suspendBlueBubblesSemanticObservation(generation) {
158
247
  function completeBlueBubblesSemanticObservation(keyHash, generation) {
159
248
  (0, latest_turn_1.clearPending)(generation.reservation);
160
249
  semanticObservationGenerations.delete(keyHash);
250
+ unfinishedTurnAttempts.delete(keyHash);
161
251
  }
162
252
  async function acquireBlueBubblesSemanticHandlingSlot(keyHash, generation) {
163
253
  const active = activeSemanticHandlingSlots.get(keyHash);
@@ -1062,12 +1152,15 @@ function createBlueBubblesCallbacks(client, chat, replyTarget, isGroupChat, onVi
1062
1152
  }
1063
1153
  if (!await canRunOutbound())
1064
1154
  return;
1155
+ // Count the message as seen once it is handed to the transport: a send
1156
+ // still in flight, or one that timed out, may reach the friend anyway, and
1157
+ // a turn that ends now must not be replayed into repeating it.
1158
+ recordVisibleActivity();
1065
1159
  await client.sendText({
1066
1160
  chat,
1067
1161
  text: trimmed,
1068
1162
  replyToMessageGuid: replyTarget.getReplyToMessageGuid(),
1069
1163
  });
1070
- recordVisibleActivity();
1071
1164
  // Note: do NOT call client.setTyping(chat, false) here — the agent is
1072
1165
  // still mid-turn, so the typing indicator stays ACTIVE.
1073
1166
  (0, runtime_1.emitNervesEvent)({
@@ -1502,6 +1595,54 @@ function promoteAcceptedBlueBubblesAncillaryState(input) {
1502
1595
  function hasObservedBlueBubblesDirection(event) {
1503
1596
  return typeof event.fromMe === "boolean";
1504
1597
  }
1598
+ /**
1599
+ * Waits for permission to send. After a minute it marks the live turn as
1600
+ * stalled, so `ouro status` reports it, and clears the mark once it resumes.
1601
+ */
1602
+ async function awaitBlueBubblesDeliveryAdmission(agentName, turnId, event, capability, signal) {
1603
+ const waitingSince = Date.now();
1604
+ let stalled = false;
1605
+ const stalledTimer = setTimeout(() => {
1606
+ stalled = true;
1607
+ (0, active_turns_1.noteBlueBubblesActiveTurnAdmissionWait)(agentName, turnId, new Date(waitingSince).toISOString());
1608
+ (0, runtime_1.emitNervesEvent)({
1609
+ level: "warn",
1610
+ component: "senses",
1611
+ event: "senses.bluebubbles_delivery_admission_stalled",
1612
+ message: "bluebubbles reply has waited over a minute for permission to send",
1613
+ meta: {
1614
+ messageGuid: event.messageGuid,
1615
+ sessionKey: event.chat.sessionKey,
1616
+ waitedMs: Date.now() - waitingSince,
1617
+ },
1618
+ });
1619
+ }, active_turns_1.BLUEBUBBLES_DELIVERY_ADMISSION_STALLED_MS);
1620
+ /* v8 ignore next -- timer handles expose unref only in some runtimes @preserve */
1621
+ if (typeof stalledTimer.unref === "function") {
1622
+ stalledTimer.unref();
1623
+ }
1624
+ try {
1625
+ return await (0, latest_turn_1.awaitDeliveryAdmission)(capability, signal);
1626
+ }
1627
+ finally {
1628
+ clearTimeout(stalledTimer);
1629
+ if (stalled)
1630
+ (0, active_turns_1.noteBlueBubblesActiveTurnAdmissionWait)(agentName, turnId, null);
1631
+ }
1632
+ }
1633
+ function emitBlueBubblesDeliveryAdmissionTimeout(event, source) {
1634
+ (0, runtime_1.emitNervesEvent)({
1635
+ level: "error",
1636
+ component: "senses",
1637
+ event: "senses.bluebubbles_delivery_admission_timeout",
1638
+ message: "bluebubbles turn gave up waiting for permission to send; the message stays pending for recovery",
1639
+ meta: {
1640
+ messageGuid: event.messageGuid,
1641
+ sessionKey: event.chat.sessionKey,
1642
+ source,
1643
+ },
1644
+ });
1645
+ }
1505
1646
  async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, options) {
1506
1647
  options.lifecycleSignal?.throwIfAborted();
1507
1648
  const client = resolvedDeps.createClient();
@@ -1609,14 +1750,33 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1609
1750
  content: buildInboundContent(event),
1610
1751
  };
1611
1752
  resolvedDeps.saveSession(sessPath, [...structuredClone(sessionMessages), structuredClone(userMessage)], existing?.lastUsage, existing?.state);
1612
- if (!await (0, latest_turn_1.awaitDeliveryAdmission)(options.latestTurnCapability)
1613
- || !(0, latest_turn_1.isCurrent)(options.latestTurnCapability)) {
1753
+ const liveTurnId = (0, active_turns_1.beginBlueBubblesActiveTurn)(agentName, event);
1754
+ activeTurnId = liveTurnId;
1755
+ // Waiting for permission to send is bounded by the turn deadline and shutdown.
1756
+ const admissionDeadline = new AbortController();
1757
+ const admissionDeadlineTimer = setTimeout(() => {
1758
+ admissionDeadline.abort(new Error("delivery_admission_timeout"));
1759
+ }, options.timeoutMs ?? BLUEBUBBLES_TURN_TIMEOUT_MS);
1760
+ let admitted;
1761
+ try {
1762
+ admitted = await awaitBlueBubblesDeliveryAdmission(agentName, liveTurnId, event, options.latestTurnCapability, options.lifecycleSignal
1763
+ ? AbortSignal.any([options.lifecycleSignal, admissionDeadline.signal])
1764
+ : admissionDeadline.signal);
1765
+ }
1766
+ catch (error) {
1767
+ if (options.lifecycleSignal?.aborted)
1768
+ throw error;
1769
+ emitBlueBubblesDeliveryAdmissionTimeout(event, source);
1770
+ return { handled: true, notifiedAgent: false, kind: event.kind, reason: "delivery_admission_timeout" };
1771
+ }
1772
+ finally {
1773
+ clearTimeout(admissionDeadlineTimer);
1774
+ }
1775
+ if (!admitted || !(0, latest_turn_1.isCurrent)(options.latestTurnCapability)) {
1614
1776
  return { handled: true, notifiedAgent: false, kind: event.kind, reason: "superseded" };
1615
1777
  }
1616
1778
  options.lifecycleSignal?.throwIfAborted();
1617
1779
  const mcpOwner = { agentName, agentRoot: (0, identity_1.getAgentRoot)(agentName) };
1618
- const liveTurnId = (0, active_turns_1.beginBlueBubblesActiveTurn)(agentName, event);
1619
- activeTurnId = liveTurnId;
1620
1780
  const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)(mcpOwner) ?? undefined;
1621
1781
  if (event.chat.isGroup) {
1622
1782
  await (0, friends_1.upsertGroupContextParticipants)({
@@ -1666,12 +1826,14 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1666
1826
  let finalTransportAccepted = false;
1667
1827
  let spokeBeforeFinalTransport = false;
1668
1828
  const outboundRuntimeConfig = (0, config_1.getBlueBubblesConfig)();
1829
+ // Aborted on the turn deadline, supersession and shutdown before the final send.
1830
+ const controller = new AbortController();
1669
1831
  const callbacks = createBlueBubblesCallbacks(client, event.chat, replyTarget, event.chat.isGroup, () => {
1670
1832
  spokeBeforeFinalTransport = true;
1671
1833
  (0, active_turns_1.noteBlueBubblesActiveTurnVisibleActivity)(agentName, liveTurnId);
1672
1834
  }, {
1673
1835
  admitOutbound: async () => (!options.lifecycleSignal?.aborted
1674
- && await (0, latest_turn_1.awaitDeliveryAdmission)(options.latestTurnCapability)
1836
+ && await awaitBlueBubblesDeliveryAdmission(agentName, liveTurnId, event, options.latestTurnCapability, controller.signal)
1675
1837
  && !options.lifecycleSignal?.aborted),
1676
1838
  isOutboundCurrent: () => (!options.lifecycleSignal?.aborted
1677
1839
  && (0, latest_turn_1.isCurrent)(options.latestTurnCapability)),
@@ -1692,7 +1854,6 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1692
1854
  },
1693
1855
  },
1694
1856
  });
1695
- const controller = new AbortController();
1696
1857
  const lifecycleSignal = options.lifecycleSignal;
1697
1858
  let rejectLifecycle;
1698
1859
  const lifecyclePromise = new Promise((_resolve, reject) => {
@@ -1720,7 +1881,15 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1720
1881
  if (!finalTransportInvoked) {
1721
1882
  const reason = lifecycleSignal.reason;
1722
1883
  controller.abort(reason);
1723
- rejectLifecycle(reason);
1884
+ // A turn the friend already heard from must not replay in the next
1885
+ // process; end it with a result so it is recorded instead.
1886
+ if (spokeBeforeFinalTransport && resolveTimeout) {
1887
+ options.publishSpokenTurnEnded("shutdown");
1888
+ resolveTimeout({ handled: true, notifiedAgent: false, kind: event.kind, reason: "shutdown", spokeBeforeEnd: true });
1889
+ }
1890
+ else {
1891
+ rejectLifecycle(reason);
1892
+ }
1724
1893
  }
1725
1894
  };
1726
1895
  lifecycleSignal?.addEventListener("abort", cancelForShutdown, { once: true });
@@ -1783,11 +1952,14 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1783
1952
  const reason = new BlueBubblesRecoveryTurnTimeoutError(timeoutMs);
1784
1953
  recoveryTimedOut = true;
1785
1954
  if (!finalTransportInvoked) {
1955
+ if (spokeBeforeFinalTransport)
1956
+ options.publishSpokenTurnEnded("turn_timeout");
1786
1957
  resolveTimeout?.({
1787
1958
  handled: true,
1788
1959
  notifiedAgent: false,
1789
1960
  kind: event.kind,
1790
1961
  reason: "turn_timeout",
1962
+ spokeBeforeEnd: spokeBeforeFinalTransport,
1791
1963
  });
1792
1964
  }
1793
1965
  callbacks.cancelOutbound("turn_timeout");
@@ -1934,6 +2106,9 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1934
2106
  };
1935
2107
  },
1936
2108
  signal: controller.signal,
2109
+ // The deadline, supersession and shutdown handlers record this
2110
+ // turn's outcome, so a turn they cancel need not wait its turn.
2111
+ stopQueueWaitOnAbort: true,
1937
2112
  runAgentOptions: {
1938
2113
  mcpManager,
1939
2114
  orientationFrame,
@@ -2014,6 +2189,10 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
2014
2189
  delivery = await callbacks.flush({ signal: controller.signal });
2015
2190
  }
2016
2191
  catch (error) {
2192
+ // Aborted before the transport ran: the deadline, supersession or
2193
+ // shutdown handler already decided this turn's result.
2194
+ if (controller.signal.aborted && !finalTransportInvoked)
2195
+ throw error;
2017
2196
  (0, runtime_1.emitNervesEvent)({
2018
2197
  level: "warn",
2019
2198
  component: "senses",
@@ -2561,6 +2740,21 @@ async function handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, so
2561
2740
  publishTerminalReceipt("message_completed");
2562
2741
  acceptedReceiptPublished = true;
2563
2742
  };
2743
+ let spokenTurnEndPublished = false;
2744
+ const publishSpokenTurnEnded = (reason) => {
2745
+ if (spokenTurnEndPublished)
2746
+ return;
2747
+ spokenTurnEndPublished = true;
2748
+ semanticHandlingCompleted = true;
2749
+ try {
2750
+ publishTerminalReceipt("message_observed", `${reason}_after_visible_speech`);
2751
+ /* v8 ignore start -- a failed write already kept the claim live and was logged, which also stops a replay @preserve */
2752
+ }
2753
+ catch {
2754
+ // Nothing more to do here.
2755
+ }
2756
+ /* v8 ignore stop */
2757
+ };
2564
2758
  try {
2565
2759
  options.lifecycleSignal?.throwIfAborted();
2566
2760
  if (captured.capture.event.fromMe) {
@@ -2589,8 +2783,27 @@ async function handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, so
2589
2783
  const durableOutbound = (0, outbound_state_1.readBlueBubblesOutboundRecordByIdempotencyKey)((0, identity_1.getAgentRoot)(), blueBubblesInboundReplyIdempotencyKey(captured.capture.keyHash));
2590
2784
  const retryFailedReply = durableOutbound?.status === "failed"
2591
2785
  && (durableOutbound.failedAttempts ?? 0) < BLUEBUBBLES_REPLY_DELIVERY_MAX_ATTEMPTS;
2786
+ const completeVisibleFailedReply = () => {
2787
+ // The send that timed out reached the chat after all; do not reply twice.
2788
+ (0, runtime_1.emitNervesEvent)({
2789
+ level: "warn",
2790
+ component: "senses",
2791
+ event: "senses.bluebubbles_inbound_reply_recovery_suppressed",
2792
+ message: "suppressed bluebubbles reply retry because a reply is already in the chat",
2793
+ meta: { messageGuid: captured.normalized.messageGuid, recordId: durableOutbound.recordId },
2794
+ });
2795
+ publishTerminalReceipt("message_completed", "reply_visible_after_failed_send");
2796
+ semanticHandlingCompleted = true;
2797
+ return { handled: true, notifiedAgent: false, kind: captured.normalized.kind, reason: "already_processed" };
2798
+ };
2592
2799
  if (retryFailedReply
2593
2800
  && Date.now() < Date.parse(durableOutbound.failedAt ?? durableOutbound.updatedAt) + BLUEBUBBLES_REPLY_RETRY_DELAY_MS) {
2801
+ // A send that timed out may still arrive. Close the message as soon as the
2802
+ // reply shows up in the chat; only a retry waits out the delay.
2803
+ const visible = await blueBubblesFailedReplyIsVisible(resolvedDeps, captured.normalized.chat, durableOutbound)
2804
+ .catch(() => false);
2805
+ if (visible)
2806
+ return completeVisibleFailedReply();
2594
2807
  return { handled: true, notifiedAgent: false, kind: captured.normalized.kind, reason: "delivery_failed" };
2595
2808
  }
2596
2809
  if (durableOutbound && !retryFailedReply) {
@@ -2705,6 +2918,7 @@ async function handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, so
2705
2918
  orientationEvidence: captured.capture.event,
2706
2919
  orientationConversationKind: canonicalEvent.chat.isGroup ? "group" : "one_to_one",
2707
2920
  publishAcceptedReceipt,
2921
+ publishSpokenTurnEnded,
2708
2922
  ...(interaction?.mutationType === "reaction" ? { isReactionSignal: true } : {}),
2709
2923
  };
2710
2924
  let failedReplyVisible = false;
@@ -2727,24 +2941,42 @@ async function handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, so
2727
2941
  return { handled: true, notifiedAgent: false, kind: captured.normalized.kind, reason: "delivery_failed" };
2728
2942
  }
2729
2943
  }
2730
- if (failedReplyVisible) {
2731
- // The send that timed out reached the chat after all; do not reply twice.
2732
- (0, runtime_1.emitNervesEvent)({
2733
- level: "warn",
2734
- component: "senses",
2735
- event: "senses.bluebubbles_inbound_reply_recovery_suppressed",
2736
- message: "suppressed bluebubbles reply retry because a reply is already in the chat",
2737
- meta: { messageGuid: captured.normalized.messageGuid, recordId: durableOutbound.recordId },
2738
- });
2739
- publishTerminalReceipt("message_completed", "reply_visible_after_failed_send");
2740
- semanticHandlingCompleted = true;
2741
- return { handled: true, notifiedAgent: false, kind: captured.normalized.kind, reason: "already_processed" };
2742
- }
2944
+ if (failedReplyVisible)
2945
+ return completeVisibleFailedReply();
2743
2946
  result = await handleBlueBubblesNormalizedEvent(canonicalEvent, resolvedDeps, source, capturedOptions);
2744
2947
  // A budget or storm-breaker block defers the message; it was never seen.
2745
2948
  // Leave it pending so a later recovery pass retries it once the block lifts.
2746
2949
  if (result.reason === "autonomy_budget_blocked")
2747
2950
  return result;
2951
+ if (result.reason === "turn_timeout" || result.reason === "delivery_admission_timeout" || result.reason === "shutdown") {
2952
+ // The turn ended without a reply or a chosen silence. Leave it pending so
2953
+ // recovery replays it, unless the friend already saw part of it or it
2954
+ // keeps failing; then record a visible failure instead.
2955
+ const attempts = (unfinishedTurnAttempts.get(identity.keyHash) ?? 0) + 1;
2956
+ unfinishedTurnAttempts.set(identity.keyHash, attempts);
2957
+ if (!result.spokeBeforeEnd && attempts < BLUEBUBBLES_REPLY_DELIVERY_MAX_ATTEMPTS)
2958
+ return result;
2959
+ (0, runtime_1.emitNervesEvent)({
2960
+ level: "error",
2961
+ component: "senses",
2962
+ event: "senses.bluebubbles_turn_abandoned",
2963
+ message: "gave up replaying a bluebubbles turn that kept ending without a reply",
2964
+ meta: {
2965
+ messageGuid: captured.normalized.messageGuid,
2966
+ reason: result.reason,
2967
+ attempts,
2968
+ spokeBeforeEnd: result.spokeBeforeEnd === true,
2969
+ },
2970
+ });
2971
+ if (result.spokeBeforeEnd) {
2972
+ publishSpokenTurnEnded(result.reason);
2973
+ }
2974
+ else {
2975
+ publishTerminalReceipt("message_observed", `${result.reason}_retries_exhausted`);
2976
+ semanticHandlingCompleted = true;
2977
+ }
2978
+ return result;
2979
+ }
2748
2980
  if (result.reason === "delivery_failed") {
2749
2981
  // The reply never reached the chat. Leave the message pending so a later
2750
2982
  // recovery pass sends it, until the per-message attempt cap is reached.
@@ -2825,22 +3057,20 @@ async function handleBlueBubblesEvent(payload, deps = {}) {
2825
3057
  }
2826
3058
  throw error;
2827
3059
  }
2828
- const observationReservation = reserveBlueBubblesObservation(normalized);
2829
- let captured;
3060
+ const scope = new BlueBubblesObservationScope();
2830
3061
  try {
2831
- captured = await captureBlueBubblesSemanticEvent(normalized, resolvedDeps, "webhook", observationReservation);
2832
- }
2833
- catch (error) {
2834
- (0, latest_turn_1.clearPending)(observationReservation);
2835
- throw error;
3062
+ const observationReservation = scope.own(reserveBlueBubblesObservation(normalized));
3063
+ const captured = await captureBlueBubblesSemanticEvent(normalized, resolvedDeps, "webhook", observationReservation);
3064
+ if (captured.status === "audit_only") {
3065
+ return { handled: true, notifiedAgent: false, kind: normalized.kind, reason: "ignored" };
3066
+ }
3067
+ return await handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, "webhook", {
3068
+ observationReservation,
3069
+ });
2836
3070
  }
2837
- if (captured.status === "audit_only") {
2838
- (0, latest_turn_1.clearPending)(observationReservation);
2839
- return { handled: true, notifiedAgent: false, kind: normalized.kind, reason: "ignored" };
3071
+ finally {
3072
+ scope.close();
2840
3073
  }
2841
- return handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, "webhook", {
2842
- observationReservation,
2843
- });
2844
3074
  }
2845
3075
  function parseTimestampMs(value) {
2846
3076
  if (!value)
@@ -2858,14 +3088,20 @@ function resolveBlueBubblesCatchUpSince(previousState, nowMs = Date.now()) {
2858
3088
  }
2859
3089
  return nowMs - BLUEBUBBLES_FIRST_CATCHUP_LOOKBACK_MS;
2860
3090
  }
2861
- function formatBlueBubblesRuntimeDetail(queued, failed, active) {
3091
+ function formatBlueBubblesRuntimeDetail(pending, failed, active) {
3092
+ const queued = pending.pendingRecoveryCount;
3093
+ if (active.admissionStalledTurnCount > 0) {
3094
+ return `iMessage reply stalled; ${active.admissionStalledTurnCount} turn(s) waiting for permission to send for ${Math.round(active.oldestAdmissionWaitAgeMs / 1000)}s`;
3095
+ }
2862
3096
  if (active.stalledTurnCount > 0) {
2863
3097
  return `iMessage live turn appears stalled; ${active.stalledTurnCount} active turn(s) older than ${BLUEBUBBLES_LIVE_TURN_STALLED_MS}ms`;
2864
3098
  }
2865
3099
  if (active.activeTurnCount > 0)
2866
3100
  return `upstream reachable; ${active.activeTurnCount} live turn(s) active`;
2867
- if (queued > 0)
2868
- return `upstream reachable but iMessage is not caught up; ${queued} recovery item(s) queued`;
3101
+ if (queued > 0) {
3102
+ /* v8 ignore next -- every capture this sense writes carries a parseable capturedAt @preserve */
3103
+ return `upstream reachable but iMessage is not caught up; ${queued} message(s) without a reply or recorded outcome, oldest ${Math.round((pending.oldestPendingRecoveryAgeMs ?? 0) / 1000)}s`;
3104
+ }
2869
3105
  if (failed > 0)
2870
3106
  return `${failed} message(s) unrecoverable this cycle; upstream ok`;
2871
3107
  return "upstream reachable";
@@ -2891,7 +3127,7 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
2891
3127
  // Allocate before the first health-probe await. Any live webhook accepted
2892
3128
  // while that probe is pending must remain causally newer than this pass.
2893
3129
  const catchUpObservationBatch = options.catchUpObservationBatch ?? (0, latest_turn_1.beginObservationBatch)(BLUEBUBBLES_CATCHUP_PAGE_SIZE * BLUEBUBBLES_CATCHUP_MAX_PAGES);
2894
- pruneBlueBubblesSemanticObservationGenerations();
3130
+ pruneBlueBubblesSemanticObservationGenerations(Date.now(), new Set((0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName).map((capture) => capture.keyHash)));
2895
3131
  const client = resolvedDeps.createClient();
2896
3132
  const checkedAt = new Date().toISOString();
2897
3133
  const previousState = (0, runtime_state_1.readBlueBubblesRuntimeState)(agentName);
@@ -2926,7 +3162,7 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
2926
3162
  // while this field stays scoped to upstream transport reachability.
2927
3163
  (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
2928
3164
  upstreamStatus: "ok",
2929
- detail: formatBlueBubblesRuntimeDetail(queued, failed, activeAfterCatchup),
3165
+ detail: formatBlueBubblesRuntimeDetail(pendingAfterCatchup, failed, activeAfterCatchup),
2930
3166
  lastCheckedAt: checkedAt,
2931
3167
  proofMethod: "bluebubbles.checkHealth",
2932
3168
  ...pendingAfterCatchup,
@@ -2992,7 +3228,7 @@ async function recoverQueuedBlueBubblesMessages(deps = {}, options = {}) {
2992
3228
  const activeSnapshot = (0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS);
2993
3229
  (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
2994
3230
  upstreamStatus: "ok",
2995
- detail: formatBlueBubblesRuntimeDetail(pendingRecoveryCount, failed, activeSnapshot),
3231
+ detail: formatBlueBubblesRuntimeDetail(pendingSnapshot, failed, activeSnapshot),
2996
3232
  lastCheckedAt: checkedAt,
2997
3233
  proofMethod: "bluebubbles.checkHealth",
2998
3234
  ...pendingSnapshot,
@@ -3019,7 +3255,10 @@ async function recoverQueuedBlueBubblesMessages(deps = {}, options = {}) {
3019
3255
  }
3020
3256
  return { recovered, skipped, failed, pendingRecoveryCount };
3021
3257
  }
3022
- async function catchUpMissedBlueBubblesMessages(deps = {}, previousState, options = {}) {
3258
+ function catchUpMissedBlueBubblesMessages(deps = {}, previousState, options = {}) {
3259
+ return withObservationScope((scope) => catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousState, options));
3260
+ }
3261
+ async function catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousState, options) {
3023
3262
  options.lifecycleSignal?.throwIfAborted();
3024
3263
  const resolvedDeps = { ...defaultDeps, ...deps };
3025
3264
  const agentName = resolvedDeps.getAgentName();
@@ -3096,10 +3335,10 @@ async function catchUpMissedBlueBubblesMessages(deps = {}, previousState, option
3096
3335
  preparedCandidates.push({
3097
3336
  status: "ready",
3098
3337
  event,
3099
- observationReservation: (0, latest_turn_1.reserveObservationFromBatch)(observationBatch, page * BLUEBUBBLES_CATCHUP_PAGE_SIZE + pageIndex, {
3338
+ observationReservation: scope.own((0, latest_turn_1.reserveObservationFromBatch)(observationBatch, page * BLUEBUBBLES_CATCHUP_PAGE_SIZE + pageIndex, {
3100
3339
  chatGuid: event.chat.chatGuid,
3101
3340
  chatIdentifier: event.chat.chatIdentifier,
3102
- }),
3341
+ })),
3103
3342
  });
3104
3343
  }
3105
3344
  if (pageEvents.length < BLUEBUBBLES_CATCHUP_PAGE_SIZE)
@@ -3133,12 +3372,10 @@ async function catchUpMissedBlueBubblesMessages(deps = {}, previousState, option
3133
3372
  await Promise.all(groupBlueBubblesObservationsByLane(readyCandidates).map(async (lane) => {
3134
3373
  for (const prepared of lane) {
3135
3374
  const { event, observationReservation } = prepared;
3136
- let semanticGenerationOwned = false;
3137
3375
  try {
3138
3376
  options.lifecycleSignal?.throwIfAborted();
3139
3377
  const captured = await captureBlueBubblesSemanticEvent(event, resolvedDeps, "upstream-catchup", observationReservation);
3140
3378
  if (captured.status === "audit_only") {
3141
- (0, latest_turn_1.clearPending)(observationReservation);
3142
3379
  result.skipped++;
3143
3380
  continue;
3144
3381
  }
@@ -3148,12 +3385,10 @@ async function catchUpMissedBlueBubblesMessages(deps = {}, previousState, option
3148
3385
  && !pendingCaptureKeyHashes().has(captured.capture.keyHash)) {
3149
3386
  // Already has an outcome. Fencing it again would hold every older
3150
3387
  // reply in this chat behind a message nobody will process.
3151
- (0, latest_turn_1.clearPending)(observationReservation);
3152
3388
  result.skipped++;
3153
3389
  continue;
3154
3390
  }
3155
3391
  const generation = adoptBlueBubblesSemanticObservation(captured.capture.keyHash, observationReservation, false);
3156
- semanticGenerationOwned = true;
3157
3392
  if (captured.writeResult === "semantic_capture_duplicate") {
3158
3393
  if (!activeSemanticHandlingSlots.has(captured.capture.keyHash)) {
3159
3394
  suspendBlueBubblesSemanticObservation(generation);
@@ -3175,7 +3410,6 @@ async function catchUpMissedBlueBubblesMessages(deps = {}, previousState, option
3175
3410
  }
3176
3411
  continue;
3177
3412
  }
3178
- semanticGenerationOwned = true;
3179
3413
  const handled = await handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, "upstream-catchup", {
3180
3414
  timeoutMs: BLUEBUBBLES_TURN_TIMEOUT_MS,
3181
3415
  autonomyBudgetTrigger: "recovery",
@@ -3197,8 +3431,6 @@ async function catchUpMissedBlueBubblesMessages(deps = {}, previousState, option
3197
3431
  }
3198
3432
  }
3199
3433
  catch (error) {
3200
- if (!semanticGenerationOwned)
3201
- (0, latest_turn_1.clearPending)(observationReservation);
3202
3434
  if (options.lifecycleSignal?.aborted)
3203
3435
  throw options.lifecycleSignal.reason;
3204
3436
  recordBlueBubblesRecoveryFailureForBudget(agentName, event, "upstream-catchup");
@@ -3226,7 +3458,10 @@ async function catchUpMissedBlueBubblesMessages(deps = {}, previousState, option
3226
3458
  }
3227
3459
  return result;
3228
3460
  }
3229
- async function recoverCapturedBlueBubblesInboundMessages(deps = {}, options = {}) {
3461
+ function recoverCapturedBlueBubblesInboundMessages(deps = {}, options = {}) {
3462
+ return withObservationScope((scope) => recoverCapturedBlueBubblesInboundMessagesInScope(scope, deps, options));
3463
+ }
3464
+ async function recoverCapturedBlueBubblesInboundMessagesInScope(scope, deps, options) {
3230
3465
  options.lifecycleSignal?.throwIfAborted();
3231
3466
  const resolvedDeps = { ...defaultDeps, ...deps };
3232
3467
  const agentName = resolvedDeps.getAgentName();
@@ -3257,7 +3492,7 @@ async function recoverCapturedBlueBubblesInboundMessages(deps = {}, options = {}
3257
3492
  status: "ready",
3258
3493
  capture,
3259
3494
  normalized,
3260
- observationReservation: seededObservationReservation(capture.keyHash, reserveBlueBubblesObservation(normalized)),
3495
+ observationReservation: seededObservationReservation(capture.keyHash, scope.own(reserveBlueBubblesObservation(normalized))),
3261
3496
  });
3262
3497
  }
3263
3498
  for (const prepared of preparedCandidates) {
@@ -3449,13 +3684,15 @@ function createBlueBubblesWebhookHandler(deps = {}, options = {}) {
3449
3684
  return;
3450
3685
  }
3451
3686
  const resolvedDeps = { ...defaultDeps, ...deps };
3452
- const observationReservation = reserveBlueBubblesObservation(normalized);
3687
+ // The scope outlives this request: it closes when the queued turn ends.
3688
+ const scope = new BlueBubblesObservationScope();
3689
+ const observationReservation = scope.own(reserveBlueBubblesObservation(normalized));
3453
3690
  let captured;
3454
3691
  try {
3455
3692
  captured = await captureBlueBubblesSemanticEvent(normalized, resolvedDeps, "webhook", observationReservation);
3456
3693
  }
3457
3694
  catch (error) {
3458
- (0, latest_turn_1.clearPending)(observationReservation);
3695
+ scope.close();
3459
3696
  (0, runtime_1.emitNervesEvent)({
3460
3697
  level: "error",
3461
3698
  component: "senses",
@@ -3470,7 +3707,7 @@ function createBlueBubblesWebhookHandler(deps = {}, options = {}) {
3470
3707
  return;
3471
3708
  }
3472
3709
  if (captured.status === "audit_only") {
3473
- (0, latest_turn_1.clearPending)(observationReservation);
3710
+ scope.close();
3474
3711
  writeJson(res, 200, {
3475
3712
  handled: true,
3476
3713
  notifiedAgent: false,
@@ -3489,10 +3726,10 @@ function createBlueBubblesWebhookHandler(deps = {}, options = {}) {
3489
3726
  });
3490
3727
  setTimeout(() => {
3491
3728
  if (options.lifecycleSignal?.aborted) {
3492
- (0, latest_turn_1.clearPending)(observationReservation);
3729
+ scope.close();
3493
3730
  return;
3494
3731
  }
3495
- void handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, "webhook", {
3732
+ trackBlueBubblesTurn(handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, "webhook", {
3496
3733
  observationReservation,
3497
3734
  lifecycleSignal: options.lifecycleSignal,
3498
3735
  }).catch((error) => {
@@ -3507,7 +3744,7 @@ function createBlueBubblesWebhookHandler(deps = {}, options = {}) {
3507
3744
  reason: error instanceof Error ? error.message : String(error),
3508
3745
  },
3509
3746
  });
3510
- });
3747
+ }).finally(() => scope.close()));
3511
3748
  }, 0);
3512
3749
  };
3513
3750
  }
@@ -3972,6 +4209,18 @@ async function drainAndSendPendingBlueBubbles(deps = {}, pendingRoot) {
3972
4209
  }
3973
4210
  return result;
3974
4211
  }
4212
+ const runningBlueBubblesApps = new WeakMap();
4213
+ /**
4214
+ * Stop the sense now. Aborting first ends every in-flight turn (each leaves its
4215
+ * inbound pending for the next process to replay) instead of letting
4216
+ * server.close() wait on them. Resolves with how many turns were still running.
4217
+ */
4218
+ async function stopBlueBubblesApp(server) {
4219
+ runningBlueBubblesApps.get(server)?.();
4220
+ server.close();
4221
+ server.closeAllConnections();
4222
+ return drainBlueBubblesTurns();
4223
+ }
3975
4224
  function startBlueBubblesApp(deps = {}) {
3976
4225
  const resolvedDeps = { ...defaultDeps, ...deps };
3977
4226
  const lifecycleController = new AbortController();
@@ -3996,7 +4245,7 @@ function startBlueBubblesApp(deps = {}) {
3996
4245
  if (recoveryPassRunning)
3997
4246
  return;
3998
4247
  recoveryPassRunning = true;
3999
- void recoverQueuedBlueBubblesMessages(resolvedDeps, {
4248
+ trackBlueBubblesTurn(recoverQueuedBlueBubblesMessages(resolvedDeps, {
4000
4249
  lifecycleSignal: lifecycleController.signal,
4001
4250
  })
4002
4251
  /* v8 ignore start -- defensive wrapper; expected per-message failures are handled inside recovery helpers @preserve */
@@ -4014,7 +4263,7 @@ function startBlueBubblesApp(deps = {}) {
4014
4263
  /* v8 ignore stop */
4015
4264
  .finally(() => {
4016
4265
  recoveryPassRunning = false;
4017
- });
4266
+ }));
4018
4267
  }
4019
4268
  function scheduleRecoveryPass() {
4020
4269
  if (closed)
@@ -4058,7 +4307,9 @@ function startBlueBubblesApp(deps = {}) {
4058
4307
  triggerRuntimeSync();
4059
4308
  }, BLUEBUBBLES_RUNTIME_SYNC_INTERVAL_MS);
4060
4309
  const recoveryTimer = setInterval(triggerRecoveryPass, BLUEBUBBLES_RECOVERY_PASS_INTERVAL_MS);
4061
- server.on?.("close", () => {
4310
+ function shutdown() {
4311
+ if (closed)
4312
+ return;
4062
4313
  closed = true;
4063
4314
  webhookReconciler?.close();
4064
4315
  webhookReconciler = null;
@@ -4069,7 +4320,9 @@ function startBlueBubblesApp(deps = {}) {
4069
4320
  clearTimeout(recoveryDelayTimer);
4070
4321
  recoveryDelayTimer = null;
4071
4322
  }
4072
- });
4323
+ }
4324
+ server.on?.("close", shutdown);
4325
+ runningBlueBubblesApps.set(server, shutdown);
4073
4326
  server.listen(channelConfig.port, () => {
4074
4327
  const blueBubblesConfig = (0, config_1.getBlueBubblesConfig)();
4075
4328
  webhookReconciler = (0, webhook_registration_1.createBlueBubblesWebhookReconciler)({
@@ -10,6 +10,7 @@ exports.promote = promote;
10
10
  exports.isCurrent = isCurrent;
11
11
  exports.observationSchedulingKeys = observationSchedulingKeys;
12
12
  exports.awaitDeliveryAdmission = awaitDeliveryAdmission;
13
+ exports.listPendingObservationsForAudit = listPendingObservationsForAudit;
13
14
  exports.isDeliveryAdmittedNow = isDeliveryAdmittedNow;
14
15
  exports.cancel = cancel;
15
16
  exports.finish = finish;
@@ -274,16 +275,46 @@ function observationSchedulingKeys(reservation) {
274
275
  }
275
276
  return Object.freeze([...keys]);
276
277
  }
277
- async function awaitDeliveryAdmission(capability) {
278
+ /**
279
+ * Resolves when every blocker settles or any signal aborts, whichever comes first.
280
+ * Listeners are removed either way, so a long-lived fence holds no references.
281
+ */
282
+ function untilSettledOrAborted(blockers, signals) {
283
+ return new Promise((resolve) => {
284
+ const done = () => {
285
+ for (const signal of signals)
286
+ signal.removeEventListener("abort", done);
287
+ resolve();
288
+ };
289
+ for (const signal of signals)
290
+ signal.addEventListener("abort", done, { once: true });
291
+ void Promise.all(blockers.map((entry) => entry.settled)).then(done);
292
+ });
293
+ }
294
+ /**
295
+ * Waits until no newer observation in this chat could still supersede the turn.
296
+ * Resolves false once the turn is no longer current (superseded, cancelled or
297
+ * timed out). Rejects with the reason when `signal` aborts, so a fence that is
298
+ * never settled can never hold a turn past its deadline or shutdown.
299
+ */
300
+ async function awaitDeliveryAdmission(capability, signal) {
278
301
  const value = internal(capability);
302
+ const signals = signal ? [value.signal, signal] : [value.signal];
279
303
  while (isCurrent(value)) {
304
+ signal?.throwIfAborted();
280
305
  const blockers = [...pending.values()].filter((entry) => pendingIntersects(value, entry));
281
306
  if (blockers.length === 0)
282
307
  return true;
283
- await Promise.all(blockers.map((entry) => entry.settled));
308
+ await untilSettledOrAborted(blockers, signals);
284
309
  }
285
310
  return false;
286
311
  }
312
+ /** Every observation still pending, oldest first. The sense's ownership audit checks each has an owner. */
313
+ function listPendingObservationsForAudit() {
314
+ return [...pending.values()]
315
+ .sort((left, right) => left.reservation.ordinal - right.reservation.ordinal)
316
+ .map((entry) => entry.reservation);
317
+ }
287
318
  function isDeliveryAdmittedNow(capability) {
288
319
  const value = internal(capability);
289
320
  return isCurrent(value)
@@ -545,7 +545,7 @@ function erroredTurnReply(errorMessage) {
545
545
  : "I couldn't finish that one: something went wrong before I had an answer. Ask me again and I'll retry.";
546
546
  }
547
547
  async function handleInboundTurn(input) {
548
- return (0, turn_execution_lease_1.withTurnExecutionLease)(() => handleInboundTurnExclusive(input));
548
+ return (0, turn_execution_lease_1.withTurnExecutionLease)(() => handleInboundTurnExclusive(input), input.stopQueueWaitOnAbort ? input.signal : undefined);
549
549
  }
550
550
  async function handleInboundTurnExclusive(input) {
551
551
  // Continuity resumption is structured caller intent. Never infer it from the
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SENSE_SHUTDOWN_GRACE_MS = void 0;
4
+ exports.installSenseShutdown = installSenseShutdown;
5
+ const runtime_1 = require("../nerves/runtime");
6
+ /**
7
+ * How long a sense may spend ending its in-flight turns after SIGTERM before it exits anyway.
8
+ * Kept under the daemon's 4 s stop timeout so the daemon sees the exit and starts the replacement.
9
+ */
10
+ exports.SENSE_SHUTDOWN_GRACE_MS = 3_000;
11
+ /**
12
+ * Exit within a bounded time on SIGTERM or SIGINT. The sense's `stop` gets
13
+ * `graceMs` to finish; if it hangs, the process exits anyway so the daemon can
14
+ * start a replacement that replays whatever was left pending.
15
+ */
16
+ function installSenseShutdown(options) {
17
+ const target = options.process ?? process;
18
+ const graceMs = options.graceMs ?? exports.SENSE_SHUTDOWN_GRACE_MS;
19
+ const onSignal = (signal) => {
20
+ uninstall();
21
+ (0, runtime_1.emitNervesEvent)({
22
+ component: "senses",
23
+ event: "senses.shutdown_started",
24
+ message: "sense shutting down",
25
+ meta: { sense: options.sense, signal, graceMs },
26
+ });
27
+ let graceTimer;
28
+ const graceExpired = new Promise((resolve) => {
29
+ graceTimer = setTimeout(() => resolve("grace_expired"), graceMs);
30
+ });
31
+ const stopped = Promise.resolve()
32
+ .then(options.stop)
33
+ .then(() => "stopped", (error) => {
34
+ (0, runtime_1.emitNervesEvent)({
35
+ level: "error",
36
+ component: "senses",
37
+ event: "senses.shutdown_error",
38
+ message: "sense stop failed during shutdown",
39
+ meta: { sense: options.sense, error: error instanceof Error ? error.message : String(error) },
40
+ });
41
+ return "stop_failed";
42
+ });
43
+ void Promise.race([stopped, graceExpired]).then((result) => {
44
+ clearTimeout(graceTimer);
45
+ if (result === "grace_expired") {
46
+ (0, runtime_1.emitNervesEvent)({
47
+ level: "warn",
48
+ component: "senses",
49
+ event: "senses.shutdown_grace_expired",
50
+ message: "sense did not stop within its shutdown grace period; exiting anyway",
51
+ meta: { sense: options.sense, graceMs },
52
+ });
53
+ }
54
+ else {
55
+ (0, runtime_1.emitNervesEvent)({
56
+ component: "senses",
57
+ event: "senses.shutdown_complete",
58
+ message: "sense stopped",
59
+ meta: { sense: options.sense, result },
60
+ });
61
+ }
62
+ target.exit(result === "stopped" ? 0 : 1);
63
+ });
64
+ };
65
+ function uninstall() {
66
+ target.removeListener("SIGTERM", onSignal);
67
+ target.removeListener("SIGINT", onSignal);
68
+ }
69
+ target.once("SIGTERM", onSignal);
70
+ target.once("SIGINT", onSignal);
71
+ return uninstall;
72
+ }
@@ -75,15 +75,14 @@ Promise.resolve().then(() => __importStar(require("../heart/runtime-credentials"
75
75
  }
76
76
  }
77
77
  }
78
- const shutdown = () => {
79
- app.stop();
80
- void (attention?.close() ?? Promise.resolve()).then(() => process.exit(0), error => {
81
- (0, runtime_1.emitNervesEvent)({ level: "error", component: "senses", event: "senses.shepherd_attention_shutdown_error", message: "could not close native session attention", meta: { error: String(error) } });
82
- process.exit(1);
83
- });
84
- };
85
- process.once("SIGTERM", shutdown);
86
- process.once("SIGINT", shutdown);
78
+ const { installSenseShutdown } = await Promise.resolve().then(() => __importStar(require("./sense-shutdown")));
79
+ installSenseShutdown({
80
+ sense: "shepherd",
81
+ stop: async () => {
82
+ app.stop();
83
+ await attention?.close();
84
+ },
85
+ });
87
86
  })
88
87
  .catch((error) => {
89
88
  (0, runtime_1.emitNervesEvent)({
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1374",
3
+ "version": "0.1.0-alpha.1376",
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.1374",
9
+ "version": "0.1.0-alpha.1376",
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.1374",
3
+ "version": "0.1.0-alpha.1376",
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": {