@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.
@@ -35,6 +35,13 @@ function valueOf(reply) {
35
35
  case "unreachable":
36
36
  throw new DeviceFileError("hand_unreachable", reply.reason);
37
37
  case "closed":
38
+ // A sent operation may have run on the hand before it was lost: uncertain, like a hand restart, never retried
39
+ // as if it had not happened. One never sent had no effect, so the hand is simply unreachable.
40
+ if (reply.sent)
41
+ throw new DeviceFileError("interrupted", "the hand link closed before the operation settled (hand_restarted)", {
42
+ reason: "hand_restarted",
43
+ uncertain: true,
44
+ });
38
45
  throw new DeviceFileError("hand_unreachable", "the hand link was closed");
39
46
  case "epoch_refused":
40
47
  throw new DeviceFileError("refused_by_policy", `epoch: ${reply.reason}`);
@@ -17,8 +17,11 @@ export type HandReply = {
17
17
  } | {
18
18
  readonly kind: "unreachable";
19
19
  readonly reason: string;
20
- } | {
20
+ }
21
+ /** The link closed before the call settled; `sent`: its invoke had been handed to the transport, so it may have run. */
22
+ | {
21
23
  readonly kind: "closed";
24
+ readonly sent: boolean;
22
25
  }
23
26
  /** The session's epoch never opened the lane (S35): a newer owner holds it, or the hand refused this sender. */
24
27
  | {
@@ -9,6 +9,9 @@ import { decodeRemoteMessage, encodeRemoteMessage, } from "./remote-protocol.js"
9
9
  */
10
10
  export function createHandLink(transport, planeHandlers = {}, filePlanes = [], epoch) {
11
11
  const pending = new Map();
12
+ // A closed link sends nothing more: its transport is closed, and the one designed re-send (a durable hand's hello)
13
+ // happens on a link that is still open. A call made after close() is settled at once as never sent.
14
+ let closed = false;
12
15
  const stamp = epoch === undefined ? {} : { epoch };
13
16
  /** Messages handed to the transport: a hand's `hello` re-sends only these, never one still waiting on its floor. */
14
17
  const sent = new Set();
@@ -55,6 +58,10 @@ export function createHandLink(transport, planeHandlers = {}, filePlanes = [], e
55
58
  });
56
59
  };
57
60
  transport.onFrame((frame) => {
61
+ // A closed link ignores every inbound frame, so it writes nothing: no ack for a late settled or terminal reply, no
62
+ // floor re-send on a hello, and no plane.refused (or any other plane answer) for a nested plane.request.
63
+ if (closed)
64
+ return;
58
65
  const nested = decodePlaneMessage(frame.payload);
59
66
  if (nested !== undefined)
60
67
  return planes.receive(frame.lane, nested);
@@ -99,6 +106,10 @@ export function createHandLink(transport, planeHandlers = {}, filePlanes = [], e
99
106
  const replied = new Promise((resolve) => {
100
107
  pending.set(executionId, { message, resolve });
101
108
  });
109
+ if (closed) {
110
+ settle(executionId, { kind: "closed", sent: false });
111
+ return replied;
112
+ }
102
113
  if (signal?.aborted) {
103
114
  settle(executionId, { kind: "aborted", sent: false });
104
115
  return replied;
@@ -144,8 +155,9 @@ export function createHandLink(transport, planeHandlers = {}, filePlanes = [], e
144
155
  });
145
156
  },
146
157
  close() {
158
+ closed = true;
147
159
  for (const executionId of [...pending.keys()])
148
- settle(executionId, { kind: "closed" });
160
+ settle(executionId, { kind: "closed", sent: sent.has(executionId) });
149
161
  transport.close();
150
162
  },
151
163
  };
@@ -40,7 +40,11 @@ export function createRemoteToolHost(options) {
40
40
  case "unreachable":
41
41
  return errorResult(`The hand is unreachable: ${reply.reason}`);
42
42
  case "closed":
43
- return errorResult("The hand link was closed before the call settled");
43
+ // The hand died or was replaced while the call was in flight (omo-service#997). A call it may have received
44
+ // ends as a hand restart with its outcome unknown; one it never received had no effect. Neither runs again.
45
+ return terminalResult(options.placement, reply.sent
46
+ ? { reason: "hand_restarted", uncertain: true, hooksRan: true }
47
+ : { reason: "cancelled", uncertain: false, hooksRan: false });
44
48
  case "epoch_refused":
45
49
  return errorResult(`The hand refused this session's epoch: ${reply.reason}`);
46
50
  }
@@ -0,0 +1,93 @@
1
+ import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
2
+ import type { WakeDrop } from "./wake-link.ts";
3
+ import { type WakeEvent, type WakeRefusal } from "./wake-types.ts";
4
+ /**
5
+ * The brain side of a hand's wakes (senpi H3): what a taken wake asks the loop to do, parsed once at this boundary,
6
+ * and its delivery to the loop session as a local session would make it. `wake.scope` is the hand's execution scope
7
+ * id: the id the brain gave the session's `ExecutionScope`. A senpi session mints a fresh random id per session
8
+ * (`pipeline-witness.ts`), so it is not the session id unless the brain chose it to be; map a scope to its sessions.
9
+ */
10
+ /** Session modes that never start a turn by themselves (a one-shot run would never end). */
11
+ export declare const ONE_SHOT_MODES: ReadonlySet<string>;
12
+ type Content = string | (TextContent | ImageContent)[];
13
+ export interface HandWakeMessage {
14
+ readonly customType: string;
15
+ readonly content: Content;
16
+ readonly display: boolean;
17
+ readonly details?: unknown;
18
+ }
19
+ export interface HandWakeMessageOptions {
20
+ readonly triggerTurn?: boolean;
21
+ readonly deliverAs?: "steer" | "followUp" | "nextTurn";
22
+ }
23
+ export interface HandWakeUserMessageOptions {
24
+ readonly deliverAs?: "steer" | "followUp";
25
+ readonly expandPromptTemplates?: boolean;
26
+ }
27
+ export type HandWakeNoticeType = "info" | "warning" | "error";
28
+ /** A wake parsed on the brain, for the loop session of its scope it names (`sessionId`), or the scope's own. */
29
+ export type HandWakeDelivery = {
30
+ readonly sessionId?: string;
31
+ } & ({
32
+ readonly kind: "message";
33
+ readonly message: HandWakeMessage;
34
+ readonly options?: HandWakeMessageOptions;
35
+ } | {
36
+ readonly kind: "user_message";
37
+ readonly content: Content;
38
+ readonly options?: HandWakeUserMessageOptions;
39
+ } | {
40
+ readonly kind: "entry";
41
+ readonly customType: string;
42
+ readonly data?: unknown;
43
+ } | {
44
+ readonly kind: "notice";
45
+ readonly message: string;
46
+ readonly type?: HandWakeNoticeType;
47
+ } | {
48
+ readonly kind: "dropped";
49
+ readonly reason: string;
50
+ readonly count: number;
51
+ });
52
+ export declare class MalformedHandWakeError extends Error {
53
+ readonly name = "MalformedHandWakeError";
54
+ readonly eventId: string;
55
+ constructor(eventId: string, what: string);
56
+ }
57
+ /** What a taken wake asks the loop to do; anything else throws {@link MalformedHandWakeError}. */
58
+ export declare function parseHandWake(wake: WakeEvent): HandWakeDelivery;
59
+ /** The brain session a wake is delivered to: the calls a local session makes, and the facts its guard reads. */
60
+ export interface HandWakeSession {
61
+ sendMessage(message: HandWakeMessage, options?: HandWakeMessageOptions): void;
62
+ sendUserMessage(content: Content, options?: HandWakeUserMessageOptions): void;
63
+ appendEntry(customType: string, data?: unknown): void;
64
+ notify(message: string, type?: HandWakeNoticeType): void;
65
+ /** The session's mode and model now, as a local notifier reads them; `undefined` before the session started. */
66
+ context(): {
67
+ readonly mode: string;
68
+ readonly model: unknown;
69
+ } | undefined;
70
+ }
71
+ /** `skipped`: the session is one-shot (print/json), has no model, or has not started, so the wake may not start a turn. */
72
+ export type HandWakeOutcome = "delivered" | "skipped";
73
+ /**
74
+ * A taken wake becomes the very call a local session makes. A wake that would start a turn (a message with
75
+ * `triggerTurn`, or a user message) is skipped when the session may not start one; entries, notices and messages for
76
+ * the next turn are always delivered. A drop report becomes a warning notice the user sees, as a local session reports
77
+ * lost background output.
78
+ */
79
+ export declare function deliverHandWake(wake: WakeEvent, session: HandWakeSession): HandWakeOutcome;
80
+ /**
81
+ * The consumer of `serveHandWakes({ onDropped })` (a best-effort `unrecorded` report, which has no durable record):
82
+ * the same warning notice a durable drop report gives, shown in each session of `drop.scope`.
83
+ */
84
+ export declare function deliverHandDrop(drop: WakeDrop, session: Pick<HandWakeSession, "notify">): void;
85
+ /**
86
+ * The brain's check that a wake names only a loop session of its own scope (senpi#6767 review L3), for
87
+ * `serveHandWakes({ check })`. `sessionsOf` answers the loop sessions bound to a scope, or `undefined` while none are
88
+ * known (refused `unknown_scope`, which the hand retries). A wake naming any other session, or a malformed session id,
89
+ * is refused `not_scope_session` for good, never committed, and reported dropped (`refused`) after the retention.
90
+ */
91
+ export declare function scopeSessionCheck(sessionsOf: (scope: string) => ReadonlySet<string> | undefined): (wake: WakeEvent) => WakeRefusal | undefined;
92
+ export {};
93
+ //# sourceMappingURL=wake-delivery.d.ts.map
@@ -0,0 +1,183 @@
1
+ import { WAKE_DROPPED_SOURCE } from "./wake-types.js";
2
+ /**
3
+ * The brain side of a hand's wakes (senpi H3): what a taken wake asks the loop to do, parsed once at this boundary,
4
+ * and its delivery to the loop session as a local session would make it. `wake.scope` is the hand's execution scope
5
+ * id: the id the brain gave the session's `ExecutionScope`. A senpi session mints a fresh random id per session
6
+ * (`pipeline-witness.ts`), so it is not the session id unless the brain chose it to be; map a scope to its sessions.
7
+ */
8
+ /** Session modes that never start a turn by themselves (a one-shot run would never end). */
9
+ export const ONE_SHOT_MODES = new Set(["print", "json"]);
10
+ export class MalformedHandWakeError extends Error {
11
+ constructor(eventId, what) {
12
+ super(`malformed hand wake ${eventId}: ${what}`);
13
+ this.name = "MalformedHandWakeError";
14
+ this.eventId = eventId;
15
+ }
16
+ }
17
+ const isObject = (value) => value !== null && value !== undefined && typeof value === "object" && !Array.isArray(value);
18
+ const isOneOf = (value, allowed) => typeof value === "string" && allowed.includes(value);
19
+ const DELIVER_AS = ["steer", "followUp", "nextTurn"];
20
+ const USER_DELIVER_AS = ["steer", "followUp"];
21
+ const NOTICE_TYPES = ["info", "warning", "error"];
22
+ const isContentPart = (value) => isObject(value) &&
23
+ ((value.type === "text" && typeof value.text === "string") ||
24
+ (value.type === "image" && typeof value.data === "string" && typeof value.mimeType === "string"));
25
+ function content(value) {
26
+ if (typeof value === "string")
27
+ return value;
28
+ if (Array.isArray(value) && value.every(isContentPart))
29
+ return value;
30
+ return undefined;
31
+ }
32
+ function message(value) {
33
+ if (!isObject(value) || typeof value.customType !== "string" || typeof value.display !== "boolean")
34
+ return undefined;
35
+ const body = content(value.content);
36
+ if (body === undefined)
37
+ return undefined;
38
+ return {
39
+ customType: value.customType,
40
+ content: body,
41
+ display: value.display,
42
+ ...(value.details === undefined ? {} : { details: value.details }),
43
+ };
44
+ }
45
+ /** A payload's `options`: absent, the fields it has, or `null` when malformed. */
46
+ function optionsOf(value, fields) {
47
+ if (value === undefined)
48
+ return undefined;
49
+ if (!isObject(value))
50
+ return null;
51
+ const out = {};
52
+ for (const [name, valid] of Object.entries(fields)) {
53
+ const field = value[name];
54
+ if (field === undefined)
55
+ continue;
56
+ if (!valid(field))
57
+ return null;
58
+ out[name] = field;
59
+ }
60
+ return out;
61
+ }
62
+ /** What a taken wake asks the loop to do; anything else throws {@link MalformedHandWakeError}. */
63
+ export function parseHandWake(wake) {
64
+ const fail = (what) => {
65
+ throw new MalformedHandWakeError(wake.eventId, what);
66
+ };
67
+ const payload = isObject(wake.payload) ? wake.payload : fail("payload");
68
+ const { sessionId } = payload;
69
+ if (sessionId !== undefined && typeof sessionId !== "string")
70
+ return fail("sessionId");
71
+ const session = typeof sessionId === "string" ? { sessionId } : {};
72
+ switch (wake.source) {
73
+ case "message": {
74
+ const options = optionsOf(payload.options, {
75
+ triggerTurn: (v) => typeof v === "boolean",
76
+ deliverAs: (v) => isOneOf(v, DELIVER_AS),
77
+ });
78
+ if (options === null)
79
+ return fail("message options");
80
+ const body = message(payload.message) ?? fail("message");
81
+ return { ...session, kind: "message", message: body, ...(options === undefined ? {} : { options }) };
82
+ }
83
+ case "user_message": {
84
+ const options = optionsOf(payload.options, {
85
+ deliverAs: (v) => isOneOf(v, USER_DELIVER_AS),
86
+ expandPromptTemplates: (v) => typeof v === "boolean",
87
+ });
88
+ if (options === null)
89
+ return fail("user message options");
90
+ const body = content(payload.content) ?? fail("user message content");
91
+ return { ...session, kind: "user_message", content: body, ...(options === undefined ? {} : { options }) };
92
+ }
93
+ case "entry": {
94
+ const customType = typeof payload.customType === "string" ? payload.customType : fail("entry customType");
95
+ return {
96
+ ...session,
97
+ kind: "entry",
98
+ customType,
99
+ ...(payload.data === undefined ? {} : { data: payload.data }),
100
+ };
101
+ }
102
+ case "notice": {
103
+ const notice = typeof payload.message === "string" ? payload.message : fail("notice");
104
+ const { type } = payload;
105
+ if (type !== undefined && !isOneOf(type, NOTICE_TYPES))
106
+ return fail("notice type");
107
+ return { ...session, kind: "notice", message: notice, ...(isOneOf(type, NOTICE_TYPES) ? { type } : {}) };
108
+ }
109
+ case WAKE_DROPPED_SOURCE: {
110
+ const { reason, count } = payload;
111
+ if (typeof reason !== "string" || typeof count !== "number")
112
+ return fail("drop report");
113
+ return { kind: "dropped", reason, count };
114
+ }
115
+ default:
116
+ return fail(`source ${wake.source}`);
117
+ }
118
+ }
119
+ /**
120
+ * Whether the session may start a turn now (senpi#6767 review M2): the guard every local notifier applies before it
121
+ * wakes a session (senpi's terminal and eval notifiers), applied here because on a hand they send without it.
122
+ */
123
+ function mayStartTurn(session) {
124
+ const context = session.context();
125
+ return context !== undefined && !ONE_SHOT_MODES.has(context.mode) && context.model !== undefined;
126
+ }
127
+ const dropNotice = (count, reason) => `${count} late result${count === 1 ? "" : "s"} from work on the user's machine never arrived (${reason}).`;
128
+ /**
129
+ * A taken wake becomes the very call a local session makes. A wake that would start a turn (a message with
130
+ * `triggerTurn`, or a user message) is skipped when the session may not start one; entries, notices and messages for
131
+ * the next turn are always delivered. A drop report becomes a warning notice the user sees, as a local session reports
132
+ * lost background output.
133
+ */
134
+ export function deliverHandWake(wake, session) {
135
+ const delivery = parseHandWake(wake);
136
+ switch (delivery.kind) {
137
+ case "message":
138
+ if (delivery.options?.triggerTurn === true && !mayStartTurn(session))
139
+ return "skipped";
140
+ session.sendMessage(delivery.message, delivery.options);
141
+ return "delivered";
142
+ case "user_message":
143
+ if (!mayStartTurn(session))
144
+ return "skipped";
145
+ session.sendUserMessage(delivery.content, delivery.options);
146
+ return "delivered";
147
+ case "entry":
148
+ session.appendEntry(delivery.customType, delivery.data);
149
+ return "delivered";
150
+ case "notice":
151
+ session.notify(delivery.message, delivery.type);
152
+ return "delivered";
153
+ case "dropped":
154
+ session.notify(dropNotice(delivery.count, delivery.reason), "warning");
155
+ return "delivered";
156
+ }
157
+ }
158
+ /**
159
+ * The consumer of `serveHandWakes({ onDropped })` (a best-effort `unrecorded` report, which has no durable record):
160
+ * the same warning notice a durable drop report gives, shown in each session of `drop.scope`.
161
+ */
162
+ export function deliverHandDrop(drop, session) {
163
+ session.notify(dropNotice(drop.count, drop.reason), "warning");
164
+ }
165
+ /**
166
+ * The brain's check that a wake names only a loop session of its own scope (senpi#6767 review L3), for
167
+ * `serveHandWakes({ check })`. `sessionsOf` answers the loop sessions bound to a scope, or `undefined` while none are
168
+ * known (refused `unknown_scope`, which the hand retries). A wake naming any other session, or a malformed session id,
169
+ * is refused `not_scope_session` for good, never committed, and reported dropped (`refused`) after the retention.
170
+ */
171
+ export function scopeSessionCheck(sessionsOf) {
172
+ return (wake) => {
173
+ const sessionId = isObject(wake.payload) ? wake.payload.sessionId : undefined;
174
+ if (sessionId === undefined)
175
+ return undefined;
176
+ const sessions = sessionsOf(wake.scope);
177
+ // Sessions not known yet (a brain restart, a bind still in progress) is not an answer: the hand retries.
178
+ if (sessions === undefined)
179
+ return "unknown_scope";
180
+ return typeof sessionId === "string" && sessions.has(sessionId) ? undefined : "not_scope_session";
181
+ };
182
+ }
183
+ //# sourceMappingURL=wake-delivery.js.map
@@ -1,6 +1,6 @@
1
1
  import type { DurableStore } from "../durable/store.ts";
2
2
  import type { AdmissionLine } from "../durable/store-admission.ts";
3
- import { type WakeEvent, type WakeInboxRecord, type WakeReceipt } from "./wake-types.ts";
3
+ import { type WakeEvent, type WakeInboxRecord, type WakeReceipt, type WakeRefusal } from "./wake-types.ts";
4
4
  export interface WakeInboxOptions {
5
5
  readonly issuer: string;
6
6
  readonly store: DurableStore;
@@ -9,11 +9,32 @@ export interface WakeInboxOptions {
9
9
  readonly clock: () => number;
10
10
  /** The authenticated hand bound to a scope (design 5.6.6), or undefined for a scope this brain does not own (yet): such a wake is refused unknown_scope and re-offered by the hand. */
11
11
  readonly owner: (scope: string) => string | undefined;
12
+ /**
13
+ * A wake the loop could not take (its consumer threw). With it, one such wake never holds the queue: it is reported
14
+ * here, stays pending for later drains, and is taken as `poisoned` (reported once more) at its `maxAttempts`-th
15
+ * failure, while every wake behind it is delivered. Without it, a failure stops the drain and rejects it, as before.
16
+ */
17
+ readonly onUndeliverable?: (failure: WakeDeliveryFailure) => void;
18
+ /** Failed deliveries before a wake is poisoned; default 3. */
19
+ readonly maxAttempts?: number;
20
+ }
21
+ export interface WakeDeliveryFailure {
22
+ readonly wake: WakeEvent;
23
+ readonly error: unknown;
24
+ /** This failure's number, from 1. */
25
+ readonly attempts: number;
26
+ /** The wake was taken without being delivered: it is never offered to the loop again. */
27
+ readonly poisoned: boolean;
12
28
  }
13
29
  /** The brain side of design 5.6.4: deduplicated by event id, acked only after the commit. */
14
30
  export interface WakeInbox {
15
- /** `sender` is the authenticated hand. The returned `ack` is the `wake_ack` to send; it exists only once committed. */
16
- receive(sender: string, wake: WakeEvent): Promise<WakeReceipt>;
31
+ /**
32
+ * `sender` is the authenticated hand. The returned `ack` is the `wake_ack` to send; it exists only once committed. In
33
+ * order: a wake already committed is acked again (`duplicate`); a closed scope refuses; an unbound scope is
34
+ * `unknown_scope` and another hand's `not_scope_hand`; then `check`, the brain's own answer for a new wake of a bound
35
+ * scope (for example `scopeSessionCheck`), runs before anything is committed.
36
+ */
37
+ receive(sender: string, wake: WakeEvent, check?: (wake: WakeEvent) => WakeRefusal | undefined): Promise<WakeReceipt>;
17
38
  /** Hands each committed wake to the loop, then removes it; drains run one at a time, and a crash in between hands the same wake over again, so the consumer is idempotent by event id. */
18
39
  drain(consume: (wake: WakeEvent) => Promise<void>): Promise<number>;
19
40
  closeScope(scope: string): Promise<void>;
@@ -1,6 +1,11 @@
1
- import { isStoreObject } from "./wake-outbox.js";
2
- import { WAKE_RETENTION_MS } from "./wake-types.js";
1
+ import { isStoreObject } from "./wake-outbox-record.js";
2
+ import { WAKE_RETENTION_MS, } from "./wake-types.js";
3
3
  const KIND = "execution.wake-inbox";
4
+ /** The record with `failures`, omitted while none is counted (so a record that never failed keeps its shape). */
5
+ const withFailures = (record, failures) => {
6
+ const { failures: _previous, ...rest } = record;
7
+ return Object.keys(failures).length === 0 ? rest : { ...rest, failures };
8
+ };
4
9
  const EMPTY = { seen: {}, pending: [], closed: {} };
5
10
  function decode(value) {
6
11
  if (value === undefined)
@@ -20,34 +25,65 @@ export function createWakeInbox(options) {
20
25
  ], () => { });
21
26
  };
22
27
  const update = (decide) => admission.admit(async () => decide(await read()));
28
+ const maxAttempts = options.maxAttempts ?? 3;
29
+ /** Removes a wake from the pending list (and its failure count) under `step`. */
30
+ const take = (wake, step) => update(async (record) => {
31
+ if (!record.pending.some((entry) => entry.eventId === wake.eventId))
32
+ return;
33
+ const pending = record.pending.filter((entry) => entry.eventId !== wake.eventId);
34
+ const { [wake.eventId]: _counted, ...failures } = record.failures ?? {};
35
+ await write(withFailures({ ...record, pending }, failures), step, wake.eventId);
36
+ });
37
+ /** Counts one failed delivery; at `maxAttempts` the wake is poisoned (taken), otherwise it stays pending. */
38
+ const failed = async (wake, error, report) => {
39
+ const attempts = ((await read()).failures?.[wake.eventId] ?? 0) + 1;
40
+ const poisoned = attempts >= maxAttempts;
41
+ if (poisoned)
42
+ await take(wake, "poison");
43
+ else
44
+ await update(async (record) => {
45
+ const failures = { ...record.failures, [wake.eventId]: attempts };
46
+ await write(withFailures(record, failures), "failed", wake.eventId);
47
+ });
48
+ report({ wake, error, attempts, poisoned });
49
+ };
23
50
  let draining = Promise.resolve();
24
51
  const drainOnce = async (consume) => {
25
52
  let taken = 0;
26
53
  for (const wake of (await read()).pending) {
27
- await consume(wake);
28
- await update(async (record) => {
29
- if (!record.pending.some((entry) => entry.eventId === wake.eventId))
30
- return;
31
- const pending = record.pending.filter((entry) => entry.eventId !== wake.eventId);
32
- await write({ ...record, pending }, "take", wake.eventId);
33
- });
54
+ try {
55
+ await consume(wake);
56
+ }
57
+ catch (error) {
58
+ const report = options.onUndeliverable;
59
+ if (report === undefined)
60
+ throw error;
61
+ await failed(wake, error, report);
62
+ continue;
63
+ }
64
+ await take(wake, "take");
34
65
  taken += 1;
35
66
  }
36
67
  return taken;
37
68
  };
38
69
  return {
39
70
  read,
40
- receive: (sender, wake) => update(async (record) => {
41
- const bound = owner(wake.scope);
42
- if (bound === undefined)
43
- return { kind: "refused", eventId: wake.eventId, reason: "unknown_scope" };
44
- if (bound !== sender)
45
- return { kind: "refused", eventId: wake.eventId, reason: "not_scope_hand" };
71
+ receive: (sender, wake, check) => update(async (record) => {
72
+ // A wake already committed gets its receipt again whatever changed since (its ack may have been lost): the
73
+ // scope's binding or sessions moving on must never turn a delivered wake into a refusal (review round 3, M1).
46
74
  const seen = record.seen[wake.scope] ?? [];
47
75
  if (seen.includes(wake.eventId))
48
76
  return { kind: "ack", eventId: wake.eventId, duplicate: true };
49
77
  if (record.closed[wake.scope] !== undefined)
50
78
  return { kind: "refused", eventId: wake.eventId, reason: "scope_closed" };
79
+ const bound = owner(wake.scope);
80
+ if (bound === undefined)
81
+ return { kind: "refused", eventId: wake.eventId, reason: "unknown_scope" };
82
+ if (bound !== sender)
83
+ return { kind: "refused", eventId: wake.eventId, reason: "not_scope_hand" };
84
+ const refusal = check?.(wake);
85
+ if (refusal !== undefined)
86
+ return { kind: "refused", eventId: wake.eventId, reason: refusal };
51
87
  await write({
52
88
  ...record,
53
89
  seen: { ...record.seen, [wake.scope]: [...seen, wake.eventId] },
@@ -74,9 +110,8 @@ export function createWakeInbox(options) {
74
110
  return [];
75
111
  const drop = new Set(gone);
76
112
  await write({
113
+ ...record,
77
114
  seen: Object.fromEntries(Object.entries(record.seen).filter(([scope]) => !drop.has(scope))),
78
- pending: record.pending,
79
- closed: record.closed,
80
115
  }, "sweep", null);
81
116
  return gone;
82
117
  }),
@@ -0,0 +1,97 @@
1
+ import type { Transport } from "../transport/transport.ts";
2
+ import type { WakeInbox } from "./wake-inbox.ts";
3
+ import { type WakeOutbox } from "./wake-outbox.ts";
4
+ import { type WakeDropReason, type WakeEvent, type WakeReceipt, type WakeRefusal } from "./wake-types.ts";
5
+ /**
6
+ * The wake link (brain/hand split H3, design 5.6.4 on the hand transport): what a hand's work produces after the call
7
+ * that started it ended reaches the brain that owns its scope at least once, or the brain is told it was dropped. The
8
+ * hand commits each wake to its durable outbox before sending it; the brain answers with a receipt only after its inbox
9
+ * commit; the hand re-offers every un-acked wake when it starts and whenever the brain asks. Everything travels on one
10
+ * lane of the hand's transport, so a relay carries it like any other lane: frames from the hand wait for the brain's
11
+ * next batch.
12
+ */
13
+ export declare const HAND_WAKE_LANE = "hand.wake";
14
+ export type { WakeDropReason };
15
+ /** What the hand reports dropped: `count` wakes of `scope`, for `reason`. */
16
+ export interface WakeDrop {
17
+ readonly scope: string;
18
+ readonly reason: WakeDropReason;
19
+ readonly count: number;
20
+ }
21
+ /**
22
+ * A `wake_dropped` with an `eventId` is a durable drop report: the brain commits it to its inbox like a wake (source
23
+ * {@link WAKE_DROPPED_SOURCE}), so it is delivered once and acked with a `wake_receipt`. Without one (reason
24
+ * `unrecorded`) it is best-effort and goes to `onDropped`.
25
+ */
26
+ export type WakeLinkMessage = {
27
+ readonly kind: "wake";
28
+ readonly wake: WakeEvent;
29
+ } | ({
30
+ readonly kind: "wake_dropped";
31
+ readonly eventId?: string;
32
+ } & WakeDrop) | {
33
+ readonly kind: "wake_receipt";
34
+ readonly receipt: WakeReceipt;
35
+ } | {
36
+ readonly kind: "wake_reoffer";
37
+ };
38
+ export declare function encodeWakeLinkMessage(message: WakeLinkMessage): Uint8Array;
39
+ /** Parses one frame payload as a wake-link message; anything else is `undefined`. */
40
+ export declare function decodeWakeLinkMessage(payload: Uint8Array): WakeLinkMessage | undefined;
41
+ export interface HandWakeLinkOptions {
42
+ /** The hand's end of its link to the brain; only {@link lane} frames reach this link. */
43
+ readonly transport: Transport;
44
+ readonly lane?: string;
45
+ readonly outbox: WakeOutbox;
46
+ /** A wake that could not be recorded or sent, or a receipt that could not be applied. Reported, never thrown. */
47
+ readonly onFault: (error: unknown) => void;
48
+ }
49
+ export interface HandWakeLink {
50
+ /** Settles once the start re-offer has sent every wake and drop report a previous process left un-acked. */
51
+ readonly ready: Promise<void>;
52
+ /**
53
+ * Commits the wake, then sends it. A wake that cannot be committed is reported to the brain as dropped
54
+ * (`unrecorded`) and to `onFault`; it never throws into the work that produced it.
55
+ */
56
+ offer(wake: Omit<WakeEvent, "eventId">): Promise<void>;
57
+ /** The scope closed on the hand: its un-acked wakes are kept for the retention, then reported dropped. */
58
+ closeScope(scope: string): Promise<void>;
59
+ close(): void;
60
+ }
61
+ /** The hand end of the wake link: the durable outbox, sent over the transport, re-offered on start and on request. */
62
+ export declare function createHandWakeLink(options: HandWakeLinkOptions): HandWakeLink;
63
+ /** The brain refused a wake by its own check (`check`): it names a session that is not its scope's. */
64
+ export declare class WakeRefusedError extends Error {
65
+ readonly name = "WakeRefusedError";
66
+ readonly wake: WakeEvent;
67
+ readonly reason: WakeRefusal;
68
+ constructor(wake: WakeEvent, reason: WakeRefusal);
69
+ }
70
+ export interface BrainWakeLinkOptions {
71
+ /** The brain's end of its link to one hand; only {@link lane} frames reach this link. */
72
+ readonly transport: Transport;
73
+ readonly lane?: string;
74
+ /** The brain's durable inbox; it decides which scopes this hand may wake (its `owner`). */
75
+ readonly inbox: WakeInbox;
76
+ /** The authenticated hand at the other end of this link (design 5.6.6), the inbox's `sender`. */
77
+ readonly hand: string;
78
+ /**
79
+ * The brain's own check of a NEW wake of a bound scope, run inside `inbox.receive` after the duplicate, closed-scope
80
+ * and binding checks (for example `scopeSessionCheck`). Its refusal is answered to the hand; `not_scope_session` is
81
+ * also reported to `onFault`. A duplicate is always acked again and never reaches it.
82
+ */
83
+ readonly check?: (wake: WakeEvent) => WakeRefusal | undefined;
84
+ /** A wake or drop report the inbox committed for the first time: the brain drains the inbox to deliver it. */
85
+ readonly onCommitted: (wake: WakeEvent) => void;
86
+ /** A best-effort drop report (`unrecorded`: the hand could not record the wake at all, so nothing is durable). */
87
+ readonly onDropped: (drop: WakeDrop) => void;
88
+ readonly onFault: (error: unknown) => void;
89
+ }
90
+ export interface BrainWakeLink {
91
+ /** Asks the hand to send every wake it holds un-acked again (after a scope is bound, or a brain restart). */
92
+ reoffer(): void;
93
+ close(): void;
94
+ }
95
+ /** The brain end of the wake link: each wake goes to the inbox, and the receipt goes back only after its commit. */
96
+ export declare function serveHandWakes(options: BrainWakeLinkOptions): BrainWakeLink;
97
+ //# sourceMappingURL=wake-link.d.ts.map