@ouro.bot/cli 0.1.0-alpha.1425 → 0.1.0-alpha.1427

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/changelog.json CHANGED
@@ -1,13 +1,31 @@
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.1427",
6
+ "changes": [
7
+ "iMessage and A2A keep each message's turn attempts and what already went out on disk, so a crash or restart no longer resets the try limit or replays a turn into sending something a second time. A message whose earlier turn already sent part of its reply, or ran a tool that messages someone, gets a recorded outcome instead of a replay. A message whose turn keeps dying or failing gets a recorded outcome after three attempts; a clean shutdown or a budget deferral does not use one up.",
8
+ "Each mid-turn iMessage now has its own outbound record (`bbout_*`), like the final reply."
9
+ ]
10
+ },
11
+ {
12
+ "version": "0.1.0-alpha.1426",
13
+ "changes": [
14
+ "Update the Ouro UI files to Ouro UI v1.3.467."
15
+ ]
16
+ },
4
17
  {
5
18
  "version": "0.1.0-alpha.1425",
6
19
  "changes": [
7
- "Eval sandbox: a new end-to-end probe saves and reads back a diary entry on a fresh sandbox (`search_facts`, `diary_write`, `consult_diary`), proving the #1735 fix for #1734 in the real two-container sandbox. A unit test pins that the record tools build `desk/_record` on an agent root that has no `desk` folder. The projection also never copies an old fact store (`psyche/memory/`) from the bundle under test.",
8
20
  "Sanctuary's owner can now load skills. The Sanctuary prompt tells the agent to \"use load_skill\", but the owner profile never granted it, so in eval round B no run loaded a skill: agents read the skill file by path or went without it. The owner profile (now version 24) and the agent-peer profile (now version 14) include `load_skill`, and `load_skill` joins the owner-only additions that only those two profiles may draw on. Household and event profiles don't list it, so they still reject it. The acceptance contract, containment fixture and Telegram owner tests now cover it, including a real `load_skill` call through Telegram."
9
21
  ]
10
22
  },
23
+ {
24
+ "version": "0.1.0-alpha.1424",
25
+ "changes": [
26
+ "Eval sandbox: a new end-to-end probe saves and reads back a diary entry on a fresh sandbox (`search_facts`, `diary_write`, `consult_diary`), proving the #1735 fix for #1734 in the real two-container sandbox. A unit test pins that the record tools build `desk/_record` on an agent root that has no `desk` folder. The projection also never copies an old fact store (`psyche/memory/`) from the bundle under test."
27
+ ]
28
+ },
11
29
  {
12
30
  "version": "0.1.0-alpha.1423",
13
31
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1425",
2
+ "runtimeVersion": "0.1.0-alpha.1427",
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.1425</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1427</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -46,6 +46,7 @@ const identity_1 = require("../heart/identity");
46
46
  const runtime_1 = require("../nerves/runtime");
47
47
  const shared_turn_1 = require("../senses/shared-turn");
48
48
  const inbound_journal_1 = require("../senses/inbound-journal");
49
+ const turn_attempts_1 = require("../senses/turn-attempts");
49
50
  const card_1 = require("./card");
50
51
  const config_1 = require("./config");
51
52
  const pin_store_1 = require("./pin-store");
@@ -181,6 +182,8 @@ async function defaultTurnRunner(input) {
181
182
  // The server records the outcome of a turn it stops itself, so a stopped turn leaves the queue at once.
182
183
  ...(input.signal ? { signal: input.signal, stopQueueWaitOnAbort: true } : {}),
183
184
  onTurnStart: input.onTurnStart,
185
+ // A tool that messages a person is noted before it runs, so a replay never sends it twice.
186
+ ...(input.onOutwardSend ? { onOutwardSend: input.onOutwardSend } : {}),
184
187
  identity: {
185
188
  provider: "a2a-agent",
186
189
  externalId: input.peerAgentId,
@@ -729,6 +732,7 @@ async function startA2AServer(options) {
729
732
  message: turnText,
730
733
  signal: controller.signal,
731
734
  onTurnStart,
735
+ onOutwardSend: (spoke) => journal.markSpoke(inboundId, spoke),
732
736
  ...(relationshipAuthorization ? { relationshipAuthorization } : {}),
733
737
  ...(delegatedCommand ? { delegatedCommand } : {}),
734
738
  }),
@@ -742,12 +746,20 @@ async function startA2AServer(options) {
742
746
  journal.settle(inboundId, "canceled");
743
747
  return respondWith(taskStore.get(record.taskId, tokenScope));
744
748
  }
745
- if (stop === "shutdown" && record.origin === "relay") {
749
+ const spokeEntry = journal.get(inboundId);
750
+ const spoke = spokeEntry?.spoke === true;
751
+ if (stop === "shutdown" && record.origin === "relay" && !spoke) {
746
752
  // Nobody waits on a relayed message's reply: it stays pending, and the next process runs it again. A clean
747
753
  // shutdown is not the turn failing, so it gives its attempt back; only crashes use attempts up.
748
754
  journal.refundAttempt(inboundId);
749
755
  return errorResponse(rpcId, -32000, AGENT_RESTARTING);
750
756
  }
757
+ if (stop === "shutdown" && spoke) {
758
+ // Running it again would send what already went out a second time.
759
+ const detail = `the agent stopped before it finished answering, after ${(0, turn_attempts_1.describeTurnSpokes)(spokeEntry.spokeRecords)} went out; it is not run again`;
760
+ recordFailure(inboundId, record, detail);
761
+ return failureResponse(rpcId, record, detail, accessToken);
762
+ }
751
763
  const seconds = Math.round(turnTimeoutMs / 1000);
752
764
  const detail = stop === "shutdown"
753
765
  ? STOPPED_BEFORE_ANSWERING
@@ -822,6 +834,11 @@ async function startA2AServer(options) {
822
834
  recordFailure(entry.id, record, `stopped after ${entry.attempts} attempts without an answer`);
823
835
  return;
824
836
  }
837
+ if (entry.spoke) {
838
+ // The earlier turn already messaged someone; a replay would send that again.
839
+ recordFailure(entry.id, record, `the turn stopped after ${(0, turn_attempts_1.describeTurnSpokes)(entry.spokeRecords)} went out, so it is not run again`);
840
+ return;
841
+ }
825
842
  if (record.verifiedChat?.onBehalfOf === "principal") {
826
843
  // It may already have acted with the principal's authority, and its grant was checked only for that moment.
827
844
  recordFailure(entry.id, record, "a delegated command is not run again after a restart; send it again");
@@ -98,6 +98,7 @@ const latest_turn_1 = require("./latest-turn");
98
98
  const active_turns_1 = require("./active-turns");
99
99
  const trust_gate_1 = require("../trust-gate");
100
100
  const pipeline_1 = require("../pipeline");
101
+ const turn_attempts_1 = require("../turn-attempts");
101
102
  const context_packet_ledger_1 = require("../context-packet-ledger");
102
103
  const context_packet_1 = require("./context-packet");
103
104
  const autonomy_budget_1 = require("../../heart/autonomy-budget");
@@ -116,9 +117,6 @@ async function drainBlueBubblesTurns() {
116
117
  return work.length;
117
118
  }
118
119
  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();
122
120
  const semanticObservationGenerations = new Map();
123
121
  const BLUEBUBBLES_VISIBLE_OUTBOUND_STATUSES = new Set([
124
122
  "accepted",
@@ -247,7 +245,28 @@ function suspendBlueBubblesSemanticObservation(generation) {
247
245
  function completeBlueBubblesSemanticObservation(keyHash, generation) {
248
246
  (0, latest_turn_1.clearPending)(generation.reservation);
249
247
  semanticObservationGenerations.delete(keyHash);
250
- unfinishedTurnAttempts.delete(keyHash);
248
+ clearBlueBubblesTurnAttempts(keyHash);
249
+ }
250
+ /** Each capture's turn attempts and sends, kept on disk so a restart neither resets the count nor repeats a send. */
251
+ function blueBubblesTurnAttempts() {
252
+ return (0, turn_attempts_1.openTurnAttempts)((0, identity_1.getAgentRoot)(), "bluebubbles");
253
+ }
254
+ function clearBlueBubblesTurnAttempts(keyHash) {
255
+ try {
256
+ blueBubblesTurnAttempts().clear(keyHash);
257
+ /* v8 ignore start -- removing a file with force fails only on a broken folder; the capture already has its outcome @preserve */
258
+ }
259
+ catch (error) {
260
+ // A leftover record is harmless: the capture has its outcome, so it is never handled again.
261
+ (0, runtime_1.emitNervesEvent)({
262
+ level: "warn",
263
+ component: "senses",
264
+ event: "senses.bluebubbles_turn_attempts_clear_failed",
265
+ message: "could not clear a bluebubbles capture's turn attempts after its outcome",
266
+ meta: { keyHash, reason: error instanceof Error ? error.message : String(error) },
267
+ });
268
+ }
269
+ /* v8 ignore stop */
251
270
  }
252
271
  async function acquireBlueBubblesSemanticHandlingSlot(keyHash, generation) {
253
272
  const active = activeSemanticHandlingSlots.get(keyHash);
@@ -944,6 +963,47 @@ function createBlueBubblesCallbacks(client, chat, replyTarget, isGroupChat, onVi
944
963
  // check catches near-duplicates from the same turn.
945
964
  const sentOutwardTextNorms = new Set();
946
965
  const sentOutwardTokenSets = [];
966
+ let midTurnSpeakCount = 0;
967
+ const toolSends = options.noteSend ? (0, turn_attempts_1.outwardSendTracker)(options.noteSend) : null;
968
+ /** Reserve a mid-turn message's own outbound record, so the send leaves a `bbout_*` record like the final reply. */
969
+ function reserveMidTurnSpeak(text, replyToMessageGuid) {
970
+ const durableOutbound = options.durableOutbound;
971
+ if (!durableOutbound?.speakIdempotencyKeyPrefix)
972
+ return null;
973
+ midTurnSpeakCount += 1;
974
+ const idempotencyKey = `${durableOutbound.speakIdempotencyKeyPrefix}:speak-${midTurnSpeakCount}`;
975
+ const reservation = (0, outbound_state_1.reserveBlueBubblesOutbound)({
976
+ agentRoot: durableOutbound.agentRoot,
977
+ idempotencyKey,
978
+ chat,
979
+ attachment: durableOutbound.attachment,
980
+ text,
981
+ tempGuid: `ouro-speak-${(0, node_crypto_1.createHash)("sha256").update(idempotencyKey).digest("hex").slice(0, 32)}`,
982
+ ...(replyToMessageGuid ? { replyToMessageGuid } : {}),
983
+ });
984
+ /* v8 ignore next -- each turn has its own random key prefix and counter, so a key is never reserved twice @preserve */
985
+ if (reservation.status !== "reserved")
986
+ return "duplicate";
987
+ return reservation.record;
988
+ }
989
+ function recordMidTurnSpeakState(record, update) {
990
+ if (!record)
991
+ return;
992
+ try {
993
+ update(record.recordId, new Date().toISOString());
994
+ /* v8 ignore start -- the send is already noted in the turn's attempts; a failed status write loses only the status @preserve */
995
+ }
996
+ catch (stateError) {
997
+ (0, runtime_1.emitNervesEvent)({
998
+ level: "error",
999
+ component: "senses",
1000
+ event: "senses.bluebubbles_outbound_state_error",
1001
+ message: "failed to record a bluebubbles mid-turn message's transport state",
1002
+ meta: { recordId: record.recordId, reason: String(stateError) },
1003
+ });
1004
+ }
1005
+ /* v8 ignore stop */
1006
+ }
947
1007
  async function canRunOutbound() {
948
1008
  if (outboundClosed)
949
1009
  return false;
@@ -1108,6 +1168,7 @@ function createBlueBubblesCallbacks(client, chat, replyTarget, isGroupChat, onVi
1108
1168
  // for debugging.
1109
1169
  if (options.enableActivitySignals !== false && !typingActive && name !== "observe" && name !== "speak")
1110
1170
  startTypingNow();
1171
+ toolSends?.started(name, _args);
1111
1172
  (0, runtime_1.emitNervesEvent)({
1112
1173
  component: "senses",
1113
1174
  event: "senses.bluebubbles_tool_start",
@@ -1115,6 +1176,10 @@ function createBlueBubblesCallbacks(client, chat, replyTarget, isGroupChat, onVi
1115
1176
  meta: { name },
1116
1177
  });
1117
1178
  },
1179
+ onToolDispatch(name) {
1180
+ // Just before the handler runs: a tool that messages a person is noted on disk first, or does not run.
1181
+ toolSends?.dispatched(name);
1182
+ },
1118
1183
  onToolEnd(name, summary, success) {
1119
1184
  (0, runtime_1.emitNervesEvent)({
1120
1185
  component: "senses",
@@ -1165,15 +1230,54 @@ function createBlueBubblesCallbacks(client, chat, replyTarget, isGroupChat, onVi
1165
1230
  }
1166
1231
  if (!await canRunOutbound())
1167
1232
  return;
1233
+ const replyToMessageGuid = replyTarget.getReplyToMessageGuid();
1234
+ const speakRecord = reserveMidTurnSpeak(trimmed, replyToMessageGuid);
1235
+ /* v8 ignore next 4 -- see reserveMidTurnSpeak: a fresh key is never already reserved @preserve */
1236
+ if (speakRecord === "duplicate") {
1237
+ emitDuplicateOutwardSuppressed("flushNow", trimmed.length);
1238
+ return;
1239
+ }
1240
+ // Written to disk first: if this throws, nothing was sent and the speak call fails.
1241
+ try {
1242
+ options.noteSend?.((0, turn_attempts_1.turnSpoke)("speak", trimmed, speakRecord?.recordId ?? null));
1243
+ }
1244
+ catch (error) {
1245
+ recordMidTurnSpeakState(speakRecord, (recordId, failedAt) => (0, outbound_state_1.markBlueBubblesOutboundFailed)({
1246
+ agentRoot: options.durableOutbound.agentRoot,
1247
+ recordId,
1248
+ failedAt,
1249
+ reason: `not sent: ${error instanceof Error ? error.message : String(error)}`,
1250
+ }));
1251
+ throw error;
1252
+ }
1168
1253
  // Count the message as seen once it is handed to the transport: a send
1169
1254
  // still in flight, or one that timed out, may reach the friend anyway, and
1170
1255
  // a turn that ends now must not be replayed into repeating it.
1171
1256
  recordVisibleActivity();
1172
- await client.sendText({
1173
- chat,
1174
- text: trimmed,
1175
- replyToMessageGuid: replyTarget.getReplyToMessageGuid(),
1176
- });
1257
+ let speakResponse;
1258
+ try {
1259
+ speakResponse = await client.sendText({
1260
+ chat,
1261
+ text: trimmed,
1262
+ replyToMessageGuid,
1263
+ ...(speakRecord ? { tempGuid: speakRecord.tempGuid } : {}),
1264
+ });
1265
+ }
1266
+ catch (error) {
1267
+ recordMidTurnSpeakState(speakRecord, (recordId, failedAt) => (0, outbound_state_1.markBlueBubblesOutboundFailed)({
1268
+ agentRoot: options.durableOutbound.agentRoot,
1269
+ recordId,
1270
+ failedAt,
1271
+ reason: error instanceof Error ? error.message : String(error),
1272
+ }));
1273
+ throw error;
1274
+ }
1275
+ recordMidTurnSpeakState(speakRecord, (recordId, acceptedAt) => (0, outbound_state_1.markBlueBubblesOutboundAccepted)({
1276
+ agentRoot: options.durableOutbound.agentRoot,
1277
+ recordId,
1278
+ acceptedAt,
1279
+ ...(speakResponse?.messageGuid ? { messageGuid: speakResponse.messageGuid } : {}),
1280
+ }));
1177
1281
  // Note: do NOT call client.setTyping(chat, false) here — the agent is
1178
1282
  // still mid-turn, so the typing indicator stays ACTIVE.
1179
1283
  (0, runtime_1.emitNervesEvent)({
@@ -1865,6 +1969,13 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
1865
1969
  serverUrl: outboundRuntimeConfig.serverUrl,
1866
1970
  accountId: outboundRuntimeConfig.accountId,
1867
1971
  },
1972
+ speakIdempotencyKeyPrefix: `${blueBubblesInboundReplyIdempotencyKey(options.currentIngressEvidence.captureKeyHash)}:turn-${(0, node_crypto_1.randomUUID)()}`,
1973
+ },
1974
+ noteSend: (spoke) => {
1975
+ // Set first, so this process never replays a turn whose send may have gone out. If the write below fails,
1976
+ // the send is stopped, and the turn errs toward a recorded outcome over a replay.
1977
+ spokeBeforeFinalTransport = true;
1978
+ blueBubblesTurnAttempts().noteSpoke(options.currentIngressEvidence.captureKeyHash, spoke);
1868
1979
  },
1869
1980
  });
1870
1981
  const lifecycleSignal = options.lifecycleSignal;
@@ -2225,7 +2336,7 @@ async function handleBlueBubblesNormalizedEvent(event, resolvedDeps, source, opt
2225
2336
  agentRoot: (0, identity_1.getAgentRoot)(),
2226
2337
  recordId: failed.recordId,
2227
2338
  decidedAt: new Date().toISOString(),
2228
- reason: "mid-turn speech was visible before the final send failed",
2339
+ reason: "part of the turn reached someone before the final send failed",
2229
2340
  });
2230
2341
  }
2231
2342
  }
@@ -2956,17 +3067,61 @@ async function handleCapturedBlueBubblesSemanticEvent(captured, resolvedDeps, so
2956
3067
  }
2957
3068
  if (failedReplyVisible)
2958
3069
  return completeVisibleFailedReply();
2959
- result = await handleBlueBubblesNormalizedEvent(canonicalEvent, resolvedDeps, source, capturedOptions);
3070
+ // Attempts and sends are on disk, so a process that died mid-turn neither resets the count nor repeats a send.
3071
+ const turnAttempts = blueBubblesTurnAttempts();
3072
+ const earlier = turnAttempts.get(identity.keyHash);
3073
+ if (earlier && earlier.spoke.length > 0) {
3074
+ // An earlier process's turn sent part of its reply and never ended. Running it again would send that twice.
3075
+ (0, runtime_1.emitNervesEvent)({
3076
+ level: "error",
3077
+ component: "senses",
3078
+ event: "senses.bluebubbles_turn_abandoned",
3079
+ message: "did not replay a bluebubbles turn that sent part of its reply before its process stopped",
3080
+ meta: {
3081
+ messageGuid: captured.normalized.messageGuid,
3082
+ reason: "replay",
3083
+ attempts: earlier.attempts,
3084
+ spokeBeforeEnd: true,
3085
+ sends: earlier.spoke.map((spoke) => ({ kind: spoke.kind, sentAt: spoke.sentAt, outboundRecordId: spoke.outboundRecordId })),
3086
+ },
3087
+ });
3088
+ publishSpokenTurnEnded("replay");
3089
+ return { handled: true, notifiedAgent: false, kind: captured.normalized.kind, reason: "already_processed", spokeBeforeEnd: true };
3090
+ }
3091
+ if (earlier && earlier.attempts >= BLUEBUBBLES_REPLY_DELIVERY_MAX_ATTEMPTS) {
3092
+ // Every attempt so far died with its process or threw: stop, rather than replay it forever.
3093
+ (0, runtime_1.emitNervesEvent)({
3094
+ level: "error",
3095
+ component: "senses",
3096
+ event: "senses.bluebubbles_turn_abandoned",
3097
+ message: "gave up replaying a bluebubbles turn that used up its attempts without ending",
3098
+ meta: { messageGuid: captured.normalized.messageGuid, reason: "replay", attempts: earlier.attempts, spokeBeforeEnd: false },
3099
+ });
3100
+ publishTerminalReceipt("message_observed", "turn_retries_exhausted");
3101
+ semanticHandlingCompleted = true;
3102
+ return { handled: true, notifiedAgent: false, kind: captured.normalized.kind, reason: "turn_timeout" };
3103
+ }
3104
+ const turnAttempt = turnAttempts.beginAttempt(identity.keyHash);
3105
+ try {
3106
+ result = await handleBlueBubblesNormalizedEvent(canonicalEvent, resolvedDeps, source, capturedOptions);
3107
+ }
3108
+ catch (error) {
3109
+ // A clean shutdown is not the turn failing, so it gives its attempt back; only crashes and failures use them up.
3110
+ if (options.lifecycleSignal?.aborted)
3111
+ turnAttempts.refundAttempt(identity.keyHash);
3112
+ throw error;
3113
+ }
2960
3114
  // A budget or storm-breaker block defers the message; it was never seen.
2961
3115
  // Leave it pending so a later recovery pass retries it once the block lifts.
2962
- if (result.reason === "autonomy_budget_blocked")
3116
+ if (result.reason === "autonomy_budget_blocked") {
3117
+ turnAttempts.refundAttempt(identity.keyHash);
2963
3118
  return result;
3119
+ }
2964
3120
  if (result.reason === "turn_timeout" || result.reason === "delivery_admission_timeout" || result.reason === "shutdown") {
2965
3121
  // The turn ended without a reply or a chosen silence. Leave it pending so
2966
3122
  // recovery replays it, unless the friend already saw part of it or it
2967
3123
  // keeps failing; then record a visible failure instead.
2968
- const attempts = (unfinishedTurnAttempts.get(identity.keyHash) ?? 0) + 1;
2969
- unfinishedTurnAttempts.set(identity.keyHash, attempts);
3124
+ const attempts = turnAttempt;
2970
3125
  if (!result.spokeBeforeEnd && attempts < BLUEBUBBLES_REPLY_DELIVERY_MAX_ATTEMPTS)
2971
3126
  return result;
2972
3127
  (0, runtime_1.emitNervesEvent)({
@@ -145,8 +145,8 @@ function openInboundJournal(agentRoot, sense, options = {}) {
145
145
  refundAttempt(id) {
146
146
  update(id, (entry) => ({ ...entry, attempts: Math.max(0, entry.attempts - 1) }));
147
147
  },
148
- markSpoke(id) {
149
- update(id, (entry) => ({ ...entry, spoke: true }));
148
+ markSpoke(id, spoke) {
149
+ update(id, (entry) => ({ ...entry, spoke: true, ...(spoke ? { spokeRecords: [...(entry.spokeRecords ?? []), spoke] } : {}) }));
150
150
  },
151
151
  settle(id, outcome, detail) {
152
152
  const entry = get(id);
@@ -945,11 +945,12 @@ async function handleInboundTurnExclusive(input) {
945
945
  ? {
946
946
  ...input.callbacks,
947
947
  onToolDispatch(name) {
948
+ // The sense's own hook goes first: when it stops the call (it could not note a send), nothing was acted on.
949
+ input.callbacks.onToolDispatch?.(name);
948
950
  if (!turnActed) {
949
951
  turnActed = true;
950
952
  pendingClaim?.settle();
951
953
  }
952
- input.callbacks.onToolDispatch?.(name);
953
954
  },
954
955
  }
955
956
  : input.callbacks;
@@ -61,6 +61,7 @@ const trust_gate_1 = require("./trust-gate");
61
61
  const pipeline_1 = require("./pipeline");
62
62
  Object.defineProperty(exports, "erroredTurnReply", { enumerable: true, get: function () { return pipeline_1.erroredTurnReply; } });
63
63
  const mcp_manager_1 = require("../repertoire/mcp-manager");
64
+ const turn_attempts_1 = require("./turn-attempts");
64
65
  const runtime_1 = require("../nerves/runtime");
65
66
  const session_transaction_1 = require("../mind/session-transaction");
66
67
  const orientation_frame_1 = require("../heart/orientation-frame");
@@ -514,6 +515,7 @@ async function runSenseTurnExclusive(options, owner) {
514
515
  ? `${committedResponseText}\n${cleaned}`
515
516
  : cleaned;
516
517
  };
518
+ const outwardSends = options.onOutwardSend ? (0, turn_attempts_1.outwardSendTracker)(options.onOutwardSend) : null;
517
519
  const deliveryErrorMessage = (error) => error instanceof Error ? error.message : String(error);
518
520
  const emitFrontendEvent = (event) => {
519
521
  options.frontendEventSink?.onEvent(event);
@@ -569,11 +571,15 @@ async function runSenseTurnExclusive(options, owner) {
569
571
  emitFrontendEvent({ type: "reasoning_delta", data: { text: chunk } });
570
572
  },
571
573
  onToolStart: (name, args) => {
574
+ outwardSends?.started(name, args);
572
575
  toolInvocationCount += 1;
573
576
  if (options.turnMetricsObserver)
574
577
  options.turnMetricsObserver.toolInvocationCount += 1;
575
578
  emitFrontendEvent({ type: "tool_started", data: { name, args } });
576
579
  },
580
+ onToolDispatch: (name) => {
581
+ outwardSends?.dispatched(name);
582
+ },
577
583
  onToolEnd: (name, _summary, success) => {
578
584
  if (name === "settle" && success)
579
585
  terminalDeliveryKind = "settle";
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.turnAttemptsDir = turnAttemptsDir;
37
+ exports.turnSpoke = turnSpoke;
38
+ exports.describeTurnSpokes = describeTurnSpokes;
39
+ exports.turnSpokeForTool = turnSpokeForTool;
40
+ exports.outwardSendTracker = outwardSendTracker;
41
+ exports.openTurnAttempts = openTurnAttempts;
42
+ const node_crypto_1 = require("node:crypto");
43
+ const fs = __importStar(require("node:fs"));
44
+ const path = __importStar(require("node:path"));
45
+ const atomic_file_1 = require("../heart/atomic-file");
46
+ const runtime_1 = require("../nerves/runtime");
47
+ function turnAttemptsDir(agentRoot, sense) {
48
+ return path.join(agentRoot, "state", "senses", sense, "turn-attempts");
49
+ }
50
+ function fileName(id) {
51
+ return `${(0, node_crypto_1.createHash)("sha256").update(id).digest("hex")}.json`;
52
+ }
53
+ function hashText(text) {
54
+ return `sha256:${(0, node_crypto_1.createHash)("sha256").update(text).digest("hex")}`;
55
+ }
56
+ /** Describe one send for `noteSpoke`: what kind it was, when, its outbound record, and a hash of its text. */
57
+ function turnSpoke(kind, text, outboundRecordId = null, nowMs = Date.now()) {
58
+ return {
59
+ kind,
60
+ sentAt: new Date(nowMs).toISOString(),
61
+ outboundRecordId,
62
+ textHash: text === null ? null : hashText(text),
63
+ textLength: text === null ? null : text.length,
64
+ };
65
+ }
66
+ /**
67
+ * Name what went out for a recorded outcome, such as `1 send (tool:send_message at 2026-11-22T10:00:00.000Z)`. An
68
+ * entry written before sends were itemized has none, and reads as "a message".
69
+ */
70
+ function describeTurnSpokes(spoke = []) {
71
+ if (spoke.length === 0)
72
+ return "a message";
73
+ const sends = spoke.map((entry) => `${entry.kind} at ${entry.sentAt}`).join(", ");
74
+ return `${spoke.length} ${spoke.length === 1 ? "send" : "sends"} (${sends})`;
75
+ }
76
+ /** Tools that send something to a person or another agent outside the turn's own reply. Running one counts as having spoken. */
77
+ const PERSON_MESSAGING_TOOLS = new Set([
78
+ "send_message",
79
+ "surface",
80
+ "teams_send_message",
81
+ "mail_send",
82
+ "send_file",
83
+ "send_result",
84
+ "house_digest_send",
85
+ "shepherd_send",
86
+ "react",
87
+ "coordinate",
88
+ ]);
89
+ /**
90
+ * The spoke record for a tool call that may message a person, or null for any other tool. `send_message` to `self`
91
+ * only queues work for the agent's own private runtime, so it reaches nobody.
92
+ */
93
+ function turnSpokeForTool(name, args, nowMs = Date.now()) {
94
+ if (!PERSON_MESSAGING_TOOLS.has(name))
95
+ return null;
96
+ if (name === "send_message" && args.friendId?.trim() === "self")
97
+ return null;
98
+ const text = args.content ?? args.message ?? args.caption ?? null;
99
+ return turnSpoke(`tool:${name}`, text, null, nowMs);
100
+ }
101
+ /**
102
+ * Notes each tool call that may message a person just before its handler runs: `started` remembers the call's
103
+ * arguments, and `dispatched` fires only for a call that passed its guards. A call refused before its handler sends
104
+ * nothing and is not noted. `onSpoke` may throw (a failed disk write), which stops the call before it runs.
105
+ */
106
+ function outwardSendTracker(onSpoke) {
107
+ // Tool calls in a turn run one at a time, so the last started call is the one being dispatched.
108
+ let last = null;
109
+ return {
110
+ started(name, args) {
111
+ last = { name, args };
112
+ },
113
+ dispatched(name) {
114
+ const args = last?.name === name ? last.args : {};
115
+ last = null;
116
+ const spoke = turnSpokeForTool(name, args);
117
+ if (spoke)
118
+ onSpoke(spoke);
119
+ },
120
+ };
121
+ }
122
+ function isState(value, id) {
123
+ if (!value || typeof value !== "object")
124
+ return false;
125
+ const record = value;
126
+ return record.schemaVersion === 1 && record.id === id && typeof record.attempts === "number" && Array.isArray(record.spoke);
127
+ }
128
+ function openTurnAttempts(agentRoot, sense, options = {}) {
129
+ const now = options.now ?? Date.now;
130
+ const dir = turnAttemptsDir(agentRoot, sense);
131
+ const filePath = (id) => path.join(dir, fileName(id));
132
+ const get = (id) => {
133
+ let parsed;
134
+ try {
135
+ parsed = JSON.parse(fs.readFileSync(filePath(id), "utf-8"));
136
+ }
137
+ catch {
138
+ return null;
139
+ }
140
+ return isState(parsed, id) ? parsed : null;
141
+ };
142
+ const write = (id, change) => {
143
+ const current = get(id) ?? { schemaVersion: 1, sense, id, attempts: 0, spoke: [], updatedAt: new Date(now()).toISOString() };
144
+ const next = { ...change(current), updatedAt: new Date(now()).toISOString() };
145
+ (0, atomic_file_1.writeJsonAtomicSync)(filePath(id), next);
146
+ return next;
147
+ };
148
+ return {
149
+ get,
150
+ beginAttempt(id) {
151
+ return write(id, (state) => ({ ...state, attempts: state.attempts + 1 })).attempts;
152
+ },
153
+ refundAttempt(id) {
154
+ if (!get(id))
155
+ return;
156
+ write(id, (state) => ({ ...state, attempts: Math.max(0, state.attempts - 1) }));
157
+ },
158
+ noteSpoke(id, spoke) {
159
+ const next = write(id, (state) => ({ ...state, spoke: [...state.spoke, spoke] }));
160
+ (0, runtime_1.emitNervesEvent)({
161
+ component: "senses",
162
+ event: "senses.turn_spoke_recorded",
163
+ message: "recorded a send before it reached the transport, so a replay does not repeat it",
164
+ meta: { sense, kind: spoke.kind, attempts: next.attempts, sends: next.spoke.length, outboundRecordId: spoke.outboundRecordId },
165
+ });
166
+ },
167
+ clear(id) {
168
+ fs.rmSync(filePath(id), { force: true });
169
+ },
170
+ };
171
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1425",
3
+ "version": "0.1.0-alpha.1427",
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.1425",
9
+ "version": "0.1.0-alpha.1427",
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.1425",
3
+ "version": "0.1.0-alpha.1427",
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": {