@ouro.bot/cli 0.1.0-alpha.1715 → 0.1.0-alpha.1717

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,13 @@
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.1717",
6
+ "changes": [
7
+ "Whether the Butler's Telegram sense is set up is now decided in one place, the Butler's product registration. The daemon's sense status and the sense lines in the Butler's prompt all read it. Before, each kept its own copy of the rule. In the Butler's image nothing changes: its Telegram is ready when both of its runtime configs can be read and neither holds a bot token, because the root gateway holds the token. It needs this machine's config, and the repair line says to finish the root authority migration rather than restore a token. Other agents' Telegram readiness is unchanged.",
8
+ "The summary works on iMessage as well as Teams. Held notices are only cleared once the reply carrying the summary is confirmed delivered; a failed or unconfirmed send keeps them for the next message."
9
+ ]
10
+ },
4
11
  {
5
12
  "version": "0.1.0-alpha.1715",
6
13
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1715",
2
+ "runtimeVersion": "0.1.0-alpha.1717",
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.1715</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1717</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -40,7 +40,7 @@ const os = __importStar(require("os"));
40
40
  const path = __importStar(require("path"));
41
41
  const runtime_1 = require("../../nerves/runtime");
42
42
  const identity_1 = require("../identity");
43
- const butler_agent_1 = require("../butler-agent");
43
+ const active_1 = require("../product/active");
44
44
  const runtime_credentials_1 = require("../runtime-credentials");
45
45
  const provider_credentials_1 = require("../provider-credentials");
46
46
  const sense_truth_1 = require("../sense-truth");
@@ -190,7 +190,7 @@ function runtimeConfigUnavailableDetail(agent, runtimeConfig) {
190
190
  return `vault ${itemName} unavailable (${compactRuntimeConfigError(agent, runtimeConfig.error)})`;
191
191
  }
192
192
  function needsMachineRuntimeConfig(agent, sense) {
193
- return sense === "bluebubbles" || sense === "voice" || sense === "a2a" || sense === "shepherd" || ((0, butler_agent_1.isButlerAgent)(agent) && sense === "telegram");
193
+ return sense === "bluebubbles" || sense === "voice" || sense === "a2a" || sense === "shepherd" || (sense === "telegram" && (0, active_1.productSense)(agent, "telegram")?.needsMachineConfig === true);
194
194
  }
195
195
  function senseFactsFromRuntimeConfig(agent, senses, runtimeConfig, machineRuntimeConfig = (0, runtime_credentials_1.readMachineRuntimeCredentialConfig)(agent), workbenchHasStaleBundleEntry = false) {
196
196
  const base = {
@@ -216,12 +216,11 @@ function senseFactsFromRuntimeConfig(agent, senses, runtimeConfig, machineRuntim
216
216
  const integrations = payload.integrations;
217
217
  const voice = machinePayload.voice;
218
218
  const a2a = machinePayload.a2a;
219
- if (senses.telegram.enabled && (0, butler_agent_1.isButlerAgent)(agent)) {
220
- const ready = runtimeConfig.ok && machineRuntimeConfig.ok
221
- && !Object.hasOwn(payload, "telegramBotToken") && !Object.hasOwn(machinePayload, "telegramBotToken");
222
- base.telegram = ready
223
- ? { configured: true, detail: "root authority transport; gateway validated at process startup" }
224
- : { configured: false, detail: "root authority migration requires available tokenless credential inventories" };
219
+ const productTelegram = senses.telegram.enabled
220
+ ? (0, active_1.productSenseReadiness)(agent, "telegram", { runtime: { ok: runtimeConfig.ok, config: payload }, machine: { ok: machineRuntimeConfig.ok, config: machinePayload } })
221
+ : null;
222
+ if (productTelegram) {
223
+ base.telegram = productTelegram;
225
224
  }
226
225
  else if (senses.telegram.enabled) {
227
226
  const missing = ["telegramBotToken", "telegramAuthorizedUserId", "telegramAuthorizedChatId"]
@@ -409,9 +408,8 @@ function senseRepairHint(agent, sense) {
409
408
  return `Agent-runnable: run 'ouro connect a2a --agent ${agent}', then restart with 'ouro up'.`;
410
409
  }
411
410
  if (sense === "telegram") {
412
- return (0, butler_agent_1.isButlerAgent)(agent)
413
- ? "Agent-runnable: complete or recover the root authority migration; do not restore a resident Telegram token."
414
- : `Agent-runnable: store Telegram bot/user/chat coordinates with 'ouro connect telegram --agent ${agent}', then restart with 'ouro up'.`;
411
+ return (0, active_1.productSenseRepairHint)(agent, "telegram")
412
+ ?? `Agent-runnable: store Telegram bot/user/chat coordinates with 'ouro connect telegram --agent ${agent}', then restart with 'ouro up'.`;
415
413
  }
416
414
  if (sense === "shepherd")
417
415
  return (0, shepherd_config_1.shepherdRepairHint)(agent);
@@ -12,6 +12,9 @@ exports.productTools = productTools;
12
12
  exports.productToolDefinitions = productToolDefinitions;
13
13
  exports.productToolSelection = productToolSelection;
14
14
  exports.productActiveWorkSections = productActiveWorkSections;
15
+ exports.productSense = productSense;
16
+ exports.productSenseRepairHint = productSenseRepairHint;
17
+ exports.productSenseReadiness = productSenseReadiness;
15
18
  const runtime_1 = require("../../nerves/runtime");
16
19
  const container_runtime_1 = require("../daemon/container-runtime");
17
20
  /** The seam version this harness runs. A product built for another stops the start. */
@@ -199,3 +202,35 @@ async function productActiveWorkSections(input) {
199
202
  throw error;
200
203
  }
201
204
  }
205
+ /** How this agent's product runs one of core's senses (J6), or null when it runs it core's way. */
206
+ function productSense(agentName, sense) {
207
+ return productFor(agentName)?.senses?.[sense] ?? null;
208
+ }
209
+ /** The product's repair line for a sense that isn't set up (J6), or null when core gives it. A throw from the product fails the status. */
210
+ function productSenseRepairHint(agentName, sense) {
211
+ const product = productFor(agentName);
212
+ const own = product?.senses?.[sense];
213
+ if (!own)
214
+ return null;
215
+ try {
216
+ return own.repairHint(agentName);
217
+ }
218
+ catch (error) {
219
+ hookFailed(product, "senses.repairHint", agentName, error, "the product's sense repair line failed, so the sense's status can't be read");
220
+ throw error;
221
+ }
222
+ }
223
+ /** The product's judgement of whether a sense is set up (J6), or null when core judges it. A throw from the product fails the status. */
224
+ function productSenseReadiness(agentName, sense, input) {
225
+ const product = productFor(agentName);
226
+ const own = product?.senses?.[sense];
227
+ if (!own)
228
+ return null;
229
+ try {
230
+ return own.readiness(input);
231
+ }
232
+ catch (error) {
233
+ hookFailed(product, "senses.readiness", agentName, error, "the product's sense readiness failed, so the sense's status can't be read");
234
+ throw error;
235
+ }
236
+ }
@@ -48,7 +48,7 @@ const path = __importStar(require("path"));
48
48
  const runtime_1 = require("../nerves/runtime");
49
49
  const manager_1 = require("./bridges/manager");
50
50
  const identity_1 = require("./identity");
51
- const butler_agent_1 = require("./butler-agent");
51
+ const active_1 = require("./product/active");
52
52
  const coding_1 = require("../repertoire/coding");
53
53
  const session_activity_1 = require("./session-activity");
54
54
  const thoughts_1 = require("./daemon/thoughts");
@@ -219,14 +219,11 @@ function readSenseStatusLines() {
219
219
  ? openAIRealtimeVoiceReady
220
220
  : cascadeVoiceReady,
221
221
  a2a: true,
222
- // Sanctuary's resident is deliberately tokenless: the root authority gateway holds the
223
- // token, so a token in the resident's config would be the misconfiguration. Mirror the
224
- // daemon's rule (sense-manager) instead of reporting a working sense as needs_config (D-047).
225
- telegram: (0, butler_agent_1.isButlerAgent)(agentName)
226
- ? runtimeConfig.ok && machineRuntimeConfig.ok && !Object.hasOwn(runtimePayload, "telegramBotToken") && !Object.hasOwn(machinePayload, "telegramBotToken")
227
- : hasTextField(runtimePayload, "telegramBotToken")
222
+ // A product that runs Telegram its own way judges its readiness, the same judgement the daemon's sense status reads (D-047).
223
+ telegram: (0, active_1.productSenseReadiness)(agentName, "telegram", { runtime: { ok: runtimeConfig.ok, config: runtimePayload }, machine: { ok: machineRuntimeConfig.ok, config: machinePayload } })?.configured
224
+ ?? (hasTextField(runtimePayload, "telegramBotToken")
228
225
  && hasTextField(runtimePayload, "telegramAuthorizedUserId")
229
- && hasTextField(runtimePayload, "telegramAuthorizedChatId"),
226
+ && hasTextField(runtimePayload, "telegramAuthorizedChatId")),
230
227
  workbench: false,
231
228
  shepherd: (0, shepherd_config_1.shepherdSenseStatus)(true, machinePayload) === "ready",
232
229
  "app-sessions": true,
@@ -73,6 +73,7 @@ const identity_1 = require("../heart/identity");
73
73
  const runtime_cwd_1 = require("../heart/runtime-cwd");
74
74
  const config_1 = require("../heart/config");
75
75
  const runtime_credentials_1 = require("../heart/runtime-credentials");
76
+ const active_1 = require("../heart/product/active");
76
77
  const runtime_mode_1 = require("../heart/daemon/runtime-mode");
77
78
  const friends_1 = require("@ouro.bot/friends");
78
79
  const runtime_1 = require("../nerves/runtime");
@@ -560,9 +561,11 @@ function localSenseStatusLines() {
560
561
  && hasTextField(voice, "whisperCliPath")
561
562
  && hasTextField(voice, "whisperModelPath"),
562
563
  a2a: true,
563
- telegram: hasTextField(runtimePayload, "telegramBotToken")
564
- && hasTextField(runtimePayload, "telegramAuthorizedUserId")
565
- && hasTextField(runtimePayload, "telegramAuthorizedChatId"),
564
+ // A product that runs Telegram its own way judges its readiness, as the daemon and turn-context do.
565
+ telegram: (0, active_1.productSenseReadiness)((0, identity_1.getAgentName)(), "telegram", { runtime: { ok: runtimeConfig.ok, config: runtimePayload }, machine: { ok: machineRuntimeConfig.ok, config: machinePayload } })?.configured
566
+ ?? (hasTextField(runtimePayload, "telegramBotToken")
567
+ && hasTextField(runtimePayload, "telegramAuthorizedUserId")
568
+ && hasTextField(runtimePayload, "telegramAuthorizedChatId")),
566
569
  workbench: false,
567
570
  shepherd: (0, shepherd_config_1.shepherdSenseStatus)(true, machinePayload) === "ready",
568
571
  "app-sessions": true,
@@ -160,6 +160,18 @@ exports.product = {
160
160
  });
161
161
  },
162
162
  },
163
+ // J6: the Butler's Telegram holds no bot token. The root authority gateway holds it, so a token in the Butler's own config
164
+ // is the misconfiguration, and both configs must be readable for the gateway to be validated at startup.
165
+ senses: {
166
+ telegram: {
167
+ needsMachineConfig: true,
168
+ readiness: ({ runtime, machine }) => runtime.ok && machine.ok
169
+ && !Object.hasOwn(runtime.config, "telegramBotToken") && !Object.hasOwn(machine.config, "telegramBotToken")
170
+ ? { configured: true, detail: "root authority transport; gateway validated at process startup" }
171
+ : { configured: false, detail: "root authority migration requires available tokenless credential inventories" },
172
+ repairHint: () => "Agent-runnable: complete or recover the root authority migration; do not restore a resident Telegram token.",
173
+ },
174
+ },
163
175
  // J5: the house check runs in the daemon, and only Supercronic may fire it on its cron schedule.
164
176
  habits: {
165
177
  "sanctuary-health": {
@@ -2068,6 +2068,9 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
2068
2068
  let resolveTimeout;
2069
2069
  let recoveryTimedOut = false;
2070
2070
  let activeRunTurn = null;
2071
+ // Held notices ride this turn's reply; they are settled only once the final send was accepted, else released.
2072
+ let heldNoticeDelivery;
2073
+ let heldNoticesConfirmed = false;
2071
2074
  // BB-specific tool context wrappers
2072
2075
  const summarize = (0, core_1.createSummarize)("human");
2073
2076
  const bbCapabilities = (0, friends_1.getChannelCapabilities)("bluebubbles");
@@ -2195,6 +2198,8 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
2195
2198
  enforceTrustGate: trust_gate_1.enforceTrustGate,
2196
2199
  drainPending: pending_1.drainPending,
2197
2200
  drainDeferredReturns: (deferredFriendId) => (0, pending_1.drainDeferredReturns)(resolvedDeps.getAgentName(), deferredFriendId),
2201
+ claimHeldNotices: (heldFriendId) => (0, pending_1.claimHeldNotices)(resolvedDeps.getAgentName(), heldFriendId),
2202
+ confirmHeldNoticeDelivery: true,
2198
2203
  prepareRunAgentOptions: async ({ messages = [], currentUserMessages = [], runAgentOptions }) => {
2199
2204
  preparedBlueBubblesContext = await buildBlueBubblesContextMessages({
2200
2205
  agentName,
@@ -2316,6 +2321,7 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
2316
2321
  /* v8 ignore stop */
2317
2322
  const runTurn = (async () => {
2318
2323
  const result = await turnPromise;
2324
+ heldNoticeDelivery = result.heldNoticeDelivery;
2319
2325
  if (recoveryTimedOut && !finalTransportInvoked) {
2320
2326
  (0, runtime_1.emitNervesEvent)({
2321
2327
  level: "warn",
@@ -2411,6 +2417,12 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
2411
2417
  : "no_visible_reply",
2412
2418
  };
2413
2419
  }
2420
+ const finalReply = result.messages?.findLast((message) => message.role === "assistant");
2421
+ const replyText = typeof finalReply?.content === "string" ? finalReply.content.trim() : "";
2422
+ if (heldNoticeDelivery && replyText.length > 0 && heldNoticeDelivery.includedIn(replyText)) {
2423
+ heldNoticeDelivery.confirm();
2424
+ heldNoticesConfirmed = true;
2425
+ }
2414
2426
  // Acceptance is the visibility boundary. Publish the terminal dedupe
2415
2427
  // receipt first, then project the private generated tail while this
2416
2428
  // chat's canonical lock remains held. Even if receipt publication
@@ -2482,6 +2494,8 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
2482
2494
  // the cross-process session lease until that work has actually quiesced.
2483
2495
  if (activeRunTurn)
2484
2496
  await activeRunTurn.catch(() => undefined);
2497
+ if (!heldNoticesConfirmed)
2498
+ heldNoticeDelivery?.release();
2485
2499
  // If a terminal error was buffered and never replayed (e.g., handleInboundTurn threw),
2486
2500
  // replay it now so the user still sees the error.
2487
2501
  /* v8 ignore start -- error replay on throw: tested via BB error test @preserve */
@@ -38,11 +38,13 @@ var __importStar = (this && this.__importStar) || (function () {
38
38
  };
39
39
  })();
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.heldNoticesIncludedIn = heldNoticesIncludedIn;
41
42
  exports.emitObligationTransitionEpisodes = emitObligationTransitionEpisodes;
42
43
  exports.selectCheckpointCurrentAsk = selectCheckpointCurrentAsk;
43
44
  exports.startPostTurnSync = startPostTurnSync;
44
45
  exports.erroredTurnReply = erroredTurnReply;
45
46
  exports.handleInboundTurn = handleInboundTurn;
47
+ const node_crypto_1 = require("node:crypto");
46
48
  const fs = __importStar(require("fs"));
47
49
  const path = __importStar(require("path"));
48
50
  const runtime_1 = require("../nerves/runtime");
@@ -83,15 +85,28 @@ const friend_link_codes_1 = require("../mind/friend-link-codes");
83
85
  const reply_gate_1 = require("./reply-gate");
84
86
  const VOICE_PENDING_MAX_AGE_MS = 15 * 60 * 1_000;
85
87
  const TELEGRAM_GENERIC_OUTREACH_PENDING_MAX_AGE_MS = 15 * 60 * 1_000;
88
+ function heldNoticeRef(notice) {
89
+ return `H-${(0, node_crypto_1.createHash)("sha1").update(`${notice.timestamp}\n${notice.content}`).digest("hex").slice(0, 6)}`;
90
+ }
91
+ // Inclusion is a contract with the model, not proof that its summary is accurate: the summary prompt gives every notice a
92
+ // reference and asks the reply to end with a "Held notices:" receipt line. Only that line is parsed, and it must name every
93
+ // notice. Anything else counts as not included and the notices are released.
94
+ function heldNoticesIncludedIn(held, reply) {
95
+ const receipt = reply.trimEnd().split("\n").pop().match(/^\s*Held notices:\s*(.*)$/i);
96
+ if (!receipt)
97
+ return held.length === 0;
98
+ const named = new Set(receipt[1].match(/H-[0-9a-f]{6}\b/g) ?? []);
99
+ return held.every((notice) => named.has(heldNoticeRef(notice)));
100
+ }
86
101
  function renderHeldNoticeSummary(held) {
87
102
  const lines = [...held]
88
103
  .sort((a, b) => a.timestamp - b.timestamp)
89
- .map((notice) => `- (${new Date(notice.timestamp).toISOString()}) ${notice.content}`);
104
+ .map((notice) => `- [${heldNoticeRef(notice)}] (${new Date(notice.timestamp).toISOString()}) ${notice.content}`);
90
105
  return {
91
106
  from: held[0].from,
92
107
  friendId: held[0].friendId,
93
108
  timestamp: Date.now(),
94
- content: `Routine notices held while they were away, not sent to them. Give them one short summary of these, folded into your reply to this message; do not send them as separate messages, and do not send this summary on its own:\n${lines.join("\n")}`,
109
+ content: `Routine notices held while they were away, not sent to them. Give them one short summary of these, folded into your reply to this message; do not send them as separate messages, and do not send this summary on its own. End your reply with a final line "Held notices: " followed by every reference below, so delivery can be confirmed:\n${lines.join("\n")}`,
95
110
  };
96
111
  }
97
112
  function pendingExpirationReason(channel, message, now, agentName) {
@@ -1427,7 +1442,7 @@ async function handleInboundTurnExclusive(input) {
1427
1442
  messages: sessionMessages,
1428
1443
  drainedPending: pending,
1429
1444
  ...(handedOffHeldNotices && heldClaimForDelivery ? {
1430
- heldNoticeDelivery: { confirm: () => heldClaimForDelivery.settle(), release: () => heldClaimForDelivery.release() },
1445
+ heldNoticeDelivery: { confirm: () => heldClaimForDelivery.settle(), release: () => heldClaimForDelivery.release(), includedIn: (reply) => heldNoticesIncludedIn(heldClaimForDelivery.messages, reply) },
1431
1446
  } : {}),
1432
1447
  ...(input.switchedProvider ? { switchedProvider: input.switchedProvider } : {}),
1433
1448
  // Every chat sense answers an errored turn. The inner channel stays silent, and the CLI keeps showing its operator the raw error.
@@ -85,6 +85,8 @@ function getUntestedClaimReason(text) {
85
85
  const NO_ACTION_NOW_PATTERN = /\b(?:nothing (?:to do|needed|for you to do)|no action (?:is )?(?:needed|required)|nothing is needed|fyi|just so you know)\b/i;
86
86
  const FUTURE_GATE_PATTERN = /\b(?:nothing to do yet|nothing (?:is )?needed (?:from you )?yet|no action (?:is )?(?:needed|required) yet)\b/i;
87
87
  const FUTURE_GATE_LATER_PATTERN = /\b(?:when|once|after|later)\b[^.]*\b(?:i'll|i will|will)\b[^.]*\b(?:send|ask|prompt|text|message)\b/i;
88
+ // Only the announced later request itself: "when it is ready I will send you a tap (to approve on your phone)". Whatever follows it is still checked.
89
+ const ANNOUNCED_REQUEST_PATTERN = /\b(?:when|once|after|later)\b[^.;!?]*?\b(?:i'll|i will|will)\s+(?:send|ask|prompt|text|message)\b(?:\s+(?:you|them))?(?:\s+(?:an?|the|one|single))?(?:\s+[a-z-]+){0,2}?(?:\s+(?:prompt|tap|request|message|text|notification|passkey|approval|link))+\b(?:\s+to approve(?:\s+on your phone)?)?/ig;
88
90
  // Anything the person must know or act on now beats routine: a risk, a correction, a request, an update they asked for.
89
91
  const MATERIAL_RISK_PATTERN = /\b(?:lost|lose|losing|data loss|outage|still (?:down|broken|failing)|is down|are down|went down|corrupt\w*|deleted|wiped|breach\w*|leak\w*|exposed|forced reboot|crash\w*|unrecoverable|at risk|urgent|failed to)\b/i;
90
92
  const CORRECTION_PATTERN = /\b(?:correction|i was wrong|i got that wrong|that was wrong|ignore (?:my )?(?:last|earlier|previous)|disregard|retract\w*|mistake|my earlier (?:message|note))\b/i;
@@ -92,9 +94,9 @@ const PRESENT_ASK_PATTERN = /\b(?:please|can you|could you|would you|do you want
92
94
  function getRoutineNoticeReason(text) {
93
95
  if (REQUESTED_STATUS_PATTERN.test(text) || MATERIAL_RISK_PATTERN.test(text) || CORRECTION_PATTERN.test(text))
94
96
  return null;
95
- // The announced later request ("I'll send you a tap to approve") is not a present ask; any other sentence's ask is.
97
+ // The announced later request ("I'll send you a tap to approve") is not a present ask; an ask after a "but" or in another sentence is.
96
98
  const futureGate = FUTURE_GATE_PATTERN.test(text) && FUTURE_GATE_LATER_PATTERN.test(text);
97
- const withoutAnnouncedRequest = futureGate ? text.replace(new RegExp(FUTURE_GATE_LATER_PATTERN.source + "[^.]*[.]?", "ig"), " ") : text;
99
+ const withoutAnnouncedRequest = futureGate ? text.replace(ANNOUNCED_REQUEST_PATTERN, " ") : text;
98
100
  if (PRESENT_ASK_PATTERN.test(withoutAnnouncedRequest))
99
101
  return null;
100
102
  if (futureGate)
@@ -345,6 +345,19 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
345
345
  // Handle the result of a stream call: if it returns a Promise (the Teams SDK
346
346
  // does async HTTP under the hood even though the interface types it as void),
347
347
  // catch its rejection so we detect a dead stream and abort the agent loop.
348
+ // Delivery ledger: only a transport acknowledgement counts as delivered.
349
+ let acked = 0;
350
+ let unacked = 0;
351
+ let lost = 0;
352
+ const inflight = [];
353
+ function track(result) {
354
+ if (result && typeof result.then === "function") {
355
+ inflight.push(result.then(() => { acked++; }, () => { lost++; }));
356
+ }
357
+ else {
358
+ unacked++;
359
+ }
360
+ }
348
361
  function catchAsync(result) {
349
362
  if (result && typeof result.catch === "function") {
350
363
  result.catch((err) => markStopped("stream-async", err));
@@ -353,15 +366,19 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
353
366
  // Safely emit a text delta to the stream with AI labels.
354
367
  // On error (e.g. 403 from Teams stop button), abort the controller.
355
368
  function safeEmit(text) {
356
- /* v8 ignore next -- defensive guard: stopped set by prior 403; tested via flush abort path @preserve */
357
- if (stopped)
369
+ if (stopped) {
370
+ lost++;
358
371
  return;
372
+ }
359
373
  try {
360
- catchAsync(stream.emit(streamChunk(text)));
374
+ const emitted = stream.emit(streamChunk(text));
375
+ catchAsync(emitted);
376
+ track(emitted);
361
377
  streamHasContent = true;
362
378
  totalEmitted += text.length;
363
379
  }
364
380
  catch (err) {
381
+ lost++;
365
382
  markStopped("safeEmit", err);
366
383
  }
367
384
  }
@@ -380,6 +397,10 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
380
397
  if (result && typeof result.then === "function") {
381
398
  awaitingTransport = true;
382
399
  await result;
400
+ acked++;
401
+ }
402
+ else {
403
+ unacked++;
383
404
  }
384
405
  return true;
385
406
  }
@@ -405,6 +426,10 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
405
426
  if (result && typeof result.then === "function") {
406
427
  awaitingTransport = true;
407
428
  await result;
429
+ acked++;
430
+ }
431
+ else {
432
+ unacked++;
408
433
  }
409
434
  return true;
410
435
  }
@@ -438,25 +463,41 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
438
463
  let sendChain = Promise.resolve();
439
464
  let sendChainBusy = false;
440
465
  function safeSend(text) {
441
- if (stopped || !sendMessage)
466
+ if (stopped || !sendMessage) {
467
+ lost++;
442
468
  return;
469
+ }
443
470
  if (!sendChainBusy) {
444
471
  // Chain is idle -- start the send synchronously and mark busy
445
472
  sendChainBusy = true;
446
473
  try {
447
- sendChain = sendMessage(text).catch((err) => markStopped("send", err)).finally(() => { sendChainBusy = false; });
474
+ const sent = sendMessage(text);
475
+ track(sent);
476
+ sendChain = sent.catch((err) => markStopped("send", err)).finally(() => { sendChainBusy = false; });
448
477
  }
449
478
  catch (err) {
450
479
  sendChainBusy = false;
480
+ lost++;
451
481
  markStopped("send", err);
452
482
  }
453
483
  }
454
484
  else {
455
485
  // Chain is busy -- queue onto the existing chain
456
486
  sendChain = sendChain.then(() => {
457
- if (stopped)
487
+ if (stopped) {
488
+ lost++;
458
489
  return;
459
- return sendMessage(text);
490
+ }
491
+ let sent;
492
+ try {
493
+ sent = sendMessage(text);
494
+ }
495
+ catch (err) {
496
+ lost++;
497
+ throw err;
498
+ }
499
+ track(sent);
500
+ return sent;
460
501
  }).catch((err) => markStopped("send-queued", err));
461
502
  }
462
503
  }
@@ -590,6 +631,7 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
590
631
  if (!delivered && sendMessage) {
591
632
  try {
592
633
  await sendMessage(trimmed);
634
+ acked++;
593
635
  delivered = true;
594
636
  lastError = null;
595
637
  }
@@ -674,6 +716,7 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
674
716
  safeSend(msg);
675
717
  }
676
718
  },
719
+ deliveryState: () => lost > 0 ? "failed" : unacked > 0 || acked === 0 ? "unconfirmed" : "confirmed",
677
720
  flush: async () => {
678
721
  stopFlushTimer();
679
722
  stopPhraseRotation();
@@ -698,20 +741,28 @@ function createTeamsCallbacks(stream, controller, sendMessage, options) {
698
741
  // Stream is dead (not from finalization) — fall back to sendMessage; split on failure as recovery.
699
742
  try {
700
743
  await sendMessage(text);
744
+ acked++;
701
745
  }
702
746
  catch (error) {
703
747
  // A lost acknowledgement is not a rejection. Only a definite size rejection permits a smaller retry.
704
748
  if (!isTeamsSizeRejection(error) || text.length <= RECOVERY_CHUNK_SIZE)
705
749
  throw error;
706
750
  const chunks = splitMessage(text, RECOVERY_CHUNK_SIZE);
707
- for (const chunk of chunks)
751
+ for (const chunk of chunks) {
708
752
  await sendMessage(chunk);
753
+ acked++;
754
+ }
709
755
  }
710
756
  }
757
+ else if (stopped && !sendMessage) {
758
+ lost++;
759
+ }
711
760
  }
712
761
  else if (!streamHasContent && !options?.suppressEmptyStreamMessage) {
713
762
  safeEmit("(completed with tool calls only — no text response)");
714
763
  }
764
+ await sendChain;
765
+ await Promise.all(inflight);
715
766
  (0, runtime_1.emitNervesEvent)({
716
767
  component: "senses",
717
768
  event: "teams.flush_done",
@@ -1228,12 +1279,14 @@ async function handleTeamsMessage(text, stream, conversationId, teamsContext, se
1228
1279
  return;
1229
1280
  }
1230
1281
  // Flush any remaining accumulated text at end of turn. The held notices are settled only once this reached the
1231
- // person with a reply; a failed or empty delivery puts them back for the next message.
1282
+ // person with a reply that the transport acknowledged and that covers them; anything less puts them back.
1232
1283
  let delivered = false;
1233
1284
  try {
1234
1285
  await callbacks.flush();
1235
1286
  const finalReply = result.messages?.findLast((message) => message.role === "assistant");
1236
- delivered = typeof finalReply?.content === "string" && finalReply.content.trim().length > 0 && result.turnOutcome !== "superseded";
1287
+ const replyText = typeof finalReply?.content === "string" ? finalReply.content.trim() : "";
1288
+ delivered = callbacks.deliveryState() === "confirmed" && result.turnOutcome !== "superseded"
1289
+ && replyText.length > 0 && (result.heldNoticeDelivery?.includedIn(replyText) ?? true);
1237
1290
  }
1238
1291
  finally {
1239
1292
  if (delivered)
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1715",
3
+ "version": "0.1.0-alpha.1717",
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.1715",
9
+ "version": "0.1.0-alpha.1717",
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.1715",
3
+ "version": "0.1.0-alpha.1717",
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": {