@cotal-ai/connector-core 0.154.0 → 0.155.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/dist/agent.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { EventEmitter } from "node:events";
3
3
  import { hostname } from "node:os";
4
- import { normalizeMentions, RUN_LAUNCH_DEADLINE_MS, subjectMatches, isConcreteChannel, isChannelFamily, assertValidChannel, channelInAllow, eventChannelPrincipal, resolvePeer as resolvePeerInRoster, peerLabel, CotalEndpoint, acquireLocalConsumer, BASELINE_LIFECYCLE_ENDPOINT, BIND_SPLIT_REISSUES, assertLifecycleToken, EpEnvelopeError, isPublishPermissionDenied, unansweredRequest, EP_UNANSWERED, controlReplyFrom, controlReplyFromThrown, runAgentBearer, partsToText, assertValidRole, turnNoticeFilter, renderOnceTask, } from "@cotal-ai/core";
4
+ import { normalizeMentions, RUN_LAUNCH_DEADLINE_MS, subjectMatches, isConcreteChannel, isChannelFamily, assertValidChannel, channelInAllow, eventChannelPrincipal, resolvePeer as resolvePeerInRoster, peerLabel, CotalEndpoint, acquireLocalConsumer, BASELINE_LIFECYCLE_ENDPOINT, BIND_SPLIT_REISSUES, assertLifecycleToken, EpEnvelopeError, isPublishPermissionDenied, unansweredRequest, EP_UNANSWERED, controlReplyFrom, controlReplyFromThrown, runAgentBearer, ANYCAST_NOTICE_KEY, partsToText, assertValidRole, turnNoticeFilter, renderOnceTask, } from "@cotal-ai/core";
5
5
  import { eventPlaneArmed } from "./config.js";
6
6
  import { TURN_PULL_RETRY_MS } from "./turn-poll.js";
7
7
  import { ONCE_HANDOFF_MS, claimOnceHandoff, confirmOnceHandoff, endOnceHandoff, exitOnceSeat, onOnceHandoffTimeout, onceHandoffState, sealOnceHandoff, stopOnceHandoffTimer } from "./once.js";
@@ -77,6 +77,11 @@ export function afterRecallMark(a, b) {
77
77
  /** How many pending messages one session buffers before the overflow valve in
78
78
  * {@link MeshAgent.buffer} evicts. Exported so the overflow smokes read the bound they exercise. */
79
79
  export const MAX_INBOX = 200;
80
+ /** How long {@link MeshAgent.takeChosen} waits for the delivery daemon before it lets a caller show
81
+ * what is already taken. A take not decided by then stays held for a later read. */
82
+ const TAKE_WAIT_MS = 2_000;
83
+ /** How long a role request whose take could not be decided waits before it is asked about again. */
84
+ const TAKE_RETRY_MS = 10_000;
80
85
  /** How many receive keys {@link MeshAgent.holdInFlight} protects at once. The overflow valve never
81
86
  * evicts a held entry, so this ceiling also bounds the inbox while holds are open, which is why it
82
87
  * is derived from {@link MAX_INBOX}. It sits above the inbox because a frame keeps its holds until
@@ -147,6 +152,11 @@ function onceSpawner(payload) {
147
152
  }
148
153
  }
149
154
  import { createHash, randomUUID } from "node:crypto";
155
+ /** Whether a DM carries a delivery daemon's anycast notice part (SPEC §8.1). Its sender is still to
156
+ * be checked against the delivery lease. */
157
+ function carriesAnycastNotice(m) {
158
+ return m.parts.some((p) => p.kind === "data" && typeof p.data === "object" && p.data !== null && !Array.isArray(p.data) && ANYCAST_NOTICE_KEY in p.data);
159
+ }
150
160
  /** #662: what an id-less channel delivery shares with its stream copy. Both are the same published
151
161
  * bytes, read through the same authentication, so their content is all that links them. */
152
162
  function idlessDigest(m) {
@@ -261,6 +271,17 @@ export class MeshAgent extends EventEmitter {
261
271
  launchEnv;
262
272
  options;
263
273
  inbox = [];
274
+ /** Role requests delivered on an auth mesh whose take is not recorded for the copy held (SPEC §8.1).
275
+ * They count toward a wake and are never shown: {@link takeChosen} asks the delivery daemon to
276
+ * record the take of each one a host chose to show, and a recorded one moves to {@link inbox}. */
277
+ gated = [];
278
+ /** Counts arrivals, to number each entry's {@link Pending.arrival}. */
279
+ arrivals = 0;
280
+ /** Why the last take could not be decided, when it could not, and when a held request may be
281
+ * asked about again. Reported by `cotal_inbox`. */
282
+ heldTake;
283
+ /** Re-announces the held role requests once {@link heldTake} lets them be asked about again. */
284
+ takeRetry;
264
285
  /** Ids already SURFACED to the model (handled) — bounded, commit-aware dedup ACROSS a drain. The
265
286
  * live↔durable transition window can deliver the two copies of one message far enough apart that the
266
287
  * first is already drained (removed from {@link inbox}) when the second arrives; the pending-inbox
@@ -465,7 +486,12 @@ export class MeshAgent extends EventEmitter {
465
486
  meta: buildMeta(config, !options.withholdProcessCwd),
466
487
  },
467
488
  });
468
- this.ep.on("message", (m, d, meta) => this.ingest(m, d, meta));
489
+ this.ep.on("message", (m, d, meta) => {
490
+ if (meta?.kind === "dm" && carriesAnycastNotice(m))
491
+ void this.ingestNotice(m, d, meta);
492
+ else
493
+ this.ingest(m, d, meta);
494
+ });
469
495
  this.ep.on("error", (e) => this.handleEndpointError(e));
470
496
  // A warning is a condition the endpoint is already surviving. Log it through the same bounded
471
497
  // operator sink, but never turn it into connectionIssue: readiness is still true.
@@ -482,8 +508,22 @@ export class MeshAgent extends EventEmitter {
482
508
  if (this._transportConnected === e.connected)
483
509
  return;
484
510
  this._transportConnected = e.connected;
485
- if (!e.connected)
511
+ if (!e.connected) {
486
512
  this.transportDrops++;
513
+ // This reader cannot vouch for a copy across a drop, so a role request taken and not yet
514
+ // handed to a host is taken again before it is shown.
515
+ for (const p of this.inbox.filter((x) => x.take && !this.inFlightIds.has(x.item.recvKey)))
516
+ this.regate(p);
517
+ }
518
+ // No take is asked while the link is down (see mayAskTakes), so a host that read then was offered
519
+ // none of the held requests. Each whose take is not out, and whose copy is still this reader's,
520
+ // is announced again now.
521
+ if (e.connected && this.mayAskTakes()) {
522
+ this.dropLapsedTakes();
523
+ for (const p of this.gated)
524
+ if (p.taking === undefined)
525
+ this.emit("incoming", p.item);
526
+ }
487
527
  this.emit("transport", e);
488
528
  // A notice lost while the transport was down can only matter to a turn this seat holds: the
489
529
  // manager repeats the notice for a turn the seat has not pulled yet. So only a holder pulls.
@@ -844,6 +884,8 @@ export class MeshAgent extends EventEmitter {
844
884
  this.emit("stopping");
845
885
  for (const key of [...this.renewals.keys()])
846
886
  this.stopRenewal(key);
887
+ clearTimeout(this.takeRetry);
888
+ this.takeRetry = undefined;
847
889
  this.managerBearers.clear();
848
890
  if (this.turnRetryTimer !== undefined) {
849
891
  clearTimeout(this.turnRetryTimer);
@@ -913,7 +955,13 @@ export class MeshAgent extends EventEmitter {
913
955
  }
914
956
  }
915
957
  // ---- inbox ---------------------------------------------------------------
916
- ingest(m, delivery, meta) {
958
+ /** A DM shaped as a delivery daemon's notice is one only when its authenticated sender holds the
959
+ * space's delivery lease. Any other sender's copy is an ordinary DM. */
960
+ async ingestNotice(m, delivery, meta) {
961
+ const holder = await this.ep.deliveryLeaseHolder(0);
962
+ this.ingest(m, delivery, meta, holder !== undefined && holder === m.from.id);
963
+ }
964
+ ingest(m, delivery, meta, notice = false) {
917
965
  // #624: an EMPTY id is never a dedup key. The id-keyed coalescing below exists to collapse the
918
966
  // copies of ONE message across the live/durable paths, and identity is what makes that safe. A
919
967
  // message that carries an empty id asserts no identity (SPEC §5 requires a unique id; the sender
@@ -946,14 +994,20 @@ export class MeshAgent extends EventEmitter {
946
994
  // dropped as-is. A durable duplicate also re-announces the still-pending item through the
947
995
  // ordinary `incoming` policy path. That turns JetStream redelivery into a timer-free retry for
948
996
  // a wake the host dropped, without bypassing quiet/attention or adapter in-flight guards.
949
- const existing = key === undefined ? undefined : this.inbox.find((p) => p.item.id === key);
997
+ const existing = key === undefined ? undefined : this.inbox.find((p) => p.item.id === key) ?? this.gated.find((p) => p.item.id === key);
950
998
  if (existing) {
951
999
  if (delivery.durable) {
952
1000
  existing.ack = delivery.ack;
953
1001
  // A fresh copy is a fresh ownership: a hold that outlived the copy it renewed keeps this one.
954
1002
  this.own(existing, delivery.redelivery);
1003
+ if (delivery.take)
1004
+ existing.take = delivery.take;
955
1005
  if (this.inFlightIds.has(existing.item.recvKey))
956
1006
  this.keepOwned(existing.item.recvKey);
1007
+ // A role request taken for an earlier copy and not yet shown needs a take of this one: the
1008
+ // broker redelivered it, so the earlier take may have lost it to another holder.
1009
+ else if (existing.take && existing.takenCount !== existing.item.deliveryCount)
1010
+ this.regate(existing);
957
1011
  this.emit("incoming", existing.item);
958
1012
  }
959
1013
  return;
@@ -961,18 +1015,12 @@ export class MeshAgent extends EventEmitter {
961
1015
  if (!meta)
962
1016
  throw new Error(`message ${m.id} delivered without MessageMeta — its class is unauthenticated`);
963
1017
  const item = this.toInboxItem(m, meta.kind, meta.historical);
964
- if (item.kind === "dm" || item.kind === "anycast") {
965
- this.senders.delete(item.fromId);
966
- this.senders.set(item.fromId, item.fromName);
967
- if (this.senders.size > MAX_CORRELATIONS)
968
- this.senders.delete(this.senders.keys().next().value);
969
- }
970
- if ((item.kind === "dm" || item.kind === "anycast") && !item.historical && item.id !== "" && !this.answersQuestion(item)) {
971
- // A DM back to this peer answers it (see dm()). An answer to our own question needs none.
972
- this.unanswered.set(item.id, { fromId: item.fromId, contextId: item.contextId, text: item.text.slice(0, 80) });
973
- if (this.unanswered.size > MAX_CORRELATIONS)
974
- this.unanswered.delete(this.unanswered.keys().next().value);
975
- }
1018
+ if (notice)
1019
+ item.notice = "anycast";
1020
+ // A notice asks for nothing and answers nothing. A role request awaiting its take is recorded
1021
+ // as asked of us only once it is taken, since a refused take drops it unseen.
1022
+ else if (!delivery.take)
1023
+ this.noteDirected(item);
976
1024
  // Per-channel override is the FINAL word for a channel message (DMs/anycast are never channel-
977
1025
  // scoped, so they bypass this entirely and always buffer). Evaluated BEFORE the global mode:
978
1026
  // - `muted` → hard drop, incl. @mention (a mention rides the channel; you can't keep it if you
@@ -1062,12 +1110,46 @@ export class MeshAgent extends EventEmitter {
1062
1110
  }
1063
1111
  this.buffer(item, delivery, false);
1064
1112
  }
1113
+ /** Record a DM or role request as a peer's message to us: its sender becomes addressable by name,
1114
+ * and it waits for an answer unless it answers our own question. */
1115
+ noteDirected(item) {
1116
+ if (item.kind !== "dm" && item.kind !== "anycast")
1117
+ return;
1118
+ this.senders.delete(item.fromId);
1119
+ this.senders.set(item.fromId, item.fromName);
1120
+ if (this.senders.size > MAX_CORRELATIONS)
1121
+ this.senders.delete(this.senders.keys().next().value);
1122
+ if (!item.historical && item.id !== "" && !this.answersQuestion(item)) {
1123
+ // A DM back to this peer answers it (see dm()). An answer to our own question needs none.
1124
+ this.unanswered.set(item.id, { fromId: item.fromId, contextId: item.contextId, text: item.text.slice(0, 80) });
1125
+ if (this.unanswered.size > MAX_CORRELATIONS)
1126
+ this.unanswered.delete(this.unanswered.keys().next().value);
1127
+ }
1128
+ }
1065
1129
  buffer(item, delivery, pullOnly, idless) {
1066
- const pending = { item, ack: delivery.ack, pullOnly, receivedAt: Date.now() };
1130
+ const pending = { item, ack: delivery.ack, pullOnly, receivedAt: Date.now(), arrival: this.arrivals++ };
1067
1131
  this.own(pending, delivery.redelivery);
1068
1132
  if (idless)
1069
1133
  pending.idless = { tally: this.focusIdless, ...idless };
1070
- this.inbox.push(pending);
1134
+ if (delivery.take) {
1135
+ // Held until its take is recorded. A copy beyond the bound is left unacked, so the broker
1136
+ // redelivers it once there is room, as the overflow valve below does for directed mail.
1137
+ pending.take = delivery.take;
1138
+ this.gated.push(pending);
1139
+ if (this.gated.length > MAX_INBOX)
1140
+ this.gated.shift();
1141
+ this.emit("incoming", item);
1142
+ return;
1143
+ }
1144
+ this.admit(pending);
1145
+ this.emit("incoming", item);
1146
+ }
1147
+ /** Put one entry in the shown inbox at its arrival place, running the overflow valve. */
1148
+ admit(pending) {
1149
+ let at = this.inbox.length;
1150
+ while (at > 0 && this.inbox[at - 1].arrival > pending.arrival)
1151
+ at--;
1152
+ this.inbox.splice(at, 0, pending);
1071
1153
  if (this.inbox.length > MAX_INBOX) {
1072
1154
  // Prefer sacrificing pull-only backlog so it cannot crowd out DMs/mentions. Overflow is bounded
1073
1155
  // local loss for channel traffic only: an evicted channel item is acked without being marked
@@ -1123,7 +1205,6 @@ export class MeshAgent extends EventEmitter {
1123
1205
  evicted.ack();
1124
1206
  }
1125
1207
  }
1126
- this.emit("incoming", item);
1127
1208
  }
1128
1209
  rememberEvicted(p) {
1129
1210
  if (p.item.kind !== "channel" || p.item.mentionsMe || !p.item.channel)
@@ -1318,10 +1399,158 @@ export class MeshAgent extends EventEmitter {
1318
1399
  };
1319
1400
  }
1320
1401
  /** Return pending messages in stable receive order. Automatic delivery excludes quiet ambient;
1321
- * pull-only is the explicit cotal_inbox lane. */
1402
+ * pull-only is the explicit cotal_inbox lane.
1403
+ *
1404
+ * A role request whose take is not yet recorded is never returned (SPEC §8.1): a host shows one
1405
+ * only through {@link takeChosen}. */
1322
1406
  peekInbox(scope = "all") {
1407
+ this.dropLapsedTakes();
1323
1408
  return this.inbox.filter((p) => this.inScope(p, scope)).map((p) => p.item);
1324
1409
  }
1410
+ /** Every pending message in scope as {@link peekInbox} will return it once the held role requests
1411
+ * that may be asked about now are taken, in that order. It is for choosing what to show, never for
1412
+ * showing: hand the choice to {@link takeChosen}. */
1413
+ inboxPreview(scope = "all") {
1414
+ this.dropLapsedTakes();
1415
+ const askable = scope === "pull-only" ? [] : this.gated.filter((p) => this.mayOffer(p));
1416
+ return [...this.inbox.filter((p) => this.inScope(p, scope)), ...askable].sort((a, b) => a.arrival - b.arrival).map((p) => p.item);
1417
+ }
1418
+ /** Choose what to show from {@link inboxPreview}, ask the delivery daemon to record the take of
1419
+ * each held role request in the choice, wait up to `waitMs` for the answers, and return the chosen
1420
+ * items that may be shown now, in the order chosen. A take is a claim that this session's agent is
1421
+ * about to see the request, which ends its sender's chance to cancel it, so call this just before
1422
+ * showing and choose only what will be shown. A request whose take is refused or not yet decided
1423
+ * is left out. Never throws. */
1424
+ async takeChosen(scope, choose, waitMs = TAKE_WAIT_MS) {
1425
+ const chosen = choose(this.inboxPreview(scope));
1426
+ const keys = new Set(chosen.map((i) => i.recvKey));
1427
+ const asked = scope === "pull-only" ? [] : this.gated
1428
+ .filter((p) => keys.has(p.item.recvKey) && this.mayOffer(p));
1429
+ for (const p of asked)
1430
+ p.awaited = (p.awaited ?? 0) + 1;
1431
+ const runs = asked.map((p) => (p.taking !== undefined && p.takingDrops === this.transportDrops ? p.taking : this.startTake(p)));
1432
+ if (runs.length) {
1433
+ let timer;
1434
+ const waited = new Promise((resolve) => { timer = setTimeout(resolve, waitMs); timer.unref?.(); });
1435
+ await Promise.race([Promise.allSettled(runs), waited]);
1436
+ clearTimeout(timer);
1437
+ }
1438
+ for (const p of asked)
1439
+ p.awaited = (p.awaited ?? 1) - 1;
1440
+ const showable = new Map(this.peekInbox(scope).map((i) => [i.recvKey, i]));
1441
+ return chosen.flatMap((i) => showable.get(i.recvKey) ?? []);
1442
+ }
1443
+ /** How many role requests are held because their take could not be decided, and why. */
1444
+ heldTakes() {
1445
+ const count = this.gated.filter((p) => p.taking === undefined).length;
1446
+ return count && this.heldTake ? { count, detail: this.heldTake.detail } : { count };
1447
+ }
1448
+ /** Whether a held role request may be asked about now: the link is up, and no take nobody could
1449
+ * decide is being waited out ({@link heldTake}). */
1450
+ mayAskTakes() {
1451
+ return this._transportConnected && (!this.heldTake || Date.now() >= this.heldTake.retryAt);
1452
+ }
1453
+ /** Whether a read may be offered a held role request now: the link is up and its take is out
1454
+ * already, or a take may be asked ({@link mayAskTakes}). A take that is out when the link drops
1455
+ * cannot admit the request until the link is back, so a read then is offered nothing of it. */
1456
+ mayOffer(p) {
1457
+ return (p.taking !== undefined && this._transportConnected) || this.mayAskTakes();
1458
+ }
1459
+ startTake(p) {
1460
+ const run = this.runTake(p).catch((e) => this.handleEndpointWarning(e)).finally(() => {
1461
+ if (p.taking === run)
1462
+ p.taking = undefined;
1463
+ });
1464
+ p.taking = run;
1465
+ p.takingDrops = this.transportDrops;
1466
+ return run;
1467
+ }
1468
+ /** Take one held role request for the copy it holds, and admit it only if it still holds that copy
1469
+ * once the take is recorded: the same delivery, its ack wait not run out, the link not dropped. */
1470
+ async runTake(p) {
1471
+ const take = p.take;
1472
+ if (!take)
1473
+ return;
1474
+ // The copy is renewed before the take is asked for, so the take cannot outlive it. A copy whose
1475
+ // ack wait already ran out may be another holder's now: drop it unacked and let the broker redeliver.
1476
+ if (!this._transportConnected)
1477
+ return;
1478
+ if (!this.renewOwned(p)) {
1479
+ this.dropGated(p);
1480
+ return;
1481
+ }
1482
+ const count = p.item.deliveryCount;
1483
+ const drops = this.transportDrops;
1484
+ const outcome = await take();
1485
+ if (!this.gated.includes(p) || p.take !== take)
1486
+ return;
1487
+ // An answer that crossed a link drop is the old link's, so the request stays held and a read
1488
+ // waiting on this take shows nothing of it. Its host is told again once the link is up, so the
1489
+ // next read takes it on the new link. While the link is down a read could not take it, and the
1490
+ // read that waited on this take may still be running, so the reconnect announces it. A read
1491
+ // that asked again on the new link owns the request now, so this take says nothing.
1492
+ if (this.transportDrops !== drops) {
1493
+ if (p.takingDrops !== drops)
1494
+ return;
1495
+ if (this._transportConnected)
1496
+ this.emit("incoming", p.item);
1497
+ return;
1498
+ }
1499
+ if (outcome.taken) {
1500
+ this.heldTake = undefined;
1501
+ const current = p.item.deliveryCount === count && p.ownedUntil !== undefined && Date.now() < p.ownedUntil;
1502
+ if (!current)
1503
+ return; // a newer copy arrived meanwhile and needs its own take
1504
+ p.takenCount = count;
1505
+ p.takenOnce = true;
1506
+ this.gated.splice(this.gated.indexOf(p), 1);
1507
+ this.noteDirected(p.item);
1508
+ this.admit(p);
1509
+ // Its arrival was announced already. A read waiting on this take shows it next; one that
1510
+ // stopped waiting is told it may be shown now, as of a new arrival.
1511
+ if (!p.awaited)
1512
+ this.emit("incoming", p.item);
1513
+ return;
1514
+ }
1515
+ if (outcome.drop) {
1516
+ this.dropGated(p);
1517
+ return;
1518
+ }
1519
+ const first = this.heldTake?.reason !== outcome.reason;
1520
+ this.heldTake = { reason: outcome.reason, detail: outcome.detail, retryAt: Date.now() + TAKE_RETRY_MS };
1521
+ // Nothing asks about a held request on its own, so its host hears of it again when it may.
1522
+ this.takeRetry ??= setTimeout(() => {
1523
+ this.takeRetry = undefined;
1524
+ for (const held of this.gated)
1525
+ this.emit("incoming", held.item);
1526
+ }, TAKE_RETRY_MS);
1527
+ this.takeRetry.unref?.();
1528
+ if (first && outcome.reason !== "daemon-busy")
1529
+ this.handleEndpointWarning(new Error(outcome.detail));
1530
+ }
1531
+ /** Forget a role request whose take was refused or whose copy ran out. It is never acked: a
1532
+ * cancelled one is gone already, and one another holder took must stay with that holder. */
1533
+ dropGated(p) {
1534
+ const i = this.gated.indexOf(p);
1535
+ if (i >= 0)
1536
+ this.gated.splice(i, 1);
1537
+ }
1538
+ /** Move a taken role request back to the held set when its copy changed before it was shown. */
1539
+ regate(p) {
1540
+ const i = this.inbox.indexOf(p);
1541
+ if (i < 0)
1542
+ return;
1543
+ this.inbox.splice(i, 1);
1544
+ p.takenCount = undefined;
1545
+ this.gated.push(p);
1546
+ }
1547
+ /** Drop every taken role request not yet shown whose copy ran out: the broker may have handed it
1548
+ * to another holder, whose take of the later copy wins. One the host holds is renewed and kept. */
1549
+ dropLapsedTakes() {
1550
+ const now = Date.now();
1551
+ this.inbox = this.inbox.filter((p) => !p.take || this.inFlightIds.has(p.item.recvKey) || (p.ownedUntil !== undefined && now < p.ownedUntil));
1552
+ this.gated = this.gated.filter((p) => p.taking !== undefined || p.ownedUntil === undefined || now < p.ownedUntil);
1553
+ }
1325
1554
  /** Mark a surfaced batch as mid-delivery, so the overflow valve will not evict it out from under
1326
1555
  * the host. Pair with {@link releaseInFlight} on the delivery verdict, whichever way it goes.
1327
1556
  *
@@ -1426,6 +1655,7 @@ export class MeshAgent extends EventEmitter {
1426
1655
  }
1427
1656
  /** Return scoped pending messages and ack them — call only when they're actually surfaced. */
1428
1657
  drainInbox(limit, scope = "all") {
1658
+ this.dropLapsedTakes();
1429
1659
  const eligible = this.inbox.filter((p) => this.inScope(p, scope));
1430
1660
  const n = limit && limit > 0 ? Math.min(limit, eligible.length) : eligible.length;
1431
1661
  const selected = eligible.slice(0, n);
@@ -1458,7 +1688,14 @@ export class MeshAgent extends EventEmitter {
1458
1688
  drainInboxDeliveries(keys) {
1459
1689
  const requested = [...new Set(keys)];
1460
1690
  const wanted = new Set(requested);
1461
- const selected = this.inbox.filter((p) => wanted.has(p.item.recvKey));
1691
+ // A role request the host surfaced can be back in the held set when its copy changed since. The
1692
+ // host showed it, so its commit acks it from there too. One never taken was never shown, so it
1693
+ // stays held: it is not acked, marked handled or reported missing.
1694
+ const regated = this.gated.filter((p) => wanted.has(p.item.recvKey) && p.takenOnce);
1695
+ const unshown = new Set(this.gated.filter((p) => wanted.has(p.item.recvKey) && !p.takenOnce).map((p) => p.item.recvKey));
1696
+ if (regated.length)
1697
+ this.gated = this.gated.filter((p) => !regated.includes(p));
1698
+ const selected = [...this.inbox.filter((p) => wanted.has(p.item.recvKey)), ...regated];
1462
1699
  this.noteAutomaticHeadProgress(selected);
1463
1700
  const present = new Set(selected.map((p) => p.item.recvKey));
1464
1701
  const pullOnly = new Map(selected.map((p) => [p.item.recvKey, p.pullOnly]));
@@ -1479,12 +1716,12 @@ export class MeshAgent extends EventEmitter {
1479
1716
  // markHandled already refuses, so skipping it here is the same at-least-once stance rather
1480
1717
  // than a new one. Recording the minted key itself would pollute handledIds with a string a
1481
1718
  // future REAL id could legitimately equal, arming the exact suppression this change removes.
1482
- if (!present.has(id) && !id.startsWith(`${this.recvKeySecret}.`)) {
1719
+ if (!present.has(id) && !unshown.has(id) && !id.startsWith(`${this.recvKeySecret}.`)) {
1483
1720
  this.markHandled(id, pullOnly.get(id) ?? false);
1484
1721
  this.evictedClassifications.delete(id);
1485
1722
  }
1486
1723
  }
1487
- return { items, missingKeys: requested.filter((key) => !present.has(key)) };
1724
+ return { items, missingKeys: requested.filter((key) => !present.has(key) && !unshown.has(key)) };
1488
1725
  }
1489
1726
  commitPending(taken) {
1490
1727
  for (const p of taken) {
@@ -1511,8 +1748,22 @@ export class MeshAgent extends EventEmitter {
1511
1748
  this.handledIds = new Set();
1512
1749
  }
1513
1750
  }
1751
+ /** Receive keys of the pending messages in scope, role requests held for their take included,
1752
+ * for bookkeeping that shows no body. */
1753
+ inboxKeys(scope = "all") {
1754
+ const held = scope === "pull-only" ? [] : this.gated;
1755
+ return [...this.inbox.filter((p) => this.inScope(p, scope)), ...held].map((p) => p.item.recvKey);
1756
+ }
1757
+ /** The pending messages in scope, role requests held for their take included, for a notice that
1758
+ * counts them and shows no body. A held request is shown only through {@link takeChosen}. */
1759
+ inboxPending(scope = "all") {
1760
+ const held = scope === "pull-only" ? [] : this.gated;
1761
+ return [...this.inbox.filter((p) => this.inScope(p, scope)), ...held].map((p) => p.item);
1762
+ }
1763
+ /** Pending messages in scope, counting role requests still held for their take. */
1514
1764
  inboxCount(scope = "all") {
1515
- return scope === "all" ? this.inbox.length : this.inbox.filter((p) => this.inScope(p, scope)).length;
1765
+ const held = scope === "pull-only" ? 0 : this.gated.length;
1766
+ return held + (scope === "all" ? this.inbox.length : this.inbox.filter((p) => this.inScope(p, scope)).length);
1516
1767
  }
1517
1768
  /**
1518
1769
  * Read a bounded presentation snapshot without draining, acknowledging, committing, holding or
@@ -1523,12 +1774,15 @@ export class MeshAgent extends EventEmitter {
1523
1774
  inboxSnapshot(limit = 3) {
1524
1775
  if (!Number.isInteger(limit) || limit < 0 || limit > 8)
1525
1776
  throw new Error(`inbox preview limit must be a whole number from 0 to 8, got ${limit}`);
1526
- return { unread: this.inbox.length, items: this.inbox.slice(0, limit).map((p) => ({ ...p.item })) };
1777
+ // A held role request is counted and never previewed: its body is shown only once a host takes
1778
+ // it to show it (SPEC §8.1).
1779
+ this.dropLapsedTakes();
1780
+ return { unread: this.inbox.length + this.gated.length, items: this.inbox.slice(0, limit).map((p) => ({ ...p.item })) };
1527
1781
  }
1528
1782
  /** Local receive time of the oldest still-buffered automatic delivery, if any. */
1529
1783
  oldestAutomaticReceivedAt() {
1530
1784
  let oldest;
1531
- for (const pending of this.inbox) {
1785
+ for (const pending of [...this.inbox, ...this.gated]) {
1532
1786
  if (pending.pullOnly)
1533
1787
  continue;
1534
1788
  if (oldest === undefined || pending.receivedAt < oldest)
@@ -1634,14 +1888,14 @@ export class MeshAgent extends EventEmitter {
1634
1888
  /** Buffered receive-time lane for one delivery, addressed by its receive key. Undefined means it
1635
1889
  * is no longer pending. */
1636
1890
  inboxScope(key) {
1637
- const pending = this.inbox.find((p) => p.item.recvKey === key);
1891
+ const pending = this.inbox.find((p) => p.item.recvKey === key) ?? this.gated.find((p) => p.item.recvKey === key);
1638
1892
  return pending ? (pending.pullOnly ? "pull-only" : "automatic") : undefined;
1639
1893
  }
1640
1894
  /** Count of automatic messages that count as directed for a wake decision: real dm/anycast
1641
1895
  * (authenticated kind) or a live channel @mention. Pull-only history never counts, including
1642
1896
  * mentions retained while focused. The Stop→idle flush uses this in `dnd`/`focus`. */
1643
1897
  directedPendingCount() {
1644
- return this.inbox.filter((p) => !p.pullOnly && (p.item.kind !== "channel" || (!p.item.historical && p.item.mentionsMe))).length;
1898
+ return this.gated.length + this.inbox.filter((p) => !p.pullOnly && (p.item.kind !== "channel" || (!p.item.historical && p.item.mentionsMe))).length;
1645
1899
  }
1646
1900
  /** Buffered items that should WAKE a Stop→idle flush — the mode-and-channel-aware predicate the
1647
1901
  * connectors use instead of branching on attention themselves:
@@ -1661,7 +1915,13 @@ export class MeshAgent extends EventEmitter {
1661
1915
  * turns. A surface that cannot surface a run turn, such as the remote gateway, waits on this, so
1662
1916
  * a turn it can never clear does not end every wait at once. */
1663
1917
  inboxWake(skip) {
1664
- return this.inbox.filter((p) => {
1918
+ // A role request held for its take wakes when a read could take it: the read the wake leads to
1919
+ // takes it. While the link is down, or a take nobody could decide is waited out, none wakes, and
1920
+ // each is announced again when the link is back or the wait ends (see runTake). A copy whose ack
1921
+ // wait ran out is dropped first, as a read drops it.
1922
+ this.dropLapsedTakes();
1923
+ const held = this.mayAskTakes() ? this.gated.filter((p) => !skip?.(p.item)).length : 0;
1924
+ return held + this.inbox.filter((p) => {
1665
1925
  const it = p.item;
1666
1926
  if (p.pullOnly || (it.kind === "channel" && it.historical) || skip?.(it))
1667
1927
  return false;
@@ -1942,16 +2202,54 @@ export class MeshAgent extends EventEmitter {
1942
2202
  // Refuse the address before recording a question it could never carry, as `dm` resolves its peer first.
1943
2203
  assertValidRole(role);
1944
2204
  await this.requireConnected();
1945
- // Like a DM's recipient status, the only holder count we can truthfully attribute is the roster
1946
- // read right before the publish. Our own task consumer competes for our own request,
1947
- // so we count when we hold the role.
1948
- const { roster, failure } = await this.readRoster();
1949
- const holdersAtSend = failure ? undefined : roster.filter((p) => p.card.role === role && p.status !== "offline").length;
2205
+ // Like a DM's recipient status, the only holders we can truthfully name are the roster read
2206
+ // right before the publish. Our own task consumer competes for our own request, so we count
2207
+ // when we hold the role.
2208
+ const holdersAtSend = await this.roleHolders(role);
1950
2209
  const { stamp, own } = this.stamp();
1951
2210
  this.recordQuestion(own, { role });
1952
2211
  const { msg, ack } = await this.ep.anycastAttributed(role, text, stamp);
2212
+ this.rememberSent(ack.seq, msg.id);
1953
2213
  return { msg, ack, holdersAtSend };
1954
2214
  }
2215
+ /** The live holders of `role` on a fresh roster read, or undefined when the read failed. */
2216
+ async roleHolders(role) {
2217
+ const { roster, failure } = await this.readRoster();
2218
+ if (failure)
2219
+ return undefined;
2220
+ return roster.filter((p) => p.card.role === role && p.status !== "offline").map((p) => ({ id: p.card.id, name: p.card.name }));
2221
+ }
2222
+ /** Message ids this session sent as role requests, by the seq the queue gave each. A queue that
2223
+ * was recreated reuses seqs, so one seq can name two of them. */
2224
+ sentRequests = new Map();
2225
+ rememberSent(seq, id) {
2226
+ const ids = this.sentRequests.get(seq) ?? [];
2227
+ if (!ids.includes(id))
2228
+ ids.push(id);
2229
+ this.sentRequests.delete(seq);
2230
+ this.sentRequests.set(seq, ids);
2231
+ if (this.sentRequests.size > MAX_CORRELATIONS)
2232
+ this.sentRequests.delete(this.sentRequests.keys().next().value);
2233
+ }
2234
+ /** The message id to name a request by. Undefined when this session did not send that seq (the
2235
+ * daemon still checks the sender); refused when it sent two requests under one seq. */
2236
+ sentRequestId(seq) {
2237
+ const ids = this.sentRequests.get(seq);
2238
+ if (ids && ids.length > 1)
2239
+ throw new Error(`seq ${seq} names ${ids.length} requests this session sent (the role queue was recreated between them), so it is ambiguous; nothing was asked or cancelled`);
2240
+ return ids?.[0];
2241
+ }
2242
+ /** The status of one of this session's own role requests, from the delivery daemon (SPEC §8.1). */
2243
+ async anycastStatus(seq) {
2244
+ await this.requireConnected();
2245
+ return this.ep.anycastStatus(seq, this.sentRequestId(seq));
2246
+ }
2247
+ /** Cancel one of this session's own role requests while it waits. A taken one is refused, and
2248
+ * the status returned names its taker. */
2249
+ async cancelAnycast(seq) {
2250
+ await this.requireConnected();
2251
+ return this.ep.cancelAnycast(seq, this.sentRequestId(seq));
2252
+ }
1955
2253
  /** Resolve a peer by instance id (exact) or display name against the roster of the last
1956
2254
  * {@link readRoster}. Deterministic and fail-loud: returns
1957
2255
  * one peer, `undefined` if none match, or throws `AmbiguousPeerError` on a same-name collision —