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