@ouro.bot/cli 0.1.0-alpha.1726 → 0.1.0-alpha.1728

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,19 @@
1
1
  {
2
2
  "_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1728",
6
+ "changes": [
7
+ "An iMessage that a newer one overtakes is no longer lost. When a link's preview fetch fails and recovery picks the message up after a newer one already has the chat, or when recovery after an outage works through a chat newest first, each older message is still saved to the conversation once the current turn ends, in the order it was sent. It doesn't start a turn of its own, so the agent sees it as unanswered at the next turn, and catching up after an outage spends no recovery budget on it.",
8
+ "A message is now told apart from its own saved copy by the record of that exact arrival rather than by its words. A retry after a timeout or restart no longer saves it twice, and \"call\" next to \"call me\", two \"ok\"s in a row, or an edit of a message already saved all reach the conversation. Conversation history now keeps that record's id on each message a friend sends, where the sense provides one."
9
+ ]
10
+ },
11
+ {
12
+ "version": "0.1.0-alpha.1727",
13
+ "changes": [
14
+ "When someone sends several messages in a row, the agent now gets every one of them, each on its own line. Before, on iMessage, a message that needed fetching from the server (a link with a preview, a picture) could lose its place to the plain message sent after it and never reach the agent: Slugger told Ari \"no link came through\" when one had. And messages waiting together reached the model run together (\"small size^from rach\"), because the model's API joins back-to-back messages with no break. Now a chat's iMessages take their turn in the order they arrived, the engine puts a line between back-to-back messages for every sense (iMessage, Teams, Telegram and the rest), and the agent's note of what was just said lists each message since its last reply, not only the newest."
15
+ ]
16
+ },
4
17
  {
5
18
  "version": "0.1.0-alpha.1726",
6
19
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1726",
2
+ "runtimeVersion": "0.1.0-alpha.1728",
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.1726</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1728</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -21,6 +21,7 @@ exports.isExternalStateQuery = isExternalStateQuery;
21
21
  exports.settleContentMismatchError = settleContentMismatchError;
22
22
  exports.getSettleRetryError = getSettleRetryError;
23
23
  exports.stripLastToolCalls = stripLastToolCalls;
24
+ exports.joinAdjacentUserMessages = joinAdjacentUserMessages;
24
25
  exports.repairOrphanedToolCalls = repairOrphanedToolCalls;
25
26
  exports.isRejectedRequest = isRejectedRequest;
26
27
  exports.dropReplayedReasoning = dropReplayedReasoning;
@@ -991,6 +992,42 @@ function stripLastToolCalls(messages) {
991
992
  // message, stop at the next assistant or user message (tool results must be
992
993
  // adjacent to their originating assistant message).
993
994
  const TOOL_SCAN_BOUNDARY_ROLES = new Set(["assistant", "user"]);
995
+ function joinUserContent(left, right) {
996
+ if (typeof left === "string" && typeof right === "string")
997
+ return `${left}\n${right}`;
998
+ const leftParts = typeof left === "string" ? [{ type: "text", text: left }] : [...left];
999
+ const rightParts = typeof right === "string" ? [{ type: "text", text: right }] : [...right];
1000
+ const last = leftParts.at(-1);
1001
+ const first = rightParts[0];
1002
+ if (last?.type === "text" && first?.type === "text") {
1003
+ return [...leftParts.slice(0, -1), { ...last, text: `${last.text}\n${first.text}` }, ...rightParts.slice(1)];
1004
+ }
1005
+ return [...leftParts, ...rightParts];
1006
+ }
1007
+ // Each message a person sends stays its own line. Two user messages in a row (a burst that arrived while a turn ran,
1008
+ // a steering follow-up, a turn that ended without a reply) would otherwise reach the model run together: Claude's API
1009
+ // merges adjacent same-role turns with no separator, which is how Slugger read "small size^from rach" on 2026-11-29.
1010
+ // This builds the request for providers that read `messages` (Anthropic, chat completions); Responses-API providers
1011
+ // build their input from the unjoined messages, where each stays a separate item. The session keeps every message as it was.
1012
+ // A system message between two user messages (a sense's context note before the newest one) doesn't keep them apart:
1013
+ // Claude's API lifts system messages out, so the two would still meet. The note moves ahead of the joined message.
1014
+ function joinAdjacentUserMessages(messages) {
1015
+ const joined = [];
1016
+ for (const message of messages) {
1017
+ let previousIndex = joined.length - 1;
1018
+ while (previousIndex >= 0 && joined[previousIndex].role === "system")
1019
+ previousIndex--;
1020
+ const previous = joined[previousIndex];
1021
+ if (message.role === "user" && previous?.role === "user") {
1022
+ joined.splice(previousIndex, 1);
1023
+ joined.push({ ...previous, content: joinUserContent(previous.content, message.content) });
1024
+ }
1025
+ else {
1026
+ joined.push(message);
1027
+ }
1028
+ }
1029
+ return joined;
1030
+ }
994
1031
  // Repair orphaned tool_calls and tool results anywhere in the message history.
995
1032
  // 1. If an assistant message has tool_calls but missing tool results, inject synthetic error results.
996
1033
  // 2. If a tool result's tool_call_id doesn't match any tool_calls in a preceding assistant message, remove it.
@@ -1826,7 +1863,7 @@ async function runCountedTurn(turnTally, messages, unboundedCallbacks, channel,
1826
1863
  : null;
1827
1864
  try {
1828
1865
  return await providerRuntime.streamTurn({
1829
- messages: attemptMessages,
1866
+ messages: joinAdjacentUserMessages(attemptMessages),
1830
1867
  activeTools,
1831
1868
  // A step narrowed to one tool (a step report, a forced repeat) sends no held-back doors either.
1832
1869
  ...(deferralPool.length > 0 && activeTools === candidateActiveTools ? { deferredTools: deferralPool } : {}),
@@ -226,13 +226,14 @@ const REPLYING_TO_LABEL = {
226
226
  other: " (someone else's message)",
227
227
  };
228
228
  function buildOrientationFrame(input) {
229
- const derivedCurrent = input.currentUserMessages
230
- ? { messages: input.currentUserMessages, firstIndex: input.messages.length }
231
- : currentUserMessagesFrom(input.messages);
229
+ // Current speech is every user message since the last reply: a burst of texts is all of what they said.
230
+ const derivedCurrent = currentUserMessagesFrom(input.messages);
232
231
  const currentUserSpeech = derivedCurrent.messages
233
232
  .map((message) => extractMessageText(message))
234
233
  .filter((text) => text.length > 0);
235
- const replyingTo = derivedCurrent.messages.map(replyingToOf).find((reply) => reply !== undefined);
234
+ // What they replied to is the newest message's: an earlier unanswered message's reply must not stand in for it.
235
+ const newestCurrent = derivedCurrent.messages.at(-1);
236
+ const replyingTo = newestCurrent ? replyingToOf(newestCurrent) : undefined;
236
237
  const previousAssistant = latestAssistantBefore(input.messages, derivedCurrent.firstIndex);
237
238
  // Only the agent's own message holds the list a "the second one" points into.
238
239
  const replyListText = replyingTo && (replyingTo.author ?? "agent") === "agent" ? replyingTo.text : undefined;
@@ -957,6 +957,9 @@ function getIngressRelations(msg) {
957
957
  replyToEventId: typeof relations.replyToEventId === "string" ? relations.replyToEventId : null,
958
958
  threadRootEventId: typeof relations.threadRootEventId === "string" ? relations.threadRootEventId : null,
959
959
  references: Array.isArray(relations.references) ? relations.references.filter((item) => typeof item === "string") : [],
960
+ ...(typeof relations.inboundMessageId === "string" && relations.inboundMessageId.length > 0
961
+ ? { inboundMessageId: relations.inboundMessageId }
962
+ : {}),
960
963
  };
961
964
  }
962
965
  function createEventTime(role, recordedAt, captureKind, ingressAt) {
@@ -1015,6 +1018,7 @@ function buildEventFromMessage(message, sequence, recordedAt, captureKind, sourc
1015
1018
  captureKind,
1016
1019
  legacyVersion,
1017
1020
  sourceMessageIndex,
1021
+ ...(role === "user" && ingressRelations?.inboundMessageId ? { inbound: { messageId: ingressRelations.inboundMessageId } } : {}),
1018
1022
  },
1019
1023
  };
1020
1024
  }
@@ -1177,6 +1181,8 @@ function normalizeSessionEvent(event, index, recordedAt) {
1177
1181
  const time = event.time;
1178
1182
  const relations = event.relations;
1179
1183
  const provenance = event.provenance;
1184
+ const inbound = provenance?.inbound;
1185
+ const inboundMessageId = typeof inbound?.messageId === "string" && inbound.messageId.length > 0 ? inbound.messageId : null;
1180
1186
  const content = sanitizeConversationContent(role, normalizeContent(event.content));
1181
1187
  return {
1182
1188
  id: typeof event.id === "string" ? event.id : makeEventId(index + 1),
@@ -1210,6 +1216,7 @@ function normalizeSessionEvent(event, index, recordedAt) {
1210
1216
  ...(isSessionEventOutbound(provenance?.outbound)
1211
1217
  ? { outbound: { origin: provenance.outbound.origin, deliveryId: provenance.outbound.deliveryId } }
1212
1218
  : {}),
1219
+ ...(inboundMessageId ? { inbound: { messageId: inboundMessageId } } : {}),
1213
1220
  },
1214
1221
  };
1215
1222
  }
@@ -1257,7 +1264,10 @@ function exactRawEvent(value, index) {
1257
1264
  return false;
1258
1265
  }
1259
1266
  const provenance = value.provenance;
1260
- if (!exactKeys(provenance, ["captureKind", "legacyVersion", "sourceMessageIndex"])
1267
+ const provenanceKeys = provenance && typeof provenance === "object" && "inbound" in provenance
1268
+ ? ["captureKind", "legacyVersion", "sourceMessageIndex", "inbound"]
1269
+ : ["captureKind", "legacyVersion", "sourceMessageIndex"];
1270
+ if (!exactKeys(provenance, provenanceKeys)
1261
1271
  || typeof provenance.captureKind !== "string" || !["live", "synthetic", "migration"].includes(provenance.captureKind)
1262
1272
  || !(provenance.legacyVersion === null || Number.isSafeInteger(provenance.legacyVersion) && Number(provenance.legacyVersion) > 0)
1263
1273
  || !(provenance.sourceMessageIndex === null || Number.isSafeInteger(provenance.sourceMessageIndex) && Number(provenance.sourceMessageIndex) >= 0))
@@ -79,6 +79,7 @@ const runtime_1 = require("../../nerves/runtime");
79
79
  const session_transaction_1 = require("../../mind/session-transaction");
80
80
  const outbound_record_1 = require("../../mind/outbound-record");
81
81
  const await_alert_1 = require("../../heart/awaiting/await-alert");
82
+ const session_events_1 = require("../../heart/session-events");
82
83
  const orientation_frame_1 = require("../../heart/orientation-frame");
83
84
  const proactive_content_guard_1 = require("../proactive-content-guard");
84
85
  const bluebubbles_meta_guard_1 = require("../bluebubbles-meta-guard");
@@ -246,7 +247,7 @@ function seededObservationReservation(keyHash, fresh) {
246
247
  function suspendBlueBubblesSemanticObservation(generation) {
247
248
  generation.retry = true;
248
249
  generation.retainedAtMs = Date.now();
249
- (0, latest_turn_1.reactivateObservation)(generation.reservation);
250
+ (0, latest_turn_1.reactivateObservation)(generation.reservation, { retained: true });
250
251
  }
251
252
  function completeBlueBubblesSemanticObservation(keyHash, generation) {
252
253
  (0, latest_turn_1.clearPending)(generation.reservation);
@@ -763,6 +764,21 @@ function sessionAlreadyAnsweredMessage(event, existingMessages) {
763
764
  const index = sessionUserMessageIndex(event, existingMessages);
764
765
  return index >= 0 && existingMessages.slice(index + 1).some((message) => (message.role === "assistant" && !(0, outbound_record_1.isRecordedOutboundText)(extractMessageText(message.content))));
765
766
  }
767
+ /**
768
+ * A superseded message's own earlier attempt may have saved it before its turn timed out or was shut down. That copy
769
+ * carries its capture key, which is one per inbound event (an edit has its own, apart from the message it edits); the
770
+ * same words in another message ("ok", "ok") do not.
771
+ */
772
+ function sessionHoldsCapture(captureKeyHash, events) {
773
+ return (events ?? []).some((saved) => saved.provenance.inbound?.messageId === captureKeyHash);
774
+ }
775
+ /** Puts an overtaken message before the newer messages still waiting after the last reply, so they keep the order they were sent in. */
776
+ function beforeUnansweredMessages(messages, message) {
777
+ let index = messages.length;
778
+ while (index > 0 && messages[index - 1].role === "user")
779
+ index--;
780
+ return [...messages.slice(0, index), message, ...messages.slice(index)];
781
+ }
766
782
  /** Drop the unanswered copy a dead turn left at the tail, so the replay adds the message once. */
767
783
  function withoutUnansweredTail(event, messages) {
768
784
  return sessionUserMessageIndex(event, messages) === messages.length - 1
@@ -1790,7 +1806,8 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1790
1806
  const agentName = resolvedDeps.getAgentName();
1791
1807
  (0, runtime_cwd_1.recoverRuntimeCwd)();
1792
1808
  let activeTurnId = null;
1793
- if (shouldUseBlueBubblesRecoveryBudget(source, options)) {
1809
+ // The budget holds back recovery turns. A message a newer one has overtaken only goes into its session, so it spends none.
1810
+ if (shouldUseBlueBubblesRecoveryBudget(source, options) && (0, latest_turn_1.isCurrent)(options.latestTurnCapability)) {
1794
1811
  const decision = (0, autonomy_budget_1.reserveAutonomyBudget)((0, identity_1.getAgentRoot)(agentName), {
1795
1812
  agent: agentName,
1796
1813
  triggerType: "recovery",
@@ -1881,15 +1898,21 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1881
1898
  // Pre-load session inside the canonical turn lock so same-chat
1882
1899
  // deliveries cannot race on stale trunk state.
1883
1900
  const existing = resolvedDeps.loadSession(sessPath);
1884
- const replaying = options.semanticRecovery || source !== "webhook";
1901
+ // A newer message in this chat took it before this one's turn, so this one only goes into the session. Matching it
1902
+ // by contained text would take it for a newer message that contains it ("call" in "call me"); it is matched exactly.
1903
+ const superseded = !(0, latest_turn_1.isCurrent)(options.latestTurnCapability);
1904
+ const replay = options.semanticRecovery === true || source !== "webhook";
1905
+ const replaying = replay && !superseded;
1885
1906
  const sessionMessages = existing?.messages && existing.messages.length > 0
1886
1907
  ? structuredClone(replaying ? withoutUnansweredTail(event, existing.messages) : existing.messages)
1887
1908
  : [{ role: "system", content: (0, prompt_1.flattenSystemPrompt)(await resolvedDeps.buildSystem("bluebubbles", {}, context)) }];
1888
1909
  // Record EARLY for audit and crash recovery. This is capture truth, not
1889
1910
  // a claim that the agent turn completed successfully.
1890
- const inboundSource = replaying && sessionAlreadyAnsweredMessage(event, existing?.messages ?? sessionMessages)
1891
- ? "recovery-bootstrap"
1892
- : source;
1911
+ // Only a replay can find its own earlier copy; a first arrival never has one.
1912
+ const alreadySaved = replay && (superseded
1913
+ ? sessionHoldsCapture(options.currentIngressEvidence.captureKeyHash, existing?.events)
1914
+ : sessionAlreadyAnsweredMessage(event, existing?.messages ?? sessionMessages));
1915
+ const inboundSource = alreadySaved ? "recovery-bootstrap" : source;
1893
1916
  (0, inbound_log_1.recordBlueBubblesInbound)(agentName, event, inboundSource);
1894
1917
  if (inboundSource === "recovery-bootstrap") {
1895
1918
  (0, runtime_1.emitNervesEvent)({
@@ -1912,7 +1935,10 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1912
1935
  role: "user",
1913
1936
  content: buildInboundContent(event),
1914
1937
  };
1915
- resolvedDeps.saveSession(sessPath, [...structuredClone(sessionMessages), structuredClone(userMessage)], existing?.lastUsage, existing?.state);
1938
+ (0, session_events_1.stampIngressRelations)(userMessage, { replyToEventId: null, threadRootEventId: null, references: [], inboundMessageId: options.currentIngressEvidence.captureKeyHash });
1939
+ resolvedDeps.saveSession(sessPath, options.overtaken
1940
+ ? beforeUnansweredMessages(structuredClone(sessionMessages), structuredClone(userMessage))
1941
+ : [...structuredClone(sessionMessages), structuredClone(userMessage)], existing?.lastUsage, existing?.state);
1916
1942
  const liveTurnId = (0, active_turns_1.beginBlueBubblesActiveTurn)(agentName, event);
1917
1943
  activeTurnId = liveTurnId;
1918
1944
  // Waiting for permission to send is bounded by the turn deadline and shutdown.
@@ -1977,7 +2003,6 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1977
2003
  const orientationFrame = (0, orientation_frame_1.buildOrientationFrame)({
1978
2004
  channel: "bluebubbles",
1979
2005
  messages: [...priorMessages, userMessage],
1980
- currentUserMessages: [userMessage],
1981
2006
  structuredOutputs: existing?.structuredOutputs ?? [],
1982
2007
  source: buildBlueBubblesOrientationSource(event, priorMessages, options.orientationEvidence, options.orientationConversationKind, repliedToText, repliedToAuthor),
1983
2008
  });
@@ -2652,11 +2677,11 @@ function semanticCaptureRequiresRoutingRepair(capture) {
2652
2677
  function hasResolvedBlueBubblesRouting(event) {
2653
2678
  return Boolean(event.chat.chatGuid?.trim() || event.chat.chatIdentifier?.trim());
2654
2679
  }
2655
- function reserveBlueBubblesObservation(event) {
2680
+ function reserveBlueBubblesObservation(event, options = {}) {
2656
2681
  return (0, latest_turn_1.reserveObservation)({
2657
2682
  chatGuid: event.chat.chatGuid,
2658
2683
  chatIdentifier: event.chat.chatIdentifier,
2659
- });
2684
+ }, options);
2660
2685
  }
2661
2686
  function groupBlueBubblesObservationsByLane(candidates) {
2662
2687
  let groups = [];
@@ -3074,29 +3099,28 @@ async function handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, so
3074
3099
  fromMe: captured.normalized.fromMe,
3075
3100
  sender: captured.normalized.sender,
3076
3101
  };
3102
+ await (0, latest_turn_1.awaitOlderObservations)(reservation, {
3103
+ chatGuid: identityGroundedRepaired.chat.chatGuid,
3104
+ chatIdentifier: identityGroundedRepaired.chat.chatIdentifier,
3105
+ }, options.lifecycleSignal);
3077
3106
  const promotion = (0, latest_turn_1.promote)(reservation, {
3078
3107
  chatGuid: identityGroundedRepaired.chat.chatGuid,
3079
3108
  chatIdentifier: identityGroundedRepaired.chat.chatIdentifier,
3080
3109
  }, {
3081
3110
  allowSameGenerationRetry: semanticHandling.allowSameGenerationRetry,
3082
3111
  });
3083
- if (promotion.status !== "promoted") {
3084
- if (!captureOnlyMutation && promotion.status === "unresolved") {
3112
+ if (promotion.status === "unresolved") {
3113
+ if (!captureOnlyMutation)
3085
3114
  throw new Error("semantic_capture_routing_invalid");
3086
- }
3087
- const disposition = captureOnlyMutation
3088
- ? captureOnlyHandledDisposition()
3089
- : { outcome: "message_observed", detailCode: null };
3115
+ const disposition = captureOnlyHandledDisposition();
3090
3116
  publishTerminalReceipt(disposition.outcome, disposition.detailCode);
3091
3117
  semanticHandlingCompleted = true;
3092
- return {
3093
- handled: true,
3094
- notifiedAgent: false,
3095
- kind: captured.normalized.kind,
3096
- reason: captureOnlyMutation ? "mutation_state_only" : "superseded",
3097
- };
3118
+ return { handled: true, notifiedAgent: false, kind: captured.normalized.kind, reason: "mutation_state_only" };
3098
3119
  }
3120
+ // A newer message took the chat first (recovery runs newest first, and a parked capture keeps its old place).
3121
+ // A stale capability carries this message into its session in order, then leaves as superseded without a turn.
3099
3122
  latestTurnCapability = promotion.capability;
3123
+ const overtaken = promotion.status === "stale";
3100
3124
  if (captureOnlyMutation) {
3101
3125
  const disposition = captureOnlyHandledDisposition();
3102
3126
  publishTerminalReceipt(disposition.outcome, disposition.detailCode);
@@ -3130,6 +3154,7 @@ async function handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, so
3130
3154
  const capturedOptions = {
3131
3155
  ...options,
3132
3156
  latestTurnCapability,
3157
+ ...(overtaken ? { overtaken: true } : {}),
3133
3158
  currentIngressEvidence: Object.freeze({
3134
3159
  schemaVersion: 1,
3135
3160
  provider: "bluebubbles",
@@ -3323,7 +3348,7 @@ async function handleBlueBubblesEvent(payload, deps = {}) {
3323
3348
  }
3324
3349
  const scope = new BlueBubblesObservationScope();
3325
3350
  try {
3326
- const observationReservation = scope.own(reserveBlueBubblesObservation(normalized));
3351
+ const observationReservation = scope.own(reserveBlueBubblesObservation(normalized, { live: true }));
3327
3352
  const captured = await captureBlueBubblesSemanticEvent(normalized, resolvedDeps, "webhook", observationReservation);
3328
3353
  if (captured.status === "audit_only") {
3329
3354
  return { handled: true, notifiedAgent: false, kind: normalized.kind, reason: "ignored" };
@@ -4133,7 +4158,7 @@ function createBlueBubblesWebhookHandler(deps = {}, options = {}) {
4133
4158
  const resolvedDeps = { ...defaultDeps, ...deps };
4134
4159
  // The scope outlives this request: it closes when the queued turn ends.
4135
4160
  const scope = new BlueBubblesObservationScope();
4136
- const observationReservation = scope.own(reserveBlueBubblesObservation(normalized));
4161
+ const observationReservation = scope.own(reserveBlueBubblesObservation(normalized, { live: true }));
4137
4162
  let captured;
4138
4163
  try {
4139
4164
  captured = await captureBlueBubblesSemanticEvent(normalized, resolvedDeps, "webhook", observationReservation);
@@ -10,6 +10,7 @@ exports.promote = promote;
10
10
  exports.isCurrent = isCurrent;
11
11
  exports.observationSchedulingKeys = observationSchedulingKeys;
12
12
  exports.awaitDeliveryAdmission = awaitDeliveryAdmission;
13
+ exports.awaitOlderObservations = awaitOlderObservations;
13
14
  exports.listPendingObservationsForAudit = listPendingObservationsForAudit;
14
15
  exports.isDeliveryAdmittedNow = isDeliveryAdmittedNow;
15
16
  exports.cancel = cancel;
@@ -23,6 +24,7 @@ const pending = new Map();
23
24
  const lanes = new Map();
24
25
  const identifierBindings = new Map();
25
26
  const reservationHints = new WeakMap();
27
+ const liveReservations = new WeakSet();
26
28
  const batchReservations = new WeakMap();
27
29
  const observationEpoch = `${new Date().toISOString()}/${(0, node_crypto_1.randomUUID)()}`;
28
30
  let nextOrdinal = 0;
@@ -64,7 +66,7 @@ function settlePending(ordinal) {
64
66
  pending.delete(ordinal);
65
67
  entry.settle();
66
68
  }
67
- function createReservation(ordinal, input) {
69
+ function createReservation(ordinal, input, live = false) {
68
70
  const knownHints = new Set(observationHints(input));
69
71
  const reservation = Object.freeze({
70
72
  observationEpoch,
@@ -74,6 +76,8 @@ function createReservation(ordinal, input) {
74
76
  },
75
77
  });
76
78
  reservationHints.set(reservation, knownHints);
79
+ if (live)
80
+ liveReservations.add(reservation);
77
81
  let settle;
78
82
  const settled = new Promise((resolve) => {
79
83
  settle = resolve;
@@ -83,11 +87,13 @@ function createReservation(ordinal, input) {
83
87
  hints: new Set(knownHints),
84
88
  settled,
85
89
  settle,
90
+ live,
86
91
  });
87
92
  return reservation;
88
93
  }
89
- function reserveObservation(input) {
90
- return createReservation(++nextOrdinal, input);
94
+ /** `live` marks a webhook arrival, which newer arrivals in its chat wait for before they take the lane. */
95
+ function reserveObservation(input, options = {}) {
96
+ return createReservation(++nextOrdinal, input, options.live === true);
91
97
  }
92
98
  function beginObservationBatch(size) {
93
99
  if (!Number.isSafeInteger(size) || size <= 0)
@@ -118,9 +124,16 @@ function reserveObservationFromBatch(batch, newestOffset, input) {
118
124
  function clearPending(reservation) {
119
125
  settlePending(reservation.ordinal);
120
126
  }
121
- function reactivateObservation(reservation) {
122
- if (pending.has(reservation.ordinal))
127
+ /** Makes a reservation pending again: in flight once more, or `retained` while it waits for recovery. */
128
+ function reactivateObservation(reservation, options = {}) {
129
+ const existing = pending.get(reservation.ordinal);
130
+ if (existing && !(options.retained && !existing.retained)) {
131
+ existing.retained = options.retained;
123
132
  return;
133
+ }
134
+ // Parking an in-flight observation settles it, which wakes newer arrivals waiting on it; it stays pending as retained.
135
+ if (existing)
136
+ settlePending(reservation.ordinal);
124
137
  const knownHints = reservationHints.get(reservation);
125
138
  if (!knownHints)
126
139
  throw new Error("bluebubbles_observation_reservation_unknown");
@@ -133,6 +146,8 @@ function reactivateObservation(reservation) {
133
146
  hints: new Set(knownHints),
134
147
  settled,
135
148
  settle,
149
+ live: liveReservations.has(reservation),
150
+ retained: options.retained,
136
151
  });
137
152
  }
138
153
  function mergeObservationReservations(primary, duplicate) {
@@ -195,10 +210,6 @@ function promote(reservation, input, options = {}) {
195
210
  const sameGenerationRetry = reservation.ordinal === lane.highWater
196
211
  && options.allowSameGenerationRetry === true
197
212
  && lane.current === null;
198
- if (reservation.ordinal < lane.highWater || (reservation.ordinal === lane.highWater && !sameGenerationRetry)) {
199
- return { status: "stale" };
200
- }
201
- lane.current?.controller.abort(new Error("superseded"));
202
213
  const controller = new AbortController();
203
214
  const capability = Object.freeze({
204
215
  ordinal: reservation.ordinal,
@@ -207,6 +218,11 @@ function promote(reservation, input, options = {}) {
207
218
  signal: controller.signal,
208
219
  controller,
209
220
  });
221
+ if (reservation.ordinal < lane.highWater || (reservation.ordinal === lane.highWater && !sameGenerationRetry)) {
222
+ controller.abort(new Error("superseded"));
223
+ return { status: "stale", capability };
224
+ }
225
+ lane.current?.controller.abort(new Error("superseded"));
210
226
  lane.highWater = reservation.ordinal;
211
227
  lane.current = capability;
212
228
  lanes.set(chatKey, lane);
@@ -232,16 +248,19 @@ function isCurrent(capability) {
232
248
  function pendingIntersects(capability, entry) {
233
249
  if (entry.reservation.ordinal <= capability.ordinal)
234
250
  return false;
251
+ return pendingIntersectsChat(entry, capability.chatKey, capability.canonicalChat.chatGuid);
252
+ }
253
+ function pendingIntersectsChat(entry, chatKey, chatGuid) {
235
254
  const hasGuidHint = [...entry.hints].some((hint) => hint.startsWith("guid:"));
236
255
  if (entry.hints.size === 0)
237
256
  return true;
238
257
  for (const hint of entry.hints) {
239
- if (hint === capability.chatKey)
258
+ if (hint === chatKey)
240
259
  return true;
241
260
  if (hint.startsWith("identifier:")) {
242
261
  const identifier = hint.slice("identifier:".length);
243
262
  const binding = identifierBindings.get(identifier);
244
- if (binding === capability.canonicalChat.chatGuid)
263
+ if (binding === chatGuid)
245
264
  return true;
246
265
  // An identifier-only observation can repair into any GUID lane. Until
247
266
  // that relation is proved, it is a temporary global delivery fence—not
@@ -309,6 +328,47 @@ async function awaitDeliveryAdmission(capability, signal) {
309
328
  }
310
329
  return false;
311
330
  }
331
+ // Only an observation known to be in this chat holds it back. One without a route yet could be in any chat; it fences
332
+ // delivery, but waiting on it here would stall every chat for its whole capture and repair.
333
+ function provablyInChat(entry, chatKey, chatGuid) {
334
+ for (const hint of entry.hints) {
335
+ if (hint === chatKey)
336
+ return true;
337
+ if (hint.startsWith("identifier:") && identifierBindings.get(hint.slice("identifier:".length)) === chatGuid)
338
+ return true;
339
+ }
340
+ return false;
341
+ }
342
+ /**
343
+ * Waits until every older observation that may belong to this chat has been promoted or settled, so a chat's messages
344
+ * take the lane, and reach its session, in the order they arrived. A message that needs a slow repair (a link preview)
345
+ * would otherwise lose the lane to the plain message after it and never reach the turn (Slugger, 2026-11-29). Only
346
+ * live webhook arrivals are waited for: recovery handles a chat newest first, one at a time, and an observation parked
347
+ * for recovery never holds newer ones back. Rejects with the reason when `signal` aborts.
348
+ */
349
+ async function awaitOlderObservations(reservation, input, signal) {
350
+ const canonicalChat = resolveCanonicalChat(input);
351
+ if (!canonicalChat)
352
+ return;
353
+ const chatKey = guidAlias(canonicalChat.chatGuid);
354
+ const signals = signal ? [signal] : [];
355
+ for (;;) {
356
+ signal?.throwIfAborted();
357
+ const blockers = [...pending.values()].filter((entry) => (entry.reservation.ordinal < reservation.ordinal
358
+ && entry.live === true
359
+ && !entry.retained
360
+ && provablyInChat(entry, chatKey, canonicalChat.chatGuid)));
361
+ if (blockers.length === 0)
362
+ return;
363
+ (0, runtime_1.emitNervesEvent)({
364
+ component: "senses",
365
+ event: "senses.bluebubbles_older_observation_wait",
366
+ message: "waiting for older messages in this chat before taking the lane",
367
+ meta: { chatKey, ordinal: reservation.ordinal, olderCount: blockers.length },
368
+ });
369
+ await untilSettledOrAborted(blockers, signals);
370
+ }
371
+ }
312
372
  /** Every observation still pending, oldest first. The sense's ownership audit checks each has an owner. */
313
373
  function listPendingObservationsForAudit() {
314
374
  return [...pending.values()]
@@ -1035,8 +1035,8 @@ async function handleInboundTurnExclusive(input) {
1035
1035
  : (currentUserMessages.length > 0
1036
1036
  ? (0, orientation_frame_1.buildOrientationFrame)({
1037
1037
  channel: input.channel,
1038
+ // Current speech is every message they sent since the last reply, so a burst reads as all of its lines.
1038
1039
  messages: sessionMessages,
1039
- currentUserMessages,
1040
1040
  structuredOutputs: session.structuredOutputs ?? [],
1041
1041
  familySpeaker,
1042
1042
  })
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1726",
3
+ "version": "0.1.0-alpha.1728",
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.1726",
9
+ "version": "0.1.0-alpha.1728",
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.1726",
3
+ "version": "0.1.0-alpha.1728",
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": {