@ouro.bot/cli 0.1.0-alpha.1390 → 0.1.0-alpha.1392

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": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1392",
6
+ "changes": [
7
+ "A2A records every inbound before its turn, ends it in one recorded outcome, and lets cancel and shutdown stop the turn."
8
+ ]
9
+ },
4
10
  {
5
11
  "version": "0.1.0-alpha.1390",
6
12
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1390",
2
+ "runtimeVersion": "0.1.0-alpha.1392",
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.1390</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1392</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.ESCALATION_CONFIRM_INTERVAL_MS = void 0;
36
+ exports.ESCALATION_CONFIRM_INTERVAL_MS = exports.A2A_TURN_TIMEOUT_MS = void 0;
37
37
  exports.a2aChatRelationship = a2aChatRelationship;
38
38
  exports.commandIdFor = commandIdFor;
39
39
  exports.startA2AServer = startA2AServer;
@@ -44,6 +44,7 @@ const friends_1 = require("@ouro.bot/friends");
44
44
  const identity_1 = require("../heart/identity");
45
45
  const runtime_1 = require("../nerves/runtime");
46
46
  const shared_turn_1 = require("../senses/shared-turn");
47
+ const inbound_journal_1 = require("../senses/inbound-journal");
47
48
  const card_1 = require("./card");
48
49
  const config_1 = require("./config");
49
50
  const pin_store_1 = require("./pin-store");
@@ -64,7 +65,20 @@ const outbox_wire_1 = require("./outbox-wire");
64
65
  const failure_reports_1 = require("../heart/failure-reports");
65
66
  const MAX_A2A_REQUEST_BYTES = 128 * 1024;
66
67
  const MAX_A2A_MESSAGE_TEXT_CHARS = 16_000;
68
+ /** How long one A2A turn may run before it is stopped and recorded as failed: the iMessage turn deadline. */
69
+ exports.A2A_TURN_TIMEOUT_MS = 10 * 60_000;
67
70
  exports.ESCALATION_CONFIRM_INTERVAL_MS = 5 * 60 * 1000;
71
+ class A2ATurnStopped extends Error {
72
+ reason;
73
+ constructor(reason) {
74
+ super(`A2A turn stopped: ${reason}`);
75
+ this.reason = reason;
76
+ }
77
+ }
78
+ /** The direct sender's view when the process stops mid-turn: the old HTTP reply is gone, so the message is not run again. */
79
+ const STOPPED_BEFORE_ANSWERING = "the agent stopped before answering this message; send it again";
80
+ /** What a message that arrives during shutdown hears. It is recorded, so the next process replays it or records why not. */
81
+ const AGENT_RESTARTING = "the agent is restarting and did not run this message yet";
68
82
  class A2ARequestError extends Error {
69
83
  status;
70
84
  code;
@@ -163,6 +177,9 @@ async function defaultTurnRunner(input) {
163
177
  sessionKey: input.sessionKey,
164
178
  userMessage: input.message,
165
179
  latencyMode: "standard",
180
+ // The server records the outcome of a turn it stops itself, so a stopped turn leaves the queue at once.
181
+ ...(input.signal ? { signal: input.signal, stopQueueWaitOnAbort: true } : {}),
182
+ onTurnStart: input.onTurnStart,
166
183
  identity: {
167
184
  provider: "a2a-agent",
168
185
  externalId: input.peerAgentId,
@@ -197,8 +214,11 @@ function a2aChatRelationship(agentRoot, friend, requestId) {
197
214
  function accessTokenHash(accessToken) {
198
215
  return (0, node_crypto_1.createHash)("sha256").update(accessToken).digest("hex");
199
216
  }
217
+ function tokenHashScope(tokenHash) {
218
+ return `a2a-task-token:${tokenHash}`;
219
+ }
200
220
  function accessTokenScope(accessToken) {
201
- return `a2a-task-token:${accessTokenHash(accessToken)}`;
221
+ return tokenHashScope(accessTokenHash(accessToken));
202
222
  }
203
223
  function untrustedTurnPeerExternalId() {
204
224
  return "unauthenticated-a2a-peer";
@@ -377,7 +397,7 @@ function taskFor(input) {
377
397
  ...input.previousTask?.metadata,
378
398
  a2a: {
379
399
  ...previousA2A,
380
- accessTokenHash: accessTokenHash(input.accessToken),
400
+ accessTokenHash: input.accessTokenHash,
381
401
  ...(input.clientTaskId ? { clientTaskId: input.clientTaskId } : {}),
382
402
  },
383
403
  },
@@ -398,6 +418,15 @@ async function startA2AServer(options) {
398
418
  /* v8 ignore next -- foreground CLI/default daemon paths own the ambient agent-root fallback; protocol tests inject an isolated root @preserve */
399
419
  const agentRoot = options.agentRoot ?? (0, identity_1.getAgentRoot)(options.agentName);
400
420
  const taskStore = new task_store_1.FileA2ATaskStore(agentRoot);
421
+ const journal = (0, inbound_journal_1.openInboundJournal)(agentRoot, "a2a");
422
+ // Taken before the server listens: anything journaled after this belongs to this process's own live turns.
423
+ const leftOver = journal.pending();
424
+ const turnTimeoutMs = options.turnTimeoutMs ?? exports.A2A_TURN_TIMEOUT_MS;
425
+ /** In-flight turns, so CancelTask and shutdown can stop them. */
426
+ const activeTurns = new Set();
427
+ // Set by close(): from then on nothing new starts, so a shutdown never spends attempts on turns it would kill.
428
+ let closing = false;
429
+ const activeTaskKey = (taskId, tokenScope) => `${tokenScope}\n${taskId}`;
401
430
  /* v8 ignore next -- default runner crosses into the full live agent pipeline; shared-turn covers that pipeline and server tests inject a deterministic runner @preserve */
402
431
  const turnRunner = options.turnRunner ?? defaultTurnRunner;
403
432
  // The inbound friends-DataPart bridge is available only when the agent has a
@@ -433,7 +462,7 @@ async function startA2AServer(options) {
433
462
  };
434
463
  // The message/send branch as one function, so a sealed message that arrives through the relay inbox runs exactly the
435
464
  // path a direct POST runs. `req` is absent for a relayed message: there are no HTTP headers to take a sender hint from.
436
- const handleMessageSend = async (rpc, req) => {
465
+ const handleMessageSend = async (rpc, req, origin = "direct") => {
437
466
  const responseStyle = rpc.method === "message/send" ? "legacy" : "latest";
438
467
  const parsedInbound = messageFromParams(rpc.params);
439
468
  const inbound = parsedInbound ? { ...parsedInbound, kind: parsedInbound.kind ?? "message" } : null;
@@ -465,7 +494,7 @@ async function startA2AServer(options) {
465
494
  const contextId = inbound.contextId ?? "default";
466
495
  const taskId = (0, node_crypto_1.randomUUID)();
467
496
  const accessToken = (0, node_crypto_1.randomUUID)();
468
- const ackTask = taskFor({ taskId, accessToken, contextId, inbound, state: "TASK_STATE_COMPLETED", response: ackText });
497
+ const ackTask = taskFor({ taskId, accessTokenHash: accessTokenHash(accessToken), contextId, inbound, state: "TASK_STATE_COMPLETED", response: ackText });
469
498
  taskStore.put(ackTask, accessTokenScope(accessToken));
470
499
  return jsonResponse(rpc.id, publicTask(ackTask, accessToken, responseStyle, true));
471
500
  }
@@ -526,18 +555,85 @@ async function startA2AServer(options) {
526
555
  const contextId = inbound.contextId ?? continuationTask?.contextId ?? "default";
527
556
  const taskId = continuationTask?.id ?? (0, node_crypto_1.randomUUID)();
528
557
  const accessToken = continuationToken && continuationTask ? continuationToken : (0, node_crypto_1.randomUUID)();
529
- const tokenScope = accessTokenScope(accessToken);
530
558
  const clientTaskId = continuationTask ? taskA2AMetadata(continuationTask).clientTaskId : inbound.taskId;
531
- let relationshipAuthorization = verifiedChat?.friend
532
- ? a2aChatRelationship(agentRoot, verifiedChat.friend, taskId)
533
- : undefined;
534
- let turnText = text;
535
- let delegatedCommand;
559
+ const record = {
560
+ origin,
561
+ responseStyle,
562
+ taskId,
563
+ accessTokenHash: accessTokenHash(accessToken),
564
+ contextId,
565
+ inbound,
566
+ ...(clientTaskId ? { clientTaskId } : {}),
567
+ ...(continuationTask ? { previousTask: continuationTask } : {}),
568
+ peerAgentId,
569
+ peerName,
570
+ text,
571
+ // Absent fields drop out when the record is written as JSON.
572
+ ...(verifiedChat ? { verifiedChat: { did: verifiedChat.did, friendId: verifiedChat.friend?.id, onBehalfOf: verifiedChat.onBehalfOf, bindingId: verifiedChat.bindingId, issuedAt: verifiedChat.issuedAt } } : {}),
573
+ };
574
+ // Written down before anything runs, so a process that dies from here on leaves it pending, not lost.
575
+ const inboundId = (0, node_crypto_1.randomUUID)();
576
+ journal.record(inboundId, record);
577
+ return runInboundTurn(rpc.id, inboundId, record, { accessToken, friend: verifiedChat?.friend });
578
+ };
579
+ /**
580
+ * Record a visible failure for an inbound: the task ends FAILED with the reason, then the journal records the
581
+ * outcome. The journal entry is settled even when the task cannot be written, so it is never left pending for the
582
+ * life of the process.
583
+ */
584
+ const recordFailure = (inboundId, record, detail) => {
585
+ if (!journal.get(inboundId))
586
+ return;
587
+ const task = taskFor({
588
+ taskId: record.taskId,
589
+ accessTokenHash: record.accessTokenHash,
590
+ contextId: record.contextId,
591
+ inbound: record.inbound,
592
+ state: "TASK_STATE_FAILED",
593
+ response: detail,
594
+ clientTaskId: record.clientTaskId,
595
+ previousTask: record.previousTask,
596
+ });
597
+ try {
598
+ taskStore.put(task, tokenHashScope(record.accessTokenHash));
599
+ }
600
+ catch (error) {
601
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "channels", event: "channel.a2a_failed_task_write_error", message: "could not write an A2A message's FAILED task; its failure is still recorded", meta: { agentName: options.agentName, inboundId, error: error instanceof Error ? error.message : /* v8 ignore next -- defensive non-Error throw branch @preserve */ String(error) } });
602
+ }
603
+ journal.settle(inboundId, "failed", detail);
604
+ };
605
+ const failureResponse = (rpcId, record, message, accessToken) =>
606
+ // A replay has no token and no one waiting; an absent token drops out of the JSON.
607
+ errorResponse(rpcId, -32000, message, { taskId: record.taskId, state: "TASK_STATE_FAILED", accessToken });
608
+ /**
609
+ * Run (or replay) one journaled inbound to its one outcome. `accessToken` is known only to the live request that
610
+ * minted it; a replay has no one waiting on its reply.
611
+ */
612
+ const runInboundTurn = async (rpcId, inboundId, record, context) => {
613
+ if (closing) {
614
+ // Recorded but not started, with no attempt spent: the next process replays it or records why not.
615
+ return errorResponse(rpcId, -32000, AGENT_RESTARTING);
616
+ }
617
+ try {
618
+ return await runRecordedInbound(rpcId, inboundId, record, context);
619
+ }
620
+ catch (error) {
621
+ // Anything that throws before or around the turn still ends the inbound in a recorded failure.
622
+ const detail = error instanceof Error ? error.message : /* v8 ignore next -- defensive non-Error throw branch @preserve */ String(error);
623
+ recordFailure(inboundId, record, detail);
624
+ return failureResponse(rpcId, record, detail, context.accessToken);
625
+ }
626
+ };
627
+ const runRecordedInbound = async (rpcId, inboundId, record, context) => {
628
+ const { accessToken, friend } = context;
629
+ const tokenScope = tokenHashScope(record.accessTokenHash);
630
+ const respondWith = (task) => jsonResponse(rpcId, publicTask(task, accessToken ?? "", record.responseStyle, accessToken !== undefined));
631
+ let relationshipAuthorization = friend ? a2aChatRelationship(agentRoot, friend, record.taskId) : undefined;
536
632
  // Only the server writes the delegated banner. Any turn that is not about to be admitted as a delegated command
537
633
  // (verified or not, including a plain unauthenticated text turn) gets a typed banner marked as the sender's own words.
538
- if (verifiedChat?.onBehalfOf !== "principal")
539
- turnText = (0, delegated_command_1.shieldDelegatedBanner)(text);
540
- if (verifiedChat?.onBehalfOf === "principal") {
634
+ let turnText = record.verifiedChat?.onBehalfOf === "principal" ? record.text : (0, delegated_command_1.shieldDelegatedBanner)(record.text);
635
+ let delegatedCommand;
636
+ if (record.verifiedChat?.onBehalfOf === "principal") {
541
637
  // A delegated command runs with the principal's authority only after the
542
638
  // server, never the model, has checked the grant and told the principal.
543
639
  let registry;
@@ -548,52 +644,178 @@ async function startA2AServer(options) {
548
644
  registry = undefined;
549
645
  }
550
646
  /* v8 ignore next -- a completed chat always carries the sender's friend record (see the receipt above) @preserve */
551
- if (!verifiedChat.friend)
647
+ if (!friend)
552
648
  throw new Error("verified chat has no friend record");
553
- const admission = await (0, delegated_command_1.admitDelegatedCommand)({ friend: verifiedChat.friend, did: verifiedChat.did, text, commandId: commandIdFor(verifiedChat), store: inboundShareDeps.store, registry, options: options.delegation });
649
+ const admission = await (0, delegated_command_1.admitDelegatedCommand)({ friend, did: record.verifiedChat.did, text: record.text, commandId: commandIdFor(record.verifiedChat), store: inboundShareDeps.store, registry, options: options.delegation });
554
650
  if (!admission.ok) {
555
651
  // The code and the "delegated command refused: <reason>" prefix stay: the replay gate and older CLIs match them.
556
652
  // Only an active family peer is told why: anyone else gets no_grant whatever the real reason was (a broken trust file, a key mismatch), which stays in the local log and nerves.
557
- const activeFamily = verifiedChat.friend.trustLevel === "family" && verifiedChat.friend.admissionState === "active";
653
+ const activeFamily = friend.trustLevel === "family" && friend.admissionState === "active";
558
654
  const shown = activeFamily ? admission.reason : "no_grant";
559
- const guidance = (0, delegated_command_1.delegationRefusalGuidance)(shown, { legacyRecordGrant: activeFamily && verifiedChat.friend.delegationGrant !== undefined });
560
- return errorResponse(rpc.id, -32004, `delegated command refused: ${shown} (${guidance.message}). Nothing ran. Next: ${guidance.next}`, { reason: shown, nothingRan: true, retry: guidance.retry, next: guidance.next });
655
+ const guidance = (0, delegated_command_1.delegationRefusalGuidance)(shown, { legacyRecordGrant: activeFamily && friend.delegationGrant !== undefined });
656
+ journal.settle(inboundId, "failed", `delegated command refused: ${admission.reason}`);
657
+ return errorResponse(rpcId, -32004, `delegated command refused: ${shown} (${guidance.message}). Nothing ran. Next: ${guidance.next}`, { reason: shown, nothingRan: true, retry: guidance.retry, next: guidance.next });
561
658
  }
562
659
  relationshipAuthorization = admission.relationship;
563
660
  turnText = admission.turnText;
564
661
  delegatedCommand = admission.context;
565
662
  }
566
- taskStore.put(taskFor({ taskId, accessToken, contextId, inbound, state: "TASK_STATE_WORKING", clientTaskId, previousTask: continuationTask ?? undefined }), tokenScope);
567
- const turn = await turnRunner({
568
- agentName: options.agentName,
569
- peerAgentId,
570
- peerName,
571
- sessionKey: contextId,
572
- message: turnText,
573
- ...(relationshipAuthorization ? { relationshipAuthorization } : {}),
574
- ...(delegatedCommand ? { delegatedCommand } : {}),
663
+ journal.beginAttempt(inboundId);
664
+ const controller = new AbortController();
665
+ const active = { task: activeTaskKey(record.taskId, tokenScope), controller };
666
+ activeTurns.add(active);
667
+ // The deadline first bounds the wait for a place in the turn queue, then starts again for the turn itself.
668
+ let started = false;
669
+ let deadline = setTimeout(() => controller.abort(new A2ATurnStopped("deadline")), turnTimeoutMs);
670
+ const onTurnStart = () => {
671
+ // A runner that reports its start after the turn has ended must not leave a new deadline running.
672
+ if (!activeTurns.has(active))
673
+ return;
674
+ started = true;
675
+ clearTimeout(deadline);
676
+ deadline = setTimeout(() => controller.abort(new A2ATurnStopped("deadline")), turnTimeoutMs);
677
+ };
678
+ // A turn that ignores its signal still ends the wait: the stop is what the sender hears, whatever the turn does next.
679
+ const stopped = new Promise((_resolve, reject) => {
680
+ controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
575
681
  });
682
+ stopped.catch(() => undefined);
683
+ let turn;
684
+ try {
685
+ taskStore.put(taskFor({ taskId: record.taskId, accessTokenHash: record.accessTokenHash, contextId: record.contextId, inbound: record.inbound, state: "TASK_STATE_WORKING", clientTaskId: record.clientTaskId, previousTask: record.previousTask }), tokenScope);
686
+ turn = await Promise.race([
687
+ turnRunner({
688
+ agentName: options.agentName,
689
+ peerAgentId: record.peerAgentId,
690
+ peerName: record.peerName,
691
+ sessionKey: record.contextId,
692
+ message: turnText,
693
+ signal: controller.signal,
694
+ onTurnStart,
695
+ ...(relationshipAuthorization ? { relationshipAuthorization } : {}),
696
+ ...(delegatedCommand ? { delegatedCommand } : {}),
697
+ }),
698
+ stopped,
699
+ ]);
700
+ }
701
+ catch (error) {
702
+ const stop = controller.signal.aborted ? controller.signal.reason.reason : undefined;
703
+ if (stop === "canceled") {
704
+ // CancelTask already wrote the CANCELED task; the turn's end must not overwrite it.
705
+ journal.settle(inboundId, "canceled");
706
+ return respondWith(taskStore.get(record.taskId, tokenScope));
707
+ }
708
+ if (stop === "shutdown" && record.origin === "relay") {
709
+ // Nobody waits on a relayed message's reply: it stays pending, and the next process runs it again. A clean
710
+ // shutdown is not the turn failing, so it gives its attempt back; only crashes use attempts up.
711
+ journal.refundAttempt(inboundId);
712
+ return errorResponse(rpcId, -32000, AGENT_RESTARTING);
713
+ }
714
+ const seconds = Math.round(turnTimeoutMs / 1000);
715
+ const detail = stop === "shutdown"
716
+ ? STOPPED_BEFORE_ANSWERING
717
+ : stop === "deadline"
718
+ ? started ? `the turn was stopped after ${seconds} s without finishing` : `the turn was stopped after ${seconds} s waiting for the turn ahead of it`
719
+ : error instanceof Error ? error.message : /* v8 ignore next -- defensive non-Error throw branch @preserve */ String(error);
720
+ recordFailure(inboundId, record, detail);
721
+ return failureResponse(rpcId, record, detail, accessToken);
722
+ }
723
+ finally {
724
+ clearTimeout(deadline);
725
+ activeTurns.delete(active);
726
+ }
727
+ try {
728
+ return finishAnswered(rpcId, inboundId, record, turn.response, respondWith);
729
+ }
730
+ catch (error) {
731
+ // The turn ran but its answer could not be stored: a visible failure, not an entry left pending.
732
+ const detail = error instanceof Error ? error.message : /* v8 ignore next -- defensive non-Error throw branch @preserve */ String(error);
733
+ recordFailure(inboundId, record, detail);
734
+ return failureResponse(rpcId, record, detail, accessToken);
735
+ }
736
+ };
737
+ const finishAnswered = (rpcId, inboundId, record, response, respondWith) => {
738
+ const tokenScope = tokenHashScope(record.accessTokenHash);
576
739
  let responseParts;
577
- if (verifiedChat) {
740
+ if (record.verifiedChat) {
578
741
  // A verified chat's reply is sealed to the sender and stored sealed, so neither
579
742
  // the wire nor a later GetTask ever carries the plaintext.
580
- const pinned = inboundShareDeps.pinStore.get(verifiedChat.did);
581
- /* v8 ignore next 4 -- receiveShare pins the verified sender before it reports a completed chat; refuse rather than reply in plaintext @preserve */
743
+ const pinned = inboundShareDeps?.pinStore.get(record.verifiedChat.did);
744
+ /* v8 ignore next 5 -- receiveShare pins the verified sender before it reports a completed chat; refuse rather than reply in plaintext @preserve */
582
745
  if (!pinned) {
583
- return errorResponse(rpc.id, -32003, "A2A chat reply cannot be sealed to the sender");
746
+ const detail = "A2A chat reply cannot be sealed to the sender";
747
+ recordFailure(inboundId, record, detail);
748
+ return errorResponse(rpcId, -32003, detail);
584
749
  }
585
750
  responseParts = (0, sealed_chat_1.sealChatMessage)({
586
751
  sodium: inboundShareDeps.sodium,
587
752
  from: options.identity,
588
- recipientDid: verifiedChat.did,
753
+ recipientDid: record.verifiedChat.did,
589
754
  recipientEd25519Pub: pinned.ed25519Pub,
590
- text: turn.response,
591
- conversationId: contextId,
755
+ text: response,
756
+ conversationId: record.contextId,
592
757
  }).parts;
593
758
  }
594
- const task = taskFor({ taskId, accessToken, contextId, inbound, state: "TASK_STATE_COMPLETED", response: turn.response, responseParts, clientTaskId, previousTask: continuationTask ?? undefined });
759
+ const task = taskFor({ taskId: record.taskId, accessTokenHash: record.accessTokenHash, contextId: record.contextId, inbound: record.inbound, state: "TASK_STATE_COMPLETED", response, responseParts, clientTaskId: record.clientTaskId, previousTask: record.previousTask });
595
760
  taskStore.put(task, tokenScope);
596
- return jsonResponse(rpc.id, publicTask(task, accessToken, responseStyle, true));
761
+ journal.settle(inboundId, "answered");
762
+ return respondWith(task);
763
+ };
764
+ /**
765
+ * The inbounds an earlier process left pending. A direct one's sender saw its connection drop and can't receive a
766
+ * late reply, so it is recorded as failed. A relayed one is run again, until it has used its attempts.
767
+ */
768
+ const replayOne = async (leftOverEntry) => {
769
+ // Read again: it may have been settled since the list was taken, and its attempts are counted on disk.
770
+ const entry = journal.get(leftOverEntry.id);
771
+ if (!entry)
772
+ return;
773
+ const record = entry.payload;
774
+ // The task was finished just before the process died, so the journal only catches up with it.
775
+ const state = taskStore.get(record.taskId, tokenHashScope(record.accessTokenHash))?.status.state;
776
+ if (state === "TASK_STATE_COMPLETED" || state === "TASK_STATE_CANCELED") {
777
+ journal.settle(entry.id, state === "TASK_STATE_COMPLETED" ? "answered" : "canceled");
778
+ return;
779
+ }
780
+ if (record.origin === "direct") {
781
+ recordFailure(entry.id, record, STOPPED_BEFORE_ANSWERING);
782
+ return;
783
+ }
784
+ if (entry.attempts >= inbound_journal_1.MAX_INBOUND_ATTEMPTS) {
785
+ recordFailure(entry.id, record, `stopped after ${entry.attempts} attempts without an answer`);
786
+ return;
787
+ }
788
+ if (record.verifiedChat?.onBehalfOf === "principal") {
789
+ // It may already have acted with the principal's authority, and its grant was checked only for that moment.
790
+ recordFailure(entry.id, record, "a delegated command is not run again after a restart; send it again");
791
+ return;
792
+ }
793
+ const friendId = record.verifiedChat?.friendId;
794
+ const friend = friendId && inboundShareDeps ? await inboundShareDeps.store.get(friendId) ?? undefined : undefined;
795
+ if (record.verifiedChat && !friend) {
796
+ recordFailure(entry.id, record, "the sender's friend record or this agent's A2A identity is gone, so the message cannot be answered");
797
+ return;
798
+ }
799
+ (0, runtime_1.emitNervesEvent)({ component: "channels", event: "channel.a2a_inbound_replayed", message: "replaying a relayed message an earlier process left pending", meta: { agentName: options.agentName, inboundId: entry.id, attempts: entry.attempts } });
800
+ await runInboundTurn(null, entry.id, record, { friend });
801
+ };
802
+ const replayPendingInbound = async () => {
803
+ for (const entry of leftOver) {
804
+ if (closing)
805
+ break;
806
+ try {
807
+ await replayOne(entry);
808
+ }
809
+ catch (error) {
810
+ // Counted, so a message that throws every time is failed once it has used its attempts instead of
811
+ // blocking every start; the messages behind it still run.
812
+ try {
813
+ journal.beginAttempt(entry.id);
814
+ }
815
+ catch { /* the event below still reports the failure */ }
816
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "channels", event: "channel.a2a_inbound_replay_error", message: "replaying a pending A2A message failed; it stays pending for the next start", meta: { agentName: options.agentName, inboundId: entry.id, error: error instanceof Error ? error.message : /* v8 ignore next -- defensive non-Error throw branch @preserve */ String(error) } });
817
+ }
818
+ }
597
819
  };
598
820
  let relayInbox;
599
821
  let publicBaseUrl = options.baseUrl;
@@ -724,6 +946,9 @@ async function startA2AServer(options) {
724
946
  status: { state: "TASK_STATE_CANCELED", timestamp: new Date().toISOString() },
725
947
  };
726
948
  taskStore.put(canceled, tokenScope);
949
+ const canceledKey = activeTaskKey(taskId, tokenScope);
950
+ for (const active of [...activeTurns].filter((turn) => turn.task === canceledKey))
951
+ active.controller.abort(new A2ATurnStopped("canceled"));
727
952
  writeJson(res, 200, jsonResponse(rpc.id, publicTask(canceled, accessToken, responseStyle, false)));
728
953
  return;
729
954
  }
@@ -767,11 +992,12 @@ async function startA2AServer(options) {
767
992
  retirements: (0, relay_retirements_1.fileRelayRetirements)(agentRoot),
768
993
  did: inboundShareDeps.identity.did,
769
994
  agentName: options.agentName,
770
- handle: (rpc) => handleMessageSend(rpc),
995
+ handle: (rpc) => handleMessageSend(rpc, undefined, "relay"),
771
996
  // Asked only after a handler throws: was this copy verified (and so recorded) before it failed?
772
997
  seen: seen.has.bind(seen),
773
998
  });
774
999
  }
1000
+ const replayed = replayPendingInbound();
775
1001
  (0, runtime_1.emitNervesEvent)({
776
1002
  component: "channels",
777
1003
  event: "channel.a2a_server_started",
@@ -783,7 +1009,11 @@ async function startA2AServer(options) {
783
1009
  url: publicBaseUrl,
784
1010
  endpointUrl: endpointUrl.toString(),
785
1011
  ...(relayInbox ? { relay: relayInbox } : {}),
1012
+ replayed,
786
1013
  close: () => new Promise((resolve, reject) => {
1014
+ closing = true;
1015
+ for (const active of activeTurns)
1016
+ active.controller.abort(new A2ATurnStopped("shutdown"));
787
1017
  clearInterval(confirmTimer);
788
1018
  relayInbox?.stop();
789
1019
  server.close((error) => {
@@ -78,6 +78,8 @@ const PROTECTED_PATH_SEGMENTS = [
78
78
  "state/a2a/relay-contacts/",
79
79
  // Relay retirements awaiting their vault write; a forged marker would skip draining an old relay inbox.
80
80
  "state/a2a/relay-retired/",
81
+ // Each sense's inbound journal: a forged pending entry would be replayed as a message from a verified sender.
82
+ "state/senses/",
81
83
  "state/outbox/",
82
84
  "state/reports/",
83
85
  ];
@@ -64,8 +64,9 @@ Promise.all([
64
64
  Promise.resolve().then(() => __importStar(require("@ouro.bot/friends/a2a-client"))),
65
65
  Promise.resolve().then(() => __importStar(require("../a2a/escalation-wiring"))),
66
66
  Promise.resolve().then(() => __importStar(require("../a2a/relay-config-vault"))),
67
+ Promise.resolve().then(() => __importStar(require("./sense-shutdown"))),
67
68
  ])
68
- .then(async ([{ startA2AServer }, { loadOrMintA2AIdentity, readStoredA2ASeed, publishOwnA2ADid }, { waitForRuntimeCredentialBootstrap, readMachineRuntimeCredentialConfig, refreshMachineRuntimeCredentialConfig, mergeMachineRuntimeCredentialConfig }, { loadOrCreateMachineIdentity }, { ready }, { escalationOptionsFor, sendOwnerNoticeViaTelegram }, { relayConfigFrom, vaultRelayConfigStore },]) => {
69
+ .then(async ([{ startA2AServer }, { loadOrMintA2AIdentity, readStoredA2ASeed, publishOwnA2ADid }, { waitForRuntimeCredentialBootstrap, readMachineRuntimeCredentialConfig, refreshMachineRuntimeCredentialConfig, mergeMachineRuntimeCredentialConfig }, { loadOrCreateMachineIdentity }, { ready }, { escalationOptionsFor, sendOwnerNoticeViaTelegram }, { relayConfigFrom, vaultRelayConfigStore }, { installSenseShutdown },]) => {
69
70
  const os = await Promise.resolve().then(() => __importStar(require("node:os")));
70
71
  // Wait for the daemon to deliver the machine-local runtime config (carrying the
71
72
  // a2a identity seed) into the in-memory cache before we read or mint identity.
@@ -99,7 +100,7 @@ Promise.all([
99
100
  const relaySettings = relayConfigFrom(machineConfig);
100
101
  const rawPort = argValue("--port");
101
102
  const port = rawPort ? Number.parseInt(rawPort, 10) : undefined;
102
- await startA2AServer({
103
+ const handle = await startA2AServer({
103
104
  agentName,
104
105
  identity,
105
106
  // The Butler accepts delegated commands from explicitly granted peers; each
@@ -126,6 +127,9 @@ Promise.all([
126
127
  ...(argValue("--base-url") ? { baseUrl: argValue("--base-url") } : {}),
127
128
  ...(argValue("--path") ? { path: argValue("--path") } : {}),
128
129
  });
130
+ // Bounded shutdown: in-flight turns stop (a relayed message stays pending for the next process) and the
131
+ // process exits within the grace period even if one of them does not.
132
+ installSenseShutdown({ sense: "a2a", stop: () => handle.close() });
129
133
  })
130
134
  .catch((error) => {
131
135
  (0, runtime_1.emitNervesEvent)({
@@ -0,0 +1,182 @@
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.INBOUND_OUTCOME_RETENTION_MS = exports.MAX_INBOUND_ATTEMPTS = void 0;
37
+ exports.readInboundOutcome = readInboundOutcome;
38
+ exports.openInboundJournal = openInboundJournal;
39
+ const node_crypto_1 = require("node:crypto");
40
+ const fs = __importStar(require("node:fs"));
41
+ const path = __importStar(require("node:path"));
42
+ const atomic_file_1 = require("../heart/atomic-file");
43
+ const runtime_1 = require("../nerves/runtime");
44
+ /**
45
+ * The shared inbound rule every sense follows (the rule iMessage got on 2026-11-22): an inbound message is
46
+ * written here before its turn runs, and leaves only when its one outcome is recorded. A process that dies
47
+ * mid-turn leaves it pending, and the next process replays it or records why it can't. Each sense keeps a
48
+ * thin adapter that decides what "replay" means for its transport.
49
+ */
50
+ /** How many turns a sense starts for one inbound before it records a failure instead of trying again. */
51
+ exports.MAX_INBOUND_ATTEMPTS = 3;
52
+ /** How long an inbound's recorded outcome is kept, so a late copy of it is not taken for a new message. */
53
+ exports.INBOUND_OUTCOME_RETENTION_MS = 30 * 24 * 60 * 60_000;
54
+ /** Counts inbounds recorded by this process; see PendingInbound.sequence. */
55
+ let recordSequence = 0;
56
+ function journalDir(agentRoot, sense) {
57
+ return path.join(agentRoot, "state", "senses", sense);
58
+ }
59
+ function fileName(id) {
60
+ return `${(0, node_crypto_1.createHash)("sha256").update(id).digest("hex")}.json`;
61
+ }
62
+ function readJson(filePath) {
63
+ try {
64
+ return JSON.parse(fs.readFileSync(filePath, "utf-8"));
65
+ }
66
+ catch {
67
+ return null;
68
+ }
69
+ }
70
+ function listJson(dir) {
71
+ try {
72
+ return fs.readdirSync(dir).filter((name) => name.endsWith(".json")).map((name) => path.join(dir, name));
73
+ }
74
+ catch {
75
+ return [];
76
+ }
77
+ }
78
+ /** The recorded outcome of one inbound, or null when it has none (still pending, never seen, or past retention). */
79
+ function readInboundOutcome(agentRoot, sense, id) {
80
+ return readJson(path.join(journalDir(agentRoot, sense), "inbound-outcomes", fileName(id)));
81
+ }
82
+ function openInboundJournal(agentRoot, sense, options = {}) {
83
+ const now = options.now ?? Date.now;
84
+ const pendingDir = path.join(journalDir(agentRoot, sense), "pending-inbound");
85
+ const outcomesDir = path.join(journalDir(agentRoot, sense), "inbound-outcomes");
86
+ fs.mkdirSync(pendingDir, { recursive: true });
87
+ fs.mkdirSync(outcomesDir, { recursive: true });
88
+ const cutoff = now() - exports.INBOUND_OUTCOME_RETENTION_MS;
89
+ for (const file of listJson(outcomesDir)) {
90
+ const outcome = readJson(file);
91
+ if (!outcome || Date.parse(outcome.settledAt) < cutoff)
92
+ fs.rmSync(file, { force: true });
93
+ }
94
+ const pendingPath = (id) => path.join(pendingDir, fileName(id));
95
+ const outcomePath = (id) => path.join(outcomesDir, fileName(id));
96
+ const get = (id) => {
97
+ if (fs.existsSync(outcomePath(id)))
98
+ return null;
99
+ return readJson(pendingPath(id));
100
+ };
101
+ const update = (id, change) => {
102
+ const entry = get(id);
103
+ if (!entry)
104
+ return null;
105
+ const next = change(entry);
106
+ (0, atomic_file_1.writeJsonAtomicSync)(pendingPath(id), next);
107
+ return next;
108
+ };
109
+ const pending = () => {
110
+ const entries = [];
111
+ for (const file of listJson(pendingDir)) {
112
+ const entry = readJson(file);
113
+ if (!entry || typeof entry.id !== "string")
114
+ continue;
115
+ // Settled just before a crash: the outcome stands and the leftover pending copy goes.
116
+ if (fs.existsSync(outcomePath(entry.id))) {
117
+ fs.rmSync(file, { force: true });
118
+ continue;
119
+ }
120
+ entries.push(entry);
121
+ }
122
+ const sequenceOf = (entry) => entry.sequence ?? 0;
123
+ return entries.sort((a, b) => a.receivedAt.localeCompare(b.receivedAt) || sequenceOf(a) - sequenceOf(b));
124
+ };
125
+ return {
126
+ record(id, payload) {
127
+ const existing = get(id);
128
+ if (existing)
129
+ return existing;
130
+ const settled = readJson(outcomePath(id));
131
+ if (settled) {
132
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.inbound_duplicate", message: "an inbound that already has an outcome arrived again; it is not run again", meta: { sense, id, outcome: settled.outcome } });
133
+ return null;
134
+ }
135
+ recordSequence += 1;
136
+ const entry = { id, sense, receivedAt: new Date(now()).toISOString(), sequence: recordSequence, attempts: 0, spoke: false, payload };
137
+ (0, atomic_file_1.writeJsonAtomicSync)(pendingPath(id), entry);
138
+ (0, runtime_1.emitNervesEvent)({ component: "senses", event: "senses.inbound_recorded", message: "recorded an inbound before its turn", meta: { sense, id } });
139
+ return entry;
140
+ },
141
+ get,
142
+ beginAttempt(id) {
143
+ return update(id, (entry) => ({ ...entry, attempts: entry.attempts + 1 }))?.attempts ?? 0;
144
+ },
145
+ refundAttempt(id) {
146
+ update(id, (entry) => ({ ...entry, attempts: Math.max(0, entry.attempts - 1) }));
147
+ },
148
+ markSpoke(id) {
149
+ update(id, (entry) => ({ ...entry, spoke: true }));
150
+ },
151
+ settle(id, outcome, detail) {
152
+ const entry = get(id);
153
+ if (!entry)
154
+ return false;
155
+ const record = {
156
+ id,
157
+ sense,
158
+ receivedAt: entry.receivedAt,
159
+ settledAt: new Date(now()).toISOString(),
160
+ outcome,
161
+ attempts: entry.attempts,
162
+ ...(detail ? { detail } : {}),
163
+ };
164
+ // The outcome file is the record; the pending copy is removed only after it has landed.
165
+ (0, atomic_file_1.writeJsonAtomicSync)(outcomePath(id), record);
166
+ fs.rmSync(pendingPath(id), { force: true });
167
+ (0, runtime_1.emitNervesEvent)({
168
+ level: outcome === "failed" ? "error" : "info",
169
+ component: "senses",
170
+ event: "senses.inbound_settled",
171
+ message: outcome === "failed" ? "recorded a visible failure for an inbound" : "recorded an inbound's outcome",
172
+ meta: { sense, id, outcome, attempts: entry.attempts, ...(detail ? { detail } : {}) },
173
+ });
174
+ return true;
175
+ },
176
+ pending,
177
+ oldestPendingAgeMs() {
178
+ const oldest = pending()[0];
179
+ return oldest ? Math.max(0, now() - Date.parse(oldest.receivedAt)) : null;
180
+ },
181
+ };
182
+ }
@@ -356,7 +356,9 @@ function getSenseSessionPath(agentName, friendId, channel, sessionKey, agentRoot
356
356
  */
357
357
  async function runSenseTurn(options) {
358
358
  options = { ...options, ...(options.shepherdSession ? { shepherdSession: Object.freeze({ ...options.shepherdSession }) } : {}) };
359
+ const queueSignal = options.stopQueueWaitOnAbort ? options.signal : undefined;
359
360
  return (0, turn_execution_lease_1.withTurnExecutionLease)(async () => {
361
+ options.onTurnStart?.();
360
362
  const owner = Object.freeze({ agentName: options.agentName, agentRoot: (0, identity_1.getAgentRoot)(options.agentName) });
361
363
  (0, identity_1.setAgentName)(owner.agentName);
362
364
  try {
@@ -367,7 +369,7 @@ async function runSenseTurn(options) {
367
369
  await releaseRuntimeMcpServersAfterTurn(owner);
368
370
  }
369
371
  }
370
- });
372
+ }, queueSignal);
371
373
  }
372
374
  async function runSenseTurnExclusive(options, owner) {
373
375
  const { channel, sessionKey, friendId } = options;
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1390",
3
+ "version": "0.1.0-alpha.1392",
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.1390",
9
+ "version": "0.1.0-alpha.1392",
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.1390",
3
+ "version": "0.1.0-alpha.1392",
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": {