@cotal-ai/connector-core 0.167.0 → 0.168.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-inbox.d.ts +531 -0
- package/dist/agent-inbox.d.ts.map +1 -0
- package/dist/agent-inbox.js +1455 -0
- package/dist/agent-inbox.js.map +1 -0
- package/dist/agent.d.ts +4 -271
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +56 -1191
- package/dist/agent.js.map +1 -1
- package/dist/docs-bundle.bin +0 -0
- package/dist/docs-bundle.generated.d.ts +1 -1
- package/dist/docs-bundle.generated.js +7 -7
- package/dist/docs-bundle.generated.js.map +1 -1
- package/dist/docs-index.bin +0 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/prompt-desk.d.ts +167 -0
- package/dist/prompt-desk.d.ts.map +1 -0
- package/dist/prompt-desk.js +696 -0
- package/dist/prompt-desk.js.map +1 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,1455 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { channelInAllow, isConcreteChannel, partsToText, ANYCAST_NOTICE_KEY, MENTION_NOTICE_KEY } from "@cotal-ai/core";
|
|
3
|
+
/** A short reconnect or modest sender-clock skew must not turn a current request into history. */
|
|
4
|
+
const CHANNEL_CATCHUP_AGE_MS = 5 * 60_000;
|
|
5
|
+
/** Total order on {@link RecallMark}: by time, then by id, so items sharing a millisecond still queue. */
|
|
6
|
+
export function afterRecallMark(a, b) {
|
|
7
|
+
// #624: recall marks and items are addressed by RECEIVE key (never the wire id), and a minted
|
|
8
|
+
// key is never the empty string, so the tie-break comparator never sees an empty id on either
|
|
9
|
+
// side: the only empty id in a RecallMark is the initial cursor {ts: 0, id: ""}, whose ts
|
|
10
|
+
// differs from every real item and so never reaches the id comparison. (The empty-id guard this
|
|
11
|
+
// comparator once carried was removed after a root chase showed it unreachable: with the wire id
|
|
12
|
+
// out of the marks, no real path can put two empty ids, or an empty id against a real one, into
|
|
13
|
+
// the comparison.)
|
|
14
|
+
return a.ts !== b.ts ? a.ts > b.ts : a.id > b.id;
|
|
15
|
+
}
|
|
16
|
+
/** How many pending messages one session buffers before the overflow valve in
|
|
17
|
+
* {@link AgentInbox.buffer} evicts. Exported so the overflow smokes read the bound they exercise. */
|
|
18
|
+
export const MAX_INBOX = 200;
|
|
19
|
+
/** How long {@link AgentInbox.takeChosen} waits for the delivery daemon before it lets a caller show
|
|
20
|
+
* what is already taken. A take not decided by then stays held for a later read. */
|
|
21
|
+
const TAKE_WAIT_MS = 2_000;
|
|
22
|
+
/** How long a role request whose take could not be decided waits before it is asked about again. */
|
|
23
|
+
const TAKE_RETRY_MS = 10_000;
|
|
24
|
+
/** How many receive keys {@link AgentInbox.holdInFlight} protects at once. The overflow valve never
|
|
25
|
+
* evicts a held entry, so this ceiling also bounds the inbox while holds are open, which is why it
|
|
26
|
+
* is derived from {@link MAX_INBOX}. It sits above the inbox because a frame keeps its holds until
|
|
27
|
+
* its own verdict, even on entries an overlapping frame has already committed. */
|
|
28
|
+
const MAX_IN_FLIGHT = MAX_INBOX * 2;
|
|
29
|
+
/** How many future-stamped recall ids one session will remember having handed over. See
|
|
30
|
+
* {@link AgentInbox.recallAheadRoom}. */
|
|
31
|
+
const MAX_AHEAD = 256;
|
|
32
|
+
/** How many overflow-evicted ambient messages {@link AgentInbox.evictedClassifications} remembers
|
|
33
|
+
* the class of. */
|
|
34
|
+
const CLASSIFICATION_CAP = 4096;
|
|
35
|
+
/** How many ids one focus episode keeps out of recall in {@link AgentInbox.focusExcludedIds}, and,
|
|
36
|
+
* bounded separately, how many id-less copies it counts in {@link AgentInbox.focusIdlessEntries}. */
|
|
37
|
+
const FOCUS_EXCLUSION_CAP = 4096;
|
|
38
|
+
/** #662: history reads one channel's recall makes while an id-less copy keeps arriving mid-read. */
|
|
39
|
+
const IDLESS_READS = 3;
|
|
40
|
+
/** How many ids each of {@link AgentInbox.protectedPullOnlyIds} and
|
|
41
|
+
* {@link AgentInbox.protectedDropIds} holds. */
|
|
42
|
+
const PROTECTED_DISPOSITION_CAP = 4096;
|
|
43
|
+
/** Which delivery daemon notice part a DM carries, anycast (SPEC §8.1) or mention (SPEC §8), if any.
|
|
44
|
+
* Its sender is still to be checked against the delivery lease. */
|
|
45
|
+
export function deliveryNoticeOf(m) {
|
|
46
|
+
for (const p of m.parts) {
|
|
47
|
+
if (p.kind !== "data" || typeof p.data !== "object" || p.data === null || Array.isArray(p.data))
|
|
48
|
+
continue;
|
|
49
|
+
if (ANYCAST_NOTICE_KEY in p.data)
|
|
50
|
+
return "anycast";
|
|
51
|
+
if (MENTION_NOTICE_KEY in p.data)
|
|
52
|
+
return "mention";
|
|
53
|
+
}
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
/** #662: what an id-less channel delivery shares with its stream copy. Both are the same published
|
|
57
|
+
* bytes, read through the same authentication, so their content is all that links them. */
|
|
58
|
+
function idlessDigest(m) {
|
|
59
|
+
return createHash("sha256").update(JSON.stringify(m)).digest("base64url");
|
|
60
|
+
}
|
|
61
|
+
/** The dedup key a received message id contributes to ingest's coalescing, or undefined when the id
|
|
62
|
+
* is EMPTY: an empty id is never a dedup key (#624). Undefined means "no identity to coalesce on",
|
|
63
|
+
* so every id-keyed lookup in {@link AgentInbox.ingest} is skipped for such a message and it flows to
|
|
64
|
+
* the buffer on its own merits. Real ids are returned unchanged: their coalescing (live/durable
|
|
65
|
+
* copies of one message, and redelivery after handle) is untouched. */
|
|
66
|
+
function ingestDedupKey(id) {
|
|
67
|
+
return id === "" ? undefined : id;
|
|
68
|
+
}
|
|
69
|
+
/** Session-local inbox, delivery ownership, attention policy and focus recall. */
|
|
70
|
+
export class AgentInbox {
|
|
71
|
+
deps;
|
|
72
|
+
constructor(deps) {
|
|
73
|
+
this.deps = deps;
|
|
74
|
+
}
|
|
75
|
+
get ep() { return this.deps.endpoint(); }
|
|
76
|
+
get config() { return this.deps.config(); }
|
|
77
|
+
get _transportConnected() { return this.deps.transportConnected(); }
|
|
78
|
+
emit(event, item) { this.deps.emit(event, item); }
|
|
79
|
+
handleEndpointWarning(error) { this.deps.warning(error); }
|
|
80
|
+
noteDirected(item) { this.deps.noteDirected(item); }
|
|
81
|
+
inOrder(write) { return this.deps.inOrder(write); }
|
|
82
|
+
requireConnected() { return this.deps.requireConnected(); }
|
|
83
|
+
seedChannelModes(config) {
|
|
84
|
+
for (const c of config.quiet ?? [])
|
|
85
|
+
this.channelModes.set(c, "quiet");
|
|
86
|
+
for (const c of config.muted ?? [])
|
|
87
|
+
this.channelModes.set(c, "muted");
|
|
88
|
+
}
|
|
89
|
+
onTransport(connected) {
|
|
90
|
+
if (!connected) {
|
|
91
|
+
this.transportDrops++;
|
|
92
|
+
for (const p of this.inbox.filter((x) => x.take && !this.inFlightIds.has(x.item.recvKey)))
|
|
93
|
+
this.regate(p);
|
|
94
|
+
}
|
|
95
|
+
if (connected && this.mayAskTakes()) {
|
|
96
|
+
this.dropLapsedTakes();
|
|
97
|
+
for (const p of this.gated)
|
|
98
|
+
if (p.taking === undefined)
|
|
99
|
+
this.emit("incoming", p.item);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
stop() {
|
|
103
|
+
for (const key of [...this.renewals.keys()])
|
|
104
|
+
this.stopRenewal(key);
|
|
105
|
+
clearTimeout(this.takeRetry);
|
|
106
|
+
this.takeRetry = undefined;
|
|
107
|
+
}
|
|
108
|
+
inbox = [];
|
|
109
|
+
/** Role requests delivered on an auth mesh whose take is not recorded for the copy held (SPEC §8.1).
|
|
110
|
+
* They count toward a wake and are never shown: {@link takeChosen} asks the delivery daemon to
|
|
111
|
+
* record the take of each one a host chose to show, and a recorded one moves to {@link inbox}. */
|
|
112
|
+
gated = [];
|
|
113
|
+
/** Counts arrivals, to number each entry's {@link Pending.arrival}. */
|
|
114
|
+
arrivals = 0;
|
|
115
|
+
/** Why the last take could not be decided, when it could not, and when a held request may be
|
|
116
|
+
* asked about again. Reported by `cotal_inbox`. */
|
|
117
|
+
heldTake;
|
|
118
|
+
/** Re-announces the held role requests once {@link heldTake} lets them be asked about again. */
|
|
119
|
+
takeRetry;
|
|
120
|
+
/** Ids already SURFACED to the model (handled) — bounded, commit-aware dedup ACROSS a drain. The
|
|
121
|
+
* live↔durable transition window can deliver the two copies of one message far enough apart that the
|
|
122
|
+
* first is already drained (removed from {@link inbox}) when the second arrives; the pending-inbox
|
|
123
|
+
* check alone would then re-buffer and double-surface it. Recorded at HANDLE time ({@link drainInbox}),
|
|
124
|
+
* never at receive time — so a later durable duplicate of an already-handled id is safe to ack (the
|
|
125
|
+
* logical message was delivered), which is exactly what the removed endpoint-level `firstSeenChat`
|
|
126
|
+
* got wrong (it acked at receive time, before handling). Two rotating windows bound memory. */
|
|
127
|
+
handledIds = new Set();
|
|
128
|
+
handledIdsPrev = new Set();
|
|
129
|
+
/** Receive-time classes for overflow-evicted, unhandled channel ambient. Capacity exhaustion
|
|
130
|
+
* permanently degrades unknown ambient to pull-only for this session rather than risk a late
|
|
131
|
+
* live/durable copy changing from quiet to automatic. */
|
|
132
|
+
evictedClassifications = new Map();
|
|
133
|
+
/** Surfaced to the host but not yet committed or abandoned, counted per holding frame because
|
|
134
|
+
* frames overlap. See {@link holdInFlight}. */
|
|
135
|
+
inFlightIds = new Map();
|
|
136
|
+
/** Ack-wait renewal timers of held durable deliveries, by receive key. See {@link keepOwned}. */
|
|
137
|
+
renewals = new Map();
|
|
138
|
+
classificationUnsafe = false;
|
|
139
|
+
/** Terminal receive-time decisions that must survive the live→durable transition: successfully
|
|
140
|
+
* surfaced pull-only messages and hard drops under muted/focus. Capacity loss degrades the
|
|
141
|
+
* corresponding whole class fail-closed for the rest of the session. */
|
|
142
|
+
protectedPullOnlyIds = new Set();
|
|
143
|
+
protectedDropIds = new Set();
|
|
144
|
+
dropUnsafe = false;
|
|
145
|
+
/** Wall-clock time of the latest inbox drain that actually committed at least one delivery.
|
|
146
|
+
* This is measured only after the backing acknowledgements succeed, never inferred from a read
|
|
147
|
+
* attempt or from an empty inbox. */
|
|
148
|
+
_lastInboxDrainedAt;
|
|
149
|
+
/** Wall-clock time of the latest drain that committed at least one AUTOMATIC delivery.
|
|
150
|
+
*
|
|
151
|
+
* Deliberately separate from {@link _lastInboxDrainedAt}, and #1233 is why: on a host-mode
|
|
152
|
+
* connector the tool inbox and the connector-managed automatic queue are different queues, and
|
|
153
|
+
* the measured seat was draining the first every few minutes while the second had not moved in
|
|
154
|
+
* 13.8 hours. A progress mark that counts a pull-only drain as progress would have reported that
|
|
155
|
+
* seat as making progress, which is the exact lie this field exists to refuse. */
|
|
156
|
+
_lastAutomaticDrainedAt;
|
|
157
|
+
/** The latest commit that took the OLDEST automatic delivery then queued (#1526).
|
|
158
|
+
*
|
|
159
|
+
* Distinct from {@link _lastAutomaticDrainedAt}, and the distinction is the defect: any automatic
|
|
160
|
+
* commit used to count, so a seat that kept committing fresh arrivals over a head it could not
|
|
161
|
+
* deliver reset its own stall clock on every turn and reported `ready` indefinitely, while the
|
|
162
|
+
* entries at the front of its queue aged past two hours. A queue drains when its head moves; a
|
|
163
|
+
* queue that serves only its newest arrivals is not draining, it is skipping. */
|
|
164
|
+
_lastAutomaticHeadDrainedAt;
|
|
165
|
+
_attention = "open"; // F3: fail-open default; reset to open on SessionStart
|
|
166
|
+
_recallCursor = { ts: 0, id: "" };
|
|
167
|
+
/** Recall items stamped ahead of this session's clock that it has already handed over. They are
|
|
168
|
+
* tracked by id rather than by {@link _recallCursor}, because a sender's clock must not be able to
|
|
169
|
+
* move this session's mark. Bounded by {@link MAX_AHEAD}. */
|
|
170
|
+
aheadDelivered = new Set();
|
|
171
|
+
/** Per-channel attention overrides — the AUTHORITATIVE runtime state (read by {@link ingest} on
|
|
172
|
+
* every message). Seeded from the agent-file default; mutated by {@link setChannelMode}; mirrored
|
|
173
|
+
* to presence for peers. An absent key ⇒ that channel follows the global {@link _attention}. Reset
|
|
174
|
+
* on restart (rebuilt from config; presence sweep clears the mirror). */
|
|
175
|
+
channelModes = new Map();
|
|
176
|
+
/** Chat-stream frontier captured when this agent entered `focus` — recall surfaces ambient
|
|
177
|
+
* published after it ("since you entered focus"). Undefined unless in focus. */
|
|
178
|
+
focusSince;
|
|
179
|
+
enteringFocus = false;
|
|
180
|
+
/** The receive-key namespace secret (#624): a per-session random value minted at construction,
|
|
181
|
+
* never written to any wire or log. Minted receive keys are `${secret}.${seq}`, so they are
|
|
182
|
+
* DISJOINT from wire ids by construction: an attacker-chosen wire id cannot equal one, so one
|
|
183
|
+
* verdict can never select two entries through a forged collision. Recognition is FUNCTIONAL
|
|
184
|
+
* (the key starts with the secret), so it cannot saturate the way a bounded set would: every
|
|
185
|
+
* minted key stays recognizable for the session's life, with nothing to expire or overflow. */
|
|
186
|
+
recvKeySecret = randomUUID().replace(/-/g, "");
|
|
187
|
+
recvKeySeq = 0;
|
|
188
|
+
focusExcludedIds = new Map();
|
|
189
|
+
/** #662: id-less channel deliveries settled this focus episode, per content digest. Live ingest has
|
|
190
|
+
* no stream sequence, so content is all an id-less delivery shares with its stream copy, and
|
|
191
|
+
* identical copies may each have had a different disposition. So recall binds each settled copy
|
|
192
|
+
* to a stream sequence and hands back only the copies no settled copy is bound to. Replaced, never
|
|
193
|
+
* cleared, per episode, so a hold from an earlier episode cannot un-count a later one. */
|
|
194
|
+
focusIdless = new Map();
|
|
195
|
+
/** Unbound copies plus bound sequences in {@link focusIdless}, bounded by
|
|
196
|
+
* {@link FOCUS_EXCLUSION_CAP}. */
|
|
197
|
+
focusIdlessEntries = 0;
|
|
198
|
+
/** Bumped as each channel's recall read starts: a copy settled before a read that the read could
|
|
199
|
+
* not bind is behind the focus frontier or out of retention, and no later read will see it. */
|
|
200
|
+
idlessEpoch = 0;
|
|
201
|
+
/** Recall runs one at a time, so an older read can never settle over a newer one (#662). */
|
|
202
|
+
recallLock = Promise.resolve();
|
|
203
|
+
/** Bumped each time the transport goes down, so a settled copy's frontier read can tell whether
|
|
204
|
+
* the connection stayed up from the copy's arrival to the answer (#662). */
|
|
205
|
+
transportDrops = 0;
|
|
206
|
+
focusRecallUnsafeChannels = new Set();
|
|
207
|
+
/** The latest successful, non-empty inbox drain in this session. */
|
|
208
|
+
get lastInboxDrainedAt() {
|
|
209
|
+
return this._lastInboxDrainedAt;
|
|
210
|
+
}
|
|
211
|
+
/** The latest drain that committed at least one AUTOMATIC (connector-managed) delivery. */
|
|
212
|
+
get lastAutomaticDrainedAt() {
|
|
213
|
+
return this._lastAutomaticDrainedAt;
|
|
214
|
+
}
|
|
215
|
+
/** The latest drain that committed the automatic delivery that was then at the FRONT of the queue
|
|
216
|
+
* (#1526). This is the fact {@link automaticQueueStalledForMs} measures progress by; the looser
|
|
217
|
+
* {@link lastAutomaticDrainedAt} is still reported beside it, because the two disagreeing is
|
|
218
|
+
* precisely the shape of a wedged head being served around. */
|
|
219
|
+
get lastAutomaticHeadDrainedAt() {
|
|
220
|
+
return this._lastAutomaticHeadDrainedAt;
|
|
221
|
+
}
|
|
222
|
+
/** The receive key of the oldest still-queued automatic delivery: the queue's head, and the entry
|
|
223
|
+
* whose commit counts as progress. */
|
|
224
|
+
oldestAutomaticKey() {
|
|
225
|
+
let head;
|
|
226
|
+
for (const pending of this.inbox) {
|
|
227
|
+
if (pending.pullOnly)
|
|
228
|
+
continue;
|
|
229
|
+
if (head === undefined || pending.receivedAt < head.receivedAt)
|
|
230
|
+
head = pending;
|
|
231
|
+
}
|
|
232
|
+
return head?.item.recvKey;
|
|
233
|
+
}
|
|
234
|
+
/** Record head progress when this batch takes the current head of the automatic queue. Call
|
|
235
|
+
* BEFORE the batch leaves {@link inbox}, since the head is read from the live queue. */
|
|
236
|
+
noteAutomaticHeadProgress(selected) {
|
|
237
|
+
const head = this.oldestAutomaticKey();
|
|
238
|
+
if (head === undefined)
|
|
239
|
+
return;
|
|
240
|
+
if (selected.some((p) => !p.pullOnly && p.item.recvKey === head))
|
|
241
|
+
this._lastAutomaticHeadDrainedAt = Date.now();
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* How long a non-empty automatic queue has been making no progress, or `undefined`.
|
|
245
|
+
*
|
|
246
|
+
* PROGRESS AT THE HEAD, not depth and not throughput. The queue is not stalled because it is deep;
|
|
247
|
+
* it is stalled because the entries at the front of it are not coming off. The clock therefore
|
|
248
|
+
* starts at the later of the arrival of the oldest still-queued delivery and the last commit that
|
|
249
|
+
* took the queue's head, so a seat that is steadily draining keeps resetting it however busy it
|
|
250
|
+
* is, and a seat that has not moved its head since that queue formed accrues from the moment it
|
|
251
|
+
* formed.
|
|
252
|
+
*
|
|
253
|
+
* Keyed on the HEAD rather than on any automatic commit (#1526). The reported session held 96
|
|
254
|
+
* deliveries with the oldest over two hours old and reported `ready` throughout: it was committing
|
|
255
|
+
* fresh arrivals, and under a looser measure each of those reset the clock for the backlog behind
|
|
256
|
+
* them. A seat that serves only its newest traffic is skipping its queue, not draining it, and the
|
|
257
|
+
* messages that are actually undelivered are the ones the measure must speak for.
|
|
258
|
+
*
|
|
259
|
+
* Measured from the oldest ARRIVAL rather than from session start so a session that never drained
|
|
260
|
+
* anything is still measurable — that is precisely the shape of a seat whose first soft interrupt
|
|
261
|
+
* timed out.
|
|
262
|
+
*/
|
|
263
|
+
automaticQueueStalledForMs(now = Date.now()) {
|
|
264
|
+
const oldest = this.oldestAutomaticReceivedAt();
|
|
265
|
+
if (oldest === undefined)
|
|
266
|
+
return undefined;
|
|
267
|
+
const since = Math.max(oldest, this._lastAutomaticHeadDrainedAt ?? 0);
|
|
268
|
+
const held = now - since;
|
|
269
|
+
return held > 0 ? held : 0;
|
|
270
|
+
}
|
|
271
|
+
/** Session-local channel degradation, independent of transport liveness. */
|
|
272
|
+
get channelDeliveryIssue() {
|
|
273
|
+
return this.dropUnsafe
|
|
274
|
+
? "Channel drop tracking exhausted. Ambient channel traffic is suppressed until restart; non-historical mentions on unmuted channels wake to pull their buffered body. Focus recall may be incomplete."
|
|
275
|
+
: undefined;
|
|
276
|
+
}
|
|
277
|
+
// ---- inbox ---------------------------------------------------------------
|
|
278
|
+
/** A DM shaped as a delivery daemon's notice is one only when its authenticated sender holds the
|
|
279
|
+
* space's delivery lease. Any other sender's copy is an ordinary DM. */
|
|
280
|
+
async ingestNotice(m, delivery, meta, notice) {
|
|
281
|
+
const holder = await this.ep.deliveryLeaseHolder(0);
|
|
282
|
+
this.ingest(m, delivery, meta, holder !== undefined && holder === m.from.id ? notice : undefined);
|
|
283
|
+
}
|
|
284
|
+
ingest(m, delivery, meta, notice) {
|
|
285
|
+
// #624: an EMPTY id is never a dedup key. The id-keyed coalescing below exists to collapse the
|
|
286
|
+
// copies of ONE message across the live/durable paths, and identity is what makes that safe. A
|
|
287
|
+
// message that carries an empty id asserts no identity (SPEC §5 requires a unique id; the sender
|
|
288
|
+
// already violated it), so keying the coalescing on "" reads empty-equals-empty as a duplicate
|
|
289
|
+
// and silently drops every empty-id message after the first: measured live, two distinct
|
|
290
|
+
// empty-id messages arrived and only the first ever buffered. Treating an empty id as NO id
|
|
291
|
+
// costs the coalescing for those messages only (a redelivered copy can surface twice), which is
|
|
292
|
+
// the wire contract's at-least-once stance; collapsing distinct messages is not a stance at all.
|
|
293
|
+
const key = ingestDedupKey(m.id);
|
|
294
|
+
// Already SURFACED and drained? This is a post-handle cross-path duplicate (the transition window's
|
|
295
|
+
// second copy, arriving after the first was handled). Don't surface it again; if it's the durable
|
|
296
|
+
// copy, ack it so JetStream stops redelivering — safe because the logical message was already
|
|
297
|
+
// handled (handledIds is recorded at drain time, never at receive time).
|
|
298
|
+
if (key !== undefined && (this.handledIds.has(key) || this.handledIdsPrev.has(key))) {
|
|
299
|
+
if (delivery.durable)
|
|
300
|
+
delivery.ack();
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
if (key !== undefined && (this.protectedPullOnlyIds.has(key) || this.protectedDropIds.has(key))) {
|
|
304
|
+
if (delivery.durable)
|
|
305
|
+
delivery.ack();
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
// Duplicate id still PENDING — keep ONE entry. Take the freshest ack handle, but NEVER downgrade a
|
|
309
|
+
// durable (committing) ack to a live no-op. Two cases produce a duplicate: same-path JetStream
|
|
310
|
+
// redelivery (always durable → upgrade to the fresh handle), and the cross-path live/durable
|
|
311
|
+
// transition window. There, if the DURABLE copy arrived first and a LIVE copy lands second,
|
|
312
|
+
// overwriting with the live no-op would leave the durable copy uncommitted → JS redelivers it → it
|
|
313
|
+
// double-surfaces. So only a durable delivery may replace the stored handle; a live duplicate is
|
|
314
|
+
// dropped as-is. A durable duplicate also re-announces the still-pending item through the
|
|
315
|
+
// ordinary `incoming` policy path. That turns JetStream redelivery into a timer-free retry for
|
|
316
|
+
// a wake the host dropped, without bypassing quiet/attention or adapter in-flight guards.
|
|
317
|
+
const existing = key === undefined ? undefined : this.inbox.find((p) => p.item.id === key) ?? this.gated.find((p) => p.item.id === key);
|
|
318
|
+
if (existing) {
|
|
319
|
+
if (delivery.durable) {
|
|
320
|
+
existing.ack = delivery.ack;
|
|
321
|
+
// A fresh copy is a fresh ownership: a hold that outlived the copy it renewed keeps this one.
|
|
322
|
+
this.own(existing, delivery.redelivery);
|
|
323
|
+
if (delivery.take)
|
|
324
|
+
existing.take = delivery.take;
|
|
325
|
+
if (this.inFlightIds.has(existing.item.recvKey))
|
|
326
|
+
this.keepOwned(existing.item.recvKey);
|
|
327
|
+
// A role request taken for an earlier copy and not yet shown needs a take of this one: the
|
|
328
|
+
// broker redelivered it, so the earlier take may have lost it to another holder.
|
|
329
|
+
else if (existing.take && existing.takenCount !== existing.item.deliveryCount)
|
|
330
|
+
this.regate(existing);
|
|
331
|
+
this.emit("incoming", existing.item);
|
|
332
|
+
}
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (!meta)
|
|
336
|
+
throw new Error(`message ${m.id} delivered without MessageMeta — its class is unauthenticated`);
|
|
337
|
+
// Only an aged durable channel copy is catch-up. Live copies and brief transport gaps must
|
|
338
|
+
// still wake, even when the sender's clock is a few seconds behind. Already buffered copies
|
|
339
|
+
// retain their classification through the dedupe above. DMs and role requests are unchanged.
|
|
340
|
+
const historical = meta.historical || (meta.kind === "channel" && delivery.durable && Date.now() - m.ts > CHANNEL_CATCHUP_AGE_MS);
|
|
341
|
+
const item = this.toInboxItem(m, meta.kind, historical);
|
|
342
|
+
if (notice)
|
|
343
|
+
item.notice = notice;
|
|
344
|
+
// A notice asks for nothing and answers nothing. A role request awaiting its take is recorded
|
|
345
|
+
// as asked of us only once it is taken, since a refused take drops it unseen.
|
|
346
|
+
else if (!delivery.take)
|
|
347
|
+
this.noteDirected(item);
|
|
348
|
+
// Per-channel override is the FINAL word for a channel message (DMs/anycast are never channel-
|
|
349
|
+
// scoped, so they bypass this entirely and always buffer). Evaluated BEFORE the global mode:
|
|
350
|
+
// - `muted` → hard drop, incl. @mention (a mention rides the channel; you can't keep it if you
|
|
351
|
+
// dropped the channel). Acking does NOT delete (Limits-retained) but it's not locally recallable.
|
|
352
|
+
// - `quiet` → buffer ambient as pull-only; an @mention remains automatic. Overrides global
|
|
353
|
+
// `focus` so "retain this channel, but only surface ambient on explicit pull" stays expressible.
|
|
354
|
+
// Focus (global, only when NOT overridden): channel ambient AND @mentions are acked-and-dropped —
|
|
355
|
+
// they stay recallable via cotal_inbox (recallAmbient), or if recall itself cannot vouch for the
|
|
356
|
+
// channel (replay=off, or a wildcard join — #977), that is reported rather than left silent; an
|
|
357
|
+
// @mention still *wakes* (mention-wake), body pulled (F4=B), never auto-injected (the mention
|
|
358
|
+
// tag is payload-forgeable).
|
|
359
|
+
if (item.kind === "channel") {
|
|
360
|
+
const cm = this.channelModes.get(item.channel ?? "");
|
|
361
|
+
// #662: an id-less delivery is counted, not excluded, since recall can only match it by content.
|
|
362
|
+
// Content cannot tell a late copy of one recall handed back from a new identical message, so
|
|
363
|
+
// every copy takes its own disposition, and a late copy surfaces again rather than a new one
|
|
364
|
+
// losing its lane (#624: an empty id asserts no identity).
|
|
365
|
+
const digest = item.id === "" && (this.enteringFocus || this._attention === "focus") ? idlessDigest(m) : undefined;
|
|
366
|
+
const tally = digest === undefined ? undefined : this.reserveIdless(digest, item.channel ?? "");
|
|
367
|
+
const copy = tally ? this.settleIdless(tally) : undefined;
|
|
368
|
+
const idless = copy && { digest: digest, copy };
|
|
369
|
+
// chatFrontier() is asynchronous. Channel traffic retained while entering focus must not also
|
|
370
|
+
// appear in post-watermark recall if it lands after the server captured the frontier.
|
|
371
|
+
if (this.enteringFocus)
|
|
372
|
+
this.excludeFromFocus(item);
|
|
373
|
+
if (this.dropUnsafe) {
|
|
374
|
+
this.excludeFromFocus(item);
|
|
375
|
+
if (cm !== "muted" && item.mentionsMe && !item.historical) {
|
|
376
|
+
// Mentions are an untrusted wake hint, never authority to inject a channel body.
|
|
377
|
+
// Keep the body in the bounded pull lane while normal ambient stays fail-closed.
|
|
378
|
+
// After exhaustion an unknown late copy can surface once, disclosed by the warning.
|
|
379
|
+
this.buffer(item, delivery, true, idless);
|
|
380
|
+
this.emit("mention-wake", item);
|
|
381
|
+
}
|
|
382
|
+
else
|
|
383
|
+
delivery.ack();
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (cm === "muted") {
|
|
387
|
+
this.evictedClassifications.delete(item.id);
|
|
388
|
+
this.excludeFromFocus(item);
|
|
389
|
+
this.protectDisposition(item.id, "drop");
|
|
390
|
+
delivery.ack();
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const remembered = item.id === "" ? undefined : this.evictedClassifications.get(item.id); // #624: an empty id never carries a remembered classification
|
|
394
|
+
if (remembered)
|
|
395
|
+
this.evictedClassifications.delete(item.id);
|
|
396
|
+
const snapshottedPullOnly = item.historical || (!item.mentionsMe && (remembered?.pullOnly ?? cm === "quiet"));
|
|
397
|
+
if (cm === "quiet" || snapshottedPullOnly)
|
|
398
|
+
this.excludeFromFocus(item);
|
|
399
|
+
// An unsafe channel cannot recall even a fresh mention. Keep that body in the existing
|
|
400
|
+
// bounded pull lane, never the automatic lane, including on quiet channels. Muted and
|
|
401
|
+
// historical traffic retain their earlier gates. Exclude this id so recall cannot repeat it.
|
|
402
|
+
if (this._attention === "focus" && item.mentionsMe && !item.historical && this.focusRecallUnsafeChannels.has(item.channel ?? "")) {
|
|
403
|
+
this.excludeFromFocus(item);
|
|
404
|
+
this.buffer(item, delivery, true, idless);
|
|
405
|
+
this.emit("mention-wake", item);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
// Current normal+focus remains the stronger hard gate unless this exact id was previously
|
|
409
|
+
// received pull-only. classificationUnsafe must not turn focus-dropped traffic into a buffer.
|
|
410
|
+
if (cm !== "quiet" && !snapshottedPullOnly && this._attention === "focus") {
|
|
411
|
+
this.protectDisposition(item.id, "drop");
|
|
412
|
+
delivery.ack();
|
|
413
|
+
// #662: recall cannot pick this copy out from an identical one with another disposition, so
|
|
414
|
+
// its body is held here, pull-only, and recall hands back only copies nothing is bound to.
|
|
415
|
+
if (item.id === "")
|
|
416
|
+
this.buffer(item, { ack: () => { } }, true, idless);
|
|
417
|
+
if (item.mentionsMe)
|
|
418
|
+
this.emit("mention-wake", item);
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
// Every historical channel message is pull-only, including mentions. Joining a channel must
|
|
422
|
+
// not revive an old request as a fresh turn. This is decided before focus handling too, so
|
|
423
|
+
// history stays recallable without emitting mention-wake.
|
|
424
|
+
// A reply on a channel is pull-only too when the host answers every turn on the channel
|
|
425
|
+
// (config.channelRepliesPullOnly): that answer replies to the message that started the turn,
|
|
426
|
+
// so a turn on a peer's reply is a turn on its automatic output, and two such seats on one
|
|
427
|
+
// channel would answer each other without end (#2395).
|
|
428
|
+
const automaticReply = this.config.channelRepliesPullOnly === true && !!item.replyTo;
|
|
429
|
+
const pullOnly = snapshottedPullOnly || (!item.mentionsMe && (automaticReply || this.classificationUnsafe));
|
|
430
|
+
if (pullOnly)
|
|
431
|
+
this.excludeFromFocus(item);
|
|
432
|
+
this.buffer(item, delivery, pullOnly, idless);
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
this.buffer(item, delivery, false);
|
|
436
|
+
}
|
|
437
|
+
buffer(item, delivery, pullOnly, idless) {
|
|
438
|
+
const pending = { item, ack: delivery.ack, pullOnly, receivedAt: Date.now(), arrival: this.arrivals++ };
|
|
439
|
+
this.own(pending, delivery.redelivery);
|
|
440
|
+
if (idless)
|
|
441
|
+
pending.idless = { tally: this.focusIdless, ...idless };
|
|
442
|
+
if (delivery.take) {
|
|
443
|
+
// Held until its take is recorded. A copy beyond the bound is left unacked, so the broker
|
|
444
|
+
// redelivers it once there is room, as the overflow valve below does for directed mail.
|
|
445
|
+
pending.take = delivery.take;
|
|
446
|
+
this.gated.push(pending);
|
|
447
|
+
if (this.gated.length > MAX_INBOX)
|
|
448
|
+
this.gated.shift();
|
|
449
|
+
this.emit("incoming", item);
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
this.admit(pending);
|
|
453
|
+
this.emit("incoming", item);
|
|
454
|
+
}
|
|
455
|
+
/** Put one entry in the shown inbox at its arrival place, running the overflow valve. */
|
|
456
|
+
admit(pending) {
|
|
457
|
+
let at = this.inbox.length;
|
|
458
|
+
while (at > 0 && this.inbox[at - 1].arrival > pending.arrival)
|
|
459
|
+
at--;
|
|
460
|
+
this.inbox.splice(at, 0, pending);
|
|
461
|
+
if (this.inbox.length > MAX_INBOX) {
|
|
462
|
+
// Prefer sacrificing pull-only backlog so it cannot crowd out DMs/mentions. Overflow is bounded
|
|
463
|
+
// local loss for channel traffic only: an evicted channel item is acked without being marked
|
|
464
|
+
// handled. An evicted directed item is never acked (below).
|
|
465
|
+
let excess = this.inbox.length - MAX_INBOX;
|
|
466
|
+
while (excess-- > 0) {
|
|
467
|
+
// Eviction order, weakest claim first. The tiers below `pullOnly` also protect against live
|
|
468
|
+
// mention floods: `mentionsMe` derives from the payload `mentions` field, forgeable by the
|
|
469
|
+
// sender. A peer that stamps every flooded message with the victim's name
|
|
470
|
+
// makes none of its traffic pull-only, so `findIndex` returned -1, the old code fell through
|
|
471
|
+
// to index 0, and index 0 is the OLDEST entry: a directed message waiting to be handled. It
|
|
472
|
+
// was spliced out and acked unhandled, which is unrecoverable (#791). Ambient channel chatter
|
|
473
|
+
// at volume did the same thing with no forgery at all.
|
|
474
|
+
//
|
|
475
|
+
// So directedness decides who gets sacrificed, and directedness is read from `kind`, which is
|
|
476
|
+
// derived from the delivering subject and broker-policed rather than from the payload.
|
|
477
|
+
//
|
|
478
|
+
// A held entry is never sacrificed: the host's verdict commits through its ack handle, and its
|
|
479
|
+
// renewal is what keeps the broker from redelivering it meanwhile. Evicting one would drop
|
|
480
|
+
// both, handing a long turn's role request to a second worker while the first still runs it
|
|
481
|
+
// and leaving the first one's completion nothing to ack. Holds are capped at
|
|
482
|
+
// {@link MAX_IN_FLIGHT}, so the buffer stays bounded.
|
|
483
|
+
const evictable = (p) => !this.inFlightIds.has(p.item.recvKey);
|
|
484
|
+
let index = this.inbox.findIndex((p) => p.pullOnly && evictable(p));
|
|
485
|
+
// Channel traffic before anything addressed to us specifically, forged mentions included.
|
|
486
|
+
if (index < 0)
|
|
487
|
+
index = this.inbox.findIndex((p) => p.item.kind === "channel" && evictable(p));
|
|
488
|
+
// Only when the whole buffer is directed mail does the oldest lose, and that case carries no
|
|
489
|
+
// attacker advantage: a peer cannot force DMs it is not authorised to send.
|
|
490
|
+
if (index < 0)
|
|
491
|
+
index = this.inbox.findIndex(evictable);
|
|
492
|
+
if (index < 0)
|
|
493
|
+
break;
|
|
494
|
+
const [evicted] = this.inbox.splice(index, 1);
|
|
495
|
+
const sacrificingDirected = evicted.item.kind !== "channel";
|
|
496
|
+
this.rememberEvicted(evicted);
|
|
497
|
+
// #662: a held id-less message is no longer settled here, so recall may hand it back.
|
|
498
|
+
if (evicted.idless?.tally === this.focusIdless)
|
|
499
|
+
this.unsettleIdless(evicted.idless.digest, evicted.idless.copy);
|
|
500
|
+
// A directed message is never acked on overflow: leaving it un-acked lets JetStream redeliver
|
|
501
|
+
// it once we have room, which turns unrecoverable loss into a delay. Channel ambient is still
|
|
502
|
+
// acked, because replaying it is what the history flood was (#775).
|
|
503
|
+
//
|
|
504
|
+
// The broker paces that delay, so nothing here has to end it. An un-acked message comes
|
|
505
|
+
// back only after its durable's ack wait, so an inbox that stays full costs one redelivery
|
|
506
|
+
// per parked message per ack wait, and the message stays pending until a redelivery finds
|
|
507
|
+
// room: a DM on the recipient's own durable (`cotal deliver pending` counts it), a role
|
|
508
|
+
// request on its role's shared queue (which that command does not read). Giving up on
|
|
509
|
+
// it instead, as a per-id eviction count once did (#807), acked a message the sender had
|
|
510
|
+
// seen stored and the live recipient never read, with one stderr line as the only trace:
|
|
511
|
+
// a seat whose turn ran long lost its oldest DMs exactly that way (#2215).
|
|
512
|
+
if (!sacrificingDirected)
|
|
513
|
+
evicted.ack();
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
rememberEvicted(p) {
|
|
518
|
+
if (p.item.kind !== "channel" || p.item.mentionsMe || !p.item.channel)
|
|
519
|
+
return;
|
|
520
|
+
if (p.item.id === "")
|
|
521
|
+
return; // #624: an empty id is never a key; one delivery's classification must not inherit to another
|
|
522
|
+
if (this.classificationUnsafe)
|
|
523
|
+
return;
|
|
524
|
+
if (!this.evictedClassifications.has(p.item.id) && this.evictedClassifications.size >= CLASSIFICATION_CAP) {
|
|
525
|
+
this.classificationUnsafe = true;
|
|
526
|
+
this.evictedClassifications.clear();
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
this.evictedClassifications.set(p.item.id, { pullOnly: p.pullOnly, channel: p.item.channel });
|
|
530
|
+
}
|
|
531
|
+
excludeFromFocus(item) {
|
|
532
|
+
if ((!this.enteringFocus && this._attention !== "focus") || item.kind !== "channel" || !item.channel)
|
|
533
|
+
return;
|
|
534
|
+
if (item.id === "")
|
|
535
|
+
return; // #662: an id-less delivery is counted in focusIdless instead
|
|
536
|
+
if (!this.focusExcludedIds.has(item.id) && this.focusExcludedIds.size >= FOCUS_EXCLUSION_CAP) {
|
|
537
|
+
const oldest = this.focusExcludedIds.entries().next().value;
|
|
538
|
+
if (oldest) {
|
|
539
|
+
this.focusExcludedIds.delete(oldest[0]);
|
|
540
|
+
this.focusRecallUnsafeChannels.add(oldest[1]);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
this.focusExcludedIds.set(item.id, item.channel);
|
|
544
|
+
}
|
|
545
|
+
/** #662: the tally for one more settled or handed-back copy of an id-less message; the caller adds
|
|
546
|
+
* the copy. At the bound, the channel's recall is reported incomplete rather than risk handing
|
|
547
|
+
* back a copy it no longer counts. */
|
|
548
|
+
reserveIdless(digest, channel) {
|
|
549
|
+
if (this.focusIdlessEntries >= FOCUS_EXCLUSION_CAP) {
|
|
550
|
+
this.focusRecallUnsafeChannels.add(channel);
|
|
551
|
+
return undefined;
|
|
552
|
+
}
|
|
553
|
+
let tally = this.focusIdless.get(digest);
|
|
554
|
+
if (!tally)
|
|
555
|
+
this.focusIdless.set(digest, (tally = { channel, unbound: [], bound: new Set() }));
|
|
556
|
+
this.focusIdlessEntries++;
|
|
557
|
+
return tally;
|
|
558
|
+
}
|
|
559
|
+
/** #662: add one settled copy, bounded by the chat frontier read after it arrived. If that read
|
|
560
|
+
* fails, or answers only after the transport dropped, nothing bounds the copy, so the channel's
|
|
561
|
+
* recall is reported incomplete instead. */
|
|
562
|
+
settleIdless(tally) {
|
|
563
|
+
const episode = this.focusIdless;
|
|
564
|
+
const drops = this.transportDrops;
|
|
565
|
+
const unbounded = () => {
|
|
566
|
+
if (episode === this.focusIdless)
|
|
567
|
+
this.focusRecallUnsafeChannels.add(tally.channel);
|
|
568
|
+
};
|
|
569
|
+
const copy = { epoch: this.idlessEpoch, ready: Promise.resolve() };
|
|
570
|
+
copy.ready = this.ep.chatFrontier().then((frontier) => {
|
|
571
|
+
if (drops === this.transportDrops)
|
|
572
|
+
copy.frontier = frontier;
|
|
573
|
+
else
|
|
574
|
+
unbounded();
|
|
575
|
+
}, unbounded);
|
|
576
|
+
tally.unbound.push(copy);
|
|
577
|
+
return copy;
|
|
578
|
+
}
|
|
579
|
+
/** #662: forget a tally with nothing left in it, so the map is bounded by the entries it counts. */
|
|
580
|
+
dropEmptyIdless(digest, tally) {
|
|
581
|
+
if (!tally.unbound.length && !tally.bound.size)
|
|
582
|
+
this.focusIdless.delete(digest);
|
|
583
|
+
}
|
|
584
|
+
/** #662: one buffered copy of an id-less message left the inbox unhandled. Only that copy is
|
|
585
|
+
* un-counted, or the sequence it was bound to freed: an identical copy may have been muted. A copy
|
|
586
|
+
* no read has bound yet stays in arrival order, marked, so the read binds it to its own stream
|
|
587
|
+
* copy rather than letting an earlier identical copy take that one. */
|
|
588
|
+
unsettleIdless(digest, copy) {
|
|
589
|
+
const tally = this.focusIdless.get(digest);
|
|
590
|
+
if (!tally)
|
|
591
|
+
return;
|
|
592
|
+
if (tally.unbound.includes(copy)) {
|
|
593
|
+
copy.evicted = true;
|
|
594
|
+
return;
|
|
595
|
+
}
|
|
596
|
+
if (copy.seq === undefined || !tally.bound.delete(copy.seq))
|
|
597
|
+
return;
|
|
598
|
+
this.focusIdlessEntries--;
|
|
599
|
+
this.dropEmptyIdless(digest, tally);
|
|
600
|
+
}
|
|
601
|
+
/** #662: after a complete read of `channel` that started at `epoch`, a copy settled before it that
|
|
602
|
+
* it could not bind will not be in a later read either, so it is dropped. The read is the
|
|
603
|
+
* channel's whole retained window, so a bound sequence it lacks aged out. */
|
|
604
|
+
settleIdlessRead(channel, epoch, retained) {
|
|
605
|
+
for (const [digest, tally] of this.focusIdless) {
|
|
606
|
+
if (tally.channel !== channel)
|
|
607
|
+
continue;
|
|
608
|
+
const before = tally.unbound.length + tally.bound.size;
|
|
609
|
+
tally.unbound = tally.unbound.filter((c) => c.epoch >= epoch);
|
|
610
|
+
for (const seq of tally.bound)
|
|
611
|
+
if (!retained.has(seq))
|
|
612
|
+
tally.bound.delete(seq);
|
|
613
|
+
this.focusIdlessEntries -= before - tally.unbound.length - tally.bound.size;
|
|
614
|
+
this.dropEmptyIdless(digest, tally);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
/** #662: the frontier reads of every copy of `channel` settled so far have answered. */
|
|
618
|
+
async idlessReady(tallies, channel) {
|
|
619
|
+
const reads = [];
|
|
620
|
+
for (const tally of tallies.values())
|
|
621
|
+
if (tally.channel === channel)
|
|
622
|
+
for (const c of tally.unbound)
|
|
623
|
+
reads.push(c.ready);
|
|
624
|
+
await Promise.all(reads);
|
|
625
|
+
}
|
|
626
|
+
/** #662: bind the copies settled before the read that started at `epoch` to its unbound stream
|
|
627
|
+
* copies `free` (ascending). Identical copies share a sender subject, so they arrive in stream
|
|
628
|
+
* order, and a frontier, read after its copy arrived, bounds that copy and every copy before it.
|
|
629
|
+
* Frontier reads can answer out of order, so their sizes say nothing about arrival order. So the
|
|
630
|
+
* copies bind in arrival order, latest first, each to the latest free stream copy at or below the
|
|
631
|
+
* lowest frontier from it on, and a stream copy none of them takes (a reconnect gap) stays free.
|
|
632
|
+
* An evicted copy takes its own stream copy and leaves it free, so recall hands that one back. */
|
|
633
|
+
bindIdless(tally, epoch, free) {
|
|
634
|
+
let bound = Infinity;
|
|
635
|
+
for (let i = tally.unbound.length - 1; i >= 0; i--) {
|
|
636
|
+
const copy = tally.unbound[i];
|
|
637
|
+
if (copy.frontier === undefined)
|
|
638
|
+
continue;
|
|
639
|
+
bound = Math.min(bound, copy.frontier);
|
|
640
|
+
if (copy.epoch >= epoch)
|
|
641
|
+
continue;
|
|
642
|
+
let at = free.length - 1;
|
|
643
|
+
while (at >= 0 && free[at] > bound)
|
|
644
|
+
at--;
|
|
645
|
+
if (at < 0)
|
|
646
|
+
continue;
|
|
647
|
+
const [seq] = free.splice(at, 1);
|
|
648
|
+
tally.unbound.splice(i, 1);
|
|
649
|
+
if (copy.evicted) {
|
|
650
|
+
this.focusIdlessEntries--;
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
copy.seq = seq;
|
|
654
|
+
tally.bound.add(seq);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
/** #662: a copy settled after the read that started at `epoch` began may or may not be in it, so it
|
|
658
|
+
* binds nothing there, and an unbound stream copy at `seq` it could be is neither free nor bound. */
|
|
659
|
+
idlessUnsure(tally, epoch, seq) {
|
|
660
|
+
if (!tally || tally.bound.has(seq))
|
|
661
|
+
return false;
|
|
662
|
+
return tally.unbound.some((c) => c.epoch >= epoch && c.frontier !== undefined && c.frontier >= seq);
|
|
663
|
+
}
|
|
664
|
+
protectDisposition(id, disposition) {
|
|
665
|
+
if (id === "")
|
|
666
|
+
return; // #624: an empty id is never a dedup key, so it is never recorded as one
|
|
667
|
+
const ids = disposition === "drop" ? this.protectedDropIds : this.protectedPullOnlyIds;
|
|
668
|
+
if ((disposition === "drop" ? this.dropUnsafe : this.classificationUnsafe) || ids.has(id))
|
|
669
|
+
return;
|
|
670
|
+
if (ids.size >= PROTECTED_DISPOSITION_CAP) {
|
|
671
|
+
if (disposition === "drop")
|
|
672
|
+
this.dropUnsafe = true;
|
|
673
|
+
else
|
|
674
|
+
this.classificationUnsafe = true;
|
|
675
|
+
// Keep known hard drops suppressed across later mode changes. The set stays bounded.
|
|
676
|
+
if (disposition !== "drop")
|
|
677
|
+
ids.clear();
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
ids.add(id);
|
|
681
|
+
}
|
|
682
|
+
/** Normalize a wire message into an {@link InboxItem}. `kind` is the **authenticated** class
|
|
683
|
+
* from {@link MessageMeta} (subject-derived), never the forgeable payload `to`/`toService`;
|
|
684
|
+
* core has already normalized `channel` and `toService` from the authenticated chat and svc
|
|
685
|
+
* subjects. Shared by live ingest and focus recall ({@link recallAmbient}). */
|
|
686
|
+
toInboxItem(m, kind, historical) {
|
|
687
|
+
const text = partsToText(m.parts);
|
|
688
|
+
return {
|
|
689
|
+
id: m.id,
|
|
690
|
+
// The wire id when there is one; a minted opaque key when the id is the empty string (#624:
|
|
691
|
+
// an empty id is never a dedup key, so it is never an address either; but the delivery still
|
|
692
|
+
// needs to be individually drainable/ackable, or it can never clear and never commit).
|
|
693
|
+
recvKey: m.id !== "" ? m.id : `${this.recvKeySecret}.${++this.recvKeySeq}`,
|
|
694
|
+
ts: m.ts,
|
|
695
|
+
fromId: m.from.id,
|
|
696
|
+
fromName: m.from.name,
|
|
697
|
+
fromRole: m.from.role,
|
|
698
|
+
kind,
|
|
699
|
+
channel: m.channel,
|
|
700
|
+
service: m.toService,
|
|
701
|
+
mentions: m.mentions,
|
|
702
|
+
mentionsMe: m.mentions?.includes(this.config.name.toLowerCase()) ?? false,
|
|
703
|
+
historical,
|
|
704
|
+
text,
|
|
705
|
+
replyTo: m.replyTo,
|
|
706
|
+
contextId: m.contextId,
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
/** Return pending messages in stable receive order. Automatic delivery excludes quiet ambient;
|
|
710
|
+
* pull-only is the explicit cotal_inbox lane.
|
|
711
|
+
*
|
|
712
|
+
* A role request whose take is not yet recorded is never returned (SPEC §8.1): a host shows one
|
|
713
|
+
* only through {@link takeChosen}. */
|
|
714
|
+
peekInbox(scope = "all") {
|
|
715
|
+
this.dropLapsedTakes();
|
|
716
|
+
return this.inbox.filter((p) => this.inScope(p, scope)).map((p) => p.item);
|
|
717
|
+
}
|
|
718
|
+
/** Every pending message in scope as {@link peekInbox} will return it once the held role requests
|
|
719
|
+
* that may be asked about now are taken, in that order. It is for choosing what to show, never for
|
|
720
|
+
* showing: hand the choice to {@link takeChosen}. */
|
|
721
|
+
inboxPreview(scope = "all") {
|
|
722
|
+
this.dropLapsedTakes();
|
|
723
|
+
const askable = scope === "pull-only" ? [] : this.gated.filter((p) => this.mayOffer(p));
|
|
724
|
+
return [...this.inbox.filter((p) => this.inScope(p, scope)), ...askable].sort((a, b) => a.arrival - b.arrival).map((p) => p.item);
|
|
725
|
+
}
|
|
726
|
+
/** Choose what to show from {@link inboxPreview}, ask the delivery daemon to record the take of
|
|
727
|
+
* each held role request in the choice, wait up to `waitMs` for the answers, and return the chosen
|
|
728
|
+
* items that may be shown now, in the order chosen. A take is a claim that this session's agent is
|
|
729
|
+
* about to see the request, which ends its sender's chance to cancel it, so call this just before
|
|
730
|
+
* showing and choose only what will be shown. A request whose take is refused or not yet decided
|
|
731
|
+
* is left out. Never throws. */
|
|
732
|
+
async takeChosen(scope, choose, waitMs = TAKE_WAIT_MS) {
|
|
733
|
+
const chosen = choose(this.inboxPreview(scope));
|
|
734
|
+
const keys = new Set(chosen.map((i) => i.recvKey));
|
|
735
|
+
const asked = scope === "pull-only" ? [] : this.gated
|
|
736
|
+
.filter((p) => keys.has(p.item.recvKey) && this.mayOffer(p));
|
|
737
|
+
for (const p of asked)
|
|
738
|
+
p.awaited = (p.awaited ?? 0) + 1;
|
|
739
|
+
const runs = asked.map((p) => (p.taking !== undefined && p.takingDrops === this.transportDrops ? p.taking : this.startTake(p)));
|
|
740
|
+
if (runs.length) {
|
|
741
|
+
let timer;
|
|
742
|
+
const waited = new Promise((resolve) => { timer = setTimeout(resolve, waitMs); timer.unref?.(); });
|
|
743
|
+
await Promise.race([Promise.allSettled(runs), waited]);
|
|
744
|
+
clearTimeout(timer);
|
|
745
|
+
}
|
|
746
|
+
for (const p of asked)
|
|
747
|
+
p.awaited = (p.awaited ?? 1) - 1;
|
|
748
|
+
const showable = new Map(this.peekInbox(scope).map((i) => [i.recvKey, i]));
|
|
749
|
+
return chosen.flatMap((i) => showable.get(i.recvKey) ?? []);
|
|
750
|
+
}
|
|
751
|
+
/** How many role requests are held because their take is pending or could not be decided, and why. */
|
|
752
|
+
heldTakes() {
|
|
753
|
+
const count = this.gated.filter((p) => p.taking === undefined).length;
|
|
754
|
+
const waiting = this.gated.filter((p) => p.taking !== undefined && p.takingDrops === this.transportDrops).length;
|
|
755
|
+
if (waiting)
|
|
756
|
+
return {
|
|
757
|
+
count: waiting + (this.heldTake ? count : 0),
|
|
758
|
+
detail: "the delivery daemon has not answered the take yet",
|
|
759
|
+
};
|
|
760
|
+
return count && this.heldTake ? { count, detail: this.heldTake.detail } : { count };
|
|
761
|
+
}
|
|
762
|
+
/** Whether a held role request may be asked about now: the link is up, and no take nobody could
|
|
763
|
+
* decide is being waited out ({@link heldTake}). */
|
|
764
|
+
mayAskTakes() {
|
|
765
|
+
return this._transportConnected && (!this.heldTake || Date.now() >= this.heldTake.retryAt);
|
|
766
|
+
}
|
|
767
|
+
/** Whether a read may be offered a held role request now: the link is up and its take is out
|
|
768
|
+
* already, or a take may be asked ({@link mayAskTakes}). A take that is out when the link drops
|
|
769
|
+
* cannot admit the request until the link is back, so a read then is offered nothing of it. */
|
|
770
|
+
mayOffer(p) {
|
|
771
|
+
return (p.taking !== undefined && this._transportConnected) || this.mayAskTakes();
|
|
772
|
+
}
|
|
773
|
+
startTake(p) {
|
|
774
|
+
const run = this.runTake(p).catch((e) => this.handleEndpointWarning(e)).finally(() => {
|
|
775
|
+
if (p.taking === run)
|
|
776
|
+
p.taking = undefined;
|
|
777
|
+
});
|
|
778
|
+
p.taking = run;
|
|
779
|
+
p.takingDrops = this.transportDrops;
|
|
780
|
+
return run;
|
|
781
|
+
}
|
|
782
|
+
/** Take one held role request for the copy it holds, and admit it only if it still holds that copy
|
|
783
|
+
* once the take is recorded: the same delivery, its ack wait not run out, the link not dropped. */
|
|
784
|
+
async runTake(p) {
|
|
785
|
+
const take = p.take;
|
|
786
|
+
if (!take)
|
|
787
|
+
return;
|
|
788
|
+
// The copy is renewed before the take is asked for, so the take cannot outlive it. A copy whose
|
|
789
|
+
// ack wait already ran out may be another holder's now: drop it unacked and let the broker redeliver.
|
|
790
|
+
if (!this._transportConnected)
|
|
791
|
+
return;
|
|
792
|
+
if (!this.renewOwned(p)) {
|
|
793
|
+
this.dropGated(p);
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
const count = p.item.deliveryCount;
|
|
797
|
+
const drops = this.transportDrops;
|
|
798
|
+
const outcome = await take();
|
|
799
|
+
if (!this.gated.includes(p) || p.take !== take)
|
|
800
|
+
return;
|
|
801
|
+
// An answer that crossed a link drop is the old link's, so the request stays held and a read
|
|
802
|
+
// waiting on this take shows nothing of it. Its host is told again once the link is up, so the
|
|
803
|
+
// next read takes it on the new link. While the link is down a read could not take it, and the
|
|
804
|
+
// read that waited on this take may still be running, so the reconnect announces it. A read
|
|
805
|
+
// that asked again on the new link owns the request now, so this take says nothing.
|
|
806
|
+
if (this.transportDrops !== drops) {
|
|
807
|
+
if (p.takingDrops !== drops)
|
|
808
|
+
return;
|
|
809
|
+
if (this._transportConnected)
|
|
810
|
+
this.emit("incoming", p.item);
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
if (outcome.taken) {
|
|
814
|
+
this.heldTake = undefined;
|
|
815
|
+
const current = p.item.deliveryCount === count && p.ownedUntil !== undefined && Date.now() < p.ownedUntil;
|
|
816
|
+
if (!current)
|
|
817
|
+
return; // a newer copy arrived meanwhile and needs its own take
|
|
818
|
+
p.takenCount = count;
|
|
819
|
+
p.takenOnce = true;
|
|
820
|
+
this.gated.splice(this.gated.indexOf(p), 1);
|
|
821
|
+
this.noteDirected(p.item);
|
|
822
|
+
this.admit(p);
|
|
823
|
+
// Its arrival was announced already. A read waiting on this take shows it next; one that
|
|
824
|
+
// stopped waiting is told it may be shown now, as of a new arrival.
|
|
825
|
+
if (!p.awaited)
|
|
826
|
+
this.emit("incoming", p.item);
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
if (outcome.drop) {
|
|
830
|
+
this.dropGated(p);
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
const first = this.heldTake?.reason !== outcome.reason;
|
|
834
|
+
this.heldTake = { reason: outcome.reason, detail: outcome.detail, retryAt: Date.now() + TAKE_RETRY_MS };
|
|
835
|
+
// Nothing asks about a held request on its own, so its host hears of it again when it may.
|
|
836
|
+
this.takeRetry ??= setTimeout(() => {
|
|
837
|
+
this.takeRetry = undefined;
|
|
838
|
+
for (const held of this.gated)
|
|
839
|
+
this.emit("incoming", held.item);
|
|
840
|
+
}, TAKE_RETRY_MS);
|
|
841
|
+
this.takeRetry.unref?.();
|
|
842
|
+
if (first && outcome.reason !== "daemon-busy")
|
|
843
|
+
this.handleEndpointWarning(new Error(outcome.detail));
|
|
844
|
+
}
|
|
845
|
+
/** Forget a role request whose take was refused or whose copy ran out. It is never acked: a
|
|
846
|
+
* cancelled one is gone already, and one another holder took must stay with that holder. */
|
|
847
|
+
dropGated(p) {
|
|
848
|
+
const i = this.gated.indexOf(p);
|
|
849
|
+
if (i >= 0)
|
|
850
|
+
this.gated.splice(i, 1);
|
|
851
|
+
}
|
|
852
|
+
/** Move a taken role request back to the held set when its copy changed before it was shown. */
|
|
853
|
+
regate(p) {
|
|
854
|
+
const i = this.inbox.indexOf(p);
|
|
855
|
+
if (i < 0)
|
|
856
|
+
return;
|
|
857
|
+
this.inbox.splice(i, 1);
|
|
858
|
+
p.takenCount = undefined;
|
|
859
|
+
this.gated.push(p);
|
|
860
|
+
}
|
|
861
|
+
/** Drop every taken role request not yet shown whose copy ran out: the broker may have handed it
|
|
862
|
+
* to another holder, whose take of the later copy wins. One the host holds is renewed and kept. */
|
|
863
|
+
dropLapsedTakes() {
|
|
864
|
+
const now = Date.now();
|
|
865
|
+
this.inbox = this.inbox.filter((p) => !p.take || this.inFlightIds.has(p.item.recvKey) || (p.ownedUntil !== undefined && now < p.ownedUntil));
|
|
866
|
+
this.gated = this.gated.filter((p) => p.taking !== undefined || p.ownedUntil === undefined || now < p.ownedUntil);
|
|
867
|
+
}
|
|
868
|
+
/** Mark a surfaced batch as mid-delivery, so the overflow valve will not evict it out from under
|
|
869
|
+
* the host. Pair with {@link releaseInFlight} on the delivery verdict, whichever way it goes.
|
|
870
|
+
*
|
|
871
|
+
* **Counted, not a set.** Hook frames overlap, so the same id is routinely in two open batches at
|
|
872
|
+
* once; if a hold were a boolean, the first frame's verdict would unprotect ids the second is
|
|
873
|
+
* still delivering, and an arrival between the two verdicts would ack one — the very loss this
|
|
874
|
+
* guard exists to stop, reached through the concurrency the per-frame keying deliberately allows.
|
|
875
|
+
*
|
|
876
|
+
* **All or nothing, and it says which.** At the {@link MAX_IN_FLIGHT} ceiling this refuses the
|
|
877
|
+
* whole batch and returns `false`; the caller must then NOT surface it. Protecting only part of a
|
|
878
|
+
* batch, or protecting none while the caller surfaces anyway, silently reopens exactly the loss
|
|
879
|
+
* this guard exists to close — the unprotected ids sit in the inbox for the whole handoff window
|
|
880
|
+
* with the overflow valve free to ack them. Declining to surface costs a deferral: the messages
|
|
881
|
+
* stay buffered and go out on a later frame, once a verdict releases capacity. */
|
|
882
|
+
holdInFlight(ids) {
|
|
883
|
+
// #624: the keys here are RECEIVE keys. An id-less delivery's wire id is "", so raw-id keying
|
|
884
|
+
// merged the counts of DISTINCT empty-id deliveries, and the eviction valve's in-flight check
|
|
885
|
+
// then deferred acking an evicted id-less item while any other id-less batch was held:
|
|
886
|
+
// cross-delivery interference in the safe direction, but interference. Receive keys are unique
|
|
887
|
+
// per delivery, so each is protected exactly for the frames holding it.
|
|
888
|
+
let fresh = 0;
|
|
889
|
+
for (const id of ids)
|
|
890
|
+
if (!this.inFlightIds.has(id))
|
|
891
|
+
fresh++;
|
|
892
|
+
if (this.inFlightIds.size + fresh > MAX_IN_FLIGHT)
|
|
893
|
+
return false;
|
|
894
|
+
for (const id of ids) {
|
|
895
|
+
this.inFlightIds.set(id, (this.inFlightIds.get(id) ?? 0) + 1);
|
|
896
|
+
this.keepOwned(id);
|
|
897
|
+
}
|
|
898
|
+
return true;
|
|
899
|
+
}
|
|
900
|
+
/** Whether this id is currently protected from the overflow valve — i.e. some frame is mid-delivery
|
|
901
|
+
* holding it. Read-only observability for the property {@link holdInFlight} establishes. A caller
|
|
902
|
+
* that needs a batch to actually BE in flight before it acts must wait on this, never on a sleep:
|
|
903
|
+
* the handoff runs through a real relay process whose latency is not the caller's to predict. */
|
|
904
|
+
isInFlight(id) {
|
|
905
|
+
return this.inFlightIds.has(id);
|
|
906
|
+
}
|
|
907
|
+
/** One frame's verdict is in (either way). The id is ordinary backlog again only once EVERY frame
|
|
908
|
+
* holding it has reported — a release from one must not speak for another still in flight. */
|
|
909
|
+
releaseInFlight(ids) {
|
|
910
|
+
for (const id of ids) {
|
|
911
|
+
const held = this.inFlightIds.get(id);
|
|
912
|
+
if (held === undefined)
|
|
913
|
+
continue;
|
|
914
|
+
if (held <= 1) {
|
|
915
|
+
this.inFlightIds.delete(id);
|
|
916
|
+
this.stopRenewal(id);
|
|
917
|
+
}
|
|
918
|
+
else
|
|
919
|
+
this.inFlightIds.set(id, held - 1);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
own(p, redelivery) {
|
|
923
|
+
p.redelivery = redelivery;
|
|
924
|
+
p.ownedUntil = redelivery && Date.now() + redelivery.ackWaitMs;
|
|
925
|
+
p.item.deliveryCount = redelivery?.deliveryCount;
|
|
926
|
+
}
|
|
927
|
+
/** Keep a held durable delivery with this reader for as long as the hold lasts, by restarting its
|
|
928
|
+
* ack wait at half the wait. Only a HELD delivery is renewed: a queued one keeps the broker's
|
|
929
|
+
* timer, so a reader busy with other work does not sit on a role request another reader could
|
|
930
|
+
* take, and an abandoned one (released) runs out and redelivers. */
|
|
931
|
+
keepOwned(key) {
|
|
932
|
+
if (this.renewals.has(key))
|
|
933
|
+
return;
|
|
934
|
+
const p = this.inbox.find((x) => x.item.recvKey === key);
|
|
935
|
+
if (!p?.redelivery || !this.renewOwned(p))
|
|
936
|
+
return;
|
|
937
|
+
const timer = setInterval(() => {
|
|
938
|
+
const held = this.inbox.find((x) => x.item.recvKey === key);
|
|
939
|
+
if (!held || !this.renewOwned(held))
|
|
940
|
+
this.stopRenewal(key);
|
|
941
|
+
}, p.redelivery.ackWaitMs / 2);
|
|
942
|
+
timer.unref?.();
|
|
943
|
+
this.renewals.set(key, timer);
|
|
944
|
+
}
|
|
945
|
+
stopRenewal(key) {
|
|
946
|
+
clearInterval(this.renewals.get(key));
|
|
947
|
+
this.renewals.delete(key);
|
|
948
|
+
}
|
|
949
|
+
/** Restart one copy's ack wait, unless this reader can no longer vouch that it still holds that
|
|
950
|
+
* copy. JetStream acks by stream sequence rather than by delivery, so a renewal sent after the
|
|
951
|
+
* wait may have run out (a stalled loop, a link down for longer than the wait) would extend the
|
|
952
|
+
* copy the broker has since handed to another reader. Renewal stops instead and the copy is the
|
|
953
|
+
* broker's to redeliver. Nothing is sent while the link is down, because the client buffers a
|
|
954
|
+
* publish and would replay it after the wait had run out; a handle whose connection was torn
|
|
955
|
+
* down throws, which is the same lost ownership. */
|
|
956
|
+
renewOwned(p) {
|
|
957
|
+
if (!p.redelivery || p.ownedUntil === undefined || Date.now() >= p.ownedUntil)
|
|
958
|
+
return false;
|
|
959
|
+
if (!this._transportConnected)
|
|
960
|
+
return true;
|
|
961
|
+
try {
|
|
962
|
+
p.redelivery.working();
|
|
963
|
+
}
|
|
964
|
+
catch {
|
|
965
|
+
return false;
|
|
966
|
+
}
|
|
967
|
+
p.ownedUntil = Date.now() + p.redelivery.ackWaitMs;
|
|
968
|
+
return true;
|
|
969
|
+
}
|
|
970
|
+
/** Return scoped pending messages and ack them — call only when they're actually surfaced. */
|
|
971
|
+
drainInbox(limit, scope = "all") {
|
|
972
|
+
this.dropLapsedTakes();
|
|
973
|
+
const eligible = this.inbox.filter((p) => this.inScope(p, scope));
|
|
974
|
+
const n = limit && limit > 0 ? Math.min(limit, eligible.length) : eligible.length;
|
|
975
|
+
const selected = eligible.slice(0, n);
|
|
976
|
+
// Head progress is read from the LIVE queue, so it must be recorded while the batch is still in
|
|
977
|
+
// it (#1526).
|
|
978
|
+
this.noteAutomaticHeadProgress(selected);
|
|
979
|
+
// Remove by OBJECT IDENTITY, not by a set of wire ids (#624): the id-less entries share "", so
|
|
980
|
+
// an id set would remove every id-less neighbor beyond the limit and outside the scope while
|
|
981
|
+
// acking only the selected — silent loss by selection. Identity removes exactly what was taken.
|
|
982
|
+
const taken = new Set(selected);
|
|
983
|
+
this.inbox = this.inbox.filter((p) => !taken.has(p));
|
|
984
|
+
const automatic = selected.some((p) => !p.pullOnly);
|
|
985
|
+
const items = this.commitPending(selected);
|
|
986
|
+
if (items.length)
|
|
987
|
+
this._lastInboxDrainedAt = Date.now();
|
|
988
|
+
// Automatic progress is recorded from the SELECTED entries' own classification, not from the
|
|
989
|
+
// returned items: `commitPending` returns `InboxItem`s, which do not carry `pullOnly`, and
|
|
990
|
+
// counting a pull-only drain as automatic progress is the #1233 lie in miniature.
|
|
991
|
+
if (items.length && automatic)
|
|
992
|
+
this._lastAutomaticDrainedAt = Date.now();
|
|
993
|
+
return items;
|
|
994
|
+
}
|
|
995
|
+
/** Ack exact surfaced deliveries without assuming they still form the physical inbox prefix.
|
|
996
|
+
* Takes RECEIVE keys ({@link InboxItem.recvKey}): the wire id for real messages, a minted key
|
|
997
|
+
* for id-less ones, and selects by them, so a host that surfaced one empty-id item drains THAT
|
|
998
|
+
* delivery, never its neighbors: the sweep the raw id produced (every pending empty-id item
|
|
999
|
+
* acked and marked handled in one call) is closed by construction, not by filtering. Every
|
|
1000
|
+
* requested key whose item is present is acked and (for a real id) marked handled, including an
|
|
1001
|
+
* item overflow-evicted during the turn. */
|
|
1002
|
+
drainInboxDeliveries(keys) {
|
|
1003
|
+
const requested = [...new Set(keys)];
|
|
1004
|
+
const wanted = new Set(requested);
|
|
1005
|
+
// A role request the host surfaced can be back in the held set when its copy changed since. The
|
|
1006
|
+
// host showed it, so its commit acks it from there too. One never taken was never shown, so it
|
|
1007
|
+
// stays held: it is not acked, marked handled or reported missing.
|
|
1008
|
+
const regated = this.gated.filter((p) => wanted.has(p.item.recvKey) && p.takenOnce);
|
|
1009
|
+
const unshown = new Set(this.gated.filter((p) => wanted.has(p.item.recvKey) && !p.takenOnce).map((p) => p.item.recvKey));
|
|
1010
|
+
if (regated.length)
|
|
1011
|
+
this.gated = this.gated.filter((p) => !regated.includes(p));
|
|
1012
|
+
const selected = [...this.inbox.filter((p) => wanted.has(p.item.recvKey)), ...regated];
|
|
1013
|
+
this.noteAutomaticHeadProgress(selected);
|
|
1014
|
+
const present = new Set(selected.map((p) => p.item.recvKey));
|
|
1015
|
+
const pullOnly = new Map(selected.map((p) => [p.item.recvKey, p.pullOnly]));
|
|
1016
|
+
for (const id of requested) {
|
|
1017
|
+
const remembered = id !== "" ? this.evictedClassifications.get(id) : undefined;
|
|
1018
|
+
if (!pullOnly.has(id) && remembered)
|
|
1019
|
+
pullOnly.set(id, remembered.pullOnly);
|
|
1020
|
+
}
|
|
1021
|
+
this.inbox = this.inbox.filter((p) => !present.has(p.item.recvKey));
|
|
1022
|
+
const automatic = selected.some((p) => !p.pullOnly);
|
|
1023
|
+
const items = this.commitPending(selected);
|
|
1024
|
+
if (items.length)
|
|
1025
|
+
this._lastInboxDrainedAt = Date.now();
|
|
1026
|
+
if (items.length && automatic)
|
|
1027
|
+
this._lastAutomaticDrainedAt = Date.now();
|
|
1028
|
+
for (const id of requested) {
|
|
1029
|
+
// A MINTED key (an id-less delivery) is never handled-authority: its wire id is "", which
|
|
1030
|
+
// markHandled already refuses, so skipping it here is the same at-least-once stance rather
|
|
1031
|
+
// than a new one. Recording the minted key itself would pollute handledIds with a string a
|
|
1032
|
+
// future REAL id could legitimately equal, arming the exact suppression this change removes.
|
|
1033
|
+
if (!present.has(id) && !unshown.has(id) && !id.startsWith(`${this.recvKeySecret}.`)) {
|
|
1034
|
+
this.markHandled(id, pullOnly.get(id) ?? false);
|
|
1035
|
+
this.evictedClassifications.delete(id);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
return { items, missingKeys: requested.filter((key) => !present.has(key) && !unshown.has(key)) };
|
|
1039
|
+
}
|
|
1040
|
+
commitPending(taken) {
|
|
1041
|
+
for (const p of taken) {
|
|
1042
|
+
p.ack();
|
|
1043
|
+
this.markHandled(p.item.id, p.pullOnly);
|
|
1044
|
+
this.evictedClassifications.delete(p.item.id);
|
|
1045
|
+
}
|
|
1046
|
+
return taken.map((p) => p.item);
|
|
1047
|
+
}
|
|
1048
|
+
inScope(p, scope) {
|
|
1049
|
+
return scope === "all" || (scope === "pull-only" ? p.pullOnly : !p.pullOnly);
|
|
1050
|
+
}
|
|
1051
|
+
/** Record an id as surfaced/handled, for {@link ingest}'s commit-aware cross-path dedup. Bounded via
|
|
1052
|
+
* two rotating windows: when the live set fills, it becomes the previous window and a fresh one
|
|
1053
|
+
* starts — so memory stays ~2× the cap while the lookup horizon never shrinks below it. */
|
|
1054
|
+
markHandled(id, pullOnly = false) {
|
|
1055
|
+
if (id === "")
|
|
1056
|
+
return; // #624: an empty id is never a dedup key, so it is never recorded as one
|
|
1057
|
+
if (pullOnly)
|
|
1058
|
+
this.protectDisposition(id, "pull-only");
|
|
1059
|
+
this.handledIds.add(id);
|
|
1060
|
+
if (this.handledIds.size >= 4096) {
|
|
1061
|
+
this.handledIdsPrev = this.handledIds;
|
|
1062
|
+
this.handledIds = new Set();
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
/** Receive keys of the pending messages in scope, role requests held for their take included,
|
|
1066
|
+
* for bookkeeping that shows no body. */
|
|
1067
|
+
inboxKeys(scope = "all") {
|
|
1068
|
+
const held = scope === "pull-only" ? [] : this.gated;
|
|
1069
|
+
return [...this.inbox.filter((p) => this.inScope(p, scope)), ...held].map((p) => p.item.recvKey);
|
|
1070
|
+
}
|
|
1071
|
+
/** The pending messages in scope, role requests held for their take included, for a notice that
|
|
1072
|
+
* counts them and shows no body. A held request is shown only through {@link takeChosen}. */
|
|
1073
|
+
inboxPending(scope = "all") {
|
|
1074
|
+
const held = scope === "pull-only" ? [] : this.gated;
|
|
1075
|
+
return [...this.inbox.filter((p) => this.inScope(p, scope)), ...held].map((p) => p.item);
|
|
1076
|
+
}
|
|
1077
|
+
/** Pending messages in scope, counting role requests still held for their take. */
|
|
1078
|
+
inboxCount(scope = "all") {
|
|
1079
|
+
const held = scope === "pull-only" ? 0 : this.gated.length;
|
|
1080
|
+
return held + (scope === "all" ? this.inbox.length : this.inbox.filter((p) => this.inScope(p, scope)).length);
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Read a bounded presentation snapshot without draining, acknowledging, committing, holding or
|
|
1084
|
+
* changing attention. Each item is a shallow copy: reassigning its fields leaves the live inbox
|
|
1085
|
+
* unchanged, but nested values such as `mentions` are shared, so callers must treat items as
|
|
1086
|
+
* read-only.
|
|
1087
|
+
*/
|
|
1088
|
+
inboxSnapshot(limit = 3) {
|
|
1089
|
+
if (!Number.isInteger(limit) || limit < 0 || limit > 8)
|
|
1090
|
+
throw new Error(`inbox preview limit must be a whole number from 0 to 8, got ${limit}`);
|
|
1091
|
+
// A held role request is counted and never previewed: its body is shown only once a host takes
|
|
1092
|
+
// it to show it (SPEC §8.1).
|
|
1093
|
+
this.dropLapsedTakes();
|
|
1094
|
+
return { unread: this.inbox.length + this.gated.length, items: this.inbox.slice(0, limit).map((p) => ({ ...p.item })) };
|
|
1095
|
+
}
|
|
1096
|
+
/** Local receive time of the oldest still-buffered automatic delivery, if any. */
|
|
1097
|
+
oldestAutomaticReceivedAt() {
|
|
1098
|
+
let oldest;
|
|
1099
|
+
for (const pending of [...this.inbox, ...this.gated]) {
|
|
1100
|
+
if (pending.pullOnly)
|
|
1101
|
+
continue;
|
|
1102
|
+
if (oldest === undefined || pending.receivedAt < oldest)
|
|
1103
|
+
oldest = pending.receivedAt;
|
|
1104
|
+
}
|
|
1105
|
+
return oldest;
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* How far this session has read the focus-mode channel recall.
|
|
1109
|
+
*
|
|
1110
|
+
* {@link recallAmbient} re-derives the same items from an unchanged frontier on every call, so a
|
|
1111
|
+
* reader that shows only what fits in one response would show the same prefix forever. This mark
|
|
1112
|
+
* moves when a response actually delivered recall items, and it belongs to ONE walk over ONE
|
|
1113
|
+
* frontier: it says how far this focus episode has read, not what the stream still holds, and
|
|
1114
|
+
* {@link setAttention} forgets it whenever the frontier under it changes.
|
|
1115
|
+
*
|
|
1116
|
+
* WHAT THIS MARK DOES NOT OWN, said here so nothing above it claims otherwise. It orders what
|
|
1117
|
+
* {@link recallAmbient} hands over; it does not decide what becomes recallable. A message that only
|
|
1118
|
+
* becomes readable after this mark has passed its timestamp, through late persistence, is below the
|
|
1119
|
+
* watermark and will not be walked to. That is governed by the frontier `recallAmbient` derives from
|
|
1120
|
+
* ({@link chatFrontier} and the focus watermark), not here, and it is the same for any
|
|
1121
|
+
* timestamp-ordered reader of that stream.
|
|
1122
|
+
*
|
|
1123
|
+
* What the mark DOES own is where it can be moved to, and only this session's own traffic may move
|
|
1124
|
+
* it: an item stamped ahead of the local clock is walked by {@link recallAhead}, not by this mark,
|
|
1125
|
+
* so no sender can push it past the messages it has not read yet.
|
|
1126
|
+
*/
|
|
1127
|
+
get recallCursor() {
|
|
1128
|
+
return this._recallCursor;
|
|
1129
|
+
}
|
|
1130
|
+
/**
|
|
1131
|
+
* Record the last recall item actually handed to the caller.
|
|
1132
|
+
*
|
|
1133
|
+
* The mark is a PAIR, not a timestamp, because two recall items can share a millisecond: a
|
|
1134
|
+
* timestamp alone either filters the twin out for good, if it advances past both, or re-serves the
|
|
1135
|
+
* one already delivered, if it stops below them. Ordering by `(ts, id)` gives every item a place of
|
|
1136
|
+
* its own, so the next call resumes strictly after the last one delivered.
|
|
1137
|
+
*/
|
|
1138
|
+
noteRecalled(mark) {
|
|
1139
|
+
if (afterRecallMark(mark, this._recallCursor))
|
|
1140
|
+
this._recallCursor = mark;
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Does this recall item claim a time this session has not reached?
|
|
1144
|
+
*
|
|
1145
|
+
* `ts` is stamped by the SENDING endpoint, so it is neither trustworthy nor bounded, and a mark
|
|
1146
|
+
* that walks it is a mark a peer can move. One message stamped far ahead otherwise parks
|
|
1147
|
+
* {@link recallCursor} in the future: every ordinary message after it sorts below the mark, is
|
|
1148
|
+
* filtered out of recall for the rest of the session, and the reply says there is no chatter. That
|
|
1149
|
+
* is one peer suppressing OTHER peers' recall, which makes it a security property and not only a
|
|
1150
|
+
* clock one, and the defence has to hold when the field is chosen rather than merely wrong.
|
|
1151
|
+
*
|
|
1152
|
+
* So the walk splits. An item at or behind this session's clock is ordered by its timestamp and
|
|
1153
|
+
* moves the mark. An item ahead of it is not ordered at all and NEVER moves the mark: it is handed
|
|
1154
|
+
* over once and remembered by id ({@link noteRecalledAhead}), so it neither leads the walk nor
|
|
1155
|
+
* comes back on the next call.
|
|
1156
|
+
*
|
|
1157
|
+
* THE LANES SWAP MEMBERSHIP, and the record is what keeps them honest with each other. An item
|
|
1158
|
+
* stamped just ahead of the clock crosses into the ordered lane the moment the clock passes it,
|
|
1159
|
+
* arriving above a mark that never moved for it, so the reader has to consult
|
|
1160
|
+
* {@link recallAheadSeen} there too or hand it over a second time. That crossing is the one part of
|
|
1161
|
+
* this mechanism that cannot be staged by choosing timestamps, so its cell waits for real time
|
|
1162
|
+
* rather than reasoning about it.
|
|
1163
|
+
*/
|
|
1164
|
+
recallAhead(item) {
|
|
1165
|
+
return item.ts > Date.now();
|
|
1166
|
+
}
|
|
1167
|
+
/** Has this future-stamped recall item already been handed over in this session? */
|
|
1168
|
+
recallAheadSeen(id) {
|
|
1169
|
+
return this.aheadDelivered.has(id);
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* How many more future-stamped recall items this session will take responsibility for.
|
|
1173
|
+
*
|
|
1174
|
+
* Exactness costs memory, and that memory is what a flood of forged stamps would grow, so it is
|
|
1175
|
+
* bounded. A caller must not hand over what it cannot record, or it will hand it over again on
|
|
1176
|
+
* every call forever; past this bound it has to say so instead. Note where the cost lands: an item
|
|
1177
|
+
* at or behind the clock never enters this set, so a peer that spends the whole bound spends it on
|
|
1178
|
+
* ITS OWN messages and cannot use it to silence anyone else's.
|
|
1179
|
+
*/
|
|
1180
|
+
recallAheadRoom() {
|
|
1181
|
+
return MAX_AHEAD - this.aheadDelivered.size;
|
|
1182
|
+
}
|
|
1183
|
+
/** Record that a future-stamped recall item was actually handed to the caller. */
|
|
1184
|
+
noteRecalledAhead(id) {
|
|
1185
|
+
if (this.aheadDelivered.size < MAX_AHEAD)
|
|
1186
|
+
this.aheadDelivered.add(id);
|
|
1187
|
+
}
|
|
1188
|
+
/**
|
|
1189
|
+
* Forget how far a recall walk had read, because the thing it was walking is gone.
|
|
1190
|
+
*
|
|
1191
|
+
* The mark is session-local, which is a longer life than it can honestly carry: it describes a
|
|
1192
|
+
* position in ONE walk over ONE frontier, and {@link setAttention} both drops the frontier on the
|
|
1193
|
+
* way out of focus and captures a new one on the way in. Measured before this reset, a mark left
|
|
1194
|
+
* over from an earlier focus episode filtered a new episode's messages out of recall whenever they
|
|
1195
|
+
* were stamped behind it, which a lagging or a chosen clock produces. The focus watermark was
|
|
1196
|
+
* already cleared here; the mark that walks it was not.
|
|
1197
|
+
*/
|
|
1198
|
+
resetRecallWalk() {
|
|
1199
|
+
this._recallCursor = { ts: 0, id: "" };
|
|
1200
|
+
this.aheadDelivered.clear();
|
|
1201
|
+
}
|
|
1202
|
+
/** Buffered receive-time lane for one delivery, addressed by its receive key. Undefined means it
|
|
1203
|
+
* is no longer pending. */
|
|
1204
|
+
inboxScope(key) {
|
|
1205
|
+
const pending = this.inbox.find((p) => p.item.recvKey === key) ?? this.gated.find((p) => p.item.recvKey === key);
|
|
1206
|
+
return pending ? (pending.pullOnly ? "pull-only" : "automatic") : undefined;
|
|
1207
|
+
}
|
|
1208
|
+
/** Count of automatic messages that count as directed for a wake decision: real dm/anycast
|
|
1209
|
+
* (authenticated kind) or a live channel @mention. Pull-only history never counts, including
|
|
1210
|
+
* mentions retained while focused. The Stop→idle flush uses this in `dnd`/`focus`. */
|
|
1211
|
+
directedPendingCount() {
|
|
1212
|
+
return this.gated.length + this.inbox.filter((p) => !p.pullOnly && (p.item.kind !== "channel" || (!p.item.historical && p.item.mentionsMe))).length;
|
|
1213
|
+
}
|
|
1214
|
+
/** The inbox half of {@link pendingWake}: buffered items that should wake the agent, without run
|
|
1215
|
+
* turns. A surface that cannot surface a run turn, such as the remote gateway, waits on this, so
|
|
1216
|
+
* a turn it can never clear does not end every wait at once. */
|
|
1217
|
+
inboxWake(skip) {
|
|
1218
|
+
// A role request held for its take wakes when a read could take it: the read the wake leads to
|
|
1219
|
+
// takes it. While the link is down, or a take nobody could decide is waited out, none wakes, and
|
|
1220
|
+
// each is announced again when the link is back or the wait ends (see runTake). An in-flight take
|
|
1221
|
+
// already owns its next announcement; an old-link take must not block a new read after reconnect.
|
|
1222
|
+
// A copy whose ack wait ran out is dropped first, as a read drops it.
|
|
1223
|
+
this.dropLapsedTakes();
|
|
1224
|
+
const held = this.mayAskTakes() ? this.gated.filter((p) => (p.taking === undefined || p.takingDrops !== this.transportDrops) && !skip?.(p.item)).length : 0;
|
|
1225
|
+
return held + this.inbox.filter((p) => {
|
|
1226
|
+
const it = p.item;
|
|
1227
|
+
if (p.pullOnly || (it.kind === "channel" && it.historical) || skip?.(it))
|
|
1228
|
+
return false;
|
|
1229
|
+
if (it.kind !== "channel" || it.mentionsMe)
|
|
1230
|
+
return true;
|
|
1231
|
+
return this._attention === "open";
|
|
1232
|
+
}).length;
|
|
1233
|
+
}
|
|
1234
|
+
// ---- attention ------------------------------------------------------------
|
|
1235
|
+
/** This agent's global attention mode. Authoritative here; mirrored to presence (advisory) so peers
|
|
1236
|
+
* can see it. Delivery never reads it back from presence — local state wins. */
|
|
1237
|
+
get attention() {
|
|
1238
|
+
return this._attention;
|
|
1239
|
+
}
|
|
1240
|
+
/** This agent's per-channel override for `channel` (undefined ⇒ follow the global mode). */
|
|
1241
|
+
channelMode(channel) {
|
|
1242
|
+
return channel ? this.channelModes.get(channel) : undefined;
|
|
1243
|
+
}
|
|
1244
|
+
/** A snapshot of every per-channel override (for the at-a-glance views). */
|
|
1245
|
+
channelModeEntries() {
|
|
1246
|
+
return Object.fromEntries(this.channelModes);
|
|
1247
|
+
}
|
|
1248
|
+
/** Set (or clear, with `"normal"`) one channel's attention override. Validates the channel is
|
|
1249
|
+
* concrete and within this agent's read ACL (`allowSubscribe` — so a mode can be pre-set for a
|
|
1250
|
+
* channel it may read but hasn't joined yet), updates the AUTHORITATIVE in-memory map, then mirrors
|
|
1251
|
+
* the whole map to presence (best-effort; advisory). Per-instance + runtime: it NEVER writes the
|
|
1252
|
+
* agent file (a shared template) and resets on restart.
|
|
1253
|
+
*
|
|
1254
|
+
* It does not purge messages already buffered from that channel. Quiet makes its buffered ambient
|
|
1255
|
+
* pull-only, and muted makes everything buffered from it pull-only, mentions included, so neither
|
|
1256
|
+
* enters another turn and both stay readable with cotal_inbox. `normal` makes nothing automatic
|
|
1257
|
+
* again. */
|
|
1258
|
+
async setChannelMode(channel, mode) {
|
|
1259
|
+
if (!isConcreteChannel(channel))
|
|
1260
|
+
throw new Error(`"${channel}" must be a concrete channel (no wildcard) to set its attention`);
|
|
1261
|
+
if (!channelInAllow(this.config.allowSubscribe, channel))
|
|
1262
|
+
throw new Error(`"${channel}" is not within your read ACL (allowSubscribe) [${this.config.allowSubscribe.join(", ")}]`);
|
|
1263
|
+
await this.inOrder(() => {
|
|
1264
|
+
if (mode === "normal")
|
|
1265
|
+
this.channelModes.delete(channel);
|
|
1266
|
+
else {
|
|
1267
|
+
this.channelModes.set(channel, mode);
|
|
1268
|
+
this.lowerBuffered(channel, mode === "muted");
|
|
1269
|
+
}
|
|
1270
|
+
return this.ep.setChannelModes(this.channelModeEntries());
|
|
1271
|
+
});
|
|
1272
|
+
}
|
|
1273
|
+
/** Make the automatic entries buffered from `channel` (a concrete channel or a pattern) pull-only,
|
|
1274
|
+
* mentions of this agent too when `mentions` is set, except on a channel `keep` still covers. An
|
|
1275
|
+
* entry a host is handing over keeps its lane, since the turn carrying it acks it. */
|
|
1276
|
+
lowerBuffered(channel, mentions, keep = []) {
|
|
1277
|
+
for (const p of this.inbox) {
|
|
1278
|
+
if (p.pullOnly || p.item.kind !== "channel" || !p.item.channel || !channelInAllow([channel], p.item.channel))
|
|
1279
|
+
continue;
|
|
1280
|
+
if (channelInAllow(keep, p.item.channel))
|
|
1281
|
+
continue;
|
|
1282
|
+
if ((p.item.mentionsMe && !mentions) || this.inFlightIds.has(p.item.recvKey))
|
|
1283
|
+
continue;
|
|
1284
|
+
p.pullOnly = true;
|
|
1285
|
+
this.excludeFromFocus(p.item);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
/** Set the attention mode. Entering `focus` captures the chat frontier as the focus-watermark
|
|
1289
|
+
* (recall surfaces ambient published after it); leaving focus clears it. Requires a live
|
|
1290
|
+
* connection only for `focus` (it reads the stream frontier). Ambient already *buffered* when
|
|
1291
|
+
* focus is entered is not retroactively ack-dropped. Traffic retained during the asynchronous
|
|
1292
|
+
* frontier read is tagged out of recall, so it surfaces once from its receive-time lane whether
|
|
1293
|
+
* it landed just before or after the captured frontier. Only ambient arriving after the local
|
|
1294
|
+
* switch is ack-dropped. */
|
|
1295
|
+
async setAttention(mode) {
|
|
1296
|
+
await this.inOrder(async () => {
|
|
1297
|
+
if (mode === "focus") {
|
|
1298
|
+
await this.requireConnected();
|
|
1299
|
+
this.focusExcludedIds.clear();
|
|
1300
|
+
this.focusIdless = new Map();
|
|
1301
|
+
this.focusIdlessEntries = 0;
|
|
1302
|
+
this.focusRecallUnsafeChannels.clear();
|
|
1303
|
+
this.enteringFocus = this._attention !== "focus";
|
|
1304
|
+
try {
|
|
1305
|
+
this.focusSince = await this.ep.chatFrontier();
|
|
1306
|
+
}
|
|
1307
|
+
catch (error) {
|
|
1308
|
+
this.enteringFocus = false;
|
|
1309
|
+
this.focusExcludedIds.clear();
|
|
1310
|
+
this.focusIdless = new Map();
|
|
1311
|
+
this.focusIdlessEntries = 0;
|
|
1312
|
+
this.focusRecallUnsafeChannels.clear();
|
|
1313
|
+
throw error;
|
|
1314
|
+
}
|
|
1315
|
+
this.enteringFocus = false;
|
|
1316
|
+
this.resetRecallWalk();
|
|
1317
|
+
}
|
|
1318
|
+
else {
|
|
1319
|
+
this.enteringFocus = false;
|
|
1320
|
+
this.focusSince = undefined;
|
|
1321
|
+
this.focusExcludedIds.clear();
|
|
1322
|
+
this.focusIdless = new Map();
|
|
1323
|
+
this.focusIdlessEntries = 0;
|
|
1324
|
+
this.focusRecallUnsafeChannels.clear();
|
|
1325
|
+
this.resetRecallWalk();
|
|
1326
|
+
}
|
|
1327
|
+
this._attention = mode;
|
|
1328
|
+
// Mirror to presence (advisory observability — peers can see "they're in focus"). Best-effort:
|
|
1329
|
+
// a no-op until the KV is bound, and never read back into delivery.
|
|
1330
|
+
await this.ep.setAttention(mode);
|
|
1331
|
+
});
|
|
1332
|
+
}
|
|
1333
|
+
/** Focus recall: the channel ambient + @mentions ack-dropped since this agent entered focus,
|
|
1334
|
+
* read back from the chat stream on demand and **replay-gated per channel** (a `replay=off`
|
|
1335
|
+
* channel yields nothing, and is named in `droppedChannels` — recall must not become a history
|
|
1336
|
+
* bypass, and it must not claim a suppressed channel's window was empty and complete either).
|
|
1337
|
+
* Items are marked `historical` (catch-up framing). `droppedChannels` also names channels whose
|
|
1338
|
+
* earliest retained message postdates the focus-watermark — older ambient may have aged out of
|
|
1339
|
+
* the per-channel window — and wildcard subscriptions (`team.>`), which recall cannot read back
|
|
1340
|
+
* per concrete sub-channel (#977: a wildcard join is not itself a channel ingest can consult a
|
|
1341
|
+
* replay policy for) and so cannot vouch for either (never-silent throughout). Empty unless in
|
|
1342
|
+
* focus. Calls run one at a time (#662). `underway` names recalled items that already went out in
|
|
1343
|
+
* part: an exclusion that lands after that does not hide one, since recall would then move past
|
|
1344
|
+
* the rest of it (#613). */
|
|
1345
|
+
async recallAmbient(underway = new Set()) {
|
|
1346
|
+
const run = this.recallLock.then(() => this.recallAmbientOnce(underway));
|
|
1347
|
+
this.recallLock = run.catch(() => { });
|
|
1348
|
+
return run;
|
|
1349
|
+
}
|
|
1350
|
+
async recallAmbientOnce(underway) {
|
|
1351
|
+
if (this._attention !== "focus" || this.focusSince === undefined)
|
|
1352
|
+
return { items: [], droppedChannels: [] };
|
|
1353
|
+
const items = [];
|
|
1354
|
+
const droppedChannels = [];
|
|
1355
|
+
for (const channel of this.ep.joinedChannels()) {
|
|
1356
|
+
if (!isConcreteChannel(channel)) {
|
|
1357
|
+
droppedChannels.push(channel);
|
|
1358
|
+
continue;
|
|
1359
|
+
}
|
|
1360
|
+
if (this.focusRecallUnsafeChannels.has(channel)) {
|
|
1361
|
+
droppedChannels.push(channel);
|
|
1362
|
+
continue;
|
|
1363
|
+
}
|
|
1364
|
+
const tallies = this.focusIdless;
|
|
1365
|
+
let epoch = 0;
|
|
1366
|
+
let read;
|
|
1367
|
+
// #662: a copy settled while a read runs may or may not be in it, so the read is retried with
|
|
1368
|
+
// that copy settled first, a bounded number of times.
|
|
1369
|
+
for (let attempt = 1; attempt <= IDLESS_READS; attempt++) {
|
|
1370
|
+
epoch = ++this.idlessEpoch;
|
|
1371
|
+
// The read starts after every copy settled before it knows its frontier, so a copy it
|
|
1372
|
+
// cannot bind is behind the focus start or out of retention.
|
|
1373
|
+
await this.idlessReady(tallies, channel);
|
|
1374
|
+
read = await this.ep.recallChannel(channel, this.focusSince);
|
|
1375
|
+
if (read.unanswered)
|
|
1376
|
+
break;
|
|
1377
|
+
await this.idlessReady(tallies, channel); // copies settled during the read
|
|
1378
|
+
const unsure = read.messages.some((m, i) => m.id === "" && this.idlessUnsure(tallies.get(idlessDigest(m)), epoch, read.seqs[i]));
|
|
1379
|
+
if (!unsure)
|
|
1380
|
+
break;
|
|
1381
|
+
}
|
|
1382
|
+
const { messages, seqs, dropped, unanswered } = read;
|
|
1383
|
+
// A read that did not answer says nothing about what the channel retains, so nothing settles.
|
|
1384
|
+
if (unanswered) {
|
|
1385
|
+
droppedChannels.push(channel);
|
|
1386
|
+
continue;
|
|
1387
|
+
}
|
|
1388
|
+
if (this.focusRecallUnsafeChannels.has(channel)) {
|
|
1389
|
+
droppedChannels.push(channel);
|
|
1390
|
+
continue;
|
|
1391
|
+
}
|
|
1392
|
+
// #662: each copy settled before the read is bound to one retained stream copy at or below its
|
|
1393
|
+
// frontier. A copy no settled copy is bound to was never received (a reconnect gap) or was
|
|
1394
|
+
// evicted; it is handed back into the inbox, which acks each by receive key, since the recall
|
|
1395
|
+
// mark cannot order identical copies.
|
|
1396
|
+
const retained = new Set();
|
|
1397
|
+
const digests = [];
|
|
1398
|
+
const free = new Map();
|
|
1399
|
+
for (const [i, m] of messages.entries()) {
|
|
1400
|
+
if (m.id !== "" || tallies !== this.focusIdless)
|
|
1401
|
+
continue;
|
|
1402
|
+
retained.add(seqs[i]);
|
|
1403
|
+
const digest = (digests[i] = idlessDigest(m));
|
|
1404
|
+
if (tallies.get(digest)?.bound.has(seqs[i]))
|
|
1405
|
+
continue;
|
|
1406
|
+
const list = free.get(digest);
|
|
1407
|
+
if (list)
|
|
1408
|
+
list.push(seqs[i]);
|
|
1409
|
+
else
|
|
1410
|
+
free.set(digest, [seqs[i]]);
|
|
1411
|
+
}
|
|
1412
|
+
for (const [digest, list] of free) {
|
|
1413
|
+
const tally = tallies.get(digest);
|
|
1414
|
+
if (tally)
|
|
1415
|
+
this.bindIdless(tally, epoch, list);
|
|
1416
|
+
}
|
|
1417
|
+
let incomplete = dropped;
|
|
1418
|
+
for (const [i, m] of messages.entries()) {
|
|
1419
|
+
if (m.id !== "") {
|
|
1420
|
+
if (underway.has(m.id) || !this.focusExcludedIds.has(m.id))
|
|
1421
|
+
items.push(this.toInboxItem(m, "channel", true));
|
|
1422
|
+
continue;
|
|
1423
|
+
}
|
|
1424
|
+
if (tallies !== this.focusIdless)
|
|
1425
|
+
continue; // focus was left or re-entered during the read
|
|
1426
|
+
const seq = seqs[i];
|
|
1427
|
+
const digest = digests[i];
|
|
1428
|
+
const tally = tallies.get(digest);
|
|
1429
|
+
if (tally?.bound.has(seq))
|
|
1430
|
+
continue;
|
|
1431
|
+
// Still unsure after the last read: neither claimed nor handed back, and reported.
|
|
1432
|
+
if (this.idlessUnsure(tally, epoch, seq)) {
|
|
1433
|
+
incomplete = true;
|
|
1434
|
+
continue;
|
|
1435
|
+
}
|
|
1436
|
+
// A full inbox leaves it in the stream for a later call, rather than evict something else.
|
|
1437
|
+
const fresh = this.inbox.length < MAX_INBOX ? this.reserveIdless(digest, channel) : undefined;
|
|
1438
|
+
if (!fresh) {
|
|
1439
|
+
incomplete = true;
|
|
1440
|
+
continue;
|
|
1441
|
+
}
|
|
1442
|
+
const copy = { epoch, frontier: seq, ready: Promise.resolve(), seq };
|
|
1443
|
+
fresh.bound.add(seq);
|
|
1444
|
+
this.buffer(this.toInboxItem(m, "channel", true), { ack: () => { } }, true, { digest, copy });
|
|
1445
|
+
}
|
|
1446
|
+
if (tallies === this.focusIdless)
|
|
1447
|
+
this.settleIdlessRead(channel, epoch, retained);
|
|
1448
|
+
if (incomplete)
|
|
1449
|
+
droppedChannels.push(channel);
|
|
1450
|
+
}
|
|
1451
|
+
items.sort((a, b) => a.ts - b.ts);
|
|
1452
|
+
return { items, droppedChannels };
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
//# sourceMappingURL=agent-inbox.js.map
|