@ouro.bot/cli 0.1.0-alpha.1406 → 0.1.0-alpha.1407

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,12 @@
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.1407",
6
+ "changes": [
7
+ "Mail, app-session and other notices for the agent's own inner turn are no longer lost when that turn fails, is aborted, or its process dies. They stay on disk until the turn acts on them or its session is saved, then replay. A notice that fails three turns is set aside as `.json.failed`."
8
+ ]
9
+ },
4
10
  {
5
11
  "version": "0.1.0-alpha.1406",
6
12
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1406",
2
+ "runtimeVersion": "0.1.0-alpha.1407",
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.1406</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1407</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -331,6 +331,7 @@ function continuationCallbacks(callbacks, text) {
331
331
  },
332
332
  onReasoningChunk: callbacks.onReasoningChunk ?? noop,
333
333
  onToolStart: callbacks.onToolStart ?? noop,
334
+ ...(callbacks.onToolDispatch ? { onToolDispatch: callbacks.onToolDispatch } : {}),
334
335
  onToolEnd: callbacks.onToolEnd ?? noop,
335
336
  onError: callbacks.onError ?? noop,
336
337
  ...(callbacks.onClearText ? { onClearText: callbacks.onClearText } : {}),
@@ -1581,6 +1582,11 @@ async function runAgent(messages, callbacks, channel, signal, options) {
1581
1582
  selectCurrentTools,
1582
1583
  };
1583
1584
  const trustedToolContext = options?.toolContext || turnOrientationFrame || habitSession ? augmentedToolContext : undefined;
1585
+ // For one call: executeTool calls beforeHandler only once its guards pass, just before the handler runs.
1586
+ const withDispatchNotice = (context, name) => ({
1587
+ ...context,
1588
+ beforeHandler: () => callbacks.onToolDispatch?.(name),
1589
+ });
1584
1590
  unresolvedHistoricalEffects = historicalFailedEffectsForExactRepeatedRequest(messages, toolSelection);
1585
1591
  // Rebase provider-owned turn state from canonical messages at user-turn start.
1586
1592
  // This prevents stale provider caches from replaying prior-turn context.
@@ -2228,11 +2234,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2228
2234
  let terminalSucceeded = false;
2229
2235
  try {
2230
2236
  if (options?.execTool && !relationship) {
2237
+ callbacks.onToolDispatch?.(soleTerminalCall.name);
2231
2238
  terminalResult = await options.execTool(soleTerminalCall.name, terminalArgs, trustedToolContext);
2232
2239
  terminalSucceeded = true;
2233
2240
  }
2234
2241
  else {
2235
- const execution = await (0, tools_1.executeTool)(soleTerminalCall.name, terminalArgs, augmentedToolContext, options?.execTool);
2242
+ const execution = await (0, tools_1.executeTool)(soleTerminalCall.name, terminalArgs, withDispatchNotice(augmentedToolContext, soleTerminalCall.name), options?.execTool);
2236
2243
  terminalResult = "error" in execution
2237
2244
  ? `error: ${execution.error instanceof Error ? execution.error.message : String(execution.error)}`
2238
2245
  : execution.text;
@@ -2647,6 +2654,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2647
2654
  });
2648
2655
  continue;
2649
2656
  }
2657
+ callbacks.onToolDispatch?.("speak");
2650
2658
  callbacks.onTextChunk(speakMessage);
2651
2659
  let speakDeliveryError = null;
2652
2660
  try {
@@ -2685,6 +2693,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2685
2693
  const parsedArgs = normalizeLegacyPonderArgs(parsePonderPayload(tc.arguments));
2686
2694
  const argSummary = (0, tools_1.summarizeArgs)(tc.name, parsedArgs, toolSelection);
2687
2695
  callbacks.onToolStart(tc.name, parsedArgs);
2696
+ callbacks.onToolDispatch?.(tc.name);
2688
2697
  let toolResult;
2689
2698
  let success = false;
2690
2699
  try {
@@ -2860,11 +2869,12 @@ async function runAgent(messages, callbacks, channel, signal, options) {
2860
2869
  const executionToolContext = routineActionSelection && augmentedToolContext ? { ...augmentedToolContext, routineActionSelection } : augmentedToolContext;
2861
2870
  if (options?.execTool && !relationship) {
2862
2871
  invoked = true;
2872
+ callbacks.onToolDispatch?.(tc.name);
2863
2873
  toolResult = await options.execTool(tc.name, args, withToolImageSink(trustedToolContext));
2864
2874
  success = true;
2865
2875
  }
2866
2876
  else {
2867
- const execution = await (0, tools_1.executeTool)(tc.name, args, withToolImageSink(executionToolContext), options?.execTool);
2877
+ const execution = await (0, tools_1.executeTool)(tc.name, args, withToolImageSink(withDispatchNotice(executionToolContext, tc.name)), options?.execTool);
2868
2878
  invoked = execution.kind !== "rejected_before_handler";
2869
2879
  success = execution.kind === "handler_succeeded";
2870
2880
  toolResult = "error" in execution ? `error: ${execution.error}` : execution.text;
@@ -61,6 +61,7 @@ exports.preTurnPullAsync = preTurnPullAsync;
61
61
  exports.postTurnPush = postTurnPush;
62
62
  exports.syncNow = syncNow;
63
63
  const child_process_1 = require("child_process");
64
+ const termination_guard_1 = require("./termination-guard");
64
65
  const crypto_1 = require("crypto");
65
66
  const fs = __importStar(require("fs"));
66
67
  const path = __importStar(require("path"));
@@ -317,8 +318,8 @@ const inFlightChildren = new Set();
317
318
  const heldLocks = new Set();
318
319
  const TERMINATION_SIGNALS = ["SIGTERM", "SIGINT"];
319
320
  const terminationListeners = {
320
- SIGTERM: () => onTerminationSignal("SIGTERM"),
321
- SIGINT: () => onTerminationSignal("SIGINT"),
321
+ SIGTERM: (0, termination_guard_1.markTerminationGuard)(() => onTerminationSignal("SIGTERM")),
322
+ SIGINT: (0, termination_guard_1.markTerminationGuard)(() => onTerminationSignal("SIGINT")),
322
323
  };
323
324
  let guardInstalled = false;
324
325
  /**
@@ -352,7 +353,7 @@ function abortInFlightSync() {
352
353
  * other listener exists does it re-raise, restoring the default exit.
353
354
  */
354
355
  function onTerminationSignal(signal) {
355
- const others = process.rawListeners(signal).filter((listener) => listener !== terminationListeners[signal]);
356
+ const others = (0, termination_guard_1.signalHandlersBesidesGuards)(signal);
356
357
  abortInFlightSync();
357
358
  removeTerminationGuard();
358
359
  /* v8 ignore next -- re-raising ends the process; the SIGTERM child-process test covers it @preserve */
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.markTerminationGuard = markTerminationGuard;
4
+ exports.signalHandlersBesidesGuards = signalHandlersBesidesGuards;
5
+ const runtime_1 = require("../nerves/runtime");
6
+ /**
7
+ * Termination guards are signal listeners that clean up synchronously and then step aside, re-raising the signal
8
+ * only when nothing else handles it (sync's git children and locks, pending claims). Each must not count another
9
+ * guard as a handler of the signal, or two guards would each wait on the other and the process would never stop.
10
+ */
11
+ const TERMINATION_GUARD = Symbol.for("ouro.terminationGuard");
12
+ /** Mark a listener as a termination guard. */
13
+ function markTerminationGuard(listener) {
14
+ Object.defineProperty(listener, TERMINATION_GUARD, { value: true });
15
+ return listener;
16
+ }
17
+ /** The listeners for a signal that are not termination guards: the process's own handlers. */
18
+ function signalHandlersBesidesGuards(signal) {
19
+ const handlers = process.rawListeners(signal).filter((listener) => listener[TERMINATION_GUARD] !== true);
20
+ (0, runtime_1.emitNervesEvent)({
21
+ component: "heart",
22
+ event: "heart.termination_guard_signal",
23
+ message: handlers.length > 0 ? "stop signal: the process has its own shutdown, so termination guards step aside" : "stop signal: no shutdown of the process's own, so termination guards clean up and re-raise it",
24
+ meta: { signal, handlers: handlers.length },
25
+ });
26
+ return handlers;
27
+ }
@@ -42,6 +42,7 @@ exports.postTurn = postTurn;
42
42
  exports.postTurnTrim = postTurnTrim;
43
43
  exports.postTurnPersist = postTurnPersist;
44
44
  exports.deferPostTurnPersist = deferPostTurnPersist;
45
+ exports.deferPostTurnPersistOrThrow = deferPostTurnPersistOrThrow;
45
46
  exports.deleteSession = deleteSession;
46
47
  const config_1 = require("../heart/config");
47
48
  const session_events_1 = require("../heart/session-events");
@@ -513,11 +514,20 @@ function enqueueSessionPersist(sessPath, fn) {
513
514
  * in the saved session.
514
515
  */
515
516
  function deferPostTurnPersist(sessPath, prepared, usage, state, lease, expectedRevision) {
516
- return enqueueSessionPersist(sessPath, () => new Promise((resolve) => {
517
+ return deferPersist(sessPath, () => postTurnPersist(sessPath, prepared, usage, state, lease, expectedRevision), "resolve");
518
+ }
519
+ /**
520
+ * Deferred persist that rejects when the persist fails, for a caller that must know the turn was saved before it
521
+ * lets go of what the turn read (the private runtime's claimed pending notices).
522
+ */
523
+ function deferPostTurnPersistOrThrow(sessPath, prepared, usage, state) {
524
+ return deferPersist(sessPath, () => postTurnPersist(sessPath, prepared, usage, state), "reject");
525
+ }
526
+ function deferPersist(sessPath, persist, onError) {
527
+ return enqueueSessionPersist(sessPath, () => new Promise((resolve, reject) => {
517
528
  setImmediate(() => {
518
529
  try {
519
- const events = postTurnPersist(sessPath, prepared, usage, state, lease, expectedRevision);
520
- resolve(events);
530
+ resolve(persist());
521
531
  }
522
532
  catch (err) {
523
533
  (0, runtime_1.emitNervesEvent)({
@@ -527,7 +537,10 @@ function deferPostTurnPersist(sessPath, prepared, usage, state, lease, expectedR
527
537
  message: "deferred session persist failed",
528
538
  meta: { error: err instanceof Error ? err.message : String(err) },
529
539
  });
530
- resolve([]);
540
+ if (onError === "reject")
541
+ reject(err);
542
+ else
543
+ resolve([]);
531
544
  }
532
545
  });
533
546
  }));
@@ -33,13 +33,15 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.PRIVATE_RUNTIME_PENDING = void 0;
36
+ exports.MAX_PENDING_FAILED_TRIES = exports.PRIVATE_RUNTIME_PENDING = void 0;
37
37
  exports.getPendingDir = getPendingDir;
38
38
  exports.getDeferredReturnDir = getDeferredReturnDir;
39
39
  exports.getPrivateRuntimePendingDir = getPrivateRuntimePendingDir;
40
+ exports.releaseHeldPendingClaimsOnExit = releaseHeldPendingClaimsOnExit;
40
41
  exports.hasPendingMessages = hasPendingMessages;
41
42
  exports.queuePendingMessage = queuePendingMessage;
42
43
  exports.queuePendingMessageOnce = queuePendingMessageOnce;
44
+ exports.claimPending = claimPending;
43
45
  exports.enqueueDeferredReturn = enqueueDeferredReturn;
44
46
  exports.drainDeferredReturns = drainDeferredReturns;
45
47
  exports.withdrawDeferredReturn = withdrawDeferredReturn;
@@ -48,8 +50,10 @@ const fs = __importStar(require("fs"));
48
50
  const path = __importStar(require("path"));
49
51
  const node_crypto_1 = require("node:crypto");
50
52
  const identity_1 = require("../heart/identity");
53
+ const atomic_file_1 = require("../heart/atomic-file");
51
54
  const session_events_1 = require("../heart/session-events");
52
55
  const runtime_1 = require("../nerves/runtime");
56
+ const termination_guard_1 = require("../heart/termination-guard");
53
57
  function getPendingDir(agentName, friendId, channel, key, agentRoot = (0, identity_1.getAgentRoot)(agentName)) {
54
58
  return path.join(agentRoot, "state", "pending", friendId, channel, key);
55
59
  }
@@ -62,11 +66,91 @@ exports.PRIVATE_RUNTIME_PENDING = { friendId: "self", channel: "inner", key: "di
62
66
  function getPrivateRuntimePendingDir(agentName, agentRoot) {
63
67
  return getPendingDir(agentName, exports.PRIVATE_RUNTIME_PENDING.friendId, exports.PRIVATE_RUNTIME_PENDING.channel, exports.PRIVATE_RUNTIME_PENDING.key, agentRoot);
64
68
  }
69
+ /** A message a turn has claimed: still on disk, under a name no other reader takes. */
70
+ const CLAIMED_SUFFIX = ".json.claimed";
71
+ /** What drainPending renames a message to while it reads it; a crash can leave one behind. */
72
+ const DRAIN_PROCESSING_SUFFIX = ".json.processing";
73
+ /** Messages a turn in this process has claimed and not yet settled or released, by claimed path. */
74
+ const heldClaims = new Map();
75
+ /** Claimed paths a turn in this process settled but could not delete: never read again, deleted when possible. */
76
+ const settledClaims = new Set();
77
+ /** Put a claim back for the next turn; `counted` writes the try against it first, so a crash between counts it once. */
78
+ function putBack(claimedPath, held, counted) {
79
+ if (counted) {
80
+ (0, atomic_file_1.writeJsonAtomicSync)(held.unclaimedPath, { ...held.message, failedTries: held.failedTries + 1 });
81
+ fs.unlinkSync(claimedPath);
82
+ }
83
+ else {
84
+ fs.renameSync(claimedPath, held.unclaimedPath);
85
+ }
86
+ }
87
+ /**
88
+ * Puts back every claim this process still holds at exit. A clean exit (a shutdown, process.exit(0)) is not the
89
+ * messages' fault, so it counts no try; a failing exit (an uncaught exception exits 1) may be, so it counts one.
90
+ * A crash that skips exit handlers leaves its claims behind, and the next claim counts them.
91
+ */
92
+ function releaseHeldPendingClaimsOnExit(code = 0) {
93
+ for (const [claimedPath, held] of heldClaims) {
94
+ heldClaims.delete(claimedPath);
95
+ try {
96
+ putBack(claimedPath, held, code !== 0);
97
+ }
98
+ catch { /* the next claim reads it as left by a crash */ }
99
+ }
100
+ }
101
+ const STOP_SIGNALS = ["SIGTERM", "SIGINT"];
102
+ const stopListeners = {
103
+ SIGTERM: (0, termination_guard_1.markTerminationGuard)(() => onStopSignal("SIGTERM")),
104
+ SIGINT: (0, termination_guard_1.markTerminationGuard)(() => onStopSignal("SIGINT")),
105
+ };
106
+ /**
107
+ * A signal's default action ends the process without running exit handlers, which would leave every held claim to
108
+ * be counted as a crash. When nothing else handles the signal, put the claims back uncounted and re-raise it. When
109
+ * the process has its own shutdown, leave the claims to it: its turns may still settle them, and its exit puts back
110
+ * the rest.
111
+ */
112
+ function onStopSignal(signal) {
113
+ if ((0, termination_guard_1.signalHandlersBesidesGuards)(signal).length > 0)
114
+ return;
115
+ releaseHeldPendingClaimsOnExit(0);
116
+ for (const each of STOP_SIGNALS)
117
+ process.removeListener(each, stopListeners[each]);
118
+ process.kill(process.pid, signal);
119
+ }
120
+ function installExitHandlers() {
121
+ if (process.listeners("exit").includes(releaseHeldPendingClaimsOnExit))
122
+ return;
123
+ process.on("exit", releaseHeldPendingClaimsOnExit);
124
+ for (const signal of STOP_SIGNALS)
125
+ process.prependListener(signal, stopListeners[signal]);
126
+ }
127
+ /** Delete a settled message's files; true once nothing of it is left. */
128
+ function deleteSettled(pendingDir, claimedPath, stem) {
129
+ try {
130
+ fs.rmSync(claimedPath, { force: true });
131
+ // A copy queued again while the turn held it is the same message.
132
+ fs.rmSync(path.join(pendingDir, `${stem}.json`), { force: true });
133
+ fs.rmSync(path.join(pendingDir, `${stem}${DRAIN_PROCESSING_SUFFIX}`), { force: true });
134
+ settledClaims.delete(claimedPath);
135
+ return true;
136
+ }
137
+ catch (error) {
138
+ settledClaims.add(claimedPath);
139
+ (0, runtime_1.emitNervesEvent)({ level: "warn", event: "mind.pending_settle_error", component: "mind", message: "could not delete a settled pending message; this process will not read it again, and deletes it later", meta: { pendingDir, error: errorMessage(error) } });
140
+ return false;
141
+ }
142
+ }
143
+ /** How long a writer may still be writing a file that does not parse yet (queuePendingMessage writes in place). */
144
+ const UNREADABLE_GRACE_MS = 60_000;
145
+ function isUnheldClaim(pendingDir, name) {
146
+ const claimedPath = path.join(pendingDir, name);
147
+ return name.endsWith(CLAIMED_SUFFIX) && !heldClaims.has(claimedPath) && !settledClaims.has(claimedPath);
148
+ }
65
149
  function hasPendingMessages(pendingDir) {
66
150
  if (!fs.existsSync(pendingDir))
67
151
  return false;
68
152
  try {
69
- return fs.readdirSync(pendingDir).some((entry) => entry.endsWith(".json") || entry.endsWith(".json.processing"));
153
+ return fs.readdirSync(pendingDir).some((entry) => entry.endsWith(".json") || entry.endsWith(DRAIN_PROCESSING_SUFFIX) || isUnheldClaim(pendingDir, entry));
70
154
  }
71
155
  catch {
72
156
  return false;
@@ -151,6 +235,150 @@ function drainQueue(queueDir) {
151
235
  recovered: processingFiles.length,
152
236
  };
153
237
  }
238
+ /** How many tries that threw or died may read a pending message before it is set aside as failed. */
239
+ exports.MAX_PENDING_FAILED_TRIES = 3;
240
+ function pendingStem(name) {
241
+ return name.slice(0, name.lastIndexOf(".json"));
242
+ }
243
+ /**
244
+ * Take a queue's messages for one turn without deleting them. Each is renamed to `.json.claimed` and deleted only
245
+ * by `settle()`, once the turn has handled it; `release()` renames it back. A claimed file that no turn in this
246
+ * process holds was left by a process that died mid-turn: it is read again and counted as a failed try. After
247
+ * MAX_PENDING_FAILED_TRIES failed tries the message is set aside as `.json.failed`, so it cannot fail every later turn.
248
+ */
249
+ function claimPending(pendingDir) {
250
+ installExitHandlers();
251
+ let held = [];
252
+ const releaseHeld = (failed) => {
253
+ for (const entry of held) {
254
+ const claim = heldClaims.get(entry.claimedPath);
255
+ // Already put back by the exit hook.
256
+ if (!claim)
257
+ continue;
258
+ heldClaims.delete(entry.claimedPath);
259
+ try {
260
+ putBack(entry.claimedPath, claim, failed);
261
+ }
262
+ catch (error) {
263
+ (0, runtime_1.emitNervesEvent)({ level: "warn", event: "mind.pending_release_error", component: "mind", message: "could not put a claimed pending message back; the next turn reads it as left by a crash", meta: { pendingDir, error: errorMessage(error) } });
264
+ }
265
+ }
266
+ held = [];
267
+ };
268
+ try {
269
+ let entries = [];
270
+ try {
271
+ entries = fs.readdirSync(pendingDir);
272
+ }
273
+ catch {
274
+ entries = [];
275
+ }
276
+ const names = entries
277
+ .filter((name) => name.endsWith(".json") || name.endsWith(CLAIMED_SUFFIX) || name.endsWith(DRAIN_PROCESSING_SUFFIX))
278
+ .sort((a, b) => a.localeCompare(b));
279
+ for (const name of names) {
280
+ const stem = pendingStem(name);
281
+ const claimedPath = path.join(pendingDir, `${stem}${CLAIMED_SUFFIX}`);
282
+ // Held by a turn in this process, or a fresh copy of a message that is.
283
+ if (heldClaims.has(claimedPath))
284
+ continue;
285
+ // Settled here already: what its turn did must not happen again. Finish deleting it.
286
+ if (settledClaims.has(claimedPath)) {
287
+ deleteSettled(pendingDir, claimedPath, stem);
288
+ continue;
289
+ }
290
+ const leftByCrash = !name.endsWith(".json");
291
+ if (name !== `${stem}${CLAIMED_SUFFIX}`) {
292
+ // A copy of a crash leftover is taken under the leftover's own name.
293
+ if (fs.existsSync(claimedPath))
294
+ continue;
295
+ try {
296
+ fs.renameSync(path.join(pendingDir, name), claimedPath);
297
+ }
298
+ catch {
299
+ // Another reader took it first.
300
+ continue;
301
+ }
302
+ }
303
+ const setAside = () => {
304
+ try {
305
+ fs.renameSync(claimedPath, path.join(pendingDir, `${stem}.json.failed`));
306
+ return true;
307
+ }
308
+ catch (error) {
309
+ (0, runtime_1.emitNervesEvent)({ level: "warn", event: "mind.pending_set_aside_error", component: "mind", message: "could not set aside a pending message; a later turn tries again", meta: { pendingDir, file: name, error: errorMessage(error) } });
310
+ return false;
311
+ }
312
+ };
313
+ let stored;
314
+ try {
315
+ const parsed = JSON.parse(fs.readFileSync(claimedPath, "utf-8"));
316
+ // Valid JSON that is not a message (null, a number, a list) is as unreadable as a torn file.
317
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
318
+ throw new Error("not a pending message");
319
+ stored = parsed;
320
+ }
321
+ catch (error) {
322
+ // A fresh file may still be being written: leave it for a later turn. One that stays unreadable, or that a
323
+ // crash left mid-read, is kept as .json.failed for a person to look at, never deleted.
324
+ // A file that is gone (a link to nothing, say) has no age; it is set aside like an old one.
325
+ const stat = fs.statSync(claimedPath, { throwIfNoEntry: false });
326
+ const recent = !leftByCrash && stat !== undefined && Date.now() - stat.mtimeMs < UNREADABLE_GRACE_MS;
327
+ if (recent) {
328
+ try {
329
+ fs.renameSync(claimedPath, path.join(pendingDir, name));
330
+ }
331
+ catch { /* left claimed; the next claim reads it as a leftover */ }
332
+ }
333
+ else if (setAside()) {
334
+ (0, runtime_1.emitNervesEvent)({ level: "error", event: "mind.pending_message_unreadable", component: "mind", message: "set aside a pending message nobody can read; it is kept as .json.failed", meta: { pendingDir, file: name, error: errorMessage(error) } });
335
+ }
336
+ continue;
337
+ }
338
+ const { failedTries: earlierFailedTries, ...message } = stored;
339
+ const failedTries = (earlierFailedTries ?? 0) + (leftByCrash ? 1 : 0);
340
+ if (failedTries >= exports.MAX_PENDING_FAILED_TRIES) {
341
+ if (setAside())
342
+ (0, runtime_1.emitNervesEvent)({ level: "error", event: "mind.pending_message_failed", component: "mind", message: "set aside a pending message that no turn finished; it is kept as .json.failed", meta: { pendingDir, file: name, failedTries } });
343
+ continue;
344
+ }
345
+ if (leftByCrash) {
346
+ try {
347
+ (0, atomic_file_1.writeJsonAtomicSync)(claimedPath, { ...message, failedTries });
348
+ }
349
+ catch {
350
+ // The count did not land, so the next claim counts this try again; better than not reading it now.
351
+ }
352
+ }
353
+ heldClaims.set(claimedPath, { unclaimedPath: path.join(pendingDir, `${stem}.json`), message, failedTries });
354
+ held.push({ claimedPath, stem, message, failedTries });
355
+ }
356
+ (0, runtime_1.emitNervesEvent)({ event: "mind.pending_claimed", component: "mind", message: "pending messages claimed for a turn", meta: { pendingDir, count: held.length } });
357
+ }
358
+ catch (error) {
359
+ releaseHeld(false);
360
+ throw error;
361
+ }
362
+ const messages = held.map((entry) => entry.message);
363
+ return {
364
+ messages,
365
+ settle(only) {
366
+ const done = only ? held.filter((entry) => only.includes(entry.message)) : held;
367
+ held = held.filter((entry) => !done.includes(entry));
368
+ for (const entry of done) {
369
+ if (!heldClaims.delete(entry.claimedPath))
370
+ continue;
371
+ deleteSettled(pendingDir, entry.claimedPath, entry.stem);
372
+ }
373
+ },
374
+ release(options) {
375
+ releaseHeld(options?.failed === true);
376
+ },
377
+ };
378
+ }
379
+ function errorMessage(error) {
380
+ return error instanceof Error ? error.message : /* v8 ignore next -- defensive non-Error throw branch @preserve */ String(error);
381
+ }
154
382
  function enqueueDeferredReturn(agentName, friendId, message) {
155
383
  const queueDir = getDeferredReturnDir(agentName, friendId);
156
384
  const filePath = writeQueueFile(queueDir, message);
@@ -164,7 +164,8 @@ class McpManager {
164
164
  server: entry.name, tools: structuredClone(entry.cachedTools), pluginId: entry.pluginId,
165
165
  }));
166
166
  }
167
- async callTool(binding, args, ownerInput) {
167
+ /** `beforeCall` runs once the binding is current and its server connected, just before the call goes to the server. */
168
+ async callTool(binding, args, ownerInput, beforeCall) {
168
169
  const owner = captureOwner(ownerInput);
169
170
  const call = await this.enqueue(async () => {
170
171
  let entry = this.currentBinding(binding, owner);
@@ -174,6 +175,7 @@ class McpManager {
174
175
  if (!entry.client.isConnected())
175
176
  throw new mcp_tools_1.McpCallRejectedError(`Server "${entry.name}" is disconnected`);
176
177
  }
178
+ beforeCall?.();
177
179
  return { entry, result: entry.client.callTool(binding.rawName, args) };
178
180
  });
179
181
  try {
@@ -142,7 +142,7 @@ function mcpToolsAsDefinitions(view) {
142
142
  if (guarded.rejected !== undefined)
143
143
  throw new McpCallRejectedError(guarded.rejected);
144
144
  try {
145
- const result = await view.manager.callTool(binding, guarded.args, { agentName: ctx.agentName, agentRoot: ctx.agentRoot });
145
+ const result = await view.manager.callTool(binding, guarded.args, { agentName: ctx.agentName, agentRoot: ctx.agentRoot }, ctx.beforeHandler);
146
146
  const { text, images } = splitMcpContent(result.content);
147
147
  if (result.isError === true) {
148
148
  throw new McpToolExecutionError("handler_failed", `[mcp error] ${entry.server}/${tool.name}: ${text}`);
@@ -566,6 +566,9 @@ async function executeTool(name, args, ctx, executor) {
566
566
  },
567
567
  }
568
568
  : authorizedContext;
569
+ // An MCP tool runs its own owner, argument and connection checks inside its handler; it says when the call goes out.
570
+ if (!def.mcpBinding)
571
+ toolContext?.beforeHandler?.();
569
572
  try {
570
573
  const result = await (executor ? executor(name, args, toolContext) : def.handler(args, toolContext));
571
574
  (0, runtime_1.emitNervesEvent)({
@@ -808,6 +808,10 @@ async function handleInboundTurnExclusive(input) {
808
808
  let syncConfig = { enabled: false, remote: "origin" };
809
809
  const liveLatencyMode = input.latencyMode === "live";
810
810
  let declinedForHome = false;
811
+ let pendingClaim;
812
+ let turnActed = false;
813
+ let turnThrew = false;
814
+ let turnFailedOnMessages = false;
811
815
  try {
812
816
  syncConfig = (0, config_1.getSyncConfig)();
813
817
  }
@@ -891,7 +895,8 @@ async function handleInboundTurnExclusive(input) {
891
895
  const deferredReturns = input.channel === "inner"
892
896
  ? []
893
897
  : (input.drainDeferredReturns?.(resolvedContext.friend.id) ?? []);
894
- const sessionPending = input.drainPending(input.pendingDir);
898
+ pendingClaim = input.claimPending?.(input.pendingDir);
899
+ const sessionPending = pendingClaim ? pendingClaim.messages : input.drainPending(input.pendingDir);
895
900
  // A deferred return was saved for the friend's next message, whenever that comes, so a
896
901
  // sense's freshness window for its own pending never drops it.
897
902
  const pending = [
@@ -902,6 +907,25 @@ async function handleInboundTurnExclusive(input) {
902
907
  messages: sessionPending,
903
908
  }),
904
909
  ];
910
+ // Expired messages were archived just now; reading them again next turn would archive them again.
911
+ const expiredPending = sessionPending.filter((message) => !pending.includes(message));
912
+ if (expiredPending.length > 0)
913
+ pendingClaim?.settle(expiredPending);
914
+ // A turn whose tool call reaches its handler may act on its pending messages, so they are settled just before it
915
+ // runs: a retry in this process or after a crash or shutdown must not read them again and repeat what the tool
916
+ // did. A call refused before its handler, or a find_tools lookup, has done nothing, so it settles nothing.
917
+ const turnCallbacks = pendingClaim
918
+ ? {
919
+ ...input.callbacks,
920
+ onToolDispatch(name) {
921
+ if (!turnActed) {
922
+ turnActed = true;
923
+ pendingClaim?.settle();
924
+ }
925
+ input.callbacks.onToolDispatch?.(name);
926
+ },
927
+ }
928
+ : input.callbacks;
905
929
  const promotedPendingUserMessages = input.channel === "inner"
906
930
  ? pending
907
931
  .filter((message) => message.from === "ouro-cli" && message.content.trim().length > 0)
@@ -1087,7 +1111,7 @@ async function handleInboundTurnExclusive(input) {
1087
1111
  }));
1088
1112
  let result;
1089
1113
  try {
1090
- result = await input.runAgent(sessionMessages, input.callbacks, input.channel, input.signal, runAgentOptions);
1114
+ result = await input.runAgent(sessionMessages, turnCallbacks, input.channel, input.signal, runAgentOptions);
1091
1115
  }
1092
1116
  catch (error) {
1093
1117
  if (runLedger)
@@ -1141,9 +1165,22 @@ async function handleInboundTurnExclusive(input) {
1141
1165
  ...(result.error ? { errorName: result.error.name } : {}),
1142
1166
  ...(result.errorClassification ? { errorCode: result.errorClassification } : {}),
1143
1167
  }));
1168
+ // The turn reached its end: once postTurn has run, its pending messages are handled. A turn that errored, was
1169
+ // aborted or was superseded (a provider outage, a shutdown, a newer message) never got to them unless it acted.
1170
+ const turnFinished = result.outcome !== "errored" && result.outcome !== "aborted" && result.outcome !== "superseded";
1171
+ // An error the provider did not classify may come from the messages themselves (one too large for the evidence
1172
+ // budget, say), so it counts against them; outages, limits and auth failures do not.
1173
+ turnFailedOnMessages = result.outcome === "errored" && result.errorClassification === "unknown";
1174
+ const persistTurn = async (...args) => {
1175
+ await input.postTurn(...args);
1176
+ if (turnFinished)
1177
+ pendingClaim?.settle();
1178
+ };
1144
1179
  if (result.outcome === "suspended") {
1145
1180
  if (!result.suspension)
1146
1181
  throw new Error("suspended agent turn omitted durable approval suspension");
1182
+ // The suspension checkpoint holds the turn, pending messages included.
1183
+ pendingClaim?.settle();
1147
1184
  (0, runtime_1.emitNervesEvent)({
1148
1185
  component: "senses",
1149
1186
  event: "senses.pipeline_approval_suspended",
@@ -1180,7 +1217,7 @@ async function handleInboundTurnExclusive(input) {
1180
1217
  mustResolveBeforeHandoff,
1181
1218
  lastFriendActivityAt,
1182
1219
  });
1183
- await input.postTurn(sessionMessages, session.sessionPath, result.usage, undefined, failoverNextState);
1220
+ await persistTurn(sessionMessages, session.sessionPath, result.usage, undefined, failoverNextState);
1184
1221
  try {
1185
1222
  const agentRoot = (0, identity_1.getAgentRoot)();
1186
1223
  const postTurnArc = readPostTurnFlightRecorderArcSnapshot(agentRoot);
@@ -1249,7 +1286,7 @@ async function handleInboundTurnExclusive(input) {
1249
1286
  mustResolveBeforeHandoff,
1250
1287
  lastFriendActivityAt,
1251
1288
  });
1252
- await input.postTurn(sessionMessages, session.sessionPath, result.usage, undefined, nextState);
1289
+ await persistTurn(sessionMessages, session.sessionPath, result.usage, undefined, nextState);
1253
1290
  try {
1254
1291
  const agentRoot = (0, identity_1.getAgentRoot)();
1255
1292
  const postTurnArc = readPostTurnFlightRecorderArcSnapshot(agentRoot);
@@ -1307,7 +1344,14 @@ async function handleInboundTurnExclusive(input) {
1307
1344
  ...(result.outcome === "errored" && input.channel !== "inner" && input.channel !== "cli" ? { failoverMessage: erroredTurnReply(result.error?.message) } : {}),
1308
1345
  };
1309
1346
  }
1347
+ catch (error) {
1348
+ turnThrew = true;
1349
+ throw error;
1350
+ }
1310
1351
  finally {
1352
+ // Pending messages a turn did not handle go back for the next turn; a throw or an unclassified error counts
1353
+ // against them. After the first tool start the claim holds nothing, so this is a no-op.
1354
+ pendingClaim?.release({ failed: turnThrew || turnFailedOnMessages });
1311
1355
  // Step 6b: Post-turn sync (opt-in). The commit is synchronous, so the
1312
1356
  // turn's edits are recorded before the reply goes out; the push runs on
1313
1357
  // without being awaited, holding the lock, and records its own failure.
@@ -1536,10 +1536,13 @@ async function runPrivateRuntimeTurn(options) {
1536
1536
  friendStore: createNoOpFriendStore(),
1537
1537
  enforceTrustGate: trust_gate_1.enforceTrustGate,
1538
1538
  drainPending: pending_1.drainPending,
1539
+ // Mail, app-session and other notices stay on disk until the turn that read them is persisted.
1540
+ claimPending: pending_1.claimPending,
1539
1541
  runAgent: core_1.runAgent,
1540
1542
  postTurn: (turnMessages, sessionPathArg, usage, hooks, state) => {
1541
1543
  const prepared = (0, context_1.postTurnTrim)(turnMessages, usage, hooks);
1542
- return (0, context_1.deferPostTurnPersist)(sessionPathArg, prepared, usage, state);
1544
+ // A failed persist must reject, so the claimed notices go back instead of being settled as handled.
1545
+ return (0, context_1.deferPostTurnPersistOrThrow)(sessionPathArg, prepared, usage, state);
1543
1546
  },
1544
1547
  accumulateFriendTokens: friends_1.accumulateFriendTokens,
1545
1548
  signal: options?.signal,
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1406",
3
+ "version": "0.1.0-alpha.1407",
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.1406",
9
+ "version": "0.1.0-alpha.1407",
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.1406",
3
+ "version": "0.1.0-alpha.1407",
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": {