agent-comm-hub 0.10.0 → 0.11.0

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/lib/cli.js CHANGED
@@ -526,6 +526,7 @@ var HUB_PEER = "hub";
526
526
  var SSE_METHOD = "notifications/message";
527
527
  var SSE_EVENT_PEERS_CHANGED = "peers_changed";
528
528
  var SSE_EVENT_MESSAGE = "message";
529
+ var SSE_EVENT_TASK_CHANGED = "task_changed";
529
530
  var MAX_HOP = 5;
530
531
  var MAX_REPLY_CHAIN = 50;
531
532
  function a2aState(status) {
@@ -549,7 +550,19 @@ function a2aState(status) {
549
550
  }
550
551
  }
551
552
  var CLIENT_ACK_STATUSES = ["accepted", "working", "input-required", "rejected", "done", "failed"];
553
+ var ALL_ACK_STATUSES = [...CLIENT_ACK_STATUSES, "canceled"];
552
554
  var TERMINAL_TASK_STATUSES = ["rejected", "done", "failed", "timeout", "canceled"];
555
+ var ALL_TASK_STATUSES = [
556
+ "pending",
557
+ "accepted",
558
+ "working",
559
+ "input-required",
560
+ "rejected",
561
+ "done",
562
+ "failed",
563
+ "timeout",
564
+ "canceled"
565
+ ];
553
566
  function ackToTaskStatus(ack) {
554
567
  return ack;
555
568
  }
@@ -603,6 +616,9 @@ function decodeContent(kind, content) {
603
616
  // src/hub.ts
604
617
  var MAX_PROFILES = 512;
605
618
  var MAX_TASKS = 1024;
619
+ var MAX_DEAD_LETTERS = 200;
620
+ var MAX_TASK_ACKS = 200;
621
+ var MAX_TASK_ARTIFACTS = 50;
606
622
  var MAX_TIMER_DELAY_MS = 2147483647;
607
623
  var DEFAULT_PARKED_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
608
624
  var DEFAULT_LEASE_TTL_MS = 6e4;
@@ -694,6 +710,40 @@ var AgentHub = class _AgentHub {
694
710
  noteEvent(kind, input = {}) {
695
711
  this.recordEvent(kind, input);
696
712
  }
713
+ /** Append one event to a task's ack timeline, keeping the timeline bounded
714
+ * (see {@link MAX_TASK_ACKS}). */
715
+ pushAckEvent(record, event) {
716
+ record.acks.push(event);
717
+ this.trimAcks(record.acks);
718
+ }
719
+ /** Append one event to one assignee's timeline, with the SAME bound
720
+ * ({@link MAX_TASK_ACKS}). A single assignee that keeps acking `working`
721
+ * grows its own timeline without limit otherwise — and `exportTasks`
722
+ * serializes the whole ledger on every flush. */
723
+ pushAssigneeAck(assignee, event) {
724
+ assignee.acks.push({ ...event });
725
+ this.trimAcks(assignee.acks);
726
+ }
727
+ /** Evict from one ack timeline until it fits {@link MAX_TASK_ACKS}.
728
+ *
729
+ * Order, oldest first within each class:
730
+ * 1. a `system: true` event is protected to the very end. Those rows are the
731
+ * DROP EVIDENCE (`noteTaskDeliveryDropped` writes `applied: false,
732
+ * system: true`), and a long task acking `working` 200 times would
733
+ * otherwise throw away "this delivery was lost" before a single chatty
734
+ * status update — the one thing a reader must be able to find out.
735
+ * 2. then an `applied: false` ack: it recorded a rejection and moved no
736
+ * ledger state.
737
+ * 3. then any non-system ack (the audited transitions a reader wants).
738
+ * 4. only if the timeline is STILL over the limit: a system row. */
739
+ trimAcks(events) {
740
+ while (events.length > MAX_TASK_ACKS) {
741
+ let victim = events.findIndex((item) => item.system !== true && item.applied !== true);
742
+ if (victim < 0) victim = events.findIndex((item) => item.system !== true);
743
+ if (victim < 0) victim = 0;
744
+ events.splice(victim, 1);
745
+ }
746
+ }
697
747
  waiters = /* @__PURE__ */ new Map();
698
748
  historyRing = [];
699
749
  /** Structured operational events, newest last. A ring, not a log: the hub is a
@@ -738,13 +788,10 @@ var AgentHub = class _AgentHub {
738
788
  continue;
739
789
  }
740
790
  if (now - parkedMs <= ttl) continue;
741
- const queue = this.queues.get(peerId) ?? [];
742
- this.queues.delete(peerId);
743
- this.parkedAt.delete(peerId);
744
- for (const message of queue) {
745
- if (message.kind === "task") this.failTaskForGoneAssignee(message.id, peerId, now, ttl);
746
- }
747
- const dropped = queue.length;
791
+ const dropped = this.dropMailboxState(
792
+ peerId,
793
+ (message) => this.failTaskForGoneAssignee(message.id, peerId, now, ttl)
794
+ ).length;
748
795
  if (dropped > 0) {
749
796
  this.options.onMailboxesChanged?.();
750
797
  this.recordEvent("mailbox_dropped", { peer: peerId, detail: { reason: "expired", dropped, ttlMs: ttl } });
@@ -770,21 +817,118 @@ var AgentHub = class _AgentHub {
770
817
  status: "failed",
771
818
  note: `recipient '${peerId}' never came back: its parked mailbox expired after ${ttl}ms and the task was dropped with it`,
772
819
  ts: now,
773
- messageId: `expired-${taskId}`,
820
+ messageId: syntheticEventId(taskId, "expired"),
774
821
  applied: true,
775
822
  system: true
776
823
  };
777
- record.acks.push(event);
824
+ this.pushAckEvent(record, event);
778
825
  assignee.status = "failed";
779
- assignee.acks.push({ ...event });
826
+ this.pushAssigneeAck(assignee, event);
780
827
  record.status = aggregateTaskStatus(record.assignees);
781
828
  record.updatedAt = now;
782
- const timer = this.taskTimers.get(taskId);
783
- if (timer !== void 0) {
784
- clearTimeout(timer);
785
- this.taskTimers.delete(taskId);
786
- }
829
+ this.realignTaskTimer(record);
787
830
  this.taskChanged(this.taskOf(taskId));
831
+ this.notifyTaskEnded(record, `recipient '${peerId}' never came back: its parked mailbox expired after ${ttl}ms and its copy of the task was dropped with it`);
832
+ }
833
+ /** Tell the SENDER of `record` that this delivery is over for good — the one
834
+ * thing it has to act on (re-send the task, or abandon it).
835
+ *
836
+ * Guarded by the same reachability precheck as {@link noteTaskDeliveryDropped}:
837
+ * a sender that has itself left the hub has nobody to warn, and `route` would
838
+ * throw on the drop path. Best effort by design — a terminal verdict is
839
+ * already in the ledger whether or not the notice can be delivered. */
840
+ notifyTaskEnded(record, why) {
841
+ if (!this.lastSeen.has(record.from) && !this.parkedAt.has(record.from)) return;
842
+ this.route(HUB_PEER, record.from, "notice", encodeContent({
843
+ message: `task ${record.id}: ${why}. That copy of the task can never be picked up or acked (task status: ${record.status}) \u2014 bridge_task can re-send it, or consider it abandoned.`,
844
+ level: "warn"
845
+ }), void 0, record.threadId, void 0, true);
846
+ }
847
+ /** Reconcile the task ledger after a `task` message was dropped for `peerId`
848
+ * because the PEER ITSELF is gone.
849
+ *
850
+ * This is one of exactly TWO drops that write a terminal state, and both mean
851
+ * the same thing — the recipient can never recover the task: this one (the
852
+ * peer left the hub, or a manager kicked it) and
853
+ * {@link failTaskForGoneAssignee} (its parked mailbox expired after
854
+ * `parkedTtlMs`). Terminal is right there on purpose: the assignee no longer
855
+ * exists, so there is no path back — no revival, no later ack — and a
856
+ * `pending` row would leave the sender waiting forever. Every other drop
857
+ * reason (`expired`, `rate`, `overflow`, dead-letter) stays NON-terminal
858
+ * instead (see {@link noteTaskDeliveryDropped}), because:
859
+ * - a dead letter can be revived with `bridge_nack`, and a task already
860
+ * marked `failed` would then refuse the revived assignee's `done`
861
+ * (`nextTaskStatus('failed', 'done')` is null → `applied: false`), so the
862
+ * sender would see a failure the hub itself declared unfixable;
863
+ * - `overflow` and `rate` are driven by THIRD-PARTY traffic — any peer
864
+ * sending ~maxQueue messages can push a task out of someone else's mailbox
865
+ * — so a terminal write there is a veto any peer can exercise over a task
866
+ * it was never assigned.
867
+ *
868
+ * Like the parked-mail reconcile, the failure is a SYSTEM event (nobody acked
869
+ * anything), only this assignee's row is marked — a fan-out task's other
870
+ * recipients keep their state — and the aggregate is recomputed the way every
871
+ * other transition does it. `reason` is the drop kind the caller counted, so
872
+ * the note and the `mailbox_dropped` event can be read together. */
873
+ failTaskForDroppedMessage(message, peerId, reason, now) {
874
+ const record = this.taskLedger.get(message.id);
875
+ if (record === void 0) return;
876
+ if (TERMINAL_TASK_STATUSES.includes(record.status)) return;
877
+ const assignee = record.assignees.find((a) => a.peerId === peerId);
878
+ if (assignee === void 0 || TERMINAL_TASK_STATUSES.includes(assignee.status)) return;
879
+ const event = {
880
+ from: peerId,
881
+ status: "failed",
882
+ note: `message dropped for '${peerId}' (${reason}): the task will never be handed to it and cannot be acked`,
883
+ ts: now,
884
+ messageId: syntheticEventId(record.id, reason),
885
+ applied: true,
886
+ system: true
887
+ };
888
+ this.pushAckEvent(record, event);
889
+ assignee.status = "failed";
890
+ delete assignee.deliveredMs;
891
+ this.pushAssigneeAck(assignee, event);
892
+ record.status = aggregateTaskStatus(record.assignees);
893
+ record.updatedAt = now;
894
+ this.realignTaskTimer(record);
895
+ this.taskChanged(this.taskOf(record.id));
896
+ this.notifyTaskEnded(record, reason === "dead-letter-evicted" ? `its last copy for '${peerId}' was evicted from the dead letters (${reason}) and can never be revived` : `'${peerId}' left the hub (${reason}) and its queued copy of the task went with it`);
897
+ }
898
+ /** Record that one delivery of a task was dropped, WITHOUT closing the task.
899
+ *
900
+ * Two things happen and nothing else (`expired` / `rate` / `overflow` /
901
+ * dead-letter drops all land here; `unregister` keeps the terminal reconcile
902
+ * above):
903
+ * 1. the ledger gets a `system: true, applied: false` event naming the drop —
904
+ * `applied: false` is the whole point, it says "recorded, state untouched";
905
+ * 2. the task's SENDER gets a `notice` from the hub: it is the only party
906
+ * that can react (re-send, or revive a dead letter with `bridge_nack`).
907
+ * ONE notice per task, not per dropped copy — see `dropNotified`.
908
+ *
909
+ * See {@link failTaskForDroppedMessage} for why a terminal write here would
910
+ * be wrong. */
911
+ noteTaskDeliveryDropped(message, peerId, reason, now) {
912
+ const record = this.taskLedger.get(message.id);
913
+ if (record === void 0) return;
914
+ this.pushAckEvent(record, {
915
+ from: peerId,
916
+ status: "failed",
917
+ note: `a delivery of this task to '${peerId}' was dropped (${reason}); the task itself is unchanged and still waiting`,
918
+ ts: now,
919
+ messageId: syntheticEventId(record.id, reason),
920
+ applied: false,
921
+ system: true
922
+ });
923
+ if (TERMINAL_TASK_STATUSES.includes(record.status)) return;
924
+ if (record.dropNotified !== void 0) return;
925
+ if (!this.lastSeen.has(record.from) && !this.parkedAt.has(record.from)) return;
926
+ record.dropNotified = now;
927
+ const hint = reason === "dead-letter" ? ` \u2014 the copy is parked in the dead letters of '${peerId}', so only that peer can revive it (bridge_nack { ids: ["${message.id}"] }); you can also re-issue the task` : " \u2014 bridge_task_status shows the task, bridge_notice or bridge_task can re-send it";
928
+ this.route(HUB_PEER, record.from, "notice", encodeContent({
929
+ message: `task ${record.id}: a delivery of it to '${peerId}' was dropped (${reason}). The task is still open${hint}.`,
930
+ level: "warn"
931
+ }), void 0, record.threadId, void 0, true);
788
932
  }
789
933
  /** All registered peer ids, insertion order. */
790
934
  peers() {
@@ -792,9 +936,22 @@ var AgentHub = class _AgentHub {
792
936
  }
793
937
  /** Register a peer; throws if the id is already taken. Client metadata
794
938
  * (when provided) refreshes the profile — with same-name sessions sharing a
795
- * peer, the freshest connect wins, which self-heals stale metadata. */
796
- register(peerId, client) {
939
+ * peer, the freshest connect wins, which self-heals stale metadata.
940
+ *
941
+ * `reclaim` is the caller asserting "this id is my own identity coming back":
942
+ * a parked peer still owns its mailbox, and only the identity may unwrap it
943
+ * into use again (see {@link ownsMailbox}). Every caller has to say so
944
+ * explicitly, so a new path cannot inherit someone else's mail by accident. */
945
+ register(peerId, client, options) {
946
+ if (peerId === BROADCAST) throw new Error(`reserved peer id: ${peerId} (it is the broadcast address)`);
947
+ if (peerId === HUB_PEER) throw new Error(`reserved peer id: ${peerId} (the hub uses it for its own notices)`);
948
+ if (this.groups.has(peerId)) {
949
+ throw new Error(`peer id '${peerId}' collides with a group: peer and group ids share one 'to' namespace, and the group would take every message addressed to it`);
950
+ }
797
951
  if (this.lastSeen.has(peerId)) throw new Error(`peer already registered: ${peerId}`);
952
+ if (!(options?.reclaim === true) && this.ownsMailbox(peerId)) {
953
+ throw new Error(`peer id '${peerId}' is parked: it still owns a mailbox for the peer that went quiet (only that identity can reclaim it; a manager can release it with bridge_unregister { peer })`);
954
+ }
798
955
  this.lastSeen.set(peerId, Date.now());
799
956
  this.parkedAt.delete(peerId);
800
957
  const existing = this.profiles.get(peerId);
@@ -825,8 +982,8 @@ var AgentHub = class _AgentHub {
825
982
  this.recordEvent("peer_parked", { peer: peerId, detail: { queued: queue.length } });
826
983
  } else {
827
984
  this.recordEvent("peer_left", { peer: peerId, detail: { queued: queue.length } });
828
- this.queues.delete(peerId);
829
- this.parkedAt.delete(peerId);
985
+ const now = Date.now();
986
+ this.dropMailboxState(peerId, (message) => this.failTaskForDroppedMessage(message, peerId, "unregistered", now));
830
987
  }
831
988
  for (const waiter of this.waiters.get(peerId) ?? []) {
832
989
  clearTimeout(waiter.timer);
@@ -836,6 +993,35 @@ var AgentHub = class _AgentHub {
836
993
  this.lastSeen.delete(peerId);
837
994
  this.options.onPeersChanged?.(this.peers());
838
995
  }
996
+ /** Forget EVERYTHING a mailbox owns — queue, in-flight leases, dead letters
997
+ * and the per-message attempt counters — in one step, calling `reconcile` on
998
+ * the tasks found in any of them.
999
+ *
1000
+ * The pieces have to go together. Anything left behind does not just leak: a
1001
+ * lease that outlives its mailbox is re-queued by the next reap under a peer
1002
+ * that has neither a registration nor a `parkedAt`, so no take and no TTL
1003
+ * sweep ever sees it and the message (and its task) stays pending forever.
1004
+ * Both callers — an explicit `unregister` (the peer left) and
1005
+ * `expireParkedMailboxes` (the parked TTL ran out) — mean the same thing
1006
+ * here, and only the ledger verdict differs, which is why that is the
1007
+ * parameter. Returns every message that went with the mailbox. */
1008
+ dropMailboxState(peerId, reconcile) {
1009
+ const queue = this.queues.get(peerId) ?? [];
1010
+ const inFlight = (this.leases.get(peerId) ?? []).map((lease) => lease.message);
1011
+ const deadLettered = this.deadLetters.get(peerId) ?? [];
1012
+ this.leases.delete(peerId);
1013
+ this.deadLetters.delete(peerId);
1014
+ for (const key of [...this.leaseAttempts.keys()]) {
1015
+ if (key.startsWith(`${peerId}\0`)) this.leaseAttempts.delete(key);
1016
+ }
1017
+ this.queues.delete(peerId);
1018
+ this.parkedAt.delete(peerId);
1019
+ const all = [...queue, ...inFlight, ...deadLettered];
1020
+ for (const message of all) {
1021
+ if (message.kind === "task") reconcile(message);
1022
+ }
1023
+ return all;
1024
+ }
839
1025
  /** Identity metadata for `peerId`, if the hub ever saw it. */
840
1026
  profileOf(peerId) {
841
1027
  return this.profiles.get(peerId);
@@ -892,7 +1078,7 @@ var AgentHub = class _AgentHub {
892
1078
  if (typeof raw !== "object" || raw === null) continue;
893
1079
  const candidate = raw;
894
1080
  const id = candidate.id;
895
- if (typeof id !== "string" || !PEER_ID_PATTERN.test(id) || id === BROADCAST) continue;
1081
+ if (typeof id !== "string" || !PEER_ID_PATTERN.test(id) || id === BROADCAST || id === HUB_PEER) continue;
896
1082
  if (this.profiles.has(id)) continue;
897
1083
  const profile = {
898
1084
  id,
@@ -932,6 +1118,12 @@ var AgentHub = class _AgentHub {
932
1118
  if (newId === HUB_PEER) throw new Error(`reserved peer id: ${newId}`);
933
1119
  if (!PEER_ID_PATTERN.test(newId)) throw new Error(`invalid peerId: ${newId} (expected [A-Za-z0-9._:-]{1,64})`);
934
1120
  if (this.lastSeen.has(newId)) throw new Error(`peer already registered: ${newId}`);
1121
+ if (this.groups.has(newId)) {
1122
+ throw new Error(`peer id '${newId}' collides with a group: peer and group ids share one 'to' namespace, and the group would take every message addressed to it`);
1123
+ }
1124
+ if (this.ownsMailbox(newId)) {
1125
+ throw new Error(`peer id '${newId}' is parked: it still owns a mailbox and will be delivered to when its owner returns (its owner takes it back with bridge_register { peerId }; a manager can release it with bridge_unregister { peer })`);
1126
+ }
935
1127
  const queue = this.queues.get(oldId);
936
1128
  const waiters = this.waiters.get(oldId);
937
1129
  const seen = this.lastSeen.get(oldId) ?? Date.now();
@@ -945,6 +1137,19 @@ var AgentHub = class _AgentHub {
945
1137
  this.profiles.delete(oldId);
946
1138
  if (queue !== void 0) this.queues.set(newId, queue);
947
1139
  if (waiters !== void 0) this.waiters.set(newId, waiters);
1140
+ const leases = this.leases.get(oldId);
1141
+ const deadLetters = this.deadLetters.get(oldId);
1142
+ this.leases.delete(oldId);
1143
+ this.deadLetters.delete(oldId);
1144
+ if (leases !== void 0) this.leases.set(newId, leases);
1145
+ if (deadLetters !== void 0) this.deadLetters.set(newId, deadLetters);
1146
+ const oldLeasePrefix = _AgentHub.leaseKey(oldId, "");
1147
+ for (const key of [...this.leaseAttempts.keys()]) {
1148
+ if (!key.startsWith(oldLeasePrefix)) continue;
1149
+ const attempts = this.leaseAttempts.get(key);
1150
+ this.leaseAttempts.delete(key);
1151
+ if (attempts !== void 0) this.leaseAttempts.set(_AgentHub.leaseKey(newId, key.slice(oldLeasePrefix.length)), attempts);
1152
+ }
948
1153
  this.lastSeen.set(newId, seen);
949
1154
  if (profile !== void 0) {
950
1155
  const merged = {
@@ -968,8 +1173,71 @@ var AgentHub = class _AgentHub {
968
1173
  if (message.from === oldId) message.from = newId;
969
1174
  if (message.to === oldId) message.to = newId;
970
1175
  }
1176
+ for (const record of this.taskLedger.values()) {
1177
+ if (record.from === oldId) record.from = newId;
1178
+ if (record.to === oldId && !this.groups.has(oldId)) record.to = newId;
1179
+ for (const event of record.acks) if (event.from === oldId) event.from = newId;
1180
+ for (const assignee of record.assignees) {
1181
+ if (assignee.peerId === oldId) assignee.peerId = newId;
1182
+ for (const event of assignee.acks) if (event.from === oldId) event.from = newId;
1183
+ }
1184
+ this.foldDuplicateAssignees(record);
1185
+ }
1186
+ let groupsChanged = false;
1187
+ for (const group of this.groups.values()) {
1188
+ if (!group.members.includes(oldId)) continue;
1189
+ group.members = [...new Set(group.members.map((member) => member === oldId ? newId : member))];
1190
+ groupsChanged = true;
1191
+ }
1192
+ if (groupsChanged) this.options.onGroupsChanged?.();
971
1193
  this.options.onPeersChanged?.(this.peers());
972
1194
  }
1195
+ /** Collapse assignee rows that ended up sharing a `peerId` (a rename onto an
1196
+ * id the task already had a row for).
1197
+ *
1198
+ * Duplicate rows break the ledger: `applyAckToLedger` finds the FIRST row for
1199
+ * the acking peer, so the second one never advances and the aggregate can sit
1200
+ * on a status no row supports. The merge prefers the row that is still open
1201
+ * (a rename must not close a task), keeps both timelines, and keeps the
1202
+ * EARLIEST delivery booking. */
1203
+ foldDuplicateAssignees(record) {
1204
+ const seen = /* @__PURE__ */ new Set();
1205
+ let duplicated = false;
1206
+ for (const assignee of record.assignees) {
1207
+ if (seen.has(assignee.peerId)) {
1208
+ duplicated = true;
1209
+ break;
1210
+ }
1211
+ seen.add(assignee.peerId);
1212
+ }
1213
+ if (!duplicated) return;
1214
+ const wasTerminal = TERMINAL_TASK_STATUSES.includes(record.status);
1215
+ const byPeer = /* @__PURE__ */ new Map();
1216
+ const folded = [];
1217
+ for (const assignee of record.assignees) {
1218
+ const first = byPeer.get(assignee.peerId);
1219
+ if (first === void 0) {
1220
+ const copy = { ...assignee, acks: [...assignee.acks] };
1221
+ byPeer.set(assignee.peerId, copy);
1222
+ folded.push(copy);
1223
+ continue;
1224
+ }
1225
+ const firstOpen = !TERMINAL_TASK_STATUSES.includes(first.status);
1226
+ if (!(firstOpen && TERMINAL_TASK_STATUSES.includes(assignee.status))) {
1227
+ first.status = assignee.status;
1228
+ }
1229
+ first.acks.push(...assignee.acks);
1230
+ this.trimAcks(first.acks);
1231
+ if (assignee.deliveredMs !== void 0 && (first.deliveredMs === void 0 || assignee.deliveredMs < first.deliveredMs)) {
1232
+ first.deliveredMs = assignee.deliveredMs;
1233
+ }
1234
+ }
1235
+ record.assignees = folded;
1236
+ record.status = aggregateTaskStatus(folded);
1237
+ if (wasTerminal && record.deadlineAt !== void 0 && !TERMINAL_TASK_STATUSES.includes(record.status)) {
1238
+ this.scheduleTaskTimeout(record);
1239
+ }
1240
+ }
973
1241
  /** Keep the profile map bounded: drop the oldest profiles of peers that are
974
1242
  * NOT currently registered (live peers are never evicted). */
975
1243
  evictOverflowProfiles() {
@@ -990,6 +1258,13 @@ var AgentHub = class _AgentHub {
990
1258
  has(peerId) {
991
1259
  return this.lastSeen.has(peerId);
992
1260
  }
1261
+ /** Does `peerId` still own state it never released — a parked record or a
1262
+ * queued mailbox? This is identity, not liveness: `has()` is false for such a
1263
+ * peer, yet the id is still taken. `register({ reclaim })` and `renamePeer`
1264
+ * both key off this, so "taken" cannot drift between the two write points. */
1265
+ ownsMailbox(peerId) {
1266
+ return this.parkedAt.has(peerId) || this.queues.has(peerId);
1267
+ }
993
1268
  /** Is the peer parked — gone from the live registry through idle GC, but still
994
1269
  * holding its mailbox and still addressable? `has()` is false for it, so a
995
1270
  * guard written only as `has()` will decide there is nothing to do and leave
@@ -1023,12 +1298,22 @@ var AgentHub = class _AgentHub {
1023
1298
  }
1024
1299
  /** Send an acknowledgement back to the sender of `ref`. Updates the task
1025
1300
  * ledger when `ref` is a known task (looked up in the ledger first, so acks
1026
- * survive history-ring eviction); chat/notice refs still route via history. */
1301
+ * survive history-ring eviction); chat/notice refs still route via history.
1302
+ *
1303
+ * Only an ASSIGNEE may ack a task. Everyone else could otherwise close someone
1304
+ * else's task — and land their own artifacts in it — just by learning the
1305
+ * message id. A ref that is not a task carries no ledger row to protect, so an
1306
+ * ack for chat/notice keeps routing without any permission check. The single
1307
+ * place this is decided is here: `bridge_ack` adds no rule of its own, so the
1308
+ * direct API (`ackForRunner`, an assignee by construction) is unaffected. */
1027
1309
  sendAck(from, ref, ack) {
1028
1310
  const task = this.taskLedger.get(ref);
1029
1311
  let target;
1030
1312
  let threadId;
1031
1313
  if (task !== void 0) {
1314
+ if (!task.assignees.some((assignee) => assignee.peerId === from)) {
1315
+ throw new Error("only an assignee of this task can ack it");
1316
+ }
1032
1317
  target = task.from;
1033
1318
  threadId = task.threadId;
1034
1319
  } else {
@@ -1088,9 +1373,9 @@ var AgentHub = class _AgentHub {
1088
1373
  messageId: message.id,
1089
1374
  applied: true
1090
1375
  };
1091
- record.acks.push(event);
1376
+ this.pushAckEvent(record, event);
1092
1377
  assignee.status = "canceled";
1093
- assignee.acks.push({ ...event });
1378
+ this.pushAssigneeAck(assignee, event);
1094
1379
  last = message;
1095
1380
  }
1096
1381
  if (last === void 0) throw new Error(`task ${ref} has no assignee left to cancel`);
@@ -1119,10 +1404,10 @@ var AgentHub = class _AgentHub {
1119
1404
  for (const assignee of targets) {
1120
1405
  const message = this.route(from, assignee.peerId, "ack", JSON.stringify(ack), ref, record.threadId);
1121
1406
  const event = { from, status: "working", note: input, ts: message.ts, messageId: message.id, applied: true };
1122
- record.acks.push(event);
1407
+ this.pushAckEvent(record, event);
1123
1408
  if (assignee.status === "input-required") {
1124
1409
  assignee.status = "working";
1125
- assignee.acks.push({ ...event });
1410
+ this.pushAssigneeAck(assignee, event);
1126
1411
  }
1127
1412
  last = message;
1128
1413
  }
@@ -1207,11 +1492,11 @@ var AgentHub = class _AgentHub {
1207
1492
  applied: true,
1208
1493
  system: true
1209
1494
  };
1210
- record.acks.push(event);
1495
+ this.pushAckEvent(record, event);
1211
1496
  for (const assignee of record.assignees) {
1212
1497
  if (!TERMINAL_TASK_STATUSES.includes(assignee.status)) {
1213
1498
  assignee.status = "timeout";
1214
- assignee.acks.push({ ...event });
1499
+ this.pushAssigneeAck(assignee, event);
1215
1500
  }
1216
1501
  }
1217
1502
  record.status = "timeout";
@@ -1226,6 +1511,23 @@ var AgentHub = class _AgentHub {
1226
1511
  this.taskTimers.delete(taskId);
1227
1512
  }
1228
1513
  }
1514
+ /** Bring the SLA timer back in line with the AGGREGATE status after a
1515
+ * per-assignee write ({@link failTaskForGoneAssignee},
1516
+ * {@link failTaskForDroppedMessage}).
1517
+ *
1518
+ * A terminal task must not fire a second, contradictory timeout. A task that
1519
+ * is still open — a fan-out with one recipient lost and another working —
1520
+ * must keep its deadline: clearing the timer there left a task that stays
1521
+ * non-terminal forever, because `deadlineAt` is only read by the timer. */
1522
+ realignTaskTimer(record) {
1523
+ if (TERMINAL_TASK_STATUSES.includes(record.status)) {
1524
+ this.clearTaskTimer(record.id);
1525
+ return;
1526
+ }
1527
+ if (record.deadlineAt === void 0) return;
1528
+ if (this.taskTimers.has(record.id)) return;
1529
+ this.scheduleTaskTimeout(record);
1530
+ }
1229
1531
  /** Note that `target` has taken delivery of a task (waiter handoff / queue). */
1230
1532
  markTaskDelivered(taskId, target, ts) {
1231
1533
  const record = this.taskLedger.get(taskId);
@@ -1245,10 +1547,9 @@ var AgentHub = class _AgentHub {
1245
1547
  applyAckToLedger(message, from, ref, ack) {
1246
1548
  const record = this.taskLedger.get(ref);
1247
1549
  if (record === void 0) return;
1248
- const next = nextTaskStatus(record.status, ack.status);
1249
1550
  const assignee = record.assignees.find((a) => a.peerId === from);
1250
1551
  const assigneeNext = assignee === void 0 ? null : nextTaskStatus(assignee.status, ack.status);
1251
- const applied = record.assignees.length <= 1 ? next !== null : assigneeNext !== null;
1552
+ const applied = assignee !== void 0 && assigneeNext !== null;
1252
1553
  const event = {
1253
1554
  from,
1254
1555
  status: ack.status,
@@ -1259,20 +1560,17 @@ var AgentHub = class _AgentHub {
1259
1560
  messageId: message.id,
1260
1561
  applied
1261
1562
  };
1262
- record.acks.push(event);
1563
+ this.pushAckEvent(record, event);
1263
1564
  if (applied && event.artifacts !== void 0) {
1264
- record.artifacts = [...record.artifacts ?? [], ...event.artifacts];
1565
+ const merged = [...record.artifacts ?? [], ...event.artifacts];
1566
+ record.artifacts = merged.length > MAX_TASK_ARTIFACTS ? merged.slice(-MAX_TASK_ARTIFACTS) : merged;
1265
1567
  }
1266
1568
  if (assignee !== void 0 && assigneeNext !== null) {
1267
1569
  assignee.status = assigneeNext;
1268
- assignee.acks.push({ ...event });
1269
- }
1270
- if (record.assignees.length <= 1) {
1271
- if (next !== null) record.status = next;
1272
- } else {
1273
- record.status = aggregateTaskStatus(record.assignees);
1570
+ this.pushAssigneeAck(assignee, event);
1274
1571
  }
1275
- record.updatedAt = message.ts;
1572
+ if (record.assignees.length > 0) record.status = aggregateTaskStatus(record.assignees);
1573
+ if (applied) record.updatedAt = message.ts;
1276
1574
  if (TERMINAL_TASK_STATUSES.includes(record.status)) this.clearTaskTimer(record.id);
1277
1575
  this.taskChanged(this.taskOf(record.id));
1278
1576
  }
@@ -1293,7 +1591,10 @@ var AgentHub = class _AgentHub {
1293
1591
  const record = this.taskLedger.get(ref);
1294
1592
  if (record === void 0) return void 0;
1295
1593
  return {
1296
- ...record,
1594
+ // `dropNotified` is INTERNAL bookkeeping (see protocol.ts). A shallow
1595
+ // spread used to hand it to bridge_task_status / bridge_tasks, which made
1596
+ // an implementation detail part of the published task shape.
1597
+ ...omit(record, "dropNotified"),
1297
1598
  acks: record.acks.map((a) => ({ ...a })),
1298
1599
  assignees: record.assignees.map((a) => ({ ...a, acks: a.acks.map((e) => ({ ...e })) }))
1299
1600
  };
@@ -1328,6 +1629,35 @@ var AgentHub = class _AgentHub {
1328
1629
  exportTasks() {
1329
1630
  return [...this.taskLedger.values()].map((record) => this.taskOf(record.id)).filter(Boolean);
1330
1631
  }
1632
+ /** Accept a peer id read from a persisted snapshot, or `undefined` when the
1633
+ * row that carries it is unusable. A state file is external input and the
1634
+ * ledger is an AUTHORIZATION source (ack rights, `bridge_task_status`,
1635
+ * `bridge_task_input`), so a row attributed to `hub`, to the broadcast
1636
+ * address, to a malformed id or to a group id would hand that identity rights
1637
+ * over someone else's task. Every place a snapshot names a peer goes through
1638
+ * here — the task sender, an ack author, an assignee — so the four fields
1639
+ * cannot drift apart. */
1640
+ importPeerRef(value) {
1641
+ if (typeof value !== "string") return void 0;
1642
+ if (!PEER_ID_PATTERN.test(value) || value === BROADCAST || value === HUB_PEER) return void 0;
1643
+ if (this.groups.has(value)) return void 0;
1644
+ return value;
1645
+ }
1646
+ /** Accept an ACK AUTHOR read from a persisted snapshot.
1647
+ *
1648
+ * Deliberately weaker than {@link importPeerRef} in exactly one direction: an
1649
+ * ack row authorizes nothing (the ledger's authorization sources are the
1650
+ * sender and the assignee rows, both checked strictly), while the hub itself
1651
+ * authors terminal markers under the task's RECIPIENT address — `from: "hub"`
1652
+ * for the "restored as unattributable" marker and `from: record.to` (a group
1653
+ * id, or `all`) for a fan-out timeout. Refusing those ids here would delete the
1654
+ * evidence that a task timed out, and the unattributable marker would be
1655
+ * re-appended on every boot because its idempotency test looks for the stored
1656
+ * `import-<id>` row. Malformed ids are still refused. */
1657
+ importAckRef(value) {
1658
+ if (typeof value !== "string" || !PEER_ID_PATTERN.test(value)) return void 0;
1659
+ return value;
1660
+ }
1331
1661
  /** Restore the task ledger at boot (and re-arm SLA timers). */
1332
1662
  importTasks(tasks) {
1333
1663
  if (!Array.isArray(tasks)) return 0;
@@ -1336,13 +1666,16 @@ var AgentHub = class _AgentHub {
1336
1666
  if (typeof raw !== "object" || raw === null) continue;
1337
1667
  const t = raw;
1338
1668
  if (typeof t.id !== "string" || typeof t.from !== "string" || typeof t.to !== "string" || typeof t.prompt !== "string") continue;
1339
- if (typeof t.status !== "string" || !TERMINAL_TASK_STATUSES.includes(t.status) && t.status !== "pending" && t.status !== "accepted" && t.status !== "working") continue;
1669
+ if (typeof t.status !== "string" || !ALL_TASK_STATUSES.includes(t.status)) continue;
1670
+ const from = this.importPeerRef(t.from);
1671
+ if (from === void 0) continue;
1340
1672
  const acks = Array.isArray(t.acks) ? t.acks.flatMap((rawAck) => {
1341
1673
  if (typeof rawAck !== "object" || rawAck === null) return [];
1342
1674
  const a = rawAck;
1343
- if (typeof a.from !== "string" || typeof a.status !== "string" || typeof a.ts !== "number" || typeof a.messageId !== "string") return [];
1675
+ const ackFrom = this.importAckRef(a.from);
1676
+ if (ackFrom === void 0 || typeof a.status !== "string" || !ALL_ACK_STATUSES.includes(a.status) || typeof a.ts !== "number" || typeof a.messageId !== "string") return [];
1344
1677
  return [{
1345
- from: a.from,
1678
+ from: ackFrom,
1346
1679
  status: a.status,
1347
1680
  ...typeof a.note === "string" ? { note: a.note } : {},
1348
1681
  ...typeof a.progress === "number" ? { progress: a.progress } : {},
@@ -1352,20 +1685,22 @@ var AgentHub = class _AgentHub {
1352
1685
  ...a.system === true ? { system: true } : {}
1353
1686
  }];
1354
1687
  }) : [];
1355
- const assignees = Array.isArray(t.assignees) && t.assignees.length > 0 ? t.assignees.flatMap((rawA) => {
1688
+ const storedAssignees = Array.isArray(t.assignees) ? t.assignees.flatMap((rawA) => {
1356
1689
  if (typeof rawA !== "object" || rawA === null) return [];
1357
1690
  const a = rawA;
1358
- if (typeof a.peerId !== "string" || typeof a.status !== "string") return [];
1691
+ const assigneeId = this.importPeerRef(a.peerId);
1692
+ if (assigneeId === void 0 || typeof a.status !== "string" || !ALL_TASK_STATUSES.includes(a.status)) return [];
1359
1693
  return [{
1360
- peerId: a.peerId,
1694
+ peerId: assigneeId,
1361
1695
  status: a.status,
1362
1696
  ...typeof a.deliveredMs === "number" ? { deliveredMs: a.deliveredMs } : {},
1363
1697
  acks: Array.isArray(a.acks) ? a.acks.flatMap((rawE) => {
1364
1698
  if (typeof rawE !== "object" || rawE === null) return [];
1365
1699
  const e = rawE;
1366
- if (typeof e.from !== "string" || typeof e.status !== "string" || typeof e.ts !== "number" || typeof e.messageId !== "string") return [];
1700
+ const eventFrom = this.importAckRef(e.from);
1701
+ if (eventFrom === void 0 || typeof e.status !== "string" || !ALL_ACK_STATUSES.includes(e.status) || typeof e.ts !== "number" || typeof e.messageId !== "string") return [];
1367
1702
  return [{
1368
- from: e.from,
1703
+ from: eventFrom,
1369
1704
  status: e.status,
1370
1705
  ...typeof e.note === "string" ? { note: e.note } : {},
1371
1706
  ts: e.ts,
@@ -1374,10 +1709,12 @@ var AgentHub = class _AgentHub {
1374
1709
  }];
1375
1710
  }) : []
1376
1711
  }];
1377
- }) : [{ peerId: t.to, status: t.status, acks: [] }];
1712
+ }) : [];
1713
+ const unattributable = storedAssignees.length === 0 && (t.to === BROADCAST || this.groups.has(t.to) || !PEER_ID_PATTERN.test(t.to));
1714
+ const assignees = storedAssignees.length > 0 ? storedAssignees : unattributable ? [] : [{ peerId: t.to, status: t.status, acks: [] }];
1378
1715
  const record = {
1379
1716
  id: t.id,
1380
- from: t.from,
1717
+ from,
1381
1718
  to: t.to,
1382
1719
  prompt: t.prompt,
1383
1720
  ...typeof t.context === "string" ? { context: t.context } : {},
@@ -1391,6 +1728,21 @@ var AgentHub = class _AgentHub {
1391
1728
  createdAt: typeof t.createdAt === "number" ? t.createdAt : Date.now(),
1392
1729
  updatedAt: typeof t.updatedAt === "number" ? t.updatedAt : Date.now()
1393
1730
  };
1731
+ if (unattributable) {
1732
+ record.status = "failed";
1733
+ if (!record.acks.some((event) => event.messageId === `import-${record.id}`)) {
1734
+ this.pushAckEvent(record, {
1735
+ from: HUB_PEER,
1736
+ status: "failed",
1737
+ note: `restored as failed: the stored record has no assignee row and its recipient '${t.to}' is not a peer id, so the task cannot be attributed to anyone and can never be acked`,
1738
+ ts: record.updatedAt,
1739
+ messageId: `import-${record.id}`,
1740
+ applied: true,
1741
+ system: true
1742
+ });
1743
+ }
1744
+ }
1745
+ if (assignees.length > 0) record.status = aggregateTaskStatus(assignees);
1394
1746
  this.taskLedger.set(record.id, record);
1395
1747
  this.scheduleTaskTimeout(record);
1396
1748
  count++;
@@ -1436,6 +1788,11 @@ var AgentHub = class _AgentHub {
1436
1788
  createGroup(id, members, createdBy, name) {
1437
1789
  if (this.groups.has(id)) throw new Error(`group already exists: ${id}`);
1438
1790
  if (!PEER_ID_PATTERN.test(id)) throw new Error(`invalid group id: ${id} (expected [A-Za-z0-9._:-]{1,64})`);
1791
+ if (id === BROADCAST) throw new Error(`group id '${id}' is taken: it is the broadcast address in the namespace peer and group ids share`);
1792
+ if (id === HUB_PEER) throw new Error(`group id '${id}' is taken: the hub uses it for its own notices`);
1793
+ if (this.lastSeen.has(id) || this.ownsMailbox(id) || this.profiles.has(id)) {
1794
+ throw new Error(`group id '${id}' collides with a peer: peer and group ids share one 'to' namespace, and a group would win every message addressed to that peer`);
1795
+ }
1439
1796
  const unique = [...new Set(members)];
1440
1797
  if (unique.length === 0) throw new Error("a group needs at least one member");
1441
1798
  for (const member of unique) {
@@ -1487,11 +1844,14 @@ var AgentHub = class _AgentHub {
1487
1844
  }
1488
1845
  /** Send a chat message to every member of a group except the sender;
1489
1846
  * members that went offline are skipped (they read the group history).
1490
- * The message carries `to` and `channel` = the group id. */
1847
+ * The message carries `to` and `channel` = the group id.
1848
+ *
1849
+ * Membership is enforced once, in {@link compose} — the single path this and
1850
+ * a plain `bridge_chat { to: <group> }` both go through. The `unknown group`
1851
+ * check stays here so a caller naming a non-group gets that error instead of
1852
+ * compose's generic "unknown recipient". */
1491
1853
  sendToGroup(from, groupId, content) {
1492
- const group = this.groups.get(groupId);
1493
- if (group === void 0) throw new Error(`unknown group: ${groupId}`);
1494
- if (!group.members.includes(from)) throw new Error(`peer '${from}' is not a member of group '${groupId}'`);
1854
+ if (!this.groups.has(groupId)) throw new Error(`unknown group: ${groupId}`);
1495
1855
  return this.route(from, groupId, "chat", content);
1496
1856
  }
1497
1857
  /** Snapshot of every group for persistence. */
@@ -1507,6 +1867,8 @@ var AgentHub = class _AgentHub {
1507
1867
  if (typeof raw !== "object" || raw === null) continue;
1508
1868
  const candidate = raw;
1509
1869
  if (typeof candidate.id !== "string" || !PEER_ID_PATTERN.test(candidate.id) || this.groups.has(candidate.id)) continue;
1870
+ if (candidate.id === BROADCAST || candidate.id === HUB_PEER) continue;
1871
+ if (this.lastSeen.has(candidate.id) || this.profiles.has(candidate.id)) continue;
1510
1872
  if (!Array.isArray(candidate.members) || candidate.members.length === 0) continue;
1511
1873
  const members = [...new Set(candidate.members.filter((m) => typeof m === "string" && PEER_ID_PATTERN.test(m)))];
1512
1874
  if (members.length === 0) continue;
@@ -1517,13 +1879,19 @@ var AgentHub = class _AgentHub {
1517
1879
  createdAt: typeof candidate.createdAt === "number" && Number.isFinite(candidate.createdAt) ? candidate.createdAt : Date.now(),
1518
1880
  ...typeof candidate.name === "string" && candidate.name !== "" ? { name: candidate.name } : {}
1519
1881
  });
1882
+ this.queues.delete(candidate.id);
1883
+ this.parkedAt.delete(candidate.id);
1520
1884
  count++;
1521
1885
  }
1522
1886
  return count;
1523
1887
  }
1524
1888
  // ---- persistence import/export (remote-mode SQLite store) -----------
1525
1889
  /** Restore the history ring at boot. Shape-invalid rows are dropped; only
1526
- * the newest {@link HubOptions.historyLimit} survive. */
1890
+ * the newest {@link HubOptions.historyLimit} survive.
1891
+ *
1892
+ * Restoring is a FIELD WHITELIST: a wire field that is not listed here is
1893
+ * silently lost across a restart (that is how `priority` went missing), so
1894
+ * every new field on {@link BridgeMessage} has to be added below. */
1527
1895
  importHistory(messages) {
1528
1896
  if (!Array.isArray(messages)) return 0;
1529
1897
  const valid = [];
@@ -1548,6 +1916,9 @@ var AgentHub = class _AgentHub {
1548
1916
  // state for history that predates the cursor.
1549
1917
  ...typeof m.seq === "number" && Number.isFinite(m.seq) && m.seq > 0 ? { seq: m.seq } : {},
1550
1918
  ...typeof m.expiresAt === "number" && Number.isFinite(m.expiresAt) && m.expiresAt > 0 ? { expiresAt: m.expiresAt } : {},
1919
+ // Same guard as compose: only a real 0 | 1 | 2 is written back, an
1920
+ // absent one stays absent so no reader has to tell 0 from "unset".
1921
+ ...m.priority === 0 || m.priority === 1 || m.priority === 2 ? { priority: m.priority } : {},
1551
1922
  ts: m.ts
1552
1923
  });
1553
1924
  }
@@ -1557,19 +1928,53 @@ var AgentHub = class _AgentHub {
1557
1928
  for (const message of valid.slice(-this.options.historyLimit)) this.historyRing.push(message);
1558
1929
  return Math.min(valid.length, this.options.historyLimit);
1559
1930
  }
1560
- /** Snapshot of every offline mailbox, keyed by peer (persistence). */
1931
+ /** Snapshot of every offline mailbox, keyed by peer (persistence).
1932
+ *
1933
+ * Manual-ack leases ride along inside the peer's queue array: appended after
1934
+ * the queued mail, in lease order, and deliberately NOT re-sorted (the
1935
+ * restore path re-orders, see {@link importMailboxes}). A lease is a
1936
+ * delivery in progress — the message left the queue but was never committed
1937
+ * — and leaving it out is how an uncommitted message used to be in neither
1938
+ * `queues` nor SQLite and vanished on restart.
1939
+ *
1940
+ * EVERY lease is exported, expired or not: this is a snapshot of what the
1941
+ * hub knows was handed out, not a reachability verdict. Expiry is decided by
1942
+ * the CONSUMER (`poll` / `wait` / `reapLeases`), which drops an expired
1943
+ * message, counts it as `droppedExpired` and reconciles the ledger. Filtering
1944
+ * on `expiresAt` here created a window with no owner at all: a lease that
1945
+ * expired but was never reaped (no take, and `gcTick` does not run when
1946
+ * `peerIdleTimeoutMs` is 0) was written out by the next unrelated flush or
1947
+ * by a graceful shutdown — i.e. neither in the queue nor in the snapshot —
1948
+ * and the message was gone for good.
1949
+ *
1950
+ * No new top-level key on purpose: an older hub reading this snapshot sees
1951
+ * ordinary queued mail and redelivers it once, which is exactly the
1952
+ * at-least-once half of the lease contract.
1953
+ *
1954
+ * `attempts` does NOT survive: the counter lives in `leaseAttempts` (memory
1955
+ * only), so a restarted hub starts the message over at attempt 1. Treat
1956
+ * `maxAttempts` as a bound per PROCESS, not per message lifetime. */
1561
1957
  exportMailboxes() {
1562
1958
  const out = {};
1563
1959
  for (const [peer, queue] of this.queues) {
1564
1960
  if (queue.length > 0) out[peer] = queue.map((message) => ({ ...message }));
1565
1961
  }
1962
+ for (const [peer, leases] of this.leases) {
1963
+ if (leases.length === 0) continue;
1964
+ const messages = out[peer] ?? (out[peer] = []);
1965
+ for (const lease of leases) messages.push({ ...lease.message });
1966
+ }
1566
1967
  return out;
1567
1968
  }
1568
- /** Restore offline mailboxes at boot (peer reconnects and drains later). */
1969
+ /** Restore offline mailboxes at boot (peer reconnects and drains later).
1970
+ *
1971
+ * Like {@link importHistory} this is a FIELD WHITELIST — a new wire field
1972
+ * must be added in both places or it is lost across a restart. */
1569
1973
  importMailboxes(mailboxes) {
1570
1974
  if (typeof mailboxes !== "object" || mailboxes === null) return 0;
1571
1975
  let count = 0;
1572
1976
  for (const [peer, queue] of Object.entries(mailboxes)) {
1977
+ if (!PEER_ID_PATTERN.test(peer) || peer === BROADCAST || peer === HUB_PEER || this.groups.has(peer)) continue;
1573
1978
  if (!Array.isArray(queue) || queue.length === 0) continue;
1574
1979
  const restored = [];
1575
1980
  for (const raw of queue) {
@@ -1592,13 +1997,27 @@ var AgentHub = class _AgentHub {
1592
1997
  // cursor has to stay continuous across a restart.
1593
1998
  ...typeof m.seq === "number" && Number.isFinite(m.seq) && m.seq > 0 ? { seq: m.seq } : {},
1594
1999
  ...typeof m.expiresAt === "number" && Number.isFinite(m.expiresAt) && m.expiresAt > 0 ? { expiresAt: m.expiresAt } : {},
2000
+ // Priority decides both the mailbox order and what overflow drops, so
2001
+ // dropping it here would quietly downgrade restored mail to FIFO.
2002
+ ...m.priority === 0 || m.priority === 1 || m.priority === 2 ? { priority: m.priority } : {},
1595
2003
  ts: m.ts
1596
2004
  });
1597
2005
  }
1598
2006
  if (restored.length > 0) {
1599
- this.queues.set(peer, restored.slice(-this.options.maxQueue));
2007
+ const mailbox = [];
2008
+ insertByPriority(mailbox, [...restored].sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0)));
2009
+ const now = Date.now();
2010
+ while (mailbox.length > this.options.maxQueue) {
2011
+ const victimIndex = lowestPriorityIndex(mailbox);
2012
+ if (victimIndex < 0) break;
2013
+ const [evicted] = mailbox.splice(victimIndex, 1);
2014
+ if (evicted === void 0) break;
2015
+ this.countDrop(peer, "overflow", now, evicted);
2016
+ if (evicted.kind === "task") this.noteTaskDeliveryDropped(evicted, peer, "overflow", now);
2017
+ }
2018
+ this.queues.set(peer, mailbox);
1600
2019
  if (!this.lastSeen.has(peer)) this.parkedAt.set(peer, Date.now());
1601
- count += restored.length;
2020
+ count += mailbox.length;
1602
2021
  }
1603
2022
  }
1604
2023
  return count;
@@ -1764,12 +2183,27 @@ var AgentHub = class _AgentHub {
1764
2183
  this.buckets.set(peerId, bucket);
1765
2184
  return true;
1766
2185
  }
1767
- countDrop(peerId, kind, now) {
2186
+ /** Count a dropped message. `message` (when the caller has it) names the loss
2187
+ * in the event detail: the counter alone told an operator that something went
2188
+ * missing, never what — and a dropped task is reconciled in the ledger, which
2189
+ * has to be matchable back to this event. */
2190
+ countDrop(peerId, kind, now, message) {
1768
2191
  const stats = this.drops.get(peerId) ?? { overflow: 0, expired: 0, rate: 0 };
1769
2192
  stats[kind] += 1;
1770
2193
  this.drops.set(peerId, stats);
1771
2194
  const total = stats.overflow + stats.expired + stats.rate;
1772
- this.recordEvent("mailbox_dropped", { peer: peerId, detail: { reason: kind, total } });
2195
+ this.recordEvent("mailbox_dropped", {
2196
+ peer: peerId,
2197
+ detail: {
2198
+ reason: kind,
2199
+ total,
2200
+ ...message !== void 0 ? { messageId: message.id } : {},
2201
+ // The ledger is keyed by the task's message id, so this repeats
2202
+ // `messageId` today; it is spelled out so a consumer looking for "the
2203
+ // task this drop killed" does not have to know that.
2204
+ ...message !== void 0 && message.kind === "task" ? { taskId: message.id } : {}
2205
+ }
2206
+ });
1773
2207
  const notice = {
1774
2208
  id: randomUUID(),
1775
2209
  seq: ++this.seqCounter,
@@ -1803,12 +2237,7 @@ var AgentHub = class _AgentHub {
1803
2237
  * was handed over. */
1804
2238
  deliverToWaiter(target, message) {
1805
2239
  const list = this.waiters.get(target) ?? [];
1806
- const index = list.findIndex((waiter2) => {
1807
- if (waiter2.from !== void 0 && waiter2.from !== message.from) return false;
1808
- if (waiter2.ref !== void 0 && !(message.kind === "ack" && message.ref === waiter2.ref)) return false;
1809
- if (waiter2.threadId !== void 0 && message.threadId !== waiter2.threadId) return false;
1810
- return true;
1811
- });
2240
+ const index = list.findIndex((waiter2) => matchesWaiter(waiter2, message, this.taskLedger));
1812
2241
  if (index < 0) return false;
1813
2242
  const [waiter] = list.splice(index, 1);
1814
2243
  this.waiters.set(target, list);
@@ -1819,15 +2248,34 @@ var AgentHub = class _AgentHub {
1819
2248
  static leaseKey(peerId, messageId) {
1820
2249
  return `${peerId}\0${messageId}`;
1821
2250
  }
1822
- /** Return expired leases to the FRONT of the queue (order preserved), or
1823
- * dead-letter them once they have been handed out too many times. Called
1824
- * before every take, so expiry needs no timer of its own. */
2251
+ /** Drop every queued message of `peerId` whose deadline passed, counting each
2252
+ * loss. Shared by `poll` and `wait`: an expired message must never be handed
2253
+ * out, and it must not sit at the head of the mailbox looking deliverable
2254
+ * either.
2255
+ *
2256
+ * The attempt counter goes with it. Nothing can hand the message out again,
2257
+ * so keeping the key would leak one `leaseAttempts` entry per expired message
2258
+ * in a long-running process. */
2259
+ sweepExpired(peerId, queue, now) {
2260
+ for (let i = queue.length - 1; i >= 0; i--) {
2261
+ const queued = queue[i];
2262
+ if (queued.expiresAt === void 0 || queued.expiresAt > now) continue;
2263
+ queue.splice(i, 1);
2264
+ this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, queued.id));
2265
+ this.countDrop(peerId, "expired", now, queued);
2266
+ if (queued.kind === "task") this.noteTaskDeliveryDropped(queued, peerId, "expired", now);
2267
+ }
2268
+ }
2269
+ /** Return expired leases to the queue in priority order, or dead-letter them
2270
+ * once they have been handed out too many times. Called before every take, so
2271
+ * expiry needs no timer of its own. */
1825
2272
  reapLeases(peerId, now) {
1826
2273
  const list = this.leases.get(peerId);
1827
2274
  if (list === void 0 || list.length === 0) return;
1828
2275
  const max = this.options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
1829
2276
  const still = [];
1830
2277
  const back = [];
2278
+ const dead = [];
1831
2279
  for (const lease of list) {
1832
2280
  if (lease.expiresAt > now) {
1833
2281
  still.push(lease);
@@ -1835,20 +2283,61 @@ var AgentHub = class _AgentHub {
1835
2283
  }
1836
2284
  const attempts = this.leaseAttempts.get(_AgentHub.leaseKey(peerId, lease.message.id)) ?? 0;
1837
2285
  if (max > 0 && attempts >= max) {
1838
- const dead = this.deadLetters.get(peerId) ?? [];
1839
2286
  dead.push(lease.message);
1840
- this.deadLetters.set(peerId, dead);
1841
2287
  continue;
1842
2288
  }
1843
2289
  back.push(lease.message);
1844
2290
  }
1845
2291
  if (still.length > 0) this.leases.set(peerId, still);
1846
2292
  else this.leases.delete(peerId);
1847
- if (back.length > 0) {
1848
- const queue = this.queues.get(peerId) ?? [];
1849
- insertByPriority(queue, back);
1850
- this.queues.set(peerId, queue);
1851
- this.options.onMailboxesChanged?.();
2293
+ if (back.length > 0) this.requeue(peerId, back, now);
2294
+ if (dead.length > 0) this.deadLetter(peerId, dead, now);
2295
+ }
2296
+ /** Put messages back into `peerId`'s mailbox, trimming to `maxQueue`.
2297
+ *
2298
+ * A message coming BACK competes for a slot exactly like arriving mail, so it
2299
+ * can never grow a full mailbox: `insertByPriority` orders it, then the tail
2300
+ * (lowest priority, newest) is what does not fit. Those go to the dead letters
2301
+ * instead of being dropped — a requeued message is a message the hub promised
2302
+ * to keep, and `bridge_nack` can still revive it. Returns how many really made
2303
+ * it into the queue. */
2304
+ requeue(peerId, messages, now) {
2305
+ if (messages.length === 0) return 0;
2306
+ const queue = this.queues.get(peerId) ?? [];
2307
+ insertByPriority(queue, messages);
2308
+ this.queues.set(peerId, queue);
2309
+ const overflow = [];
2310
+ while (queue.length > this.options.maxQueue) overflow.push(queue.pop());
2311
+ this.options.onMailboxesChanged?.();
2312
+ if (overflow.length > 0) this.deadLetter(peerId, overflow, now);
2313
+ const inQueue = new Set(queue);
2314
+ return messages.reduce((kept, message) => kept + (inQueue.has(message) ? 1 : 0), 0);
2315
+ }
2316
+ /** Park messages that can no longer be handed out (attempts exhausted, or no
2317
+ * room in the mailbox). One bounded list per peer — see MAX_DEAD_LETTERS.
2318
+ *
2319
+ * The OLDEST entry is evicted first: it is the one a `bridge_nack` is least
2320
+ * likely to still want, and reviving resets attempts anyway. The eviction is
2321
+ * COUNTED (`droppedOverflow` + a `mailbox_dropped` event naming the message)
2322
+ * rather than silent, so a full dead-letter list is still visible.
2323
+ *
2324
+ * An evicted TASK is the exception: it settles as a terminal failure. A dead
2325
+ * letter is the last copy of a message the hub promised to keep, and the
2326
+ * sender was told `bridge_nack` can revive it — once it is evicted, no
2327
+ * revival path exists, so leaving the ledger non-terminal would keep
2328
+ * promising something that cannot happen (same rule as `unregistered`). */
2329
+ deadLetter(peerId, messages, now) {
2330
+ const dead = this.deadLetters.get(peerId) ?? [];
2331
+ dead.push(...messages);
2332
+ const evicted = dead.length > MAX_DEAD_LETTERS ? dead.splice(0, dead.length - MAX_DEAD_LETTERS) : [];
2333
+ this.deadLetters.set(peerId, dead);
2334
+ for (const message of messages) {
2335
+ if (message.kind === "task") this.noteTaskDeliveryDropped(message, peerId, "dead-letter", now);
2336
+ }
2337
+ for (const message of evicted) {
2338
+ this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, message.id));
2339
+ this.countDrop(peerId, "overflow", now, message);
2340
+ if (message.kind === "task") this.failTaskForDroppedMessage(message, peerId, "dead-letter-evicted", now);
1852
2341
  }
1853
2342
  }
1854
2343
  /** Hand a message to `peerId`. Without `manual` it is gone; with it the hub
@@ -1862,6 +2351,7 @@ var AgentHub = class _AgentHub {
1862
2351
  const list = this.leases.get(peerId) ?? [];
1863
2352
  list.push({ message, expiresAt });
1864
2353
  this.leases.set(peerId, list);
2354
+ this.options.onMailboxesChanged?.();
1865
2355
  return { ...message, attempts, leaseExpiresAt: expiresAt };
1866
2356
  }
1867
2357
  /** Mark leased messages as consumed; returns how many leases were released. */
@@ -1869,12 +2359,17 @@ var AgentHub = class _AgentHub {
1869
2359
  const wanted = new Set(ids);
1870
2360
  const list = this.leases.get(peerId);
1871
2361
  if (list === void 0) return 0;
1872
- const still = list.filter((lease) => !wanted.has(lease.message.id));
1873
- const released = list.length - still.length;
1874
- for (const id of wanted) this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, id));
2362
+ const still = [];
2363
+ const released = [];
2364
+ for (const lease of list) {
2365
+ if (wanted.has(lease.message.id)) released.push(lease.message);
2366
+ else still.push(lease);
2367
+ }
2368
+ for (const message of released) this.leaseAttempts.delete(_AgentHub.leaseKey(peerId, message.id));
1875
2369
  if (still.length > 0) this.leases.set(peerId, still);
1876
2370
  else this.leases.delete(peerId);
1877
- return released;
2371
+ if (released.length > 0) this.options.onMailboxesChanged?.();
2372
+ return released.length;
1878
2373
  }
1879
2374
  /** Give messages back NOW — from live leases or from the dead letters. Attempts
1880
2375
  * are kept, so a message that keeps failing still eventually dead-letters;
@@ -1904,25 +2399,14 @@ var AgentHub = class _AgentHub {
1904
2399
  if (still.length > 0) this.deadLetters.set(peerId, still);
1905
2400
  else this.deadLetters.delete(peerId);
1906
2401
  }
1907
- if (back.length === 0) return 0;
1908
- const queue = this.queues.get(peerId) ?? [];
1909
- insertByPriority(queue, back);
1910
- this.queues.set(peerId, queue);
1911
- this.options.onMailboxesChanged?.();
1912
- return back.length;
2402
+ return this.requeue(peerId, back, Date.now());
1913
2403
  }
1914
2404
  /** Non-blocking drain of everything queued for `peer` (optionally from one sender). */
1915
2405
  poll(peerId, from, options) {
1916
2406
  const now = Date.now();
1917
2407
  this.reapLeases(peerId, now);
1918
2408
  const queue = this.queues.get(peerId) ?? [];
1919
- for (let i = queue.length - 1; i >= 0; i--) {
1920
- const queued = queue[i];
1921
- if (queued.expiresAt !== void 0 && queued.expiresAt <= now) {
1922
- queue.splice(i, 1);
1923
- this.countDrop(peerId, "expired", now);
1924
- }
1925
- }
2409
+ this.sweepExpired(peerId, queue, now);
1926
2410
  const drained = from === void 0 ? queue.splice(0, queue.length) : drainFrom(queue, from);
1927
2411
  if (drained.length > 0) this.options.onMailboxesChanged?.();
1928
2412
  return drained.map((message) => this.handOut(peerId, message, options?.manual === true, now));
@@ -1931,32 +2415,30 @@ var AgentHub = class _AgentHub {
1931
2415
  * Long-poll for the next message addressed to `peer`: resolves immediately
1932
2416
  * when a matching one is queued, otherwise waits up to `timeoutMs` (capped
1933
2417
  * by `waitTimeoutMs`) or until `signal` aborts. `from` narrows to one sender.
1934
- * `ref` narrows to the ack of a specific task message id.
2418
+ * `ref` narrows to that task's reply — an ack, or the `chat` an assignee hands
2419
+ * the result back in — with `statuses` / `terminalOnly` narrowing the ack half
2420
+ * (see {@link matchesWaiter}).
1935
2421
  *
1936
2422
  * Takes ONLY the first matching queued message. Calling poll() here would
1937
2423
  * drain the whole mailbox and discard every message after the first —
1938
2424
  * a multi-message burst (or a reconnect with a full queue) would silently
1939
2425
  * lose messages that never reach wait/poll again.
1940
2426
  */
1941
- wait(peerId, timeoutMs, from, signal, ref, threadId, manual, maxMessages = 1) {
2427
+ wait(peerId, timeoutMs, from, signal, ref, threadId, manual, maxMessages = 1, statuses, terminalOnly) {
1942
2428
  const startedAt = Date.now();
1943
- const matches = (message) => {
1944
- if (from !== void 0 && message.from !== from) return false;
1945
- if (ref !== void 0 && !(message.kind === "ack" && message.ref === ref)) return false;
1946
- if (threadId !== void 0 && message.threadId !== threadId) return false;
1947
- return true;
2429
+ const matches = (message) => matchesWaiter({ from, ref, statuses, terminalOnly, threadId }, message, this.taskLedger);
2430
+ const isParty = (record) => record.from === peerId || record.assignees.some((assignee) => assignee.peerId === peerId);
2431
+ const timedOut = () => {
2432
+ const record = ref === void 0 ? void 0 : this.taskLedger.get(ref);
2433
+ return {
2434
+ type: "timeout",
2435
+ waitedMs: Date.now() - startedAt,
2436
+ ...record !== void 0 && isParty(record) ? { ref: { status: record.status, a2aState: a2aState(record.status) } } : {}
2437
+ };
1948
2438
  };
1949
2439
  this.reapLeases(peerId, startedAt);
1950
2440
  const queue = this.queues.get(peerId);
1951
- if (queue !== void 0) {
1952
- for (let i = queue.length - 1; i >= 0; i--) {
1953
- const queued = queue[i];
1954
- if (queued.expiresAt !== void 0 && queued.expiresAt <= startedAt) {
1955
- queue.splice(i, 1);
1956
- this.countDrop(peerId, "expired", startedAt);
1957
- }
1958
- }
1959
- }
2441
+ if (queue !== void 0) this.sweepExpired(peerId, queue, startedAt);
1960
2442
  if (queue !== void 0 && queue.length > 0) {
1961
2443
  const take = Math.max(1, Math.floor(maxMessages));
1962
2444
  const taken = [];
@@ -1982,7 +2464,7 @@ var AgentHub = class _AgentHub {
1982
2464
  };
1983
2465
  const onAbort = () => {
1984
2466
  removeFromRegistry();
1985
- settle({ type: "timeout", waitedMs: Date.now() - startedAt });
2467
+ settle(timedOut());
1986
2468
  };
1987
2469
  const removeFromRegistry = () => {
1988
2470
  const list2 = this.waiters.get(peerId);
@@ -1990,7 +2472,7 @@ var AgentHub = class _AgentHub {
1990
2472
  };
1991
2473
  const timer = setTimeout(() => {
1992
2474
  removeFromRegistry();
1993
- settle({ type: "timeout", waitedMs: Date.now() - startedAt });
2475
+ settle(timedOut());
1994
2476
  }, budget);
1995
2477
  if (signal?.aborted) {
1996
2478
  onAbort();
@@ -2004,6 +2486,8 @@ var AgentHub = class _AgentHub {
2004
2486
  onAbort,
2005
2487
  ...from !== void 0 ? { from } : {},
2006
2488
  ...ref !== void 0 ? { ref } : {},
2489
+ ...statuses !== void 0 ? { statuses } : {},
2490
+ ...terminalOnly === true ? { terminalOnly } : {},
2007
2491
  ...threadId !== void 0 ? { threadId } : {},
2008
2492
  ...manual === true ? { manual } : {},
2009
2493
  // A batch request keeps the batch SHAPE even when the wait ends with a
@@ -2031,6 +2515,9 @@ var AgentHub = class _AgentHub {
2031
2515
  if (to !== BROADCAST && group === void 0 && !known) {
2032
2516
  throw new Error(`unknown recipient: ${to} (registered peers: ${this.peers().join(", ") || "none"})`);
2033
2517
  }
2518
+ if (group !== void 0 && !system && !group.members.includes(from)) {
2519
+ throw new Error(`peer '${from}' is not a member of group '${to}'`);
2520
+ }
2034
2521
  let hop = 0;
2035
2522
  if (ref !== void 0) {
2036
2523
  const parent = this.historyRing.findLast((m) => m.id === ref);
@@ -2084,18 +2571,15 @@ var AgentHub = class _AgentHub {
2084
2571
  deliver(target, message) {
2085
2572
  this.bumpTraffic(target, "received");
2086
2573
  if (message.expiresAt !== void 0 && message.expiresAt <= Date.now()) {
2087
- this.countDrop(target, "expired", Date.now());
2574
+ const now = Date.now();
2575
+ this.countDrop(target, "expired", now, message);
2576
+ if (message.kind === "task") this.noteTaskDeliveryDropped(message, target, "expired", now);
2088
2577
  return;
2089
2578
  }
2090
2579
  const list = this.waiters.get(target) ?? [];
2091
- const index = list.findIndex((waiter) => {
2092
- if (waiter.from !== void 0 && waiter.from !== message.from) return false;
2093
- if (waiter.ref !== void 0 && !(message.kind === "ack" && message.ref === waiter.ref)) return false;
2094
- if (waiter.threadId !== void 0 && message.threadId !== waiter.threadId) return false;
2095
- return true;
2096
- });
2097
- if (message.kind === "task") this.markTaskDelivered(message.id, target, message.ts);
2580
+ const index = list.findIndex((waiter) => matchesWaiter(waiter, message, this.taskLedger));
2098
2581
  if (index >= 0) {
2582
+ if (message.kind === "task") this.markTaskDelivered(message.id, target, message.ts);
2099
2583
  const [waiter] = list.splice(index, 1);
2100
2584
  this.waiters.set(target, list);
2101
2585
  clearTimeout(waiter.timer);
@@ -2104,19 +2588,22 @@ var AgentHub = class _AgentHub {
2104
2588
  return;
2105
2589
  }
2106
2590
  if (!this.takeToken(target, Date.now())) {
2107
- this.countDrop(target, "rate", Date.now());
2591
+ const now = Date.now();
2592
+ this.countDrop(target, "rate", now, message);
2593
+ if (message.kind === "task") this.noteTaskDeliveryDropped(message, target, "rate", now);
2108
2594
  return;
2109
2595
  }
2110
2596
  const queue = this.queues.get(target) ?? [];
2111
2597
  if (queue.length >= this.options.maxQueue) {
2112
- const lowest = priorityOf(queue[queue.length - 1]);
2113
- let victim = queue.length - 1;
2114
- while (victim > 0 && priorityOf(queue[victim - 1]) === lowest) victim--;
2115
- queue.splice(victim, 1);
2116
- this.countDrop(target, "overflow", Date.now());
2598
+ const [evicted] = queue.splice(lowestPriorityIndex(queue), 1);
2599
+ const now = Date.now();
2600
+ if (evicted !== void 0) this.leaseAttempts.delete(_AgentHub.leaseKey(target, evicted.id));
2601
+ this.countDrop(target, "overflow", now, evicted);
2602
+ if (evicted !== void 0 && evicted.kind === "task") this.noteTaskDeliveryDropped(evicted, target, "overflow", now);
2117
2603
  }
2118
2604
  insertByPriority(queue, [message]);
2119
2605
  this.queues.set(target, queue);
2606
+ if (message.kind === "task") this.markTaskDelivered(message.id, target, message.ts);
2120
2607
  this.options.onQueued?.(message, target);
2121
2608
  if (message.kind === "task") this.options.onTaskQueued?.(message, target);
2122
2609
  }
@@ -2138,6 +2625,13 @@ function insertByPriority(queue, messages) {
2138
2625
  queue.splice(at, 0, message);
2139
2626
  }
2140
2627
  }
2628
+ function lowestPriorityIndex(queue) {
2629
+ if (queue.length === 0) return -1;
2630
+ const lowest = priorityOf(queue[queue.length - 1]);
2631
+ let victim = queue.length - 1;
2632
+ while (victim > 0 && priorityOf(queue[victim - 1]) === lowest) victim--;
2633
+ return victim;
2634
+ }
2141
2635
  function priorityOf(message) {
2142
2636
  const value = message.priority;
2143
2637
  return value === 1 || value === 2 ? value : 0;
@@ -2146,7 +2640,7 @@ function drainFrom(queue, from) {
2146
2640
  const kept = [];
2147
2641
  const drained = [];
2148
2642
  for (const message of queue) {
2149
- if (message.from === from) drained.push(message);
2643
+ if (message.from === from || message.from === HUB_PEER) drained.push(message);
2150
2644
  else kept.push(message);
2151
2645
  }
2152
2646
  queue.splice(0, queue.length, ...kept);
@@ -2156,6 +2650,41 @@ function omit(value, key) {
2156
2650
  const { [key]: _dropped, ...rest } = value;
2157
2651
  return rest;
2158
2652
  }
2653
+ function matchesWaiter(waiter, message, ledger) {
2654
+ const fromHub = message.from === HUB_PEER;
2655
+ if (!fromHub && waiter.from !== void 0 && message.from !== waiter.from) return false;
2656
+ if (!fromHub && waiter.ref !== void 0) {
2657
+ if (message.ref !== waiter.ref) return false;
2658
+ if (message.kind !== "ack" && message.kind !== "chat") return false;
2659
+ if (message.kind === "chat") {
2660
+ const record = ledger.get(waiter.ref);
2661
+ if (record !== void 0 && record.from !== message.from && !record.assignees.some((assignee) => assignee.peerId === message.from)) return false;
2662
+ }
2663
+ if (waiter.statuses !== void 0 || waiter.terminalOnly === true) {
2664
+ const status = ackStatusOf(message);
2665
+ if (status === void 0) return false;
2666
+ if (waiter.statuses !== void 0 && !waiter.statuses.includes(status)) return false;
2667
+ if (waiter.terminalOnly === true && !TERMINAL_TASK_STATUSES.includes(ackToTaskStatus(status))) return false;
2668
+ }
2669
+ }
2670
+ if (waiter.threadId !== void 0 && message.threadId !== waiter.threadId) return false;
2671
+ return true;
2672
+ }
2673
+ function ackStatusOf(message) {
2674
+ if (message.kind !== "ack") return void 0;
2675
+ const decoded = decodeContent("ack", message.content);
2676
+ if (typeof decoded === "string") return void 0;
2677
+ const status = decoded.status;
2678
+ if (typeof status !== "string") return void 0;
2679
+ return ALL_ACK_STATUSES.includes(status) ? status : void 0;
2680
+ }
2681
+ function syntheticEventId(taskId, reason) {
2682
+ if (reason === "expired") return `expired-${taskId}`;
2683
+ if (reason === "dead-letter") return `dead-letter-${taskId}`;
2684
+ if (reason === "dead-letter-evicted") return `evicted-${taskId}`;
2685
+ if (reason === "unregistered") return `unregistered-${taskId}`;
2686
+ return `dropped-${taskId}`;
2687
+ }
2159
2688
 
2160
2689
  // src/auth.ts
2161
2690
  import { randomBytes } from "node:crypto";
@@ -2185,7 +2714,7 @@ function loadTokenFile(file) {
2185
2714
  if (PLACEHOLDER_TOKEN.test(token)) {
2186
2715
  throw new Error(msg("uses the example placeholder token \u2014 generate one with `agent-comm-hub auth gen`"));
2187
2716
  }
2188
- if (typeof peer !== "string" || !PEER_ID_PATTERN.test(peer) || peer === "all") {
2717
+ if (typeof peer !== "string" || !PEER_ID_PATTERN.test(peer) || peer === BROADCAST || peer === HUB_PEER) {
2189
2718
  throw new Error(msg(`has an invalid peer id '${String(peer)}'`));
2190
2719
  }
2191
2720
  if (role !== "agent" && role !== "manager") {
@@ -2306,7 +2835,7 @@ function loadTokenFileVoid(rows) {
2306
2835
  if (PLACEHOLDER_TOKEN.test(token)) {
2307
2836
  throw new Error(`example placeholder token for peer '${peer}' \u2014 generate one with \`agent-comm-hub auth gen\``);
2308
2837
  }
2309
- if (!PEER_ID_PATTERN.test(peer) || peer === "all") throw new Error(`invalid peer id '${peer}'`);
2838
+ if (!PEER_ID_PATTERN.test(peer) || peer === BROADCAST || peer === HUB_PEER) throw new Error(`invalid peer id '${peer}'`);
2310
2839
  if (role !== "agent" && role !== "manager") throw new Error(`invalid role '${role}'`);
2311
2840
  if (table.has(token)) throw new Error("duplicate token");
2312
2841
  if (peers.has(peer)) throw new Error(`duplicate peer '${peer}'`);
@@ -2348,12 +2877,13 @@ function autoRegisterPeer(hub, registry, sessionId, clientName, clientVersion) {
2348
2877
  if (bound !== void 0) return bound;
2349
2878
  if (registry.isSuppressed(sessionId)) return void 0;
2350
2879
  const tokenPeer = registry.tokenFor(sessionId)?.peer;
2351
- const peerId = tokenPeer === ANON_JOIN_PEER ? `join-${sanitizePeerId(clientName ?? "agent")}-${Math.random().toString(36).slice(2, 6)}` : tokenPeer ?? sanitizePeerId(clientName ?? "agent");
2880
+ const derived = tokenPeer === ANON_JOIN_PEER ? `join-${sanitizePeerId(clientName ?? "agent")}-${Math.random().toString(36).slice(2, 6)}` : tokenPeer ?? sanitizePeerId(clientName ?? "agent");
2881
+ const peerId = derived === BROADCAST || derived === HUB_PEER || hub.groupOf(derived) !== void 0 ? `agent-${Math.random().toString(36).slice(2, 6)}` : derived;
2352
2882
  if (!hub.has(peerId)) {
2353
2883
  hub.register(peerId, {
2354
2884
  ...clientName !== void 0 ? { name: clientName } : {},
2355
2885
  ...clientVersion !== void 0 ? { version: clientVersion } : {}
2356
- });
2886
+ }, { reclaim: true });
2357
2887
  }
2358
2888
  registry.bindPeer(sessionId, peerId);
2359
2889
  hub.touch(peerId);
@@ -2407,6 +2937,7 @@ function rosterFor(hub, registry) {
2407
2937
  };
2408
2938
  });
2409
2939
  }
2940
+ var MAX_LEASE_IDS = 1e3;
2410
2941
  function isManagerCaller(registry, sessionId, peer, options) {
2411
2942
  if (registry.tokenFor(sessionId)?.role === "manager") return true;
2412
2943
  if (options.managerTokenRequired === true) return registry.isManagerSession(sessionId);
@@ -2432,10 +2963,32 @@ function hubTools(hub, registry, options) {
2432
2963
  const optPriority = (value) => value === 0 || value === 1 || value === 2 ? { priority: value } : {};
2433
2964
  const idList = (value, tool) => {
2434
2965
  if (!Array.isArray(value)) throw new Error(`${tool} expects ids: an array of message ids`);
2966
+ if (value.length > MAX_LEASE_IDS) {
2967
+ throw new Error(`${tool} accepts at most ${MAX_LEASE_IDS} ids per call (got ${value.length}); commit or nack in batches`);
2968
+ }
2435
2969
  const ids = value.filter((id) => typeof id === "string" && id !== "");
2436
2970
  if (ids.length === 0) throw new Error(`${tool} expects at least one message id`);
2437
2971
  return ids;
2438
2972
  };
2973
+ const ackStatuses = (value, terminalOnly) => {
2974
+ if (value === void 0) return void 0;
2975
+ if (!Array.isArray(value)) throw new Error("statuses must be an array of ack statuses");
2976
+ if (value.length === 0) throw new Error("statuses must not be empty \u2014 omit it to wait for any ack");
2977
+ const out = [];
2978
+ for (const entry of value) {
2979
+ if (typeof entry !== "string" || !ALL_ACK_STATUSES.includes(entry)) {
2980
+ throw new Error(`invalid statuses entry: ${JSON.stringify(entry)} (expected one of ${ALL_ACK_STATUSES.join(" | ")})`);
2981
+ }
2982
+ out.push(entry);
2983
+ }
2984
+ if (terminalOnly) {
2985
+ const terminalAcks = TERMINAL_TASK_STATUSES.filter((status) => ALL_ACK_STATUSES.includes(status));
2986
+ if (!out.some((status) => terminalAcks.includes(ackToTaskStatus(status)))) {
2987
+ throw new Error(`statuses and terminalOnly are combined by intersection, and ${out.join(" | ")} contains no terminal ack status (${terminalAcks.join(" | ")}) \u2014 the wait could never resolve`);
2988
+ }
2989
+ }
2990
+ return out;
2991
+ };
2439
2992
  const deadline = (value) => {
2440
2993
  const at = Number(value);
2441
2994
  if (!Number.isFinite(at) || at <= 0) throw new Error(`invalid expiresAt: ${String(value)} (expected epoch milliseconds)`);
@@ -2609,6 +3162,9 @@ function hubTools(hub, registry, options) {
2609
3162
  throw new Error(`peer already registered by another connection: ${peerId}`);
2610
3163
  }
2611
3164
  const current = registry.peerFor(sessionId);
3165
+ if (hub.ownsMailbox(peerId) && current !== peerId && registry.attachedCount(peerId) > 0) {
3166
+ throw new Error(`peer id '${peerId}' is parked but still attached to another connection: it keeps its mailbox and is still addressable`);
3167
+ }
2612
3168
  if (current !== void 0 && current !== peerId) {
2613
3169
  if (registry.attachedCount(current) === 1) {
2614
3170
  hub.renamePeer(current, peerId);
@@ -2619,7 +3175,7 @@ function hubTools(hub, registry, options) {
2619
3175
  }
2620
3176
  }
2621
3177
  registry.bindPeer(sessionId, peerId);
2622
- if (!hub.has(peerId)) hub.register(peerId);
3178
+ if (!hub.has(peerId)) hub.register(peerId, void 0, { reclaim: true });
2623
3179
  registry.clearSuppress(sessionId);
2624
3180
  hub.touch(peerId);
2625
3181
  if (alias !== void 0) hub.setAlias(peerId, alias);
@@ -2657,7 +3213,7 @@ function hubTools(hub, registry, options) {
2657
3213
  },
2658
3214
  {
2659
3215
  name: "bridge_rename",
2660
- description: "Rename on the hub, two layers: (1) `alias` sets a display name \u2014 cosmetic only, it shows up in bridge_peers / bridge_status and the desktop roster while routing, mailboxes, and history keep the immutable peer id; renaming yourself is open to everyone. (2) `peerId` truly re-keys another registered peer (manager rights required): mailbox, waiters, session bindings, and history attribution move atomically, so queued messages and acks stay continuous. Renaming ANOTHER peer (either layer) requires manager rights (hub managerPeers).",
3216
+ description: "Rename on the hub, two layers: (1) `alias` sets a display name \u2014 cosmetic only, it shows up in bridge_peers / bridge_status and the desktop roster while routing, mailboxes, and history keep the immutable peer id; renaming yourself is open to everyone. (2) `peerId` truly re-keys another registered peer (manager rights required): mailbox, waiters, in-flight manual leases, dead letters, session bindings, and history attribution move atomically, so queued messages and acks stay continuous and a lease you took under the old id is still yours to commit. Renaming ANOTHER peer (either layer) requires manager rights (hub managerPeers).",
2661
3217
  inputSchema: schema({
2662
3218
  alias: optStr("New display name (1-64 chars, spaces/CJK allowed; empty string clears back to no alias)."),
2663
3219
  peerId: optStr("New routing id for `peer` \u2014 a true rename that moves all state (manager only). Target must be a registered peer."),
@@ -2669,17 +3225,26 @@ function hubTools(hub, registry, options) {
2669
3225
  if (!hasAlias && !hasPeerId) {
2670
3226
  throw new Error("nothing to rename: pass alias and/or peerId");
2671
3227
  }
3228
+ if (hasPeerId && args.peer === void 0) {
3229
+ throw new Error("peerId requires peer \u2014 to change your own id, call bridge_register(newId)");
3230
+ }
3231
+ const tokenPeer = registry.tokenFor(sessionId)?.peer;
3232
+ if (hasPeerId && tokenPeer !== void 0) {
3233
+ requireManager(peer, `re-keying '${args.peer === void 0 ? peer : String(args.peer)}'`, sessionId);
3234
+ }
2672
3235
  let target = args.peer === void 0 ? peer : String(args.peer);
2673
3236
  if (target !== peer) requireManager(peer, `renaming '${target}'`, sessionId);
2674
3237
  let previousId;
2675
3238
  if (hasPeerId) {
2676
- if (args.peer === void 0) {
2677
- throw new Error("peerId requires peer \u2014 to change your own id, call bridge_register(newId)");
2678
- }
2679
3239
  const newId = String(args.peerId);
2680
3240
  if (!PEER_ID_PATTERN.test(newId)) {
2681
3241
  throw new Error(`invalid peerId: ${newId} (expected [A-Za-z0-9._:-]{1,64})`);
2682
3242
  }
3243
+ const boundPeers = new Set(options.tokenPeers?.() ?? []);
3244
+ for (const identity of registry.tokenBindings.values()) boundPeers.add(identity.peer);
3245
+ if (boundPeers.has(newId) && newId !== tokenPeer) {
3246
+ throw new Error(`peerId '${newId}' is bound to an access token \u2014 a token's identity cannot be reassigned by a rename`);
3247
+ }
2683
3248
  previousId = target;
2684
3249
  hub.renamePeer(target, newId);
2685
3250
  registry.rebindPeerId(target, newId);
@@ -2698,7 +3263,7 @@ function hubTools(hub, registry, options) {
2698
3263
  description: 'Send a chat message to another agent on the hub. Use bridge_wait (long-poll) or bridge_poll to receive replies. `to` is the target peerId, a group id, or "all" to broadcast. Optional `threadId` groups multi-turn dialogs; optional `ref` marks a reply-to and carries the chain depth in `hop`. Reply chains are counted, not enforced (50 hops for chat/ack, 5 for a task replying to a task): past the ceiling the message and its `ref` are delivered unchanged and only `hop` stops counting, so nothing is ever refused and no correlation is lost.',
2699
3264
  inputSchema: schema(
2700
3265
  {
2701
- to: str('Target peerId, group id, or "all" to broadcast.'),
3266
+ to: str('Target peerId, group id, or "all" to broadcast. A group id fans out to its members, so you must be one of them.'),
2702
3267
  message: str("The message text."),
2703
3268
  threadId: optStr("Optional conversation / workflow thread id."),
2704
3269
  priority: priorityField(),
@@ -2719,7 +3284,7 @@ function hubTools(hub, registry, options) {
2719
3284
  description: 'Send a system-flavoured notice to another agent (peer, group id, or "all"). Use it for things the recipient should see differently from chat: "your mailbox dropped 3 messages", "hub restarting", "that task was cancelled". `level` is info | warn | error (default info). The payload is structured ({message, level}) rather than plain text, and the message is a normal routed message \u2014 it queues for a parked peer like any other. It does NOT create a task ledger row.',
2720
3285
  inputSchema: schema(
2721
3286
  {
2722
- to: str('Target peerId, group id, or "all" to broadcast.'),
3287
+ to: str('Target peerId, group id, or "all" to broadcast. A group id fans out to its members, so you must be one of them.'),
2723
3288
  message: str("The notice text."),
2724
3289
  level: { type: "string", enum: ["info", "warn", "error"], description: "Severity (default info)." },
2725
3290
  threadId: optStr("Optional conversation / workflow thread id."),
@@ -2744,10 +3309,10 @@ function hubTools(hub, registry, options) {
2744
3309
  },
2745
3310
  {
2746
3311
  name: "bridge_task",
2747
- description: 'Delegate a structured task to another agent (peer, group, or "all"). The assignee acks with accepted | working | rejected | done | failed (bridge_ack). Track with bridge_task_status(ref) / bridge_tasks; wait for the ack with bridge_wait({ ref }). Optional timeoutMs marks the task `timeout` when the SLA expires without a terminal ack; any positive duration is honored, including multi-day deadlines (the hub re-arms its timer instead of overflowing it). Optional `ref` names the task this one answers \u2014 when the parent is itself a task the new one is a re-delegation, and `hop` counts that chain depth (saturating at 5; the task is always delivered).',
3312
+ description: 'Delegate a structured task to another agent (peer, group, or "all"). The assignee acks with accepted | working | rejected | done | failed (bridge_ack). Track with bridge_task_status(ref) / bridge_tasks; wait for the reply with bridge_wait({ ref }). A `ref` wait can resolve on an intermediate beat (`working`) or on the result chat, so pass `terminalOnly: true` when you want the outcome. Optional timeoutMs marks the task `timeout` when the SLA expires without a terminal ack; any positive duration is honored, including multi-day deadlines (the hub re-arms its timer instead of overflowing it). Optional `ref` names the task this one answers \u2014 when the parent is itself a task the new one is a re-delegation, and `hop` counts that chain depth (saturating at 5; the task is always delivered).',
2748
3313
  inputSchema: schema(
2749
3314
  {
2750
- to: str('Target peerId, group id, or "all" to broadcast.'),
3315
+ to: str('Target peerId, group id, or "all" to broadcast. A group id fans out to its members, so you must be one of them.'),
2751
3316
  prompt: str("What the receiving agent should do."),
2752
3317
  context: optStr("Optional background information for the task."),
2753
3318
  deliverable: optStr("Optional expected deliverable description."),
@@ -2798,10 +3363,10 @@ function hubTools(hub, registry, options) {
2798
3363
  },
2799
3364
  {
2800
3365
  name: "bridge_tasks",
2801
- description: "List delegated tasks involving you, newest first. role=sent = tasks you assigned; role=received = tasks assigned to you (or broadcast/group); status filters the ledger state (pending/accepted/working/rejected/done/failed/timeout). Each row carries the full ack timeline and per-assignee state.",
3366
+ description: "List delegated tasks involving you, newest first. role=sent = tasks you assigned; role=received = tasks assigned to you (or broadcast/group); status filters the ledger state (pending/accepted/working/input-required/rejected/done/failed/timeout/canceled). Each row carries the full ack timeline and per-assignee state.",
2802
3367
  inputSchema: schema({
2803
3368
  role: { type: "string", enum: ["sent", "received", "all"], description: "Which side of the task to list (default all)." },
2804
- status: { type: "string", enum: ["pending", "accepted", "working", "rejected", "done", "failed", "timeout"], description: "Only tasks whose current ledger status matches." },
3369
+ status: { type: "string", enum: [...ALL_TASK_STATUSES], description: "Only tasks whose current ledger status matches." },
2805
3370
  peer: optStr('Manager only: "all" or another peerId for the admin board.'),
2806
3371
  limit: int("How many tasks to return (default 50).")
2807
3372
  }),
@@ -2811,14 +3376,15 @@ function hubTools(hub, registry, options) {
2811
3376
  throw new Error(`invalid role: ${role} (expected sent | received | all)`);
2812
3377
  }
2813
3378
  const status = args.status === void 0 ? void 0 : String(args.status);
2814
- const validStatus = ["pending", "accepted", "working", "rejected", "done", "failed", "timeout"];
3379
+ const validStatus = ALL_TASK_STATUSES;
2815
3380
  if (status !== void 0 && !validStatus.includes(status)) {
2816
3381
  throw new Error(`invalid status: ${status} (expected ${validStatus.join(" | ")})`);
2817
3382
  }
2818
3383
  let target = peer;
2819
3384
  if (args.peer !== void 0) {
2820
3385
  target = String(args.peer);
2821
- if (target !== peer) requireManager(peer, `listing tasks of '${target}'`, sessionId);
3386
+ if (target === BROADCAST) requireManager(peer, "listing the full task ledger", sessionId);
3387
+ else if (target !== peer) requireManager(peer, `listing tasks of '${target}'`, sessionId);
2822
3388
  }
2823
3389
  const tasks = hub.listTasks(target === "all" ? "all" : target, {
2824
3390
  ...role !== void 0 ? { role } : {},
@@ -2830,7 +3396,7 @@ function hubTools(hub, registry, options) {
2830
3396
  },
2831
3397
  {
2832
3398
  name: "bridge_task_status",
2833
- description: "Status of one delegated task: current ledger state (pending \u2192 accepted/working \u2192 done/failed/timeout, or rejected), the original prompt/context/deliverable, per-assignee state, and every ack event (who, status, note, progress, when). Use the task message id (the same id you pass as bridge_ack ref). Readable by the sender, by an assignee (a group task carries the GROUP id in `to`, so its assignees read it through their assignee row) and by a group member; everyone else needs manager rights.",
3399
+ description: "Status of one delegated task: current ledger state (pending \u2192 accepted/working \u2192 done/failed/timeout, or input-required/rejected/canceled), the original prompt/context/deliverable, per-assignee state, and every ack event (who, status, note, progress, when). Use the task message id (the same id you pass as bridge_ack ref). Readable by the sender, by an assignee (a group task carries the GROUP id in `to`, so its assignees read it through their assignee row) and by a group member; everyone else needs manager rights.",
2834
3400
  inputSchema: schema({ ref: str("Task message id (the id returned by bridge_task, also used as ack ref).") }, ["ref"]),
2835
3401
  handler: wrap(true, async (args, peer, sessionId) => {
2836
3402
  const ref = String(args.ref);
@@ -2915,10 +3481,19 @@ function hubTools(hub, registry, options) {
2915
3481
  },
2916
3482
  {
2917
3483
  name: "bridge_wait",
2918
- description: 'Wait (long-poll) for the next message addressed to you. Resolves immediately when one is queued; otherwise blocks until one arrives or the timeout fires. `from` narrows to one sender. `ref` waits specifically for the ack of that task id. `threadId` narrows to one conversation thread. Loop this tool to hold a real-time conversation. With `ack: "manual"` the message is LEASED rather than consumed: it comes back (with `attempts` incremented) if you do not call bridge_commit in time, and is dead-lettered after too many hand-outs. Use it when losing a message would be worse than handling one twice.',
3484
+ description: 'Wait (long-poll) for the next message addressed to you. Resolves immediately when one is queued; otherwise blocks until one arrives or the timeout fires. `from` narrows to one sender \u2014 but it never hides a notice sent by the hub itself (`from: "hub"`), so a sender waiting with `from: <assignee>` still hears "that delivery was dropped" and "the task is over". Hub notices (`from: "hub"`) are not filtered by `from`, by `ref`, or by `statuses` / `terminalOnly`, so a `ref` wait still hears that its delivery was dropped or that its assignee is gone (a `threadId` filter still narrows them, like any other message). `ref` waits for that task\'s reply: an ack OR the chat an assignee sends the result back in (a chat carrying a task id nobody but that task\'s sender or assignees sent is ignored). An ack is a STATUS BEAT, not a verdict \u2014 an assignee that acks `working` and then `done` resolves a plain `ref` wait on the FIRST one, so pass `terminalOnly: true` (or `statuses`) when you need the outcome rather than "it started"; combining the two is an intersection, and a pair that can never match is rejected rather than waited out. A wait that times out returns the task\'s current ledger status under `ref` when you passed a ref and are a party to it (only the sender and the assignees read a task\'s state that way). `threadId` narrows to one conversation thread. Loop this tool to hold a real-time conversation. With `ack: "manual"` the message is LEASED rather than consumed: it comes back (with `attempts` incremented) if you do not call bridge_commit in time, and is dead-lettered after too many hand-outs. Use it when losing a message would be worse than handling one twice.',
2919
3485
  inputSchema: schema({
2920
- from: optStr("Only wait for messages from this peerId."),
2921
- ref: optStr("Only wait for the ack of this task message id (bridge_task id)."),
3486
+ from: optStr('Only wait for messages from this peerId. Hub notices (from "hub") are never filtered out.'),
3487
+ ref: optStr("Only wait for a reply carrying this ref: the ack of that task id (bridge_task id), or a chat answering it. A chat carrying a task id sent by a peer that is neither that task's sender nor one of its assignees is ignored."),
3488
+ statuses: {
3489
+ type: "array",
3490
+ items: { type: "string", enum: [...ALL_ACK_STATUSES] },
3491
+ description: "With `ref`: only resolve on an ack carrying one of these statuses. A chat reply has no status, so it never matches a status filter. An ack whose payload carries no valid status never matches either. Combined with `terminalOnly` by intersection: a list containing no terminal status is rejected instead of waiting out the timeout."
3492
+ },
3493
+ terminalOnly: {
3494
+ type: "boolean",
3495
+ description: "With `ref`: only resolve on a TERMINAL ack (rejected | done | failed | canceled) \u2014 skip the `accepted` / `working` / `input-required` beats. A chat reply is not a terminal ack and is skipped as well. Combined with `statuses` by intersection."
3496
+ },
2922
3497
  threadId: optStr("Only wait for messages carrying this threadId."),
2923
3498
  timeoutMs: int(`Max wait in milliseconds (default ${DEFAULT_WAIT_MS}, ceiling is server waitTimeoutMs).`),
2924
3499
  maxMessages: int('Take up to this many already-queued messages in one call (default 1). With > 1 the result is {type:"messages", messages:[\u2026]} instead of {type:"message", message:{\u2026}} \u2014 the shape follows the request, not how many happened to be queued.'),
@@ -2932,14 +3507,16 @@ function hubTools(hub, registry, options) {
2932
3507
  args.ref === void 0 ? void 0 : String(args.ref),
2933
3508
  args.threadId === void 0 ? void 0 : String(args.threadId),
2934
3509
  args.ack === "manual",
2935
- args.maxMessages === void 0 ? 1 : Math.max(1, Number(args.maxMessages))
3510
+ args.maxMessages === void 0 ? 1 : Math.max(1, Number(args.maxMessages)),
3511
+ ackStatuses(args.statuses, args.terminalOnly === true),
3512
+ args.terminalOnly === true
2936
3513
  )))
2937
3514
  },
2938
3515
  {
2939
3516
  name: "bridge_poll",
2940
- description: 'Non-blocking: drain every message currently queued for you. Empty list when nothing is waiting. `from` narrows to one sender. `ack: "manual"` leases what it drains (see bridge_wait) instead of consuming it.',
3517
+ description: 'Non-blocking: drain every message currently queued for you. Empty list when nothing is waiting. `from` narrows to one sender (a hub notice with `from: "hub"` is always included). `ack: "manual"` leases what it drains (see bridge_wait) instead of consuming it.',
2941
3518
  inputSchema: schema({
2942
- from: optStr("Only drain messages from this peerId."),
3519
+ from: optStr('Only drain messages from this peerId. Hub notices (from "hub") are never filtered out.'),
2943
3520
  ack: { type: "string", enum: ["auto", "manual"], description: '"auto" (default) consumes; "manual" leases until bridge_commit.' }
2944
3521
  }),
2945
3522
  handler: wrap(true, async (args, peer) => ({
@@ -2950,16 +3527,16 @@ function hubTools(hub, registry, options) {
2950
3527
  name: "bridge_commit",
2951
3528
  description: 'Acknowledge messages you received under a manual lease (bridge_wait / bridge_poll with ack: "manual"). Until you commit, the hub keeps them in flight and hands them out again once the lease expires \u2014 committing is what makes handling them final. Returns how many leases were released.',
2952
3529
  inputSchema: schema(
2953
- { ids: { type: "array", items: { type: "string" }, description: "Message ids you received and have finished handling." } },
3530
+ { ids: { type: "array", items: { type: "string" }, description: "Message ids you received and have finished handling. At most 1000 per call." } },
2954
3531
  ["ids"]
2955
3532
  ),
2956
3533
  handler: wrap(true, async (args, peer) => ({ committed: hub.commit(peer, idList(args.ids, "bridge_commit")) }))
2957
3534
  },
2958
3535
  {
2959
3536
  name: "bridge_nack",
2960
- description: "Give leased messages back NOW instead of waiting for the lease to expire \u2014 use it when handling failed. They return to the head of your queue (another session of the same peer can retry), their attempt count is kept, and a message that keeps failing ends up dead-lettered instead of looping. It also revives a dead-lettered message (resetting its attempts). Returns how many were requeued.",
3537
+ description: "Give leased messages back NOW instead of waiting for the lease to expire \u2014 use it when handling failed. They go back into your mailbox in normal delivery order (another session of the same peer can retry), their attempt count is kept, and a message that keeps failing ends up dead-lettered instead of looping. It also revives a dead-lettered message (resetting its attempts). Requeued mail competes for a slot like arriving mail, so if the mailbox is already full what does not fit stays dead-lettered (revive it again later). Returns how many were requeued.",
2961
3538
  inputSchema: schema(
2962
- { ids: { type: "array", items: { type: "string" }, description: "Message ids to give back." } },
3539
+ { ids: { type: "array", items: { type: "string" }, description: "Message ids to give back. At most 1000 per call." } },
2963
3540
  ["ids"]
2964
3541
  ),
2965
3542
  handler: wrap(true, async (args, peer) => ({ requeued: hub.nack(peer, idList(args.ids, "bridge_nack")) }))
@@ -3008,8 +3585,10 @@ function hubTools(hub, registry, options) {
3008
3585
  }
3009
3586
  const since = sinceRaw;
3010
3587
  const target = args.peer === void 0 ? peer : String(args.peer);
3011
- if (target !== peer) {
3012
- requireManager(peer, `reading ${target === BROADCAST ? "the full history" : `peer '${target}' history`}`, sessionId);
3588
+ if (target === BROADCAST) {
3589
+ requireManager(peer, "reading the full history", sessionId);
3590
+ } else if (target !== peer) {
3591
+ requireManager(peer, `reading peer '${target}' history`, sessionId);
3013
3592
  }
3014
3593
  if (args.channel !== void 0) {
3015
3594
  const groupId = String(args.channel);
@@ -4019,7 +4598,7 @@ function readBody(req) {
4019
4598
  import { DatabaseSync } from "node:sqlite";
4020
4599
  var KIND_NAMES = ["chat", "task", "notice", "ack"];
4021
4600
  function messageToRow(message) {
4022
- return [message.id, message.from, message.to, message.kind, message.content, message.ref ?? null, message.channel ?? null, message.threadId ?? null, message.ts, message.hop ?? null, message.seq ?? null, message.expiresAt ?? null];
4601
+ return [message.id, message.from, message.to, message.kind, message.content, message.ref ?? null, message.channel ?? null, message.threadId ?? null, message.ts, message.hop ?? null, message.seq ?? null, message.expiresAt ?? null, message.priority ?? null];
4023
4602
  }
4024
4603
  function rowToMessage(row) {
4025
4604
  const id = row.id;
@@ -4048,6 +4627,17 @@ function rowToMessage(row) {
4048
4627
  // Deadline: restored so a message that expired while the hub was down is
4049
4628
  // dropped rather than delivered late.
4050
4629
  ...typeof row.expires_at === "number" && Number.isFinite(row.expires_at) && row.expires_at > 0 ? { expiresAt: row.expires_at } : {},
4630
+ // Delivery priority: ONLY a real 0 | 1 | 2 restores. Anything else — NULL
4631
+ // from a database written before this column existed, or an out-of-range
4632
+ // value — restores as UNSET, deliberately not as 0. An absent priority is a
4633
+ // different claim from "the sender asked for 0": `compose` keeps an unset
4634
+ // one off the wire and `priorityOf` reads absent as 0 anyway, so writing 0
4635
+ // here would hand every restored message a priority its sender never gave.
4636
+ // That matters because a restored message is re-inserted (lease return,
4637
+ // nack, mail queued while the hub was down) and `insertByPriority` +
4638
+ // overflow dropping then act on it: a p2 instruction restored as p0 loses
4639
+ // its slot to chatter, which is exactly the bug this column prevents.
4640
+ ...row.priority === 0 || row.priority === 1 || row.priority === 2 ? { priority: row.priority } : {},
4051
4641
  ts
4052
4642
  };
4053
4643
  }
@@ -4062,11 +4652,11 @@ var SQLiteStateStore = class {
4062
4652
  );
4063
4653
  CREATE TABLE IF NOT EXISTS messages (
4064
4654
  seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, from_peer TEXT NOT NULL,
4065
- to_peer TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL, ref TEXT, channel TEXT, thread_id TEXT, ts INTEGER NOT NULL, hop INTEGER, mseq INTEGER, expires_at INTEGER
4655
+ to_peer TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL, ref TEXT, channel TEXT, thread_id TEXT, ts INTEGER NOT NULL, hop INTEGER, mseq INTEGER, expires_at INTEGER, priority INTEGER
4066
4656
  );
4067
4657
  CREATE TABLE IF NOT EXISTS mailboxes (
4068
4658
  peer TEXT NOT NULL, seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, from_peer TEXT NOT NULL,
4069
- to_peer TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL, ref TEXT, channel TEXT, thread_id TEXT, ts INTEGER NOT NULL, hop INTEGER, mseq INTEGER, expires_at INTEGER
4659
+ to_peer TEXT NOT NULL, kind TEXT NOT NULL, content TEXT NOT NULL, ref TEXT, channel TEXT, thread_id TEXT, ts INTEGER NOT NULL, hop INTEGER, mseq INTEGER, expires_at INTEGER, priority INTEGER
4070
4660
  );
4071
4661
  CREATE TABLE IF NOT EXISTS groups (
4072
4662
  id TEXT PRIMARY KEY, name TEXT, members TEXT NOT NULL, created_by TEXT NOT NULL, created_at INTEGER NOT NULL
@@ -4076,7 +4666,7 @@ var SQLiteStateStore = class {
4076
4666
  );
4077
4667
  `);
4078
4668
  for (const table of ["messages", "mailboxes"]) {
4079
- for (const column of ["thread_id TEXT", "hop INTEGER", "mseq INTEGER", "expires_at INTEGER"]) {
4669
+ for (const column of ["thread_id TEXT", "hop INTEGER", "mseq INTEGER", "expires_at INTEGER", "priority INTEGER"]) {
4080
4670
  try {
4081
4671
  this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column}`);
4082
4672
  } catch {
@@ -4098,14 +4688,14 @@ var SQLiteStateStore = class {
4098
4688
  /** Insert buffered messages and re-snapshot mailboxes/profiles/groups/tasks. */
4099
4689
  flush(snapshot) {
4100
4690
  const insert = this.db.prepare(
4101
- "INSERT INTO messages (id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop, mseq, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
4691
+ "INSERT INTO messages (id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop, mseq, expires_at, priority) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
4102
4692
  );
4103
4693
  for (const message of this.buffer.splice(0, this.buffer.length)) {
4104
4694
  insert.run(...messageToRow(message));
4105
4695
  }
4106
4696
  this.db.exec("DELETE FROM mailboxes");
4107
4697
  const insertMail = this.db.prepare(
4108
- "INSERT INTO mailboxes (peer, id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop, mseq, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
4698
+ "INSERT INTO mailboxes (peer, id, from_peer, to_peer, kind, content, ref, channel, thread_id, ts, hop, mseq, expires_at, priority) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
4109
4699
  );
4110
4700
  for (const [peer, queue] of Object.entries(snapshot.mailboxes)) {
4111
4701
  for (const message of queue) insertMail.run(peer, ...messageToRow(message));
@@ -4209,7 +4799,7 @@ function cardField(raw) {
4209
4799
 
4210
4800
  // src/index.ts
4211
4801
  var SERVER_NAME = "agent-comm-hub";
4212
- var SERVER_VERSION = "0.10.0";
4802
+ var SERVER_VERSION = "0.11.0";
4213
4803
  var DEFAULT_HOST = "127.0.0.1";
4214
4804
  var DEFAULT_PORT = 18764;
4215
4805
  var DEFAULT_PATH = "/mcp";
@@ -4334,6 +4924,27 @@ function startHub(config = {}, log2 = console) {
4334
4924
  });
4335
4925
  }
4336
4926
  };
4927
+ const MAX_TASK_PUSH_MEMORY = 512;
4928
+ const lastTaskPush = /* @__PURE__ */ new Map();
4929
+ const pushTaskChanged = (task) => {
4930
+ const data = {
4931
+ event: SSE_EVENT_TASK_CHANGED,
4932
+ taskId: task.id,
4933
+ status: task.status,
4934
+ // A2A naming, so a client that speaks A2A does not have to carry the
4935
+ // ledger's own vocabulary — same mapping bridge_task_status publishes.
4936
+ a2aState: a2aState(task.status),
4937
+ updatedAt: task.updatedAt
4938
+ };
4939
+ const seen = /* @__PURE__ */ new Set();
4940
+ for (const peer of [task.from, ...task.assignees.map((assignee) => assignee.peerId)]) {
4941
+ if (seen.has(peer)) continue;
4942
+ seen.add(peer);
4943
+ const sessions = registry.sessionsForPeer(peer);
4944
+ if (sessions.length === 0) continue;
4945
+ mcp.notify(oneStreamPer(`task:${peer}`, sessions), SSE_METHOD, { level: "info", logger: "bridge", data });
4946
+ }
4947
+ };
4337
4948
  let saveTimer;
4338
4949
  let rosterDirty = false;
4339
4950
  let dbDirty = false;
@@ -4446,11 +5057,26 @@ function startHub(config = {}, log2 = console) {
4446
5057
  },
4447
5058
  // Task ledger transitions (ack folding, SLA timeout, first delivery) are
4448
5059
  // their own persistence trigger: without it a crash between two roster
4449
- // events loses the ledger state the admin board reads back.
4450
- onTaskChanged: () => {
4451
- if (dbStore === void 0) return;
4452
- dbDirty = true;
4453
- scheduleSave();
5060
+ // events loses the ledger state the admin board reads back. They are also
5061
+ // the SSE `task_changed` signal for the two parties of a task.
5062
+ onTaskChanged: (task) => {
5063
+ if (dbStore !== void 0) {
5064
+ dbDirty = true;
5065
+ scheduleSave();
5066
+ }
5067
+ if (lastTaskPush.get(task.id) === task.status) return;
5068
+ try {
5069
+ pushTaskChanged(task);
5070
+ } catch (error) {
5071
+ log2.warn(`task_changed notification failed: ${error.message}`);
5072
+ }
5073
+ lastTaskPush.delete(task.id);
5074
+ lastTaskPush.set(task.id, task.status);
5075
+ while (lastTaskPush.size > MAX_TASK_PUSH_MEMORY) {
5076
+ const oldest = lastTaskPush.keys().next().value;
5077
+ if (oldest === void 0) break;
5078
+ lastTaskPush.delete(oldest);
5079
+ }
4454
5080
  },
4455
5081
  onGroupsChanged: () => {
4456
5082
  if (dbStore === void 0) return;
@@ -4510,9 +5136,9 @@ function startHub(config = {}, log2 = console) {
4510
5136
  log2.info(`roster restored: ${importedProfiles} profile(s) from ${resolved.db}`);
4511
5137
  }
4512
5138
  const restoredMessages = hub.importHistory(state.messages);
4513
- const restoredQueued = hub.importMailboxes(state.mailboxes);
4514
5139
  const restoredGroups = hub.importGroups(state.groups);
4515
5140
  const restoredTasks = hub.importTasks(state.tasks);
5141
+ const restoredQueued = hub.importMailboxes(state.mailboxes);
4516
5142
  if (restoredMessages + restoredQueued + restoredGroups > 0) {
4517
5143
  log2.info(`state restored from ${resolved.db}: ${restoredMessages} message(s), ${restoredQueued} queued, ${restoredGroups} group(s)`);
4518
5144
  dbDirty = true;
@@ -4568,7 +5194,13 @@ function startHub(config = {}, log2 = console) {
4568
5194
  herdr,
4569
5195
  herdrControlPeers: resolved.herdrControlPeers === "all" || resolved.herdrControlPeers === void 0 ? "all" : new Set(resolved.herdrControlPeers),
4570
5196
  managerPeers: resolved.managerPeers === "all" ? "all" : new Set(resolved.managerPeers ?? DEFAULT_CONFIG.managerPeers),
4571
- managerTokenRequired: managerToken !== void 0
5197
+ managerTokenRequired: managerToken !== void 0,
5198
+ // Token identities are an authorization fact of the TABLE, not of the live
5199
+ // sessions: `bridge_rename` must not re-key onto a configured id whose
5200
+ // owner has not connected yet. Read from the file on every call because
5201
+ // the token admin API adds/removes rows at runtime (and `readTokens`
5202
+ // returns [] in loopback mode, where no id is reserved).
5203
+ ...resolved.authTokens === void 0 ? {} : { tokenPeers: () => new Set(readTokens(resolved.authTokens).map((row) => row.peer)) }
4572
5204
  }),
4573
5205
  { name: SERVER_NAME, version: SERVER_VERSION },
4574
5206
  registry,