@code-yeongyu/senpi-agent-core 2026.11.15-4 → 2026.11.17

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.
@@ -0,0 +1,198 @@
1
+ import { WakeOverflowError } from "./wake-outbox.js";
2
+ import { WAKE_DROPPED_SOURCE, } from "./wake-types.js";
3
+ /**
4
+ * The wake link (brain/hand split H3, design 5.6.4 on the hand transport): what a hand's work produces after the call
5
+ * that started it ended reaches the brain that owns its scope at least once, or the brain is told it was dropped. The
6
+ * hand commits each wake to its durable outbox before sending it; the brain answers with a receipt only after its inbox
7
+ * commit; the hand re-offers every un-acked wake when it starts and whenever the brain asks. Everything travels on one
8
+ * lane of the hand's transport, so a relay carries it like any other lane: frames from the hand wait for the brain's
9
+ * next batch.
10
+ */
11
+ export const HAND_WAKE_LANE = "hand.wake";
12
+ const REFUSALS = ["not_scope_hand", "unknown_scope", "scope_closed", "not_scope_session"];
13
+ const DROP_REASONS = ["overflow", "expired", "refused", "malformed", "unrecorded"];
14
+ const encoder = new TextEncoder();
15
+ const decoder = new TextDecoder();
16
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17
+ const isId = (value) => typeof value === "string" && value.length > 0;
18
+ export function encodeWakeLinkMessage(message) {
19
+ return encoder.encode(JSON.stringify(message));
20
+ }
21
+ function decodeWake(value) {
22
+ if (!isRecord(value) || !isId(value.eventId) || !isId(value.scope) || !isId(value.source) || !("payload" in value))
23
+ return undefined;
24
+ return { eventId: value.eventId, scope: value.scope, source: value.source, payload: value.payload };
25
+ }
26
+ function decodeReceipt(value) {
27
+ if (!isRecord(value) || !isId(value.eventId))
28
+ return undefined;
29
+ if (value.kind === "ack" && typeof value.duplicate === "boolean")
30
+ return { kind: "ack", eventId: value.eventId, duplicate: value.duplicate };
31
+ if (value.kind === "refused" && REFUSALS.includes(value.reason))
32
+ return { kind: "refused", eventId: value.eventId, reason: value.reason };
33
+ return undefined;
34
+ }
35
+ function decodeDrop(value) {
36
+ const { scope, reason, count, eventId } = value;
37
+ if (!isId(scope) || !DROP_REASONS.includes(reason))
38
+ return undefined;
39
+ if (typeof count !== "number" || !Number.isSafeInteger(count) || count <= 0)
40
+ return undefined;
41
+ if (eventId !== undefined && !isId(eventId))
42
+ return undefined;
43
+ const drop = { kind: "wake_dropped", scope, reason: reason, count };
44
+ return eventId === undefined ? drop : { ...drop, eventId };
45
+ }
46
+ /** Parses one frame payload as a wake-link message; anything else is `undefined`. */
47
+ export function decodeWakeLinkMessage(payload) {
48
+ let value;
49
+ try {
50
+ value = JSON.parse(decoder.decode(payload));
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
55
+ if (!isRecord(value))
56
+ return undefined;
57
+ switch (value.kind) {
58
+ case "wake": {
59
+ const wake = decodeWake(value.wake);
60
+ return wake === undefined ? undefined : { kind: "wake", wake };
61
+ }
62
+ case "wake_receipt": {
63
+ const receipt = decodeReceipt(value.receipt);
64
+ return receipt === undefined ? undefined : { kind: "wake_receipt", receipt };
65
+ }
66
+ case "wake_dropped":
67
+ return decodeDrop(value);
68
+ case "wake_reoffer":
69
+ return { kind: "wake_reoffer" };
70
+ default:
71
+ return undefined;
72
+ }
73
+ }
74
+ /** The frame a due outbox entry travels as: a drop report as `wake_dropped` with its event id, any other as `wake`. */
75
+ function frameOf(wake) {
76
+ const { payload } = wake;
77
+ if (wake.source !== WAKE_DROPPED_SOURCE || !isRecord(payload))
78
+ return { kind: "wake", wake };
79
+ const { reason, count } = payload;
80
+ return {
81
+ kind: "wake_dropped",
82
+ eventId: wake.eventId,
83
+ scope: wake.scope,
84
+ reason: reason,
85
+ count: Number(count),
86
+ };
87
+ }
88
+ /** The hand end of the wake link: the durable outbox, sent over the transport, re-offered on start and on request. */
89
+ export function createHandWakeLink(options) {
90
+ const { transport, outbox, onFault } = options;
91
+ const lane = options.lane ?? HAND_WAKE_LANE;
92
+ let closed = false;
93
+ const send = (message) => {
94
+ if (closed)
95
+ return Promise.resolve();
96
+ return transport.send(lane, encodeWakeLinkMessage(message)).catch(onFault);
97
+ };
98
+ // Expired and malformed entries become drop reports first; then every report and un-acked wake is sent again (the
99
+ // brain's inbox answers a duplicate with its ack, so a re-send never wakes the loop twice).
100
+ const reoffer = async () => {
101
+ await outbox.sweep();
102
+ for (const wake of await outbox.due())
103
+ await send(frameOf(wake));
104
+ };
105
+ transport.onFrame(async (frame) => {
106
+ const message = decodeWakeLinkMessage(frame.payload);
107
+ try {
108
+ if (message === undefined)
109
+ onFault(new Error(`an undecodable frame on ${lane} was dropped`));
110
+ else if (message.kind === "wake_receipt")
111
+ await outbox.receipt(message.receipt);
112
+ else if (message.kind === "wake_reoffer")
113
+ await reoffer();
114
+ }
115
+ catch (error) {
116
+ onFault(error);
117
+ }
118
+ });
119
+ const ready = reoffer().catch(onFault);
120
+ return {
121
+ ready,
122
+ async offer(wake) {
123
+ let event;
124
+ try {
125
+ event = await outbox.offer(wake);
126
+ }
127
+ catch (error) {
128
+ // An overflow is already recorded as a durable drop report; anything else left no record at all.
129
+ if (error instanceof WakeOverflowError)
130
+ return;
131
+ onFault(error);
132
+ return send({ kind: "wake_dropped", scope: wake.scope, reason: "unrecorded", count: 1 });
133
+ }
134
+ return send({ kind: "wake", wake: event });
135
+ },
136
+ closeScope: (scope) => outbox.closeScope(scope).catch(onFault),
137
+ close() {
138
+ closed = true;
139
+ },
140
+ };
141
+ }
142
+ /** The brain refused a wake by its own check (`check`): it names a session that is not its scope's. */
143
+ export class WakeRefusedError extends Error {
144
+ constructor(wake, reason) {
145
+ super(`the brain refused wake ${wake.eventId} of scope ${wake.scope}: ${reason}`);
146
+ this.name = "WakeRefusedError";
147
+ this.wake = wake;
148
+ this.reason = reason;
149
+ }
150
+ }
151
+ /** The brain end of the wake link: each wake goes to the inbox, and the receipt goes back only after its commit. */
152
+ export function serveHandWakes(options) {
153
+ const { transport, inbox, hand, onFault } = options;
154
+ const lane = options.lane ?? HAND_WAKE_LANE;
155
+ let closed = false;
156
+ const send = (message) => {
157
+ if (!closed)
158
+ transport.send(lane, encodeWakeLinkMessage(message)).catch(onFault);
159
+ };
160
+ const commit = async (wake) => {
161
+ // The brain's own check runs inside the inbox, after its scope binding: an unbound scope is `unknown_scope` (the
162
+ // hand retries it), so only a bound scope's own answer can refuse a wake for good (review round 2, M4).
163
+ const check = wake.source === WAKE_DROPPED_SOURCE ? undefined : options.check;
164
+ const receipt = await inbox.receive(hand, wake, check);
165
+ if (receipt.kind === "refused" && receipt.reason === "not_scope_session")
166
+ onFault(new WakeRefusedError(wake, receipt.reason));
167
+ send({ kind: "wake_receipt", receipt });
168
+ if (receipt.kind === "ack" && !receipt.duplicate)
169
+ options.onCommitted(wake);
170
+ };
171
+ transport.onFrame(async (frame) => {
172
+ if (closed)
173
+ return;
174
+ const message = decodeWakeLinkMessage(frame.payload);
175
+ try {
176
+ if (message === undefined)
177
+ onFault(new Error(`an undecodable frame on ${lane} was dropped`));
178
+ else if (message.kind === "wake")
179
+ await commit(message.wake);
180
+ else if (message.kind === "wake_dropped" && message.eventId !== undefined) {
181
+ const { eventId, scope, reason, count } = message;
182
+ await commit({ eventId, scope, source: WAKE_DROPPED_SOURCE, payload: { reason, count } });
183
+ }
184
+ else if (message.kind === "wake_dropped")
185
+ options.onDropped({ scope: message.scope, reason: message.reason, count: message.count });
186
+ }
187
+ catch (error) {
188
+ onFault(error);
189
+ }
190
+ });
191
+ return {
192
+ reoffer: () => send({ kind: "wake_reoffer" }),
193
+ close() {
194
+ closed = true;
195
+ },
196
+ };
197
+ }
198
+ //# sourceMappingURL=wake-link.js.map
@@ -0,0 +1,29 @@
1
+ import type { StoreValue } from "../durable/store.ts";
2
+ import { type WakeDropReason, type WakeEvent, type WakeOutboxRecord } from "./wake-types.ts";
3
+ export declare const isStoreObject: (value: StoreValue | undefined) => value is {
4
+ readonly [key: string]: StoreValue;
5
+ };
6
+ /** A record as read: its well-formed entries, and the raw entries that are not wakes (dropped at the next sweep). */
7
+ export interface DecodedOutbox {
8
+ readonly record: WakeOutboxRecord;
9
+ readonly malformed: readonly StoreValue[];
10
+ }
11
+ /**
12
+ * Parses the outbox document strictly (senpi#6767 review L2): every pending wake and drop report must be a whole
13
+ * wake, every refusal a known reason with its time. Anything else is set aside, never offered, and dropped by `sweep`.
14
+ * A document that is not an outbox record at all is corrupt and throws.
15
+ */
16
+ export declare function decodeOutbox(value: StoreValue | undefined): DecodedOutbox;
17
+ /** The scope a malformed entry names, if it names one; it is reported under that scope. */
18
+ export declare function malformedScope(entry: StoreValue): string | undefined;
19
+ /**
20
+ * Adds `count` drops of `reason` in `scope` to the drop reports. A report not yet sent by this outbox instance (`fresh`)
21
+ * is coalesced, so a brain that stays away gets one report per scope and reason, not one per dropped wake. A report
22
+ * this process (or an earlier one) may have sent keeps its count: the brain deduplicates by its event id.
23
+ */
24
+ export declare function addDrop(drops: readonly WakeEvent[], drop: {
25
+ readonly scope: string;
26
+ readonly reason: WakeDropReason;
27
+ readonly count: number;
28
+ }, fresh: Set<string>, mint: () => string): readonly WakeEvent[];
29
+ //# sourceMappingURL=wake-outbox-record.d.ts.map
@@ -0,0 +1,73 @@
1
+ import { WAKE_DROPPED_SOURCE, } from "./wake-types.js";
2
+ const REFUSALS = ["not_scope_hand", "unknown_scope", "scope_closed", "not_scope_session"];
3
+ export const isStoreObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
4
+ const isId = (value) => typeof value === "string" && value.length > 0;
5
+ function wakeOf(value) {
6
+ if (!isStoreObject(value) || !isId(value.eventId) || !isId(value.scope) || !isId(value.source))
7
+ return undefined;
8
+ if (!("payload" in value))
9
+ return undefined;
10
+ return { eventId: value.eventId, scope: value.scope, source: value.source, payload: value.payload ?? null };
11
+ }
12
+ function refusalOf(value) {
13
+ if (!isStoreObject(value) || typeof value.at !== "number" || typeof value.reason !== "string")
14
+ return undefined;
15
+ return REFUSALS.includes(value.reason) ? { reason: value.reason, at: value.at } : undefined;
16
+ }
17
+ /**
18
+ * Parses the outbox document strictly (senpi#6767 review L2): every pending wake and drop report must be a whole
19
+ * wake, every refusal a known reason with its time. Anything else is set aside, never offered, and dropped by `sweep`.
20
+ * A document that is not an outbox record at all is corrupt and throws.
21
+ */
22
+ export function decodeOutbox(value) {
23
+ if (value === undefined)
24
+ return { record: { pending: [], drops: [], refused: {}, closed: {} }, malformed: [] };
25
+ if (!isStoreObject(value) || !Array.isArray(value.pending) || !isStoreObject(value.closed))
26
+ throw new Error("corrupt wake outbox record");
27
+ const malformed = [];
28
+ const wakes = (list) => (Array.isArray(list) ? list : []).flatMap((entry) => {
29
+ const wake = wakeOf(entry);
30
+ if (wake === undefined)
31
+ malformed.push(entry);
32
+ return wake === undefined ? [] : [wake];
33
+ });
34
+ const refused = Object.fromEntries(Object.entries(isStoreObject(value.refused) ? value.refused : {}).flatMap(([eventId, entry]) => {
35
+ const refusal = refusalOf(entry);
36
+ return refusal === undefined ? [] : [[eventId, refusal]];
37
+ }));
38
+ const closed = Object.fromEntries(Object.entries(value.closed).flatMap(([scope, at]) => (typeof at === "number" ? [[scope, at]] : [])));
39
+ return { record: { pending: wakes(value.pending), drops: wakes(value.drops), refused, closed }, malformed };
40
+ }
41
+ /** The scope a malformed entry names, if it names one; it is reported under that scope. */
42
+ export function malformedScope(entry) {
43
+ return isStoreObject(entry) && isId(entry.scope) ? entry.scope : undefined;
44
+ }
45
+ /**
46
+ * Adds `count` drops of `reason` in `scope` to the drop reports. A report not yet sent by this outbox instance (`fresh`)
47
+ * is coalesced, so a brain that stays away gets one report per scope and reason, not one per dropped wake. A report
48
+ * this process (or an earlier one) may have sent keeps its count: the brain deduplicates by its event id.
49
+ */
50
+ export function addDrop(drops, drop, fresh, mint) {
51
+ const at = drops.findLastIndex((report) => fresh.has(report.eventId) &&
52
+ report.scope === drop.scope &&
53
+ isStoreObject(report.payload) &&
54
+ report.payload.reason === drop.reason);
55
+ const previous = at === -1 ? undefined : drops[at];
56
+ if (previous !== undefined && isStoreObject(previous.payload) && typeof previous.payload.count === "number") {
57
+ const merged = {
58
+ ...previous,
59
+ payload: { reason: drop.reason, count: previous.payload.count + drop.count },
60
+ };
61
+ return drops.map((report, index) => (index === at ? merged : report));
62
+ }
63
+ const eventId = mint();
64
+ fresh.add(eventId);
65
+ const report = {
66
+ eventId,
67
+ scope: drop.scope,
68
+ source: WAKE_DROPPED_SOURCE,
69
+ payload: { reason: drop.reason, count: drop.count },
70
+ };
71
+ return [...drops, report];
72
+ }
73
+ //# sourceMappingURL=wake-outbox-record.js.map
@@ -1,6 +1,6 @@
1
1
  import type { DurableStore, StoreValue } from "../durable/store.ts";
2
2
  import type { AdmissionLine } from "../durable/store-admission.ts";
3
- import { type WakeEvent, type WakeReceipt } from "./wake-types.ts";
3
+ import { type WakeEvent, type WakeLimits, type WakeReceipt } from "./wake-types.ts";
4
4
  export interface WakeOutboxOptions {
5
5
  /** The hand this outbox belongs to; every event id it mints starts with it. */
6
6
  readonly hand: string;
@@ -8,23 +8,47 @@ export interface WakeOutboxOptions {
8
8
  readonly epoch: number;
9
9
  readonly admission: AdmissionLine;
10
10
  readonly clock: () => number;
11
+ /**
12
+ * The un-acked bound. Past it a wake the brain refused for good is evicted (reported `refused`); with none to evict,
13
+ * the new wake is refused before it is sent (`WakeOverflowError`, reported `overflow`). Absent: no bound.
14
+ */
15
+ readonly limits?: WakeLimits;
16
+ /** A pending entry that is not a wake: `sweep` drops it and keeps a drop report (`malformed`) under its scope. */
17
+ readonly onFault?: (error: Error) => void;
11
18
  }
12
19
  /** The hand side of design 5.6.4: a wake is durable before it is sent and removed only by its `wake_ack`. */
13
20
  export interface WakeOutbox {
14
21
  /** Commits the wake and returns it; the caller sends it (or a later `reoffer` does). */
15
22
  offer(wake: Omit<WakeEvent, "eventId">): Promise<WakeEvent>;
16
- /** Sends every un-acked wake in offer order (on reconnect) but those refused for good (not_scope_hand, scope_closed); a failed send or an unknown scope leaves it pending for the next re-offer. */
23
+ /** Sends every due wake in offer order (on reconnect); a failed send or an unknown scope leaves it for the next re-offer. */
17
24
  reoffer(send: (wake: WakeEvent) => Promise<WakeReceipt>): Promise<number>;
18
- /** Applies one brain answer: an ack removes the wake; a refusal keeps it for retention and stops its re-offers. Idempotent. */
25
+ /**
26
+ * What a re-offer sends: every drop report, then every un-acked wake, but those refused for good (not_scope_hand,
27
+ * scope_closed, not_scope_session). Drop reports returned here are never coalesced again by this outbox.
28
+ */
29
+ due(): Promise<readonly WakeEvent[]>;
30
+ /** Applies one brain answer: an ack removes the wake or report; a refusal keeps it until the retention. Idempotent. */
19
31
  receipt(receipt: WakeReceipt): Promise<void>;
20
32
  /** The scope closed: its un-acked wakes are kept until `closedAt + WAKE_RETENTION_MS`. */
21
33
  closeScope(scope: string): Promise<void>;
22
- /** Drops the wakes past retention, each with a logged `wake_expired` record; returns their ids. */
34
+ /**
35
+ * Drops what is past retention: wakes of a closed scope (each logged `wake_expired`, and reported per scope as an
36
+ * `expired` drop), wakes refused for good, and malformed entries (reported `malformed`). Returns the expired wakes' ids.
37
+ */
23
38
  sweep(): Promise<readonly string[]>;
39
+ /** The un-acked wakes, without the drop reports. */
24
40
  pending(): Promise<readonly WakeEvent[]>;
25
41
  }
26
- export declare const isStoreObject: (value: StoreValue | undefined) => value is {
27
- readonly [key: string]: StoreValue;
28
- };
42
+ /** The outbox is at its bound with only in-flight wakes: this wake was refused before it was sent, and reported. */
43
+ export declare class WakeOverflowError extends Error {
44
+ readonly name = "WakeOverflowError";
45
+ readonly wake: WakeEvent;
46
+ constructor(wake: WakeEvent);
47
+ }
48
+ export declare class MalformedWakeError extends Error {
49
+ readonly name = "MalformedWakeError";
50
+ readonly entry: StoreValue;
51
+ constructor(entry: StoreValue);
52
+ }
29
53
  export declare function createWakeOutbox(options: WakeOutboxOptions): WakeOutbox;
30
54
  //# sourceMappingURL=wake-outbox.d.ts.map
@@ -1,21 +1,29 @@
1
- import { WAKE_RETENTION_MS } from "./wake-types.js";
1
+ import { addDrop, decodeOutbox, malformedScope } from "./wake-outbox-record.js";
2
+ import { WAKE_RETENTION_MS, } from "./wake-types.js";
2
3
  const KIND = "execution.wake-outbox";
3
- const EMPTY = { pending: [], refused: {}, closed: {} };
4
- export const isStoreObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
5
- function decode(value) {
6
- if (value === undefined)
7
- return EMPTY;
8
- if (isStoreObject(value) &&
9
- Array.isArray(value.pending) &&
10
- isStoreObject(value.refused) &&
11
- isStoreObject(value.closed))
12
- return value;
13
- throw new Error("corrupt wake outbox record");
4
+ /** The outbox is at its bound with only in-flight wakes: this wake was refused before it was sent, and reported. */
5
+ export class WakeOverflowError extends Error {
6
+ constructor(wake) {
7
+ super(`the hand's wake outbox is full; wake ${wake.eventId} of scope ${wake.scope} was dropped (overflow)`);
8
+ this.name = "WakeOverflowError";
9
+ this.wake = wake;
10
+ }
11
+ }
12
+ export class MalformedWakeError extends Error {
13
+ constructor(entry) {
14
+ super(`a malformed wake was dropped from the outbox: ${JSON.stringify(entry)}`);
15
+ this.name = "MalformedWakeError";
16
+ this.entry = entry;
17
+ }
14
18
  }
15
19
  export function createWakeOutbox(options) {
16
- const { hand, store, epoch, admission, clock } = options;
20
+ const { hand, store, epoch, admission, clock, limits } = options;
17
21
  const key = `${KIND}:${JSON.stringify([hand])}`;
18
- const read = async () => decode(await store.getDocument(key));
22
+ const mint = () => `${hand}:${store.mintId()}`;
23
+ // Drop reports this instance created and never handed to a re-offer: the only ones safe to coalesce into.
24
+ const fresh = new Set();
25
+ const decoded = async () => decodeOutbox(await store.getDocument(key));
26
+ const read = async () => (await decoded()).record;
19
27
  const write = async (record, step, eventId, extra = []) => {
20
28
  const data = { step, eventId };
21
29
  await store.commit(epoch, [
@@ -30,56 +38,118 @@ export function createWakeOutbox(options) {
30
38
  ], () => { });
31
39
  };
32
40
  const update = (decide) => admission.admit(async () => decide(await read()));
41
+ const withDrops = (record, scope, reason, count) => ({
42
+ ...record,
43
+ drops: addDrop(record.drops, { scope, reason, count }, fresh, mint),
44
+ });
45
+ /** Removes a wake and every bit of its state, reporting it as `reason` under its own scope. */
46
+ const evict = (record, wake, reason) => {
47
+ const { [wake.eventId]: _gone, ...refused } = record.refused;
48
+ const pending = record.pending.filter((entry) => entry.eventId !== wake.eventId);
49
+ return withDrops({ ...record, pending, refused }, wake.scope, reason, 1);
50
+ };
51
+ /**
52
+ * Past a bound, only a wake the brain refused for good is evicted: it is never sent again, so nothing in flight is
53
+ * lost. Every other pending wake may already be on its way to the brain (review round 2, L6), so when none can go the
54
+ * new wake is the one refused: `undefined`, and it is never sent.
55
+ */
56
+ const bounded = (record, scope) => {
57
+ if (limits === undefined)
58
+ return record;
59
+ let next = record;
60
+ const over = () => next.pending.filter((wake) => wake.scope === scope).length > limits.perScope ||
61
+ next.pending.length > limits.total;
62
+ while (over()) {
63
+ const inScope = next.pending.filter((wake) => wake.scope === scope).length > limits.perScope;
64
+ const evictable = next.pending.find((wake) => next.refused[wake.eventId] !== undefined && (!inScope || wake.scope === scope));
65
+ if (evictable === undefined)
66
+ return undefined;
67
+ next = evict(next, evictable, "refused");
68
+ }
69
+ return next;
70
+ };
33
71
  const receipt = (answer) => update(async (record) => {
34
- if (!record.pending.some((wake) => wake.eventId === answer.eventId))
72
+ const known = [...record.pending, ...record.drops].some((wake) => wake.eventId === answer.eventId);
73
+ if (!known)
35
74
  return;
36
75
  if (answer.kind === "refused") {
37
76
  // The scope may not be bound yet (a brain restart, a bind racing this outbox): only a refusal that cannot change
38
77
  // is recorded and stops the re-offers.
39
- if (answer.reason === "unknown_scope" || record.refused[answer.eventId] === answer.reason)
78
+ if (answer.reason === "unknown_scope" || record.refused[answer.eventId] !== undefined)
40
79
  return;
41
- await write({ ...record, refused: { ...record.refused, [answer.eventId]: answer.reason } }, "refused", answer.eventId);
80
+ const refusal = { reason: answer.reason, at: clock() };
81
+ await write({ ...record, refused: { ...record.refused, [answer.eventId]: refusal } }, "refused", answer.eventId);
42
82
  return;
43
83
  }
44
- const pending = record.pending.filter((wake) => wake.eventId !== answer.eventId);
84
+ const kept = (wake) => wake.eventId !== answer.eventId;
45
85
  const { [answer.eventId]: _settled, ...refused } = record.refused;
46
- await write({ ...record, pending, refused }, "ack", answer.eventId);
86
+ const settled = { ...record, pending: record.pending.filter(kept), drops: record.drops.filter(kept), refused };
87
+ await write(settled, "ack", answer.eventId);
47
88
  });
89
+ const due = async () => {
90
+ const record = await read();
91
+ for (const report of record.drops)
92
+ fresh.delete(report.eventId);
93
+ return [...record.drops, ...record.pending].filter((wake) => record.refused[wake.eventId] === undefined);
94
+ };
48
95
  return {
49
96
  offer: (wake) => update(async (record) => {
50
- const event = { ...wake, eventId: `${hand}:${store.mintId()}` };
51
- await write({ ...record, pending: [...record.pending, event] }, "offer", event.eventId);
97
+ const event = { ...wake, eventId: mint() };
98
+ const next = bounded({ ...record, pending: [...record.pending, event] }, event.scope);
99
+ if (next === undefined) {
100
+ await write(withDrops(record, event.scope, "overflow", 1), "overflow", event.eventId);
101
+ throw new WakeOverflowError(event);
102
+ }
103
+ await write(next, "offer", event.eventId);
52
104
  return event;
53
105
  }),
54
106
  reoffer: async (send) => {
55
- let sent = 0;
56
- const record = await read();
57
- for (const wake of record.pending) {
58
- if (record.refused[wake.eventId] !== undefined)
59
- continue;
107
+ const wakes = await due();
108
+ for (const wake of wakes)
60
109
  await receipt(await send(wake));
61
- sent += 1;
62
- }
63
- return sent;
110
+ return wakes.length;
64
111
  },
112
+ due,
65
113
  receipt,
66
114
  closeScope: (scope) => update(async (record) => {
67
115
  if (record.closed[scope] !== undefined)
68
116
  return;
69
117
  await write({ ...record, closed: { ...record.closed, [scope]: clock() } }, "close", null);
70
118
  }),
71
- sweep: () => update(async (record) => {
119
+ sweep: () => admission.admit(async () => {
120
+ const { record, malformed } = await decoded();
72
121
  const now = clock();
73
- const expired = record.pending.filter((wake) => {
122
+ const lapsed = (wake) => {
74
123
  const closedAt = record.closed[wake.scope];
75
- return closedAt !== undefined && now > closedAt + WAKE_RETENTION_MS;
76
- });
77
- if (expired.length === 0)
124
+ const refusedAt = record.refused[wake.eventId]?.at;
125
+ return ((closedAt !== undefined && now > closedAt + WAKE_RETENTION_MS) ||
126
+ (refusedAt !== undefined && now > refusedAt + WAKE_RETENTION_MS));
127
+ };
128
+ const expired = record.pending.filter(lapsed);
129
+ const lapsedDrops = record.drops.filter(lapsed);
130
+ // A refusal whose wake is gone (an older outbox evicted it without its state) is purged.
131
+ const held = new Set([...record.pending, ...record.drops].map((wake) => wake.eventId));
132
+ const orphans = Object.keys(record.refused).filter((eventId) => !held.has(eventId));
133
+ if (expired.length + lapsedDrops.length + malformed.length + orphans.length === 0)
78
134
  return [];
79
- const gone = new Set(expired.map((wake) => wake.eventId));
80
- const refused = Object.fromEntries(Object.entries(record.refused).filter(([eventId]) => !gone.has(eventId)));
81
- await write({ ...record, pending: record.pending.filter((wake) => !gone.has(wake.eventId)), refused }, "sweep", null, expired.map((wake) => ({ reason: "wake_expired", eventId: wake.eventId, scope: wake.scope })));
82
- return [...gone];
135
+ const gone = new Set([...expired, ...lapsedDrops].map((wake) => wake.eventId).concat(orphans));
136
+ let next = {
137
+ ...record,
138
+ pending: record.pending.filter((wake) => !gone.has(wake.eventId)),
139
+ drops: record.drops.filter((wake) => !gone.has(wake.eventId)),
140
+ refused: Object.fromEntries(Object.entries(record.refused).filter(([eventId]) => !gone.has(eventId))),
141
+ };
142
+ // A lapsed wake is reported: `refused` when the brain refused it for good (review round 2, M4), else `expired`.
143
+ for (const wake of expired)
144
+ next = withDrops(next, wake.scope, record.refused[wake.eventId] === undefined ? "expired" : "refused", 1);
145
+ for (const entry of malformed) {
146
+ options.onFault?.(new MalformedWakeError(entry));
147
+ const scope = malformedScope(entry);
148
+ if (scope !== undefined)
149
+ next = withDrops(next, scope, "malformed", 1);
150
+ }
151
+ await write(next, "sweep", null, expired.map((wake) => ({ reason: "wake_expired", eventId: wake.eventId, scope: wake.scope })));
152
+ return expired.map((wake) => wake.eventId);
83
153
  }),
84
154
  pending: async () => (await read()).pending,
85
155
  };
@@ -1,14 +1,37 @@
1
1
  import type { StoreValue } from "../durable/store.ts";
2
2
  /** Design 5.6.4: an un-acked wake lives until its scope closes plus this long, then it is dropped as `wake_expired`. */
3
3
  export declare const WAKE_RETENTION_MS: number;
4
- /** One durable wake from a hand to the brain that owns its scope. `eventId` is unique per hand and stable on re-offer. */
4
+ /**
5
+ * One durable wake from a hand to the brain that owns its scope. `eventId` is unique per hand and stable on re-offer.
6
+ * `scope` is the hand's execution scope id: the id the brain gave the session's `ExecutionScope` for the call whose
7
+ * work produced the wake. It equals a session id only if the brain chose it to (a senpi session mints a random one per
8
+ * session), so a brain resolves it to the scope's loop sessions; `payload.sessionId`, when present, names one of them.
9
+ */
5
10
  export type WakeEvent = {
6
11
  readonly eventId: string;
7
12
  readonly scope: string;
8
13
  readonly source: string;
9
14
  readonly payload: StoreValue;
10
15
  };
11
- export type WakeRefusal = "not_scope_hand" | "unknown_scope" | "scope_closed";
16
+ /**
17
+ * Why the brain refused a wake. `not_scope_session` (senpi#6767 review L3): the wake names a loop session that is not
18
+ * one of its scope's sessions.
19
+ */
20
+ export type WakeRefusal = "not_scope_hand" | "unknown_scope" | "scope_closed" | "not_scope_session";
21
+ /**
22
+ * Why wakes never reached the brain: `overflow` (the hand's un-acked bound: a new wake refused before it was sent),
23
+ * `refused` (the brain refused it for good, reported once it is evicted or its retention lapsed), `expired` (un-acked past
24
+ * the closed scope's retention), `malformed` (an entry the hand's outbox could not read), `unrecorded` (the hand could
25
+ * not commit it at all; reported best-effort, as it has no durable record).
26
+ */
27
+ export type WakeDropReason = "overflow" | "expired" | "refused" | "malformed" | "unrecorded";
28
+ /** The source of a drop report: a durable wake whose payload is `{ reason, count }` (a {@link WakeDropReason}). */
29
+ export declare const WAKE_DROPPED_SOURCE = "wake.dropped";
30
+ /** The un-acked wakes a hand keeps, per scope and in total; past either, a new wake is refused (`overflow`) unless a refused one can be evicted. */
31
+ export interface WakeLimits {
32
+ readonly perScope: number;
33
+ readonly total: number;
34
+ }
12
35
  /** What the brain answers a wake: `ack` only after the inbox commit; a refusal commits nothing and is never acked. */
13
36
  export type WakeReceipt = {
14
37
  readonly kind: "ack";
@@ -21,9 +44,14 @@ export type WakeReceipt = {
21
44
  };
22
45
  export type WakeOutboxRecord = {
23
46
  readonly pending: readonly WakeEvent[];
24
- /** Pending wakes the brain refused for good, by event id: kept for retention, never re-offered. */
47
+ /** Drop reports not yet acked (source {@link WAKE_DROPPED_SOURCE}); acked and expired like wakes, never bounded by limits. */
48
+ readonly drops: readonly WakeEvent[];
49
+ /** Wakes the brain refused for good, by event id, with the refusal time: never re-offered, dropped after the retention. */
25
50
  readonly refused: {
26
- readonly [eventId: string]: WakeRefusal;
51
+ readonly [eventId: string]: {
52
+ readonly reason: WakeRefusal;
53
+ readonly at: number;
54
+ };
27
55
  };
28
56
  /** Scopes the hand closed, with the close time that starts their retention. */
29
57
  readonly closed: {
@@ -41,5 +69,9 @@ export type WakeInboxRecord = {
41
69
  readonly closed: {
42
70
  readonly [scope: string]: number;
43
71
  };
72
+ /** Failed deliveries of a pending wake, by event id; absent while none failed. */
73
+ readonly failures?: {
74
+ readonly [eventId: string]: number;
75
+ };
44
76
  };
45
77
  //# sourceMappingURL=wake-types.d.ts.map
@@ -1,3 +1,5 @@
1
1
  /** Design 5.6.4: an un-acked wake lives until its scope closes plus this long, then it is dropped as `wake_expired`. */
2
2
  export const WAKE_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
3
+ /** The source of a drop report: a durable wake whose payload is `{ reason, count }` (a {@link WakeDropReason}). */
4
+ export const WAKE_DROPPED_SOURCE = "wake.dropped";
3
5
  //# sourceMappingURL=wake-types.js.map
package/dist/index.d.ts CHANGED
@@ -16,7 +16,7 @@ export { createAdmissionLine } from "./durable/store-admission.ts";
16
16
  export type { SessionHandle, SessionHeader, StoredEntry, StoredSession, SyncSessionHandle, } from "./durable/session-store.ts";
17
17
  export { appendRecordWrites, divergenceWrite, manifestWrite, openSessionStore, openSyncSessionStore, readSessionState, rewriteRecordWrite, SessionStoreError, type SessionState, } from "./durable/session-store.ts";
18
18
  export type { SyncCommit, SyncCommitStore } from "./durable/store.ts";
19
- export { createMemoryStoreMedium, openMemoryStore } from "./durable/store-memory.ts";
19
+ export { createMemoryStoreMedium, type MemoryStoreMedium, openMemoryStore } from "./durable/store-memory.ts";
20
20
  export { createBatchCoordinator } from "./execution/coordinator.ts";
21
21
  export type { BatchExecutor, BatchPlan } from "./execution/coordinator-types.ts";
22
22
  export { createExecutionLedger } from "./execution/ledger.ts";
@@ -31,6 +31,11 @@ export { admitChainCall, CHAIN_COUNT_LIMIT, CHAIN_ORIGIN, ChainCountLimitError,
31
31
  export { decodePlaneMessage, encodePlaneMessage, type NestedRequest, type PlaneHandler, type PlaneMessage, PlaneRefusedError, } from "./execution/plane.ts";
32
32
  export { createLoopHookHost, type LoopHookHost, type LoopHookHostOptions, LoopHookFailedError, LoopHookRestartedError, } from "./execution/loop-hook-host.ts";
33
33
  export { type LoopHookHand, type LoopHookHandOptions, type LoopHookPoint, type LoopHookRunner, serveLoopHooks, } from "./execution/loop-hook-host-hand.ts";
34
+ export { type BrainWakeLink, type BrainWakeLinkOptions, createHandWakeLink, decodeWakeLinkMessage, encodeWakeLinkMessage, HAND_WAKE_LANE, type HandWakeLink, type HandWakeLinkOptions, serveHandWakes, type WakeDrop, type WakeLinkMessage, WakeRefusedError, } from "./execution/wake-link.ts";
35
+ export { deliverHandDrop, deliverHandWake, type HandWakeDelivery, type HandWakeMessage, type HandWakeMessageOptions, type HandWakeNoticeType, type HandWakeOutcome, type HandWakeSession, type HandWakeUserMessageOptions, MalformedHandWakeError, ONE_SHOT_MODES, parseHandWake, scopeSessionCheck, } from "./execution/wake-delivery.ts";
36
+ export { createWakeInbox, type WakeDeliveryFailure, type WakeInbox, type WakeInboxOptions, } from "./execution/wake-inbox.ts";
37
+ export { createWakeOutbox, MalformedWakeError, type WakeOutbox, type WakeOutboxOptions, } from "./execution/wake-outbox.ts";
38
+ export { WAKE_DROPPED_SOURCE, WAKE_RETENTION_MS, type WakeDropReason, type WakeEvent, type WakeLimits, type WakeReceipt, type WakeRefusal, } from "./execution/wake-types.ts";
34
39
  export { createRemoteToolHost, type HandPlacement, type RemoteToolHostOptions } from "./execution/remote-tool-host.ts";
35
40
  export { canonicalJson } from "./execution/canonical-digest.ts";
36
41
  export { toStoreValue } from "./execution/prepared/executor-freeze.ts";