@sema-agent/core 7.68.4 → 7.68.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ ## 7.68.5 — 2026-11-16
2
+
3
+ ### A finished run lets go of what it handed its session's process-level seats: a long-lived host with a mailbox store no longer keeps each session's last leg for the life of the process (#4672; fix; behavior change: one, below, open to veto; narrowing: none; widening: none; hard-breaking: none; closed sets: none; exports: none; wire: none)
4
+
5
+ - **Before.** Since 7.4.0, on a deployment whose sessions have a session box (a mailbox store safe across processes over a session store that reads a row by id), every top-level leg mounts the box drain, which opens its session's idle machine and the held queue of each box it drains — process-level seats, one per session address. The drain bound them sinks built inside the leg; at the leg's loop end only the held queue's injector was detached, and every other sink still closed over the leg. A timer a seat armed for the leg (an idle ask's 12 h, a held card's deadline) also kept the async context of the run that armed it. So each session's last leg — its prepared state, tool table, guard rows, harness and conversation — stayed reachable for as long as the process lived. Measured on the engine alone (one Runner on the file backend, a new session per run, 50 caller tools, the session deleted through the store after each run, 300 runs, base and fix alternated twice): 771,232 and 771,686 bytes of heap and one whole leg (its harness, its session object, its 50 tools) kept per run on 7.68.4; 11,812 and 11,895 bytes and no leg with this fix (what is left is the "Not fixed" paragraph below).
6
+ - **Affected.** Long-lived hosts that wire a mailbox store: every session they ever ran keeps its last leg. A host that runs each request in a new session grows by one leg per request (about 770 KB in the measurement above; more with a longer conversation or a larger tool table) until the heap runs out.
7
+ - **Now.** What a leg binds its session's seats is handed through the run's end — the one end that already takes back the listeners a run hangs on a signal it does not own — and taken back once the run has settled, whatever way it ended: each seat is re-bound to the session's facts as the leg ended with them (its mode class, its name, its last turn's text) and to the deployment's own seats, nothing of the leg. A seat is re-bound only while it still holds this leg's binding: when two legs of one session are bound at once (two Runners in one process on one session id), the run's end of the one that ends first leaves the other's binding — its injector, its live readings — in place (that leg's loop end can still take the other's injector off the held queue until the other's next pass, as on every released version). A seat (a held queue, either idle half) arms its timers outside any run, on whatever clock it was given. Each seat is taken back on its own: if re-binding one throws, the others are still re-bound, and the fault reaches `RunnerDeps.onError` (`phase: "degraded"`, `classification: "run-end-take-back"`), never the process as an unhandled rejection; the run's result is unchanged. A Runner with no `onError` hears nothing of it, as with its other degraded arms.
8
+ - **Not changed.** Between legs the seats stand and work as before: a subscription recorded in one leg is fired at the end of a later one; a subscription fired after the leg ended reaches its requester, authored as before; a session's own idle ask answers it `expired` at 12 h; a held card expires at its deadline with its receipt, and an approval between legs answers `released_pending`. The host face (`peerIdleMachineIfAny`, `peerHeldQueueIfAny`, `listPeerHeldQueues`) reads them as before. Deleting a session does to its seats what it did before (nothing; a new occupant of the id replaces them). `realPeerClock` is a plain clock as before (a timer armed on it directly keeps its caller's async context).
9
+ - **Not fixed (as in every released version).** Each session whose legs mounted the drain keeps its idle machine and its held queue in this process until the process ends or a new occupant of the id replaces them — now without the leg: about 7.6 KB per session (measured: a host-owned session store, each session's box dropped, 2,400 sessions per pass, the heap slope with the seats kept less the slope with them cleared each round: 7,619 and 7,637 bytes in two passes). A host that calls the root `runTask(spec, deps)` once per request (a new Runner each call) keeps more: each session also keeps one Runner — about 22 KB per session in one measurement (an in-memory session store, 20 caller tools, one shared file mailbox; about 361 KB before the fix); what holds it is, by reading the code and not traced, the seats' resting form reaching that call's Runner through its error sink. A seat whose re-bind throws at the run's end keeps the leg it was bound (the fault reaches the error sink; no take-back is known to throw today). Deleting the session, through the engine's store or the host's own, does not remove them, and `listPeerHeldQueues()` keeps listing each ended session's empty queue. On the file backend, a host that does not drop a deleted session's box also keeps the box's open log in the mailbox store until the store closes: about 850 bytes (866 and 834 in the same two passes) and one open log per session, so one file descriptor each by reading the code (the descriptors were not counted). The drop is the deletion cascade's mailbox leg, `mailboxStore.drop`, at the scope the session's legs drained it in — the leg's `isolationScope`, else its `principal`, else `"default"`; the file mailbox keys a box by a digest of the scope's bytes, so another spelling drops another box.
10
+ - **Behavior change, an exit (open to veto).** `PeerIdleTarget.configure` no longer clears an exit the host declared (`exited`); `busy` (the session starts working) does. For a Runner's leg that begins it is the same moment as before (the leg binds and then begins). Two forms differ: a leg refused after the drain mounted and before it begins no longer clears the exit (measured: after `exited` and one such refused leg, a subscription was recorded on 7.68.4 and is answered `full` now; after the next leg that runs it is recorded on both), and between a leg's bind and its first turn a subscription is answered `full` where it was recorded (by reading the code, not measured); the run's end re-binding the seats no longer revives a target the host declared exited. A host that drives `createPeerIdleTarget` directly and re-binds it after `exited` sees subscriptions refused until it calls `busy`.
11
+ - **Rules.** The run's end gains one verb (`lend`: hand something over and name how it is taken back); listening to a signal is one use of it; the stream leg ends the run through one call that hands a take-back's fault to the error sink. The leg's seat logic (judgment, route, receipt, disclosure, the three sinks) has one spelling, read by the bound and the resting form; every bind of a seat goes through one function that records which leg's bind landed, and a leg whose run ended re-binds only a seat still its own (or one a failed bind left with no known holder). A seat's timers are armed outside any run (one clock wrapper, read by the three seat factories).
12
+ - **Pins.** `test/backlog4672-session-machine-lets-go-of-the-leg.test.ts` — R (an in-memory session store and the file backend; nothing after the run / the session deleted; a prepare that refuses after the drain mounted; the no-mailbox control), B1–B4 (each with the leg collected first: a subscriber told after the leg; a subscription across two legs; a session's own 12 h ask; a held card's deadline and an approval between legs), F1 (a real Runner whose seat throws when the run's end re-binds it: no unhandled rejection, one `run-end-take-back` error, every other take-back ran, the result unchanged), F2 (the first seat's re-bind throws: the others are still re-bound), O1 (two legs of one session bound at once: the first to end re-binds nothing the other bound), O2 (a bind that throws leaves no known holder: the earlier leg still takes the seat back), E1–E3, E5–E7 (a getter that throws at the run's end keeps nothing of the leg; a pass after the end binds the resting form; an exit stands across the take-back; with the real clock, and with a clock the host supplies, a leg whose idle ask is outstanding is collected; `realPeerClock` itself unchanged).
13
+ - **Consumers.** Nothing to change to get the fix. What a long-lived host still keeps per ended session is the "Not fixed" paragraph above: a host on the file backend that deletes sessions should drop each session's box at that exact scope; a host that shows `listPeerHeldQueues()` to people sees ended sessions' empty queues. A host whose `onError` sink sorts by `classification` has one more word, `run-end-take-back`.
14
+
1
15
  ## 7.68.4 — 2026-11-16
2
16
 
3
17
  ### A host can declare that every process opening a file data root runs in this one process table, and the directory locks under that root then judge a lock written by an engine before 7.67.0 by its pid; without the declaration nothing changes but the refusal's sentence and one re-read under the reclaim gate, below (#4667; ruled C-R2243; new host declaration; default unchanged; narrowing: none; widening: one, below, open to veto @server @cli; hard-breaking: none; closed sets: one, `EngineNoticeCode` +1; exports: two, `declareDataRoot`, `DataRootDeclaration`, and one optional member on the exported class `FileStoreLockError`, `ownerFingerprintUnread`; wire: none)
@@ -44,10 +44,15 @@ export interface PeerClock {
44
44
  clearTimeout(handle: unknown): void;
45
45
  }
46
46
  export declare const realPeerClock: PeerClock;
47
+ /** The clock a seat (a held queue, an idle half) arms its timers on: `clock`, with every timer armed outside any run. A timer
48
+ * keeps the async context it was armed in until it fires or is cleared, and with it the stores of the run whose code armed it
49
+ * (the run's whole state); a seat outlives every run (an idle ask waits 12 h), so its timers are armed, and fire, outside any. */
50
+ export declare function peerSeatClock(clock?: PeerClock): PeerClock;
47
51
  /** The live seats a bound run gives the queue. `inject` is the ONLY member that is run-scoped (a run's
48
52
  * own injection lane); the others survive the run (the receipt route rides the mailbox, the judge
49
53
  * reads the deployment's settings getter, the decision seat is the store) and are what a headless
50
- * deadline settles through. */
54
+ * deadline settles through — so what the queue keeps after the run closes over nothing of it (the
55
+ * queue is process-lived: the session-box drain hands its sinks through the run's end). */
51
56
  export interface PeerHeldQueueSink {
52
57
  /** Re-judge an entry against the recipient's CURRENT settings and mode class (CC `M`). */
53
58
  judge: (entry: PeerHeldEntry) => CrossSessionInboundVerdict;
@@ -1,3 +1,4 @@
1
+ import { AsyncResource } from "node:async_hooks";
1
2
  import { isMailboxDecisionDeliverable, isMailboxDecisionFinal } from "../core/mailbox-store.js";
2
3
  import { sameOccupant } from "../engine/session/repo-utils.js";
3
4
  import { PEER_HELD_QUEUE_CAP, PEER_HELD_REVIEW_CAUSES, peerHeldReceiptStateOf } from "./peer-notices.js";
@@ -18,10 +19,18 @@ export const realPeerClock = {
18
19
  },
19
20
  clearTimeout: (h) => clearTimeout(h),
20
21
  };
22
+ const outsideAnyRun = AsyncResource.bind((arm) => arm());
23
+ export function peerSeatClock(clock = realPeerClock) {
24
+ return {
25
+ now: () => clock.now(),
26
+ setTimeout: (fn, ms) => outsideAnyRun(() => clock.setTimeout(fn, ms)),
27
+ clearTimeout: (h) => clock.clearTimeout(h),
28
+ };
29
+ }
21
30
  const crashHandlers = new WeakMap();
22
31
  export function createPeerHeldQueue(key, opts = {}) {
23
32
  const cap = opts.cap ?? PEER_HELD_QUEUE_CAP;
24
- const clock = opts.clock ?? realPeerClock;
33
+ const clock = peerSeatClock(opts.clock);
25
34
  const entries = [];
26
35
  const deadlines = new Map();
27
36
  const releasedBy = new WeakMap();
@@ -36,6 +36,8 @@ export interface PeerIdleTargetSink {
36
36
  }
37
37
  export type PeerIdleSubscribeOutcome = "recorded" | "refreshed" | "full";
38
38
  export interface PeerIdleTarget {
39
+ /** Bind the sink the machine routes through (a leg's, then the session's resting one). Binding is not working: an exit stands
40
+ * until the session works again ({@link busy}). */
39
41
  configure(sink: PeerIdleTargetSink): void;
40
42
  configured(): boolean;
41
43
  /** CC `tYt` (sans pid classes): same requester ⇒ refresh; table full ⇒ `"full"` (the caller answers
@@ -43,7 +45,7 @@ export interface PeerIdleTarget {
43
45
  subscribe(sub: PeerIdleSubscriber): PeerIdleSubscribeOutcome;
44
46
  /** CC `A`: drop subscribers older than the TTL, silently. Returns how many. */
45
47
  sweep(now?: number): number;
46
- /** The session started working (a run began): cancel a pending fire. */
48
+ /** The session started working (a run began): cancel a pending fire; an earlier exit no longer stands (subscriptions are taken again). */
47
49
  busy(): void;
48
50
  /** The session's run ended with nothing queued: schedule the one-shot `idle` fire (debounced; parked
49
51
  * while the held buffer is non-empty and re-checked). `finishedAt` = when the turn ended. */
@@ -1,9 +1,9 @@
1
1
  import { sameOccupant } from "../engine/session/repo-utils.js";
2
2
  import { PEER_IDLE_FIRE_DEBOUNCE_MS, PEER_IDLE_HELD_BACKOFF_MS, PEER_IDLE_OUTSTANDING_CAP, PEER_IDLE_PRIORS_KEPT, PEER_IDLE_SUBSCRIBER_TABLE_CAP, PEER_IDLE_SUBSCRIPTION_TTL_MS } from "./peer-notices.js";
3
- import { realPeerClock } from "./peer-held-queue.js";
3
+ import { peerSeatClock } from "./peer-held-queue.js";
4
4
  import { peerSessionBoxHandle } from "./peer-directory.js";
5
5
  export function createPeerIdleTarget(opts = {}) {
6
- const clock = opts.clock ?? realPeerClock;
6
+ const clock = peerSeatClock(opts.clock);
7
7
  const cap = opts.tableCap ?? PEER_IDLE_SUBSCRIBER_TABLE_CAP;
8
8
  const ttl = opts.ttlMs ?? PEER_IDLE_SUBSCRIPTION_TTL_MS;
9
9
  const subs = [];
@@ -87,7 +87,6 @@ export function createPeerIdleTarget(opts = {}) {
87
87
  return {
88
88
  configure(next) {
89
89
  sink = next;
90
- exitedFlag = false;
91
90
  },
92
91
  configured: () => sink !== undefined,
93
92
  subscribe(sub) {
@@ -115,6 +114,7 @@ export function createPeerIdleTarget(opts = {}) {
115
114
  sweep,
116
115
  busy() {
117
116
  idleState = undefined;
117
+ exitedFlag = false;
118
118
  cancelPending();
119
119
  },
120
120
  idle(finishedAt) {
@@ -143,7 +143,7 @@ export function createPeerIdleTarget(opts = {}) {
143
143
  };
144
144
  }
145
145
  export function createPeerIdleRequester(opts = {}) {
146
- const clock = opts.clock ?? realPeerClock;
146
+ const clock = peerSeatClock(opts.clock);
147
147
  const cap = opts.cap ?? PEER_IDLE_OUTSTANDING_CAP;
148
148
  const priorsKept = opts.priorsKept ?? PEER_IDLE_PRIORS_KEPT;
149
149
  const ttl = opts.ttlMs ?? PEER_IDLE_SUBSCRIPTION_TTL_MS;
@@ -15,6 +15,7 @@ import type { SendMessageToolOptions } from "./send-message-tool.js";
15
15
  import type { PeerChannel } from "../core/peer-channel.js";
16
16
  import { type PeerClock, type PeerHeldQueue } from "./peer-held-queue.js";
17
17
  import { type PeerIdleMachine } from "./peer-idle.js";
18
+ import type { RunEnd } from "../core/runner/end-of-run.js";
18
19
  /** design/385 §1.2④ — the drain lease TTL. Same sizing law as the tier-3 revive lease: well under the
19
20
  * store's stale-row floor, long enough to cover one turn (a longer turn renews on the same owner at
20
21
  * its next boundary; an expired lease re-serves the batch — at-least-once). */
@@ -217,7 +218,8 @@ export interface PeerSessionDrainOptions {
217
218
  lane?: Partial<PeerLaneConfig>;
218
219
  /** The recipient's self-token set for the hop check, read live (the run's peer identity ref). */
219
220
  ownTokens: () => readonly string[];
220
- /** The recipient's `crossSessionInbound` layers, read at every drain. */
221
+ /** The recipient's `crossSessionInbound` layers, read at every drain — and by the session's seats after the leg (a held card's
222
+ * deadline or approval, an idle notice's detail), so it reads the deployment's seat and closes over nothing of the leg. */
221
223
  settingLayers: () => CrossSessionInboundSettingLayers | undefined;
222
224
  /** The recipient's own permission-mode class, read at every drain (the manifest's ask fold). */
223
225
  selfModeClass: () => PermissionModeClass | "unknown";
@@ -251,6 +253,10 @@ export interface PeerSessionDrainOptions {
251
253
  leaseTtlMs?: number;
252
254
  /** Tests: a virtual clock for the held deadlines and idle timers (honored when this process first sees the session). */
253
255
  clock?: PeerClock;
256
+ /** The run's end (end-of-run.ts): what this leg binds the session's process-level seats is handed through it, and taken back
257
+ * there — the seats then read the session's facts as the leg ended with them. Absent outside a Runner's stream: the leg's
258
+ * binding stays until the session's next leg binds its own. */
259
+ runEnd?: Pick<RunEnd, "lend">;
254
260
  }
255
261
  export interface PeerSessionDrain {
256
262
  /**
@@ -447,5 +453,7 @@ export declare function bindPeerLaneDrain(harness: PeerDrainHarness, args: {
447
453
  /** The assistant seat the host handed the leg (`RunInternals.principalInboxAssistant`, as handed): its letter observer rides the
448
454
  * `pullOnly` lane that seat made ({@link PeerSessionDrainOptions.onLetters}). */
449
455
  assistantSeat?: unknown;
456
+ /** The run's end ({@link PeerSessionDrainOptions.runEnd}). */
457
+ runEnd?: Pick<RunEnd, "lend">;
450
458
  }): PeerSessionDrain;
451
459
  export {};
@@ -137,6 +137,133 @@ export function sessionBoxVerdictOf(deps, at) {
137
137
  };
138
138
  }
139
139
  export const PEER_RESUPPLY_CAP = 1;
140
+ function readOnce(read) {
141
+ let read1;
142
+ try {
143
+ read1 = { value: read() };
144
+ }
145
+ catch (e) {
146
+ read1 = { fault: thrownText(e) };
147
+ }
148
+ if ("fault" in read1) {
149
+ const { fault } = read1;
150
+ return () => {
151
+ throw new Error(fault);
152
+ };
153
+ }
154
+ const { value } = read1;
155
+ return () => value;
156
+ }
157
+ function restingSeatFacts(live) {
158
+ const { mailbox, scope, sessionId, occupant, runId, settingLayers, onNotice, onError } = live;
159
+ return { mailbox, scope, sessionId, occupant, runId, settingLayers, onNotice, onError, selfModeClass: readOnce(live.selfModeClass), selfName: readOnce(live.selfName), lastTurnText: live.lastTurnText === undefined ? undefined : readOnce(live.lastTurnText) };
160
+ }
161
+ function readSeatJudgment(f) {
162
+ const layers = f.settingLayers() ?? {};
163
+ return { setting: resolveCrossSessionInboundSetting(layers), principalSetting: resolveCrossSessionInboundSetting(principalInboundLayers(layers)), selfModeClass: f.selfModeClass() };
164
+ }
165
+ function judgeSeatMeta(sessionId, facts, meta) {
166
+ return meta?.fromScope !== undefined
167
+ ? judgeCrossSessionInbound({ setting: facts.principalSetting, selfModeClass: facts.selfModeClass, sender: { fromScope: meta.fromScope } })
168
+ : judgeCrossSessionInbound({ setting: facts.setting, selfModeClass: facts.selfModeClass, sender: { ...(meta?.fromMode !== undefined ? { fromMode: meta.fromMode } : {}), selfSent: meta?.fromSession !== undefined && meta.fromSession.toLowerCase() === sessionId.toLowerCase() } });
169
+ }
170
+ function seatRoute(f) {
171
+ return {
172
+ mailbox: f.mailbox,
173
+ scope: f.scope,
174
+ self: { sessionId: f.sessionId, ...(f.selfName() !== undefined ? { name: f.selfName() } : {}), ...(f.occupant !== undefined ? { occupant: f.occupant } : {}), modeClass: f.selfModeClass },
175
+ ...(f.onError !== undefined ? { onError: f.onError } : {}),
176
+ };
177
+ }
178
+ function seatReceiptAddress(kind, entry) {
179
+ const from = kind === "session" ? entry.peerMeta?.fromSession : undefined;
180
+ return from === undefined ? undefined : { sessionId: from, occupant: entry.peerMeta?.fromOccupant };
181
+ }
182
+ function seatReceipt(f, kind) {
183
+ return async (entry, state, releasedBy) => {
184
+ const to = seatReceiptAddress(kind, entry);
185
+ if (to === undefined)
186
+ return;
187
+ const faults = [];
188
+ const via = {
189
+ ...seatRoute(f),
190
+ onError: (error, ctx) => {
191
+ faults.push(error);
192
+ f.onError?.(error, ctx);
193
+ },
194
+ };
195
+ if (state === "dropped")
196
+ await routePeerDroppedReceipt(via, to, entry.seq);
197
+ else
198
+ await routePeerDeliveryReceipt(via, to, state, entry.seq, releasedBy);
199
+ if (faults.length > 0)
200
+ throw faults[0];
201
+ };
202
+ }
203
+ function discloseSeatDisposition(f, lane, disposition, cause, m, heldNote) {
204
+ deliverEngineNotice(f.onNotice, {
205
+ code: "peer.inbound_disposition",
206
+ message: `cross-session message seq ${m.seq} in ${lane.label} was ${disposition === "held"
207
+ ? `HELD${heldNote !== undefined ? ` (${heldNote})` : lane.kind === "session" ? ` (it entered this session's held queue and STAYS IN THE BOX — the box is that queue's durable seat, so it is not acked until it settles; it is re-judged at every boundary, released or refused with a receipt to the sender, ${isCrossSessionHoldCause(cause) && peerHeldReceiptStateOf(cause) === "held" ? "and expires with a receipt under dialogExpiry" : "and has no expiry deadline: its cause is this session's own settings or state, not a review"})` : " (it entered this session's held queue for the principal inbox and STAYS IN THE BOX until it settles; it is re-judged at every boundary. The sender is another principal: no receipt reaches it from here — the delivery gate's receipt is its record)"}`
208
+ : disposition === "refused"
209
+ ? "refused by this session's crossSessionInbound setting"
210
+ : disposition === "resupply_exhausted"
211
+ ? "settled WITHOUT being read: its frame was summarized away by a compaction, re-supplied once, and summarized away again — the engine has stopped handing it over. The sender was not told; reply-worthy content is GONE from this session's context"
212
+ : disposition === "notice_unrouted"
213
+ ? "settled WITHOUT delivery (a notice-kind record the notice face cannot render)"
214
+ : disposition === "notice_user_only"
215
+ ? "surfaced to the user only (a notice whose sender this session's parity would hold; the model did not read it)"
216
+ : "refused by the inbound admission gate"}: ${cause}`,
217
+ detail: { disposition, cause, seq: m.seq, box: lane.boxHandle, ...(m.peerMeta?.fromSession !== undefined ? { fromSession: m.peerMeta.fromSession } : {}), sessionId: f.sessionId, runId: f.runId },
218
+ });
219
+ }
220
+ function idleTargetSink(f, queues) {
221
+ return {
222
+ notify: (sub, notice) => void routePeerIdleNotice(seatRoute(f), { sessionId: sub.requester, occupant: sub.requesterOccupant }, notice),
223
+ judge: (sub) => judgeSeatMeta(f.sessionId, readSeatJudgment(f), { ...(sub.fromMode !== undefined ? { fromMode: sub.fromMode } : {}), ...(sub.selfSent ? { fromSession: f.sessionId } : {}) }),
224
+ heldCount: () => queues.reduce((n, queue) => n + queue.size(), 0),
225
+ ...(f.lastTurnText !== undefined ? { lastTurnText: f.lastTurnText } : {}),
226
+ };
227
+ }
228
+ function idleRequesterSink(f) {
229
+ return { expired: (o) => void routePeerIdleNotice(seatRoute(f), { sessionId: f.sessionId, occupant: f.occupant }, { kind: "expired", label: o.label }) };
230
+ }
231
+ const seatBinders = new WeakMap();
232
+ function bindPeerSeat(seat, binder, legEnded, config) {
233
+ const holder = seatBinders.get(seat);
234
+ if (legEnded && holder !== undefined && holder !== binder)
235
+ return;
236
+ seatBinders.delete(seat);
237
+ seat.configure(config());
238
+ seatBinders.set(seat, binder);
239
+ }
240
+ function heldQueueSink(f, lane, drainOwner, leg) {
241
+ return {
242
+ judge: (entry) => judgeSeatMeta(f.sessionId, readSeatJudgment(f), entry.peerMeta),
243
+ ...(leg !== undefined ? { inject: leg.inject, canInject: leg.canInject } : {}),
244
+ receipt: seatReceipt(f, lane.kind),
245
+ tellsSender: (entry) => seatReceiptAddress(lane.kind, entry) !== undefined,
246
+ decide: (entry, expect, next) => moveMailboxDecision(f.mailbox, f.scope, lane.boxHandle, entry.seq, expect, next, drainOwner),
247
+ onFault: (entry, e) => f.onError?.(e, { phase: "degraded", sessionId: f.sessionId, classification: `peer-decision-move:${entry.box}#${entry.seq}` }),
248
+ onHeld: (entry, count, cause, reannounce) => {
249
+ if (!reannounce && leg?.disclosedHeld.has(entry.seq) === true)
250
+ return;
251
+ leg?.disclosedHeld.add(entry.seq);
252
+ discloseSeatDisposition(f, lane, "held", cause, entry, reannounce ? `still held; its cause moved to ${cause} (${count} held)` : undefined);
253
+ },
254
+ onSettled: (entry, settlement, reason, count) => {
255
+ if (leg !== undefined && entry.box === lane.boxHandle && settlement !== "delivered" && settlement !== "retired")
256
+ leg.settled(entry.seq, settlement);
257
+ const replyTo = seatReceiptAddress(lane.kind, entry);
258
+ const told = reason !== "decided_elsewhere" && settlement !== "retired" && replyTo !== undefined;
259
+ deliverEngineNotice(f.onNotice, {
260
+ code: "peer.held_settled",
261
+ message: `held cross-session message seq ${entry.seq} left this session's held queue: ${settlement} (${reason}); ${count} still held${settlement === "expired" && reason === "evicted" ? " — the held queue was full, so the oldest entry was expired to make room" : ""}${settlement === "retired" ? (reason === "superseded" ? " — its record is no longer in the box (another consumer settled it); nothing was decided here" : " — no decision was taken: it stays held in the box, and the next drain presents it again") : ""}${reason === "decided_elsewhere" ? " — another consumer of the box decided it first" : ""}. The sender ${told ? "was sent a receipt" : replyTo !== undefined ? "was not sent a receipt from here" : "has no reply address and was not told"}.`,
262
+ detail: { settlement, reason, seq: entry.seq, box: lane.boxHandle, ...(entry.peerMeta?.fromSession !== undefined ? { fromSession: entry.peerMeta.fromSession } : {}), heldCount: count, sessionId: f.sessionId, runId: f.runId },
263
+ });
264
+ },
265
+ };
266
+ }
140
267
  export function createPeerSessionDrain(opts) {
141
268
  const { mailbox, sessionId, runId, scope } = opts;
142
269
  const storedSessionAddress = (fromSession) => fromSession !== undefined && isPeerSessionId(fromSession) ? peerSessionBoxHandle(fromSession) : undefined;
@@ -171,34 +298,11 @@ export function createPeerSessionDrain(opts) {
171
298
  let noticeRound = 0;
172
299
  let currentRound;
173
300
  const idleMachine = peerIdleMachineFor(scope, sessionId, { ...clockOpt, ...occupantOpt });
174
- const disclose = (lane, disposition, cause, m, heldNote) => deliverEngineNotice(opts.onNotice, {
175
- code: "peer.inbound_disposition",
176
- message: `cross-session message seq ${m.seq} in ${lane.label} was ${disposition === "held"
177
- ? `HELD${heldNote !== undefined ? ` (${heldNote})` : lane.kind === "session" ? ` (it entered this session's held queue and STAYS IN THE BOX \u2014 the box is that queue's durable seat, so it is not acked until it settles; it is re-judged at every boundary, released or refused with a receipt to the sender, ${isCrossSessionHoldCause(cause) && peerHeldReceiptStateOf(cause) === "held" ? "and expires with a receipt under dialogExpiry" : "and has no expiry deadline: its cause is this session's own settings or state, not a review"})` : " (it entered this session's held queue for the principal inbox and STAYS IN THE BOX until it settles; it is re-judged at every boundary. The sender is another principal: no receipt reaches it from here \u2014 the delivery gate's receipt is its record)"}`
178
- : disposition === "refused"
179
- ? "refused by this session's crossSessionInbound setting"
180
- : disposition === "resupply_exhausted"
181
- ? "settled WITHOUT being read: its frame was summarized away by a compaction, re-supplied once, and summarized away again \u2014 the engine has stopped handing it over. The sender was not told; reply-worthy content is GONE from this session's context"
182
- : disposition === "notice_unrouted"
183
- ? "settled WITHOUT delivery (a notice-kind record the notice face cannot render)"
184
- : disposition === "notice_user_only"
185
- ? "surfaced to the user only (a notice whose sender this session's parity would hold; the model did not read it)"
186
- : "refused by the inbound admission gate"}: ${cause}`,
187
- detail: { disposition, cause, seq: m.seq, box: lane.boxHandle, ...(m.peerMeta?.fromSession !== undefined ? { fromSession: m.peerMeta.fromSession } : {}), sessionId, runId },
188
- });
189
- const readFacts = () => {
190
- const layers = opts.settingLayers() ?? {};
191
- return { setting: resolveCrossSessionInboundSetting(layers), principalSetting: resolveCrossSessionInboundSetting(principalInboundLayers(layers)), selfModeClass: opts.selfModeClass() };
192
- };
193
- const judgeMeta = (facts, meta) => meta?.fromScope !== undefined
194
- ? judgeCrossSessionInbound({ setting: facts.principalSetting, selfModeClass: facts.selfModeClass, sender: { fromScope: meta.fromScope } })
195
- : judgeCrossSessionInbound({ setting: facts.setting, selfModeClass: facts.selfModeClass, sender: { ...(meta?.fromMode !== undefined ? { fromMode: meta.fromMode } : {}), selfSent: meta?.fromSession !== undefined && meta.fromSession.toLowerCase() === sessionId.toLowerCase() } });
196
- const route = () => ({
197
- mailbox,
198
- scope,
199
- self: { sessionId, ...(opts.selfName?.() !== undefined ? { name: opts.selfName() } : {}), ...occupantOpt, modeClass: opts.selfModeClass },
200
- ...(opts.onError !== undefined ? { onError: opts.onError } : {}),
201
- });
301
+ const seat = { mailbox, scope, sessionId, occupant: opts.occupant, runId, settingLayers: opts.settingLayers, selfModeClass: opts.selfModeClass, selfName: () => opts.selfName?.(), lastTurnText: opts.lastTurnText, onNotice: opts.onNotice, onError: opts.onError };
302
+ const disclose = (lane, disposition, cause, m, heldNote) => discloseSeatDisposition(seat, lane, disposition, cause, m, heldNote);
303
+ const readFacts = () => readSeatJudgment(seat);
304
+ const judgeMeta = (facts, meta) => judgeSeatMeta(sessionId, facts, meta);
305
+ const route = () => seatRoute(seat);
202
306
  const buildPeerMessagePayload = (lane, m) => {
203
307
  const { boxHandle } = lane;
204
308
  const meta = m.peerMeta;
@@ -232,29 +336,7 @@ export function createPeerSessionDrain(opts) {
232
336
  crossSessionNotice: { kind, text },
233
337
  _sema_provenance: { kind: "cross_session_notice", from: encodePeerAddress(storedSessionAddress(m.peerMeta?.fromSession) ?? (m.from ?? "unknown")), taskId: boxHandle, seq: m.seq, ...(m.peerMeta !== undefined ? { peerMeta: { ...m.peerMeta } } : {}) },
234
338
  });
235
- const receiptAddress = (lane, entry) => {
236
- const from = lane.kind === "session" ? entry.peerMeta?.fromSession : undefined;
237
- return from === undefined ? undefined : { sessionId: from, occupant: entry.peerMeta?.fromOccupant };
238
- };
239
- const receipt = (lane) => async (entry, state, releasedBy) => {
240
- const to = receiptAddress(lane, entry);
241
- if (to === undefined)
242
- return;
243
- const faults = [];
244
- const via = {
245
- ...route(),
246
- onError: (error, ctx) => {
247
- faults.push(error);
248
- opts.onError?.(error, ctx);
249
- },
250
- };
251
- if (state === "dropped")
252
- await routePeerDroppedReceipt(via, to, entry.seq);
253
- else
254
- await routePeerDeliveryReceipt(via, to, state, entry.seq, releasedBy);
255
- if (faults.length > 0)
256
- throw faults[0];
257
- };
339
+ const receiptAddress = (lane, entry) => seatReceiptAddress(lane.kind, entry);
258
340
  const settleConsumed = (lane, seq, payload, by, reason) => {
259
341
  lane.ledger.set(seq, { kind: "terminal", why: "consumed" });
260
342
  const peerMeta = payload._sema_provenance?.kind === "cross_session_message" ? payload._sema_provenance.peerMeta : undefined;
@@ -262,63 +344,43 @@ export function createPeerSessionDrain(opts) {
262
344
  if (to !== undefined)
263
345
  void routePeerDeliveryReceipt(route(), to, "refused", seq, by === "engine" ? "the receiving engine (it could not judge the message)" : `extension ${by} of that session: ${reason}`);
264
346
  };
265
- const heldSink = (lane, live) => ({
266
- judge: (entry) => judgeMeta(readFacts(), entry.peerMeta),
267
- ...(live
268
- ? {
269
- inject: async (entry) => {
270
- if (currentRound === undefined || !currentRound.holds(lane))
271
- return "deferred";
272
- const payload = buildPeerMessagePayload(lane, entry);
273
- if (currentRound.out !== undefined && opts.receive?.listens() === true) {
274
- currentRound.batch.push({ lane, payload, priority: "next", urgent: false, seq: entry.seq, attempt: 1, source: entry });
275
- return undefined;
276
- }
277
- if (currentRound.out === undefined && payload._sema_provenance?.peerMeta?.fromScope !== undefined && opts.markExternalContent !== undefined) {
278
- const round = currentRound;
279
- try {
280
- await opts.markExternalContent(`a letter from another principal (cross-principal message seq ${entry.seq} in ${lane.boxHandle}) was delivered into this session`);
281
- }
282
- catch (e) {
283
- opts.onError?.(e, { phase: "degraded", sessionId, classification: "peer-external-mark" });
284
- return "deferred";
285
- }
286
- if (currentRound !== round || !round.holds(lane))
287
- return "deferred";
288
- }
289
- if (currentRound.deliver(payload, "next") === "deferred")
290
- return "deferred";
291
- noteDelivered(lane, entry.seq, 1, payload, entry, currentRound.carrier);
292
- return undefined;
293
- },
294
- canInject: () => currentRound !== undefined && currentRound.holds(lane) && !currentRound.spent,
347
+ const heldLegSeats = (lane) => ({
348
+ inject: async (entry) => {
349
+ if (currentRound === undefined || !currentRound.holds(lane))
350
+ return "deferred";
351
+ const payload = buildPeerMessagePayload(lane, entry);
352
+ if (currentRound.out !== undefined && opts.receive?.listens() === true) {
353
+ currentRound.batch.push({ lane, payload, priority: "next", urgent: false, seq: entry.seq, attempt: 1, source: entry });
354
+ return undefined;
295
355
  }
296
- : {}),
297
- receipt: receipt(lane),
298
- tellsSender: (entry) => receiptAddress(lane, entry) !== undefined,
299
- decide: (entry, expect, next) => moveMailboxDecision(mailbox, scope, lane.boxHandle, entry.seq, expect, next, drainOwner),
300
- onFault: (entry, e) => opts.onError?.(e, { phase: "degraded", sessionId, classification: `peer-decision-move:${entry.box}#${entry.seq}` }),
301
- onHeld: (entry, count, cause, reannounce) => {
302
- if (!reannounce && lane.disclosedHeld.has(entry.seq))
303
- return;
304
- lane.disclosedHeld.add(entry.seq);
305
- disclose(lane, "held", cause, entry, reannounce ? `still held; its cause moved to ${cause} (${count} held)` : undefined);
356
+ if (currentRound.out === undefined && payload._sema_provenance?.peerMeta?.fromScope !== undefined && opts.markExternalContent !== undefined) {
357
+ const round = currentRound;
358
+ try {
359
+ await opts.markExternalContent(`a letter from another principal (cross-principal message seq ${entry.seq} in ${lane.boxHandle}) was delivered into this session`);
360
+ }
361
+ catch (e) {
362
+ opts.onError?.(e, { phase: "degraded", sessionId, classification: "peer-external-mark" });
363
+ return "deferred";
364
+ }
365
+ if (currentRound !== round || !round.holds(lane))
366
+ return "deferred";
367
+ }
368
+ if (currentRound.deliver(payload, "next") === "deferred")
369
+ return "deferred";
370
+ noteDelivered(lane, entry.seq, 1, payload, entry, currentRound.carrier);
371
+ return undefined;
306
372
  },
307
- onSettled: (entry, settlement, reason, count) => {
308
- if (entry.box === lane.boxHandle && settlement !== "delivered" && settlement !== "retired")
309
- lane.ledger.set(entry.seq, { kind: "terminal", why: `held_${settlement}` });
310
- const replyTo = receiptAddress(lane, entry);
311
- const told = reason !== "decided_elsewhere" && settlement !== "retired" && replyTo !== undefined;
312
- deliverEngineNotice(opts.onNotice, {
313
- code: "peer.held_settled",
314
- message: `held cross-session message seq ${entry.seq} left this session's held queue: ${settlement} (${reason}); ${count} still held${settlement === "expired" && reason === "evicted" ? " — the held queue was full, so the oldest entry was expired to make room" : ""}${settlement === "retired" ? (reason === "superseded" ? " — its record is no longer in the box (another consumer settled it); nothing was decided here" : " — no decision was taken: it stays held in the box, and the next drain presents it again") : ""}${reason === "decided_elsewhere" ? " — another consumer of the box decided it first" : ""}. The sender ${told ? "was sent a receipt" : replyTo !== undefined ? "was not sent a receipt from here" : "has no reply address and was not told"}.`,
315
- detail: { settlement, reason, seq: entry.seq, box: lane.boxHandle, ...(entry.peerMeta?.fromSession !== undefined ? { fromSession: entry.peerMeta.fromSession } : {}), heldCount: count, sessionId, runId },
316
- });
373
+ canInject: () => currentRound !== undefined && currentRound.holds(lane) && !currentRound.spent,
374
+ settled: (seq, settlement) => {
375
+ lane.ledger.set(seq, { kind: "terminal", why: `held_${settlement}` });
317
376
  },
377
+ disclosedHeld: lane.disclosedHeld,
318
378
  });
319
379
  let dialogExpiryMs = resolveCrossSessionDialogExpiry(undefined).ms;
320
380
  let dialogExpiryAnnounced = false;
321
- const bindHeld = (lane, live) => {
381
+ const binder = Symbol("peer-seat-binder");
382
+ let resting;
383
+ const bindHeld = (lane) => {
322
384
  try {
323
385
  const resolved = resolveCrossSessionDialogExpiry(opts.dialogExpiry?.());
324
386
  dialogExpiryMs = resolved.ms;
@@ -330,19 +392,22 @@ export function createPeerSessionDrain(opts) {
330
392
  catch (e) {
331
393
  opts.onError?.(e, { phase: "degraded", sessionId, classification: "peer-dialog-expiry" });
332
394
  }
333
- lane.held.configure({ sink: heldSink(lane, live), dialogExpiryMs });
395
+ bindPeerSeat(lane.held, binder, resting !== undefined, () => ({ sink: heldSinkOf(lane), dialogExpiryMs }));
334
396
  };
397
+ const heldSinkOf = (lane) => (resting === undefined ? heldQueueSink(seat, lane, drainOwner, heldLegSeats(lane)) : heldQueueSink(resting, { kind: lane.kind, boxHandle: lane.boxHandle, label: lane.label }, drainOwner));
335
398
  for (const lane of lanes)
336
- bindHeld(lane, true);
337
- idleMachine.target.configure({
338
- notify: (sub, notice) => void routePeerIdleNotice(route(), { sessionId: sub.requester, occupant: sub.requesterOccupant }, notice),
339
- judge: (sub) => judgeMeta(readFacts(), { ...(sub.fromMode !== undefined ? { fromMode: sub.fromMode } : {}), ...(sub.selfSent ? { fromSession: sessionId } : {}) }),
340
- heldCount: () => lanes.reduce((n, lane) => n + lane.held.size(), 0),
341
- ...(opts.lastTurnText !== undefined ? { lastTurnText: opts.lastTurnText } : {}),
342
- });
343
- idleMachine.requester.configure({
344
- expired: (o) => void routePeerIdleNotice(route(), { sessionId, occupant: opts.occupant }, { kind: "expired", label: o.label }),
345
- });
399
+ bindHeld(lane);
400
+ const heldQueues = lanes.map((lane) => lane.held);
401
+ const bindTarget = () => bindPeerSeat(idleMachine.target, binder, resting !== undefined, () => idleTargetSink(resting ?? seat, heldQueues));
402
+ const bindRequester = () => bindPeerSeat(idleMachine.requester, binder, resting !== undefined, () => idleRequesterSink(resting ?? seat));
403
+ bindTarget();
404
+ bindRequester();
405
+ for (const bind of [bindTarget, bindRequester, ...lanes.map((lane) => () => bindPeerSeat(lane.held, binder, true, () => ({ sink: heldSinkOf(lane), dialogExpiryMs })))]) {
406
+ opts.runEnd?.lend(() => {
407
+ resting ??= restingSeatFacts(seat);
408
+ bind();
409
+ });
410
+ }
346
411
  const reconcileHeld = async (lane, lease) => {
347
412
  const live = lease.messages.filter((m) => lane.ackedUpTo === undefined || m.seq > lane.ackedUpTo);
348
413
  lane.held.reconcile(new Map(live.map((m) => [m.seq, m.decision])));
@@ -735,7 +800,7 @@ export function createPeerSessionDrain(opts) {
735
800
  return { pending: 0, urgent: 0 };
736
801
  round.lease(leased.map((c) => c.lane));
737
802
  for (const { lane, lease } of leased) {
738
- bindHeld(lane, true);
803
+ bindHeld(lane);
739
804
  await reconcileHeld(lane, lease);
740
805
  await lane.held.rejudge();
741
806
  }
@@ -1090,6 +1155,9 @@ export function mountListAgents(args) {
1090
1155
  ...(args.readSeats ?? {}),
1091
1156
  });
1092
1157
  }
1158
+ function crossSessionInboundOf(deps) {
1159
+ return () => (typeof deps.crossSessionInbound === "function" ? deps.crossSessionInbound() : deps.crossSessionInbound);
1160
+ }
1093
1161
  export function bindPeerSessionDrain(harness, opts) {
1094
1162
  const drain = createPeerSessionDrain(opts);
1095
1163
  const round = async () => {
@@ -1148,8 +1216,9 @@ export function bindPeerLaneDrain(harness, args) {
1148
1216
  inject: args.inject,
1149
1217
  ...(deps.peerLane !== undefined ? { lane: deps.peerLane } : {}),
1150
1218
  ownTokens: args.ownTokens,
1151
- settingLayers: () => (typeof deps.crossSessionInbound === "function" ? deps.crossSessionInbound() : deps.crossSessionInbound),
1219
+ settingLayers: crossSessionInboundOf(deps),
1152
1220
  selfModeClass: () => peerModeClassOf(args.refs),
1221
+ ...(args.runEnd !== undefined ? { runEnd: args.runEnd } : {}),
1153
1222
  dialogExpiry: () => (typeof deps.crossSessionDialogExpiry === "function" ? deps.crossSessionDialogExpiry() : deps.crossSessionDialogExpiry),
1154
1223
  selfName: () => rowName ?? args.selfName?.(),
1155
1224
  warmup: lookupRowName,
@@ -1,19 +1,22 @@
1
1
  /**
2
- * The run's end: one per run, and the one release of every listener the run hangs on a signal it does not own.
2
+ * The run's end: one per run, and the one place a run takes back everything it handed to something that outlives it.
3
3
  *
4
- * A run reaches signals that can outlive it — the caller's `TaskSpec.signal` (a host may keep one controller for many runs, or
5
- * never abort it), the caller-stop gate composed from it, a parent leg's tool signal a child run is handed. A listener left on
6
- * such a signal stays reachable for as long as the signal does, and so does everything it closes over (the run's prepared
7
- * state, its conversation, its images). A composed signal (`AbortSignal.any`) or a timeout signal that carries an abort
8
- * listener is held by the runtime itself until it aborts, so dropping the signal frees nothing either.
4
+ * A run reaches holders that can outlive it — the caller's `TaskSpec.signal` (a host may keep one controller for many runs, or
5
+ * never abort it), the caller-stop gate composed from it, a parent leg's tool signal a child run is handed, and the process-level
6
+ * seats of its session (the idle machine, the held queue of each box the leg drains), which live as long as the process. What the
7
+ * run leaves on such a holder — a listener, a sink — stays reachable for as long as the holder does, and so does everything it
8
+ * closes over (the run's prepared state, its conversation, its tool table, its images). A composed signal (`AbortSignal.any`) or a
9
+ * timeout signal that carries an abort listener is held by the runtime itself until it aborts, so dropping the signal frees nothing
10
+ * either.
9
11
  *
10
- * The rule: the run listens to such a signal only through {@link RunEnd.listen}. The stream leg mints the end when the run
11
- * starts and ends it once the run has settled — its result published by the run body, or by the failure backstop after a
12
- * throw — so every listener is taken off whether or not its signal ever fired, and the host owes no abort after the run. A
13
- * listener whose job ends sooner takes itself off sooner (the release `listen` returns); none outlives the run. Ending the run
14
- * fires nothing and answers nothing: the caller-stop gate still answers "did the caller ask this run to stop?".
12
+ * The rule: the run hands such a thing over only through its end — {@link RunEnd.listen} for a listener on a signal it does not
13
+ * own, {@link RunEnd.lend} for anything else, naming how it is taken back. The stream leg mints the end when the run starts and
14
+ * ends it once the run has settled — its result published by the run body, or by the failure backstop after a throw — so every
15
+ * hand-over is taken back whether or not the run reached its loop, and the host owes nothing after the run. A hand-over whose job
16
+ * ends sooner is taken back sooner (the release each verb returns); none outlives the run. Ending the run fires nothing and
17
+ * answers nothing: the caller-stop gate still answers "did the caller ask this run to stop?".
15
18
  *
16
- * The release is an explicit `removeEventListener`, not the `{ signal }` listener option: the runtime keeps the latest
19
+ * A listener's release is an explicit `removeEventListener`, not the `{ signal }` listener option: the runtime keeps the latest
17
20
  * listener hung with that option reachable through its target for as long as the target lives, so on a host's long-lived
18
21
  * signal it would keep the last run reachable.
19
22
  */
@@ -23,7 +26,17 @@ export interface RunEnd {
23
26
  * the run ended. A signal that already fired is the caller's to read: an abort is not replayed to a late listener.
24
27
  */
25
28
  listen(signal: AbortSignal, onAbort: () => void): () => void;
26
- /** The run ended: every listener still hung through `listen` is taken off; idempotent. */
29
+ /**
30
+ * Something was handed to a holder that outlives the run: `takeBack` takes it back, once — at the run's end, or sooner through
31
+ * the return (idempotent). Lent after the run ended, it is taken back at once. `takeBack` must not throw; the end runs every
32
+ * take-back before it reports one that did.
33
+ */
34
+ lend(takeBack: () => void): () => void;
35
+ /** The run ended: every hand-over not yet taken back is taken back; idempotent. Throws, once every take-back ran, when one threw. */
27
36
  end(): void;
28
37
  }
38
+ /** The stream leg's end of the run: `runEnd` ends once `settled` settles, either way. A take-back that threw (reported by
39
+ * {@link RunEnd.end} once every other one ran) goes to `onError`, not to the process as an unhandled rejection; the run's result
40
+ * stands. `onError` must not throw: the stream leg hands the deployment's error sink, which the Runner guards where it takes it. */
41
+ export declare function endOnSettle(runEnd: RunEnd, settled: Promise<unknown>, onError: (err: unknown) => void): void;
29
42
  export declare function mintRunEnd(): RunEnd;
@@ -1,22 +1,53 @@
1
+ export function endOnSettle(runEnd, settled, onError) {
2
+ const end = () => {
3
+ try {
4
+ runEnd.end();
5
+ }
6
+ catch (err) {
7
+ onError(err);
8
+ }
9
+ };
10
+ void settled.then(end, end);
11
+ }
1
12
  export function mintRunEnd() {
2
- let hung = new Set();
13
+ let lent = new Set();
14
+ const lend = (takeBack) => {
15
+ let done = false;
16
+ const release = () => {
17
+ if (done)
18
+ return;
19
+ done = true;
20
+ lent?.delete(release);
21
+ takeBack();
22
+ };
23
+ if (lent === undefined)
24
+ release();
25
+ else
26
+ lent.add(release);
27
+ return release;
28
+ };
3
29
  return {
4
30
  listen(signal, onAbort) {
5
- if (hung === undefined)
31
+ if (lent === undefined)
6
32
  return () => undefined;
7
33
  signal.addEventListener("abort", onAbort, { once: true });
8
- const release = () => {
9
- signal.removeEventListener("abort", onAbort);
10
- hung?.delete(release);
11
- };
12
- hung.add(release);
13
- return release;
34
+ return lend(() => signal.removeEventListener("abort", onAbort));
14
35
  },
36
+ lend,
15
37
  end() {
16
- const all = hung;
17
- hung = undefined;
18
- for (const release of all ?? [])
19
- release();
38
+ const all = lent;
39
+ lent = undefined;
40
+ const faults = [];
41
+ for (const release of all ?? []) {
42
+ try {
43
+ release();
44
+ }
45
+ catch (e) {
46
+ faults.push(e);
47
+ }
48
+ }
49
+ if (faults.length > 0)
50
+ throw faults.length === 1 ? faults[0] : new AggregateError(faults, "RunEnd.end: a take-back threw");
20
51
  },
21
52
  };
22
53
  }
@@ -906,7 +906,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
906
906
  const autoStripNotice = createAutoStripNotice({ onNotice: deps.onNotice, legNotice, runId, announced: { announcedListingsRef, frameReceipts } });
907
907
  const { basePolicyForResumeEdit, denyNarrowingPolicy, skillGrantLane, allowEntryLanes, policyLayers, effectivePolicy, inheritedUnavailableAsks, deferredAskIdentities, inheritedAskGrants, riskAxesOf, ruleOffersOf, grantBindingOf, permissionRuleLane, permissionRuleGateLane, ruleLaneFacts, permissionRuleOrgLane, storedRuleWholeToolRefusals, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, foldAskClasses, ancestorSandboxAdmissions, ancestorArbitrations, inheritedInstallations } = await preparePolicyChain({ hostFloor: doors.hostFloor, spec, deps, sessionId, runId, hostTaskId, approvalWords, engineText, taskRootFinal, additionalRootsCanonical, writeLocation, executionEnv, lockedPreflight: installedPreflight, pathRuleAnchors: { leg: legAnchors, chainTop }, headLeads, tools, harnessTools, selector: toolFaceSnapshot.selector, toolEffects, egressTools, irreversibilityTier, axisExplicitNegatives, shellGatedTools, toolMarkSources, envHandToolNames, handsCwdRef, readDenyMatcher, personRows, questionToolMounted, runtimeCaps, approvalParkNotResumable, notResumableSays, forcedGateNotResumable, inheritedAncestorRules, ancestorSessionRulesRef, inheritedParentConstraints, seedInheritedGate, skillGrants, skillSpecs, allowedToolTables, frozenOnAsk, hookEnvSource, notifyOwnHookCrash, modBus: legMods.bus, ownModChain, autoModeDecider: () => autoModeDeciderRef.current, whileClassifying: toolOccurrences.whileClassifying, readFace: () => resolvedReadFace, permissionMode, autoStripNotice, toolRosterDeltas: rosterSeat, stopForDenialLimit, askSource, abortController, now, ownSessionRulesRef });
908
908
  toolTableViewRef.current = createToolTableView({ policy: effectivePolicy, stored: { wholeToolRefusals: storedRuleWholeToolRefusals }, roster: rosterSeat, fpRef, turnSnapshotRef });
909
- const { onAsk, preToolContexts, blockedToolCalls, batchHaltRef, blockedTracked, suspendTargetGap, durableSuspendInfraReady, suspendLaneGap, resourceSuspendEligible, usageGovernance, durableApproval, wiringManifest, writeProtection, parkLaneArmed, gateMachineryActive, hookIdentity, hookEnvFace, sessionBoxBound } = prepareWiringManifest({ spec, deps, askSeat: doors.askSeat, hostFloorPosture: doors.hostFloor?.posture, crossBoundaryStationEngaged: crossBoundary.stationEngaged, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus: legMods.bus, standingModBus: legMods.standing, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard: advertisedWritableDirs?.planFile !== undefined ? { ...legWriteGuard, exemptFiles: [advertisedWritableDirs.planFile] } : legWriteGuard, mcp, irreversibleTools, egressTools, shellReadStationArmed: handsReadFace.shellReadStationArmed, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, receiveSeat, harness, pausedRef, liveInheritedGate, delegation, approvalParkNotResumable, forcedGateNotResumable, toolRoster, toolPlan, readDenyBuiltinTiersActive: handsReadFace.readDenyBuiltinTiersActive, lspManagerWired, lspDiagnosticsLive: lspDiagnostics !== undefined, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive: ownSessionRulesRef.current !== undefined, sessionBox, sessionAddress, checkpointScope, memoryPollution: () => memoryEngineSession?.pollution, advisorFact: advisor.manifest, runOrigin: doors.runOrigin, commandSandboxFact: commandSandboxRun.state === "unavailable" ? { state: "unavailable", reason: commandSandboxRun.reason } : { state: commandSandboxRun.state } });
909
+ const { onAsk, preToolContexts, blockedToolCalls, batchHaltRef, blockedTracked, suspendTargetGap, durableSuspendInfraReady, suspendLaneGap, resourceSuspendEligible, usageGovernance, durableApproval, wiringManifest, writeProtection, parkLaneArmed, gateMachineryActive, hookIdentity, hookEnvFace, sessionBoxBound } = prepareWiringManifest({ spec, deps, askSeat: doors.askSeat, hostFloorPosture: doors.hostFloor?.posture, crossBoundaryStationEngaged: crossBoundary.stationEngaged, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus: legMods.bus, standingModBus: legMods.standing, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard: advertisedWritableDirs?.planFile !== undefined ? { ...legWriteGuard, exemptFiles: [advertisedWritableDirs.planFile] } : legWriteGuard, mcp, irreversibleTools, egressTools, shellReadStationArmed: handsReadFace.shellReadStationArmed, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, receiveSeat, harness, pausedRef, liveInheritedGate, delegation, approvalParkNotResumable, forcedGateNotResumable, toolRoster, toolPlan, readDenyBuiltinTiersActive: handsReadFace.readDenyBuiltinTiersActive, lspManagerWired, lspDiagnosticsLive: lspDiagnostics !== undefined, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive: ownSessionRulesRef.current !== undefined, sessionBox, sessionAddress, runEnd, checkpointScope, memoryPollution: () => memoryEngineSession?.pollution, advisorFact: advisor.manifest, runOrigin: doors.runOrigin, commandSandboxFact: commandSandboxRun.state === "unavailable" ? { state: "unavailable", reason: commandSandboxRun.reason } : { state: commandSandboxRun.state } });
910
910
  refuseDisplayWithoutSentences(legMods.bus, legEventsOf(hookIdentity));
911
911
  agentStationsRef.current = createAgentStations({ bus: legMods.bus, identity: hookIdentity, permissionMode: () => permissionMode.observed });
912
912
  sendStationRef.current = createSessionSendStation({ bus: legMods.bus, identity: hookIdentity });
@@ -170,6 +170,7 @@ export interface PrepareWiringManifestInput {
170
170
  sessionBox: SessionBoxBinding | undefined;
171
171
  /** borrowed-readonly — the leg's own session address (`sessionAddressOf`): the box is drained for it. */
172
172
  sessionAddress: SessionAddress;
173
+ /** borrowed-mutable — the run's end: the drain hands what it binds the session's process-level seats through it (absent outside a stream). */ runEnd?: import("./end-of-run.js").RunEnd | undefined;
173
174
  /** borrowed-readonly, read late — the memory session's one-way pollution face (absent with no memory session). The drain marks
174
175
  * it when it INJECTS a letter from another principal (the injection path; the tool path is accounted by `ReadInbox`'s class). */
175
176
  memoryPollution?: () => Pick<NonNullable<Prepared["memoryEngineSession"]>["pollution"], "markPolluted"> | undefined;
@@ -158,7 +158,7 @@ export function durableSuspendInfraGaps(facts) {
158
158
  return gaps;
159
159
  }
160
160
  export function prepareWiringManifest(input) {
161
- const { spec, deps, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus, standingModBus, checkpointScope, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard, mcp, irreversibleTools, egressTools, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, receiveSeat, sessionBox, sessionAddress, harness, pausedRef, askSeat, liveInheritedGate, delegation, approvalParkNotResumable, forcedGateNotResumable, toolRoster, toolPlan, readDenyBuiltinTiersActive, lspManagerWired, shellReadStationArmed, crossBoundaryStationEngaged, lspDiagnosticsLive, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive, memoryPollution, advisorFact, hostFloorPosture, runOrigin, commandSandboxFact } = input;
161
+ const { spec, deps, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus, standingModBus, checkpointScope, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard, mcp, irreversibleTools, egressTools, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, receiveSeat, sessionBox, sessionAddress, runEnd, harness, pausedRef, askSeat, liveInheritedGate, delegation, approvalParkNotResumable, forcedGateNotResumable, toolRoster, toolPlan, readDenyBuiltinTiersActive, lspManagerWired, shellReadStationArmed, crossBoundaryStationEngaged, lspDiagnosticsLive, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive, memoryPollution, advisorFact, hostFloorPosture, runOrigin, commandSandboxFact } = input;
162
162
  const onAsk = askSeat.value;
163
163
  const handWriteTools = toolRoster.entries.filter((e) => e.mountedBy === "hands" && (e.effect === "write" || e.effect === "idempotent")).map((e) => e.name);
164
164
  const hasEffectAwareGate = policyLayers.length > 0 || chainJudges(standingModBus);
@@ -286,7 +286,7 @@ export function prepareWiringManifest(input) {
286
286
  deps, lanes: drainLanes, assistantSeat: internals.principalInboxAssistant,
287
287
  address: sessionAddress,
288
288
  sessions,
289
- runId,
289
+ runId, ...(runEnd !== undefined ? { runEnd } : {}),
290
290
  scope: taskScope,
291
291
  inject: internals.onTaskNotification,
292
292
  ownTokens: () => internals?.peerSelfRef?.current.ownTokens ?? [],
@@ -35,7 +35,7 @@ import { ToolDetachHub } from "../tool-detach.js";
35
35
  import { assertContextSettingsValue, assertContextSettingsWords, contextOverlayFor } from "../context-settings.js";
36
36
  import { createRunState } from "./initial-run-state.js";
37
37
  import { SessionWriteLedger } from "./session-write-ledger.js";
38
- import { mintRunEnd } from "./end-of-run.js";
38
+ import { endOnSettle, mintRunEnd } from "./end-of-run.js";
39
39
  import { teardownLegBudget } from "./teardown-bounded.js";
40
40
  import { emitSettled, reconciledEnd } from "./tool-end-body.js";
41
41
  import { answerFaceForRedeemedCall } from "./decide-continuation.js";
@@ -408,7 +408,7 @@ export class Runner {
408
408
  }).onRunRejected);
409
409
  void settled.then(() => acceptedSteerInputs.clear(), () => acceptedSteerInputs.clear());
410
410
  void settled.then(() => declarationHold.release(), () => declarationHold.release());
411
- void settled.then(() => runEnd.end(), () => runEnd.end());
411
+ endOnSettle(runEnd, settled, (err) => this.deps.onError?.(err, { phase: "degraded", sessionId: taskIdRef.sessionId ?? "(pre-session)", classification: "run-end-take-back" }));
412
412
  const { reapSuspended } = streamReap({
413
413
  live, runner: this.depsSeat,
414
414
  locallyClaimedTokens: this.locallyClaimedTokens, parentConstraintRegistry: this.parentConstraintRegistry, suspendedEnvReaps: this.suspendedEnvReaps,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sema-agent/core",
3
- "version": "7.68.4",
3
+ "version": "7.68.5",
4
4
  "description": "Stateless, task-oriented AI agent core",
5
5
  "type": "module",
6
6
  "license": "BUSL-1.1",
@@ -133,7 +133,7 @@
133
133
  "dependencies": {
134
134
  "@modelcontextprotocol/client": "2.4.0",
135
135
  "@modelcontextprotocol/core": "2.4.0",
136
- "@sema-agent/primitives": "7.68.4",
136
+ "@sema-agent/primitives": "7.68.5",
137
137
  "typebox": "1.1.39",
138
138
  "undici": "7.30.2"
139
139
  },
@@ -0,0 +1,39 @@
1
+ {
2
+ "repo": "core",
3
+ "package": "@sema-agent/core-stores-sql",
4
+ "version": "7.68.5",
5
+ "from": "e0b2b38e123d0cdeb43e9a86547e590947893b9a",
6
+ "to": "v7.68.5",
7
+ "added": [],
8
+ "removed": [],
9
+ "changed": [],
10
+ "subpaths": [],
11
+ "subpathsUnread": [
12
+ "from",
13
+ "to"
14
+ ],
15
+ "narrowed": [],
16
+ "faces": {
17
+ "open": [],
18
+ "source": null
19
+ },
20
+ "closedSetMembers": [],
21
+ "closedSetsUnreadable": [],
22
+ "typeKeys": [],
23
+ "typeKeysUnreadableArms": [],
24
+ "typeKeysFlattenedCount": 3,
25
+ "signatures": [],
26
+ "versionLiterals": [],
27
+ "declarationMoves": [],
28
+ "mintMoves": [],
29
+ "criteriaObserves": [],
30
+ "consumersHint": {
31
+ "cli": [],
32
+ "server": [],
33
+ "sdk": [],
34
+ "note": "scanned cli@a51393fdd server@3bad3612e sdk@3724afe — a name listed is MENTIONED there today, which is evidence of consumption, not proof of it"
35
+ },
36
+ "breakingCount": 0,
37
+ "breakingItems": [],
38
+ "toResolvedAt": "8aa5c0cd4702103b499194011931ebfc28a00f18"
39
+ }
@@ -0,0 +1,141 @@
1
+ {
2
+ "repo": "core",
3
+ "version": "7.68.5",
4
+ "from": "e0b2b38e123d0cdeb43e9a86547e590947893b9a",
5
+ "to": "v7.68.5",
6
+ "added": [],
7
+ "removed": [],
8
+ "changed": [],
9
+ "subpaths": [],
10
+ "narrowed": [],
11
+ "faces": {
12
+ "open": [
13
+ "TRACE_EVENT_KINDS",
14
+ "TraceEvent"
15
+ ],
16
+ "source": "src/core/contract-faces.ts"
17
+ },
18
+ "closedSetMembers": [],
19
+ "closedSetsUnreadable": [],
20
+ "typeKeys": [],
21
+ "typeKeysUnreadableArms": [],
22
+ "typeKeysFlattenedCount": 305,
23
+ "signatures": [],
24
+ "versionLiterals": [],
25
+ "declarationMoves": [],
26
+ "mintMoves": [],
27
+ "criteriaObserves": [
28
+ {
29
+ "kind": "engineNoticeCode",
30
+ "name": "peer.held_settled",
31
+ "assertions": [
32
+ "G3.a"
33
+ ]
34
+ },
35
+ {
36
+ "kind": "typeMember",
37
+ "name": "PeerHeldQueue.settle",
38
+ "assertions": [
39
+ "G3.a"
40
+ ]
41
+ },
42
+ {
43
+ "kind": "typeMember",
44
+ "name": "PeerIdleMachine.requester",
45
+ "assertions": [
46
+ "G2.b"
47
+ ]
48
+ },
49
+ {
50
+ "kind": "typeMember",
51
+ "name": "PeerIdleMachine.target",
52
+ "assertions": [
53
+ "G2.a",
54
+ "G5.a"
55
+ ]
56
+ },
57
+ {
58
+ "kind": "typeMember",
59
+ "name": "PeerIdleTarget.busy",
60
+ "assertions": [
61
+ "G6.b"
62
+ ]
63
+ },
64
+ {
65
+ "kind": "typeMember",
66
+ "name": "PeerIdleTarget.configure",
67
+ "assertions": [
68
+ "G6.b"
69
+ ]
70
+ },
71
+ {
72
+ "kind": "typeMember",
73
+ "name": "PeerIdleTarget.exited",
74
+ "assertions": [
75
+ "G6.a"
76
+ ]
77
+ },
78
+ {
79
+ "kind": "typeMember",
80
+ "name": "PeerIdleTarget.subscribe",
81
+ "assertions": [
82
+ "G2.a",
83
+ "G5.a",
84
+ "G6.a"
85
+ ]
86
+ },
87
+ {
88
+ "kind": "typeMember",
89
+ "name": "RunnerDeps.mailboxStore",
90
+ "assertions": [
91
+ "G1.a"
92
+ ]
93
+ },
94
+ {
95
+ "kind": "typeMember",
96
+ "name": "RunnerDeps.onError",
97
+ "assertions": [
98
+ "G4.a"
99
+ ]
100
+ },
101
+ {
102
+ "kind": "typeMember",
103
+ "name": "TaskResult.terminal.kind",
104
+ "assertions": [
105
+ "G1.a",
106
+ "G1.b",
107
+ "G4.a"
108
+ ]
109
+ },
110
+ {
111
+ "kind": "typeMember",
112
+ "name": "TaskSpec.sessionId",
113
+ "assertions": [
114
+ "G1.a"
115
+ ]
116
+ },
117
+ {
118
+ "kind": "typeMember",
119
+ "name": "TaskSpec.signal",
120
+ "assertions": [
121
+ "G4.a"
122
+ ]
123
+ },
124
+ {
125
+ "kind": "typeMember",
126
+ "name": "TaskSpec.tools",
127
+ "assertions": [
128
+ "G1.b"
129
+ ]
130
+ }
131
+ ],
132
+ "consumersHint": {
133
+ "cli": [],
134
+ "server": [],
135
+ "sdk": [],
136
+ "note": "scanned cli@a51393fdd server@3bad3612e sdk@3724afe — a name listed is MENTIONED there today, which is evidence of consumption, not proof of it"
137
+ },
138
+ "breakingCount": 0,
139
+ "breakingItems": [],
140
+ "toResolvedAt": "8aa5c0cd4702103b499194011931ebfc28a00f18"
141
+ }
@@ -0,0 +1,39 @@
1
+ {
2
+ "repo": "core",
3
+ "package": "@sema-agent/mods-kernel",
4
+ "version": "7.68.5",
5
+ "from": "e0b2b38e123d0cdeb43e9a86547e590947893b9a",
6
+ "to": "v7.68.5",
7
+ "added": [],
8
+ "removed": [],
9
+ "changed": [],
10
+ "subpaths": [],
11
+ "subpathsUnread": [
12
+ "from",
13
+ "to"
14
+ ],
15
+ "narrowed": [],
16
+ "faces": {
17
+ "open": [],
18
+ "source": null
19
+ },
20
+ "closedSetMembers": [],
21
+ "closedSetsUnreadable": [],
22
+ "typeKeys": [],
23
+ "typeKeysUnreadableArms": [],
24
+ "typeKeysFlattenedCount": 1,
25
+ "signatures": [],
26
+ "versionLiterals": [],
27
+ "declarationMoves": [],
28
+ "mintMoves": [],
29
+ "criteriaObserves": [],
30
+ "consumersHint": {
31
+ "cli": [],
32
+ "server": [],
33
+ "sdk": [],
34
+ "note": "scanned cli@a51393fdd server@3bad3612e sdk@3724afe — a name listed is MENTIONED there today, which is evidence of consumption, not proof of it"
35
+ },
36
+ "breakingCount": 0,
37
+ "breakingItems": [],
38
+ "toResolvedAt": "8aa5c0cd4702103b499194011931ebfc28a00f18"
39
+ }
@@ -0,0 +1,39 @@
1
+ {
2
+ "repo": "core",
3
+ "package": "@sema-agent/primitives",
4
+ "version": "7.68.5",
5
+ "from": "e0b2b38e123d0cdeb43e9a86547e590947893b9a",
6
+ "to": "v7.68.5",
7
+ "added": [],
8
+ "removed": [],
9
+ "changed": [],
10
+ "subpaths": [],
11
+ "subpathsUnread": [
12
+ "from",
13
+ "to"
14
+ ],
15
+ "narrowed": [],
16
+ "faces": {
17
+ "open": [],
18
+ "source": null
19
+ },
20
+ "closedSetMembers": [],
21
+ "closedSetsUnreadable": [],
22
+ "typeKeys": [],
23
+ "typeKeysUnreadableArms": [],
24
+ "typeKeysFlattenedCount": 7,
25
+ "signatures": [],
26
+ "versionLiterals": [],
27
+ "declarationMoves": [],
28
+ "mintMoves": [],
29
+ "criteriaObserves": [],
30
+ "consumersHint": {
31
+ "cli": [],
32
+ "server": [],
33
+ "sdk": [],
34
+ "note": "scanned cli@a51393fdd server@3bad3612e sdk@3724afe — a name listed is MENTIONED there today, which is evidence of consumption, not proof of it"
35
+ },
36
+ "breakingCount": 0,
37
+ "breakingItems": [],
38
+ "toResolvedAt": "8aa5c0cd4702103b499194011931ebfc28a00f18"
39
+ }
@@ -0,0 +1,39 @@
1
+ {
2
+ "repo": "core",
3
+ "package": "@sema-agent/wiki-gate",
4
+ "version": "7.68.5",
5
+ "from": "e0b2b38e123d0cdeb43e9a86547e590947893b9a",
6
+ "to": "v7.68.5",
7
+ "added": [],
8
+ "removed": [],
9
+ "changed": [],
10
+ "subpaths": [],
11
+ "subpathsUnread": [
12
+ "from",
13
+ "to"
14
+ ],
15
+ "narrowed": [],
16
+ "faces": {
17
+ "open": [],
18
+ "source": null
19
+ },
20
+ "closedSetMembers": [],
21
+ "closedSetsUnreadable": [],
22
+ "typeKeys": [],
23
+ "typeKeysUnreadableArms": [],
24
+ "typeKeysFlattenedCount": 5,
25
+ "signatures": [],
26
+ "versionLiterals": [],
27
+ "declarationMoves": [],
28
+ "mintMoves": [],
29
+ "criteriaObserves": [],
30
+ "consumersHint": {
31
+ "cli": [],
32
+ "server": [],
33
+ "sdk": [],
34
+ "note": "scanned cli@a51393fdd server@3bad3612e sdk@3724afe — a name listed is MENTIONED there today, which is evidence of consumption, not proof of it"
35
+ },
36
+ "breakingCount": 0,
37
+ "breakingItems": [],
38
+ "toResolvedAt": "8aa5c0cd4702103b499194011931ebfc28a00f18"
39
+ }