@code-yeongyu/senpi-agent-core 2026.11.4-2 → 2026.11.5-1

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.
Files changed (100) hide show
  1. package/dist/agent-loop.js +14 -140
  2. package/dist/agent.d.ts +4 -0
  3. package/dist/agent.js +4 -0
  4. package/dist/conformance/index.d.ts +7 -0
  5. package/dist/conformance/index.js +4 -0
  6. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  7. package/dist/conformance/loop-core-manifest.js +17 -0
  8. package/dist/conformance/registry.js +11 -17
  9. package/dist/egress/types.d.ts +102 -0
  10. package/dist/egress/types.js +7 -0
  11. package/dist/execution/canonical-digest.d.ts +10 -0
  12. package/dist/execution/canonical-digest.js +20 -0
  13. package/dist/execution/chain-count.d.ts +26 -0
  14. package/dist/execution/chain-count.js +45 -0
  15. package/dist/execution/coordinator-plan.d.ts +1 -2
  16. package/dist/execution/coordinator-plan.js +4 -17
  17. package/dist/execution/device-files-node.js +39 -1
  18. package/dist/execution/device-files.d.ts +30 -1
  19. package/dist/execution/device-files.js +38 -1
  20. package/dist/execution/ledger-types.d.ts +3 -1
  21. package/dist/execution/ledger.d.ts +9 -3
  22. package/dist/execution/ledger.js +8 -2
  23. package/dist/execution/loop-hook-host-hand.d.ts +33 -0
  24. package/dist/execution/loop-hook-host-hand.js +71 -0
  25. package/dist/execution/loop-hook-host-protocol.d.ts +46 -0
  26. package/dist/execution/loop-hook-host-protocol.js +47 -0
  27. package/dist/execution/loop-hook-host.d.ts +40 -0
  28. package/dist/execution/loop-hook-host.js +87 -0
  29. package/dist/execution/plane-session.d.ts +56 -0
  30. package/dist/execution/plane-session.js +178 -0
  31. package/dist/execution/plane.d.ts +5 -2
  32. package/dist/execution/plane.js +1 -1
  33. package/dist/execution/prepared/executor-body.d.ts +22 -0
  34. package/dist/execution/prepared/executor-body.js +73 -0
  35. package/dist/execution/prepared/executor-freeze.d.ts +17 -0
  36. package/dist/execution/prepared/executor-freeze.js +42 -0
  37. package/dist/execution/prepared/executor-pipeline.d.ts +11 -0
  38. package/dist/execution/prepared/executor-pipeline.js +26 -0
  39. package/dist/execution/prepared/executor-types.d.ts +131 -0
  40. package/dist/execution/prepared/executor-types.js +2 -0
  41. package/dist/execution/prepared/executor.d.ts +8 -0
  42. package/dist/execution/prepared/executor.js +261 -0
  43. package/dist/execution/prepared/memory-batch-store.d.ts +4 -0
  44. package/dist/execution/prepared/memory-batch-store.js +4 -0
  45. package/dist/execution/prepared/pipeline-prepared-batch.d.ts +27 -0
  46. package/dist/execution/prepared/pipeline-prepared-batch.js +175 -0
  47. package/dist/execution/prepared/pipeline-prepared.d.ts +10 -0
  48. package/dist/execution/prepared/pipeline-prepared.js +54 -0
  49. package/dist/execution/remote-device-files.js +33 -4
  50. package/dist/execution/remote-epoch-gate.d.ts +19 -0
  51. package/dist/execution/remote-epoch-gate.js +46 -0
  52. package/dist/execution/remote-epoch.d.ts +53 -0
  53. package/dist/execution/remote-epoch.js +74 -0
  54. package/dist/execution/remote-executor.d.ts +8 -1
  55. package/dist/execution/remote-executor.js +24 -6
  56. package/dist/execution/remote-file-call.js +1 -0
  57. package/dist/execution/remote-hand-ledger.d.ts +11 -3
  58. package/dist/execution/remote-hand-ledger.js +31 -15
  59. package/dist/execution/remote-link.d.ts +6 -1
  60. package/dist/execution/remote-link.js +50 -14
  61. package/dist/execution/remote-protocol.d.ts +30 -1
  62. package/dist/execution/remote-protocol.js +30 -0
  63. package/dist/execution/remote-tool-host.d.ts +12 -0
  64. package/dist/execution/remote-tool-host.js +3 -1
  65. package/dist/execution/testing/epoch-cases.d.ts +8 -0
  66. package/dist/execution/testing/epoch-cases.js +84 -0
  67. package/dist/execution/testing/epoch-harness.d.ts +47 -0
  68. package/dist/execution/testing/epoch-harness.js +172 -0
  69. package/dist/execution/testing/epoch-registry.d.ts +3 -0
  70. package/dist/execution/testing/epoch-registry.js +17 -0
  71. package/dist/execution/testing/hand-harness.d.ts +3 -0
  72. package/dist/execution/testing/hand-harness.js +27 -22
  73. package/dist/execution/testing/hand-registry.d.ts +3 -0
  74. package/dist/execution/testing/hand-registry.js +20 -0
  75. package/dist/execution/testing/kill-epoch.d.ts +9 -0
  76. package/dist/execution/testing/kill-epoch.js +71 -0
  77. package/dist/execution/testing/kill-hook.d.ts +14 -0
  78. package/dist/execution/testing/kill-hook.js +117 -0
  79. package/dist/execution/testing/multi-epoch-cases.d.ts +4 -0
  80. package/dist/execution/testing/multi-epoch-cases.js +29 -0
  81. package/dist/execution/tool-host.d.ts +13 -1
  82. package/dist/execution/tool-host.js +18 -1
  83. package/dist/harness/agent-harness.d.ts +6 -0
  84. package/dist/harness/execution/tool-host-call.d.ts +13 -0
  85. package/dist/harness/execution/tool-host-call.js +55 -0
  86. package/dist/harness/execution/tools.d.ts +2 -1
  87. package/dist/harness/execution/tools.js +32 -17
  88. package/dist/harness/runtime/drive/tools.js +1 -1
  89. package/dist/harness/runtime/harness.js +1 -0
  90. package/dist/harness/runtime/types.d.ts +1 -0
  91. package/dist/index.d.ts +16 -2
  92. package/dist/index.js +14 -1
  93. package/dist/public-entry.d.ts +10 -0
  94. package/dist/public-entry.js +23 -0
  95. package/dist/step-commit.d.ts +24 -0
  96. package/dist/step-commit.js +24 -0
  97. package/dist/tool-name-alias.d.ts +1 -7
  98. package/dist/tool-name-alias.js +0 -17
  99. package/dist/types.d.ts +37 -1
  100. package/package.json +3 -3
@@ -0,0 +1,46 @@
1
+ export function createEpochGate(epoch, send) {
2
+ const lanes = new Map();
3
+ const decide = (state, refusal) => {
4
+ state.verdict = { refusal };
5
+ state.decided.resolve(refusal);
6
+ };
7
+ const ask = (lane, state) => {
8
+ if (state.verdict !== undefined) {
9
+ state.verdict = undefined;
10
+ state.decided = Promise.withResolvers();
11
+ }
12
+ const asked = state.decided;
13
+ send(lane, { kind: "floor", epoch }).catch((error) => {
14
+ const reason = error instanceof Error ? error.message : String(error);
15
+ if (state.decided === asked && state.verdict === undefined)
16
+ decide(state, `hand_unreachable: ${reason}`);
17
+ });
18
+ };
19
+ return {
20
+ open(lane) {
21
+ const known = lanes.get(lane);
22
+ if (known !== undefined)
23
+ return known.verdict === undefined ? known.decided.promise : Promise.resolve(known.verdict.refusal);
24
+ const state = { decided: Promise.withResolvers(), verdict: undefined };
25
+ lanes.set(lane, state);
26
+ ask(lane, state);
27
+ return state.decided.promise;
28
+ },
29
+ answer(lane, message) {
30
+ const state = lanes.get(lane);
31
+ if (state === undefined || state.verdict !== undefined)
32
+ return;
33
+ if (message.kind === "floor_refused")
34
+ return decide(state, message.reason);
35
+ if (message.floor === epoch)
36
+ return decide(state, undefined);
37
+ decide(state, message.floor > epoch ? "epoch_superseded" : "epoch_floor_mismatch");
38
+ },
39
+ resend() {
40
+ for (const [lane, state] of lanes)
41
+ if (state.verdict?.refusal === undefined)
42
+ ask(lane, state);
43
+ },
44
+ };
45
+ }
46
+ //# sourceMappingURL=remote-epoch-gate.js.map
@@ -0,0 +1,53 @@
1
+ import type { AdmissionLine } from "../durable/store-admission.ts";
2
+ import type { DurableStore } from "../durable/store.ts";
3
+ import type { EpochRefusal, RemoteHandMessage } from "./remote-protocol.ts";
4
+ /** A raise moves a scope's floor by at most one epoch, counted from 0 (relay design 4.4, SP6 `EPOCH_FLOOR_MAX_STEP`). */
5
+ export declare const EPOCH_FLOOR_MAX_STEP = 1;
6
+ /** The hand-store documents holding each scope's floor: this prefix, then the scope ID. */
7
+ export declare const EPOCH_FLOOR_PREFIX = "hand.epoch-floor:";
8
+ /** The sender a self link (fused, split-local) presents to the fence; a peer link presents its authenticated peer. */
9
+ export declare const HAND_SELF_SENDER = "self";
10
+ export type FloorRaise = {
11
+ readonly kind: "acked";
12
+ readonly floor: number;
13
+ } | {
14
+ readonly kind: "refused";
15
+ readonly reason: Exclude<EpochRefusal, "epoch_unsupported">;
16
+ };
17
+ export interface HandEpochFence {
18
+ /** Settles once the floors persisted by an earlier process are in force; nothing is admitted before. */
19
+ readonly ready: Promise<void>;
20
+ /** Raises `scope`'s floor to `epoch` for `sender`, or says why not; a raise below the floor answers the floor. */
21
+ raise(scope: string, epoch: number, sender: string): Promise<FloorRaise>;
22
+ /**
23
+ * Whether a message from `sender` at `epoch` (none: from before epochs) may act on `scope`: anything above the floor,
24
+ * or the floor's own owner at the floor's epoch. Synchronous, so it can run inside a ledger step's admission slot.
25
+ */
26
+ admits(scope: string, epoch: number | undefined, sender: string): boolean;
27
+ }
28
+ export interface HandEpochFenceOptions {
29
+ /**
30
+ * The brain principal that owns each scope's session now: the embedder's placement record, which changes when the
31
+ * session moves. Only that owner raises the scope's floor; any other sender is refused, whatever grant it holds.
32
+ */
33
+ readonly ownerOf: (scope: string) => string | undefined;
34
+ /**
35
+ * Where floors persist: the hand's store, under its owner epoch, on the execution ledger's admission line, so a floor
36
+ * and every ledger step are ordered and a restarted hand keeps the floors it acked. Without it, floors live as long
37
+ * as the process.
38
+ */
39
+ readonly durable?: {
40
+ readonly store: DurableStore;
41
+ readonly epoch: number;
42
+ readonly admission: AdmissionLine;
43
+ };
44
+ }
45
+ /**
46
+ * A hand's epoch floors, one per execution scope (brain/hand S35): the hand side of SP6's `EpochFence`. The floor
47
+ * never lowers and remembers its owner, so after a move the old owner's delayed invoke, abort or ack is refused and a
48
+ * rival at the new owner's epoch is fenced.
49
+ */
50
+ export declare function createHandEpochFence(options: HandEpochFenceOptions): HandEpochFence;
51
+ /** The hand's answer to a floor on `scope`: a hand with no fence refuses it, so its session never dispatches unfenced. */
52
+ export declare function answerFloor(fence: HandEpochFence | undefined, scope: string, epoch: number, sender: string): Promise<RemoteHandMessage>;
53
+ //# sourceMappingURL=remote-epoch.d.ts.map
@@ -0,0 +1,74 @@
1
+ /** A raise moves a scope's floor by at most one epoch, counted from 0 (relay design 4.4, SP6 `EPOCH_FLOOR_MAX_STEP`). */
2
+ export const EPOCH_FLOOR_MAX_STEP = 1;
3
+ /** The hand-store documents holding each scope's floor: this prefix, then the scope ID. */
4
+ export const EPOCH_FLOOR_PREFIX = "hand.epoch-floor:";
5
+ /** The sender a self link (fused, split-local) presents to the fence; a peer link presents its authenticated peer. */
6
+ export const HAND_SELF_SENDER = "self";
7
+ function decodeFloor(data) {
8
+ if (typeof data === "object" && data !== null && !Array.isArray(data) && "epoch" in data && "owner" in data) {
9
+ const { epoch, owner } = data;
10
+ if (typeof epoch === "number" && Number.isSafeInteger(epoch) && epoch >= 1 && typeof owner === "string")
11
+ return { epoch, owner };
12
+ }
13
+ throw new Error("A stored epoch floor is malformed");
14
+ }
15
+ /**
16
+ * A hand's epoch floors, one per execution scope (brain/hand S35): the hand side of SP6's `EpochFence`. The floor
17
+ * never lowers and remembers its owner, so after a move the old owner's delayed invoke, abort or ack is refused and a
18
+ * rival at the new owner's epoch is fenced.
19
+ */
20
+ export function createHandEpochFence(options) {
21
+ const { durable, ownerOf } = options;
22
+ const floors = new Map();
23
+ const ready = (async () => {
24
+ if (durable === undefined)
25
+ return;
26
+ for (const document of await durable.store.scanDocuments(EPOCH_FLOOR_PREFIX))
27
+ floors.set(document.key.slice(EPOCH_FLOOR_PREFIX.length), decodeFloor(document.data));
28
+ })();
29
+ const raiseNow = async (scope, epoch, sender) => {
30
+ if (ownerOf(scope) !== sender)
31
+ return { kind: "refused", reason: "peer_unauthorized" };
32
+ const current = floors.get(scope);
33
+ const floor = current?.epoch ?? 0;
34
+ if (epoch < floor)
35
+ return { kind: "acked", floor };
36
+ if (current !== undefined && epoch === floor)
37
+ return current.owner === sender ? { kind: "acked", floor } : { kind: "refused", reason: "epoch_fenced" };
38
+ if (epoch - floor > EPOCH_FLOOR_MAX_STEP)
39
+ return { kind: "refused", reason: "epoch_step_exceeded" };
40
+ const next = { epoch, owner: sender };
41
+ if (durable === undefined)
42
+ floors.set(scope, next);
43
+ else {
44
+ const write = { op: "put", key: `${EPOCH_FLOOR_PREFIX}${scope}`, data: { ...next } };
45
+ await durable.store.commit(durable.epoch, [write], () => floors.set(scope, next));
46
+ }
47
+ return { kind: "acked", floor: epoch };
48
+ };
49
+ return {
50
+ ready,
51
+ async raise(scope, epoch, sender) {
52
+ await ready;
53
+ const run = () => raiseNow(scope, epoch, sender);
54
+ return durable === undefined ? run() : durable.admission.admit(run);
55
+ },
56
+ admits(scope, epoch, sender) {
57
+ const floor = floors.get(scope);
58
+ if (floor === undefined)
59
+ return true;
60
+ const at = epoch ?? 0;
61
+ return at > floor.epoch || (at === floor.epoch && floor.owner === sender);
62
+ },
63
+ };
64
+ }
65
+ /** The hand's answer to a floor on `scope`: a hand with no fence refuses it, so its session never dispatches unfenced. */
66
+ export async function answerFloor(fence, scope, epoch, sender) {
67
+ if (fence === undefined)
68
+ return { kind: "floor_refused", reason: "epoch_unsupported" };
69
+ const raised = await fence.raise(scope, epoch, sender);
70
+ return raised.kind === "acked"
71
+ ? { kind: "floor_ack", floor: raised.floor }
72
+ : { kind: "floor_refused", reason: raised.reason };
73
+ }
74
+ //# sourceMappingURL=remote-epoch.js.map
@@ -2,6 +2,7 @@ import type { Transport } from "../transport/transport.ts";
2
2
  import type { AgentToolResult } from "../types.ts";
3
3
  import { type NestedRequest } from "./plane.ts";
4
4
  import { type HandAuthority } from "./grant-verify.ts";
5
+ import { type HandEpochFence } from "./remote-epoch.ts";
5
6
  import type { HandLedger } from "./remote-hand-ledger.ts";
6
7
  import type { ExecutionScope } from "./tool-host.ts";
7
8
  /** One call as a hand runs it: the raw name and arguments, never anything about the session that sent it. */
@@ -25,7 +26,7 @@ export interface HandScope {
25
26
  * Runs one device file operation (S40) after its grant was checked: the scope's `tool_call` handlers, filesystem
26
27
  * policy and the operation itself, the outcome in `details.file`. Absent: the scope serves no file channel.
27
28
  */
28
- file?(op: string, args: unknown, signal: AbortSignal): Promise<AgentToolResult<unknown>>;
29
+ file?(op: string, args: unknown, signal: AbortSignal, nested: NestedRequest): Promise<AgentToolResult<unknown>>;
29
30
  dispose(): Promise<void>;
30
31
  }
31
32
  export type OpenHandScope = (scope: ExecutionScope) => Promise<HandScope>;
@@ -45,6 +46,12 @@ export interface RemoteExecutorOptions {
45
46
  * recorded outcome. Without it, the hand remembers execution IDs only while it lives.
46
47
  */
47
48
  readonly ledger?: HandLedger;
49
+ /**
50
+ * The hand's epoch floors (S35), shared by every link's executor in this process. With it, a scope's owner raises the
51
+ * floor before it dispatches, and an invoke, abort or ack below the floor is refused or ignored. Without it, a floor
52
+ * is refused `epoch_unsupported`, so a session that moves never dispatches to this hand.
53
+ */
54
+ readonly fence?: HandEpochFence;
48
55
  /** This hand process's identity in its `hello`; a fresh one per start by default. */
49
56
  readonly instance?: string;
50
57
  /** Announce the device file channel (S40) in `hello`; its scopes then serve `HandScope.file`. */
@@ -1,8 +1,9 @@
1
- import { FILE_CHANNEL } from "./device-files.js";
1
+ import { FILE_CHANNEL, RUN_CHANNEL } from "./device-files.js";
2
2
  import { createPlaneClient, decodePlaneMessage } from "./plane.js";
3
3
  import { fileCall, fileRefusal, fileStopped } from "./remote-file-call.js";
4
4
  import { decodeRemoteMessage, encodeRemoteMessage, HAND_CONTROL_LANE, toRemoteToolResult, } from "./remote-protocol.js";
5
5
  import { authorize } from "./grant-verify.js";
6
+ import { answerFloor, HAND_SELF_SENDER } from "./remote-epoch.js";
6
7
  /**
7
8
  * The hand's side of remote tool execution (brain/hand split, S27a). Each scope keeps its own state, opened lazily and
8
9
  * bound to the root it was opened with: a later call naming the same scope with another root is refused, as is any
@@ -10,7 +11,9 @@ import { authorize } from "./grant-verify.js";
10
11
  * passed on: the hand keys on the scope and does not know the session (R16).
11
12
  */
12
13
  export function createRemoteExecutor(options) {
13
- const { transport, openScope, ledger, authority } = options;
14
+ const { transport, openScope, ledger, authority, fence } = options;
15
+ const sender = authority.kind === "peer" ? authority.peer : HAND_SELF_SENDER;
16
+ const admits = (lane, epoch) => fence === undefined || fence.admits(lane, epoch, sender);
14
17
  const scopes = new Map();
15
18
  const accepted = [];
16
19
  const seen = new Set();
@@ -46,6 +49,8 @@ export function createRemoteExecutor(options) {
46
49
  const verdict = authorize(authority, call.scope.root);
47
50
  if (!verdict.ok)
48
51
  return refuse(lane, call.executionId, verdict.reason);
52
+ if (!admits(lane, call.epoch))
53
+ return refuse(lane, call.executionId, "epoch_fenced");
49
54
  if (ledger === undefined && seen.has(call.executionId))
50
55
  return refuse(lane, call.executionId, "duplicate_execution");
51
56
  seen.add(call.executionId);
@@ -61,7 +66,7 @@ export function createRemoteExecutor(options) {
61
66
  return refuse(lane, call.executionId, `scope_unavailable: ${reason}`);
62
67
  }
63
68
  if (ledger !== undefined) {
64
- const admission = await ledger.admit(call);
69
+ const admission = await ledger.admit(call, () => admits(lane, call.epoch));
65
70
  if (admission.kind === "reply")
66
71
  return reply(lane, admission.message);
67
72
  if (admission.kind === "in_flight")
@@ -78,6 +83,12 @@ export function createRemoteExecutor(options) {
78
83
  : [];
79
84
  const done = (async () => {
80
85
  await Promise.allSettled(dependencies);
86
+ // Without a ledger this is the call's dispatch point: a floor raised while its scope opened or it waited on
87
+ // earlier calls fences it here. With a ledger, the guarded `dispatch` step already decided it atomically.
88
+ if (ledger === undefined && !admits(lane, call.epoch)) {
89
+ running.delete(call.executionId);
90
+ return refuse(lane, call.executionId, "epoch_fenced");
91
+ }
81
92
  let result;
82
93
  try {
83
94
  // The grant must still hold when the call starts: a snapshot installed while it waited (scope opening,
@@ -95,7 +106,9 @@ export function createRemoteExecutor(options) {
95
106
  })
96
107
  : scope.file === undefined
97
108
  ? fileRefusal("unsupported", "this hand serves no file channel")
98
- : await scope.file(file.op, call.arguments, controller.signal);
109
+ : await scope.file(file.op, call.arguments, controller.signal,
110
+ // Only planes the brain lets file operations host answer it (a two-sided extension's forwarded tool events).
111
+ planes.requestFor(call.executionId, lane, controller.signal));
99
112
  // A file operation that ended aborted ships no payload: a revoked grant is a refusal (R7), never data.
100
113
  if (file !== undefined && controller.signal.aborted)
101
114
  result = fileStopped(authorize(authority, call.scope.root).ok);
@@ -133,6 +146,7 @@ export function createRemoteExecutor(options) {
133
146
  // The connect hook: one `hello` per hand start, after recovery. The reliable transport re-delivers it across carrier
134
147
  // re-attaches, so only a new hand process announces a new identity.
135
148
  const ready = (async () => {
149
+ await fence?.ready;
136
150
  if (ledger !== undefined)
137
151
  for (const { lane, message } of await ledger.recover())
138
152
  reply(lane, message);
@@ -140,7 +154,7 @@ export function createRemoteExecutor(options) {
140
154
  kind: "hello",
141
155
  instance: options.instance ?? crypto.randomUUID(),
142
156
  durable: ledger !== undefined,
143
- ops: options.fileChannel === true ? [FILE_CHANNEL] : [],
157
+ ops: options.fileChannel === true ? [FILE_CHANNEL, RUN_CHANNEL] : [],
144
158
  });
145
159
  })();
146
160
  ready.catch((error) => options.onFault(error));
@@ -164,12 +178,16 @@ export function createRemoteExecutor(options) {
164
178
  try {
165
179
  if (message.kind === "invoke")
166
180
  await invoke(frame.lane, message);
181
+ else if (message.kind === "floor")
182
+ reply(frame.lane, await answerFloor(fence, frame.lane, message.epoch, sender));
183
+ else if ((message.kind === "abort" || message.kind === "ack") && !admits(frame.lane, message.epoch))
184
+ return;
167
185
  else if (message.kind === "file")
168
186
  await invoke(frame.lane, fileCall(message), { op: message.op });
169
187
  else if (message.kind === "abort")
170
188
  running.get(message.executionId)?.controller.abort();
171
189
  else if (message.kind === "ack")
172
- await ledger?.ack(message.executionId);
190
+ await ledger?.ack(message.executionId, () => admits(frame.lane, message.epoch));
173
191
  }
174
192
  catch (error) {
175
193
  options.onFault(error);
@@ -13,6 +13,7 @@ export function fileCall(message) {
13
13
  toolCallId: message.executionId,
14
14
  name: `file.${message.op}`,
15
15
  arguments: message.args,
16
+ ...(message.epoch === undefined ? {} : { epoch: message.epoch }),
16
17
  };
17
18
  }
18
19
  export function fileResult(outcome) {
@@ -21,10 +21,18 @@ export type HandAdmission = {
21
21
  readonly kind: "in_flight";
22
22
  };
23
23
  export interface HandLedger {
24
- admit(invoke: RemoteInvoke): Promise<HandAdmission>;
24
+ /**
25
+ * `admits` is the sender's epoch check (S35), run inside every step of the walk: once it fails, the walk stops, a
26
+ * record it already wrote is cancelled (the call never dispatches), and the invoke is refused `epoch_fenced`.
27
+ */
28
+ admit(invoke: RemoteInvoke, admits?: () => boolean): Promise<HandAdmission>;
25
29
  settle(invoke: RemoteInvoke, result: RemoteToolResult): Promise<RemoteHandMessage>;
26
- ack(executionId: string): Promise<void>;
27
- /** Runs the ledger's restart recovery, then returns every outcome the session has not acknowledged, by lane. */
30
+ /** `admits` is the sender's epoch check, run inside the ack's admission slot: a fenced ack changes nothing. */
31
+ ack(executionId: string, admits?: () => boolean): Promise<void>;
32
+ /**
33
+ * Runs the ledger's restart recovery, then returns every outcome the session has not acknowledged, by lane. Only the
34
+ * first call recovers: a later link's executor on the same live hand gets nothing, and its calls keep running.
35
+ */
28
36
  recover(): Promise<Array<{
29
37
  readonly lane: string;
30
38
  readonly message: RemoteHandMessage;
@@ -34,7 +34,9 @@ function asStoreValue(value) {
34
34
  export function createHandLedger(options) {
35
35
  const { ledger, executor, issuer, workspace, now, leaseMs } = options;
36
36
  const keyOf = (executionId) => ({ issuer, commandId: executionId });
37
- const apply = (executionId, event, actor) => ledger.apply({ key: keyOf(executionId), generation: GENERATION, actor: { id: actor }, now: now(), event });
37
+ const apply = (executionId, event, actor, guard) => ledger.apply({ key: keyOf(executionId), generation: GENERATION, actor: { id: actor }, now: now(), event }, guard);
38
+ let recovered;
39
+ const fencedBy = (admits) => admits === undefined ? undefined : () => (admits() ? undefined : "epoch_fenced");
38
40
  /** Calls this process admitted or runs; a duplicate invoke for one of them waits on that run. */
39
41
  const owned = new Set();
40
42
  const replyFrom = (reply, executionId) => {
@@ -44,7 +46,7 @@ export function createHandLedger(options) {
44
46
  return { kind: "refused", executionId, reason: "result_expired" };
45
47
  return outcomeOf(reply.entry) ?? { kind: "refused", executionId, reason: "not_settled" };
46
48
  };
47
- const admitNew = (invoke, digest) => {
49
+ const admitNew = (invoke, digest, guard) => {
48
50
  const admittedAt = now();
49
51
  return ledger.admit({
50
52
  issuer,
@@ -57,7 +59,13 @@ export function createHandLedger(options) {
57
59
  admittedAt,
58
60
  leaseUntil: admittedAt + leaseMs,
59
61
  reconcilable: false,
60
- });
62
+ }, guard);
63
+ };
64
+ /** A fenced walk: the record it wrote (if any) is cancelled so it never dispatches, and the invoke is refused. */
65
+ const fenced = async (executionId) => {
66
+ if ((await ledger.read(keyOf(executionId))) !== undefined)
67
+ await apply(executionId, { kind: "cancel" }, issuer);
68
+ return { kind: "reply", message: { kind: "refused", executionId, reason: "epoch_fenced" } };
61
69
  };
62
70
  /**
63
71
  * Walks a call to `dispatched` from whatever its record holds: a new call from admission, a `prepared` or
@@ -65,8 +73,9 @@ export function createHandLedger(options) {
65
73
  * that holds another request under this execution ID (other name, arguments or scope) is refused
66
74
  * `identity_conflict`, as the ledger refuses such an admission: a resumed call runs only what was frozen.
67
75
  */
68
- const advance = async (invoke) => {
76
+ const advance = async (invoke, guard) => {
69
77
  const { executionId } = invoke;
78
+ const isFenced = (reply) => reply.status === "refused" && reply.reason === "epoch_fenced";
70
79
  const args = asStoreValue(invoke.arguments);
71
80
  const frozen = { name: invoke.name, args, digest: JSON.stringify([invoke.name, args]) };
72
81
  const prior = await ledger.read(keyOf(executionId));
@@ -76,23 +85,27 @@ export function createHandLedger(options) {
76
85
  if (settled !== undefined)
77
86
  return { kind: "reply", message: settled };
78
87
  const fromStart = [
79
- () => admitNew(invoke, frozen.digest),
80
- () => apply(executionId, { kind: "prepare" }, executor),
81
- () => apply(executionId, { kind: "effect" }, executor),
82
- () => apply(executionId, { kind: "freeze", call: frozen, awaitingConsent: false }, executor),
88
+ () => admitNew(invoke, frozen.digest, guard),
89
+ () => apply(executionId, { kind: "prepare" }, executor, guard),
90
+ () => apply(executionId, { kind: "effect" }, executor, guard),
91
+ () => apply(executionId, { kind: "freeze", call: frozen, awaitingConsent: false }, executor, guard),
83
92
  ];
84
93
  const state = prior?.progress.state;
85
94
  const steps = state === undefined ? fromStart : state === "prepared" || state === "released" ? [] : undefined;
86
95
  if (steps === undefined)
87
96
  return { kind: "in_flight" };
88
- for (const step of [...steps, () => apply(executionId, { kind: "release" }, issuer)]) {
97
+ for (const step of [...steps, () => apply(executionId, { kind: "release" }, issuer, guard)]) {
89
98
  const reply = await step();
99
+ if (isFenced(reply))
100
+ return fenced(executionId);
90
101
  if (reply.status === "replayed" && reply.entry.progress.state !== "settled")
91
102
  continue;
92
103
  if (reply.status !== "applied" || reply.entry.progress.state === "settled")
93
104
  return { kind: "reply", message: replyFrom(reply, executionId) };
94
105
  }
95
- const dispatched = await apply(executionId, { kind: "dispatch" }, executor);
106
+ const dispatched = await apply(executionId, { kind: "dispatch" }, executor, guard);
107
+ if (isFenced(dispatched))
108
+ return fenced(executionId);
96
109
  if (dispatched.status === "applied" && dispatched.entry.progress.state === "dispatched")
97
110
  return { kind: "run" };
98
111
  if (dispatched.status === "replayed" && dispatched.entry.progress.state !== "settled")
@@ -100,12 +113,12 @@ export function createHandLedger(options) {
100
113
  return { kind: "reply", message: replyFrom(dispatched, executionId) };
101
114
  };
102
115
  return {
103
- async admit(invoke) {
116
+ async admit(invoke, admits) {
104
117
  const { executionId } = invoke;
105
118
  if (owned.has(executionId))
106
119
  return { kind: "in_flight" };
107
120
  owned.add(executionId);
108
- const admission = await advance(invoke).catch((error) => {
121
+ const admission = await advance(invoke, fencedBy(admits)).catch((error) => {
109
122
  owned.delete(executionId);
110
123
  throw error;
111
124
  });
@@ -122,11 +135,14 @@ export function createHandLedger(options) {
122
135
  owned.delete(invoke.executionId);
123
136
  }
124
137
  },
125
- async ack(executionId) {
126
- await apply(executionId, { kind: "ack" }, issuer);
138
+ async ack(executionId, admits) {
139
+ await apply(executionId, { kind: "ack" }, issuer, fencedBy(admits));
127
140
  },
128
141
  async recover() {
129
- await ledger.recover(now());
142
+ if (recovered !== undefined)
143
+ return recovered.then(() => []);
144
+ recovered = ledger.recover(now());
145
+ await recovered;
130
146
  return (await ledger.scan()).flatMap((entry) => {
131
147
  const message = entry.progress.state === "settled" ? outcomeOf(entry) : undefined;
132
148
  return message === undefined ? [] : [{ lane: entry.scope, message }];
@@ -19,6 +19,11 @@ export type HandReply = {
19
19
  readonly reason: string;
20
20
  } | {
21
21
  readonly kind: "closed";
22
+ }
23
+ /** The session's epoch never opened the lane (S35): a newer owner holds it, or the hand refused this sender. */
24
+ | {
25
+ readonly kind: "epoch_refused";
26
+ readonly reason: string;
22
27
  };
23
28
  export interface HandLink {
24
29
  dispatch(message: RemoteInvoke | RemoteFile, signal?: AbortSignal): Promise<HandReply>;
@@ -32,5 +37,5 @@ export interface HandLink {
32
37
  * hand with a record answers what it already holds, while a hand without one would run a re-sent call again or refuse
33
38
  * it as a duplicate, so its waiting calls are left to the paths that already end them.
34
39
  */
35
- export declare function createHandLink(transport: Transport, planeHandlers?: Readonly<Record<string, PlaneHandler>>): HandLink;
40
+ export declare function createHandLink(transport: Transport, planeHandlers?: Readonly<Record<string, PlaneHandler>>, filePlanes?: readonly string[], epoch?: number): HandLink;
36
41
  //# sourceMappingURL=remote-link.d.ts.map
@@ -1,4 +1,5 @@
1
1
  import { createPlaneServer, decodePlaneMessage } from "./plane.js";
2
+ import { createEpochGate } from "./remote-epoch-gate.js";
2
3
  import { decodeRemoteMessage, encodeRemoteMessage, } from "./remote-protocol.js";
3
4
  /**
4
5
  * The session's end of the link to a hand (S27a, S40): every waiting call and file operation by execution ID, their
@@ -6,15 +7,24 @@ import { decodeRemoteMessage, encodeRemoteMessage, } from "./remote-protocol.js"
6
7
  * hand with a record answers what it already holds, while a hand without one would run a re-sent call again or refuse
7
8
  * it as a duplicate, so its waiting calls are left to the paths that already end them.
8
9
  */
9
- export function createHandLink(transport, planeHandlers = {}) {
10
+ export function createHandLink(transport, planeHandlers = {}, filePlanes = [], epoch) {
10
11
  const pending = new Map();
11
- // Nested requests (S31) are admitted only while their parent CALL is live on its lane; a file operation hosts none.
12
+ const stamp = epoch === undefined ? {} : { epoch };
13
+ /** Messages handed to the transport: a hand's `hello` re-sends only these, never one still waiting on its floor. */
14
+ const sent = new Set();
15
+ // Nested requests (S31) are admitted only while their parent CALL is live on its lane. A pending file operation
16
+ // (S40) hosts only the planes in `filePlanes` (a two-sided extension's forwarded tool events, S29); every other
17
+ // plane under it is refused as if it had no live parent. An abort names no plane and reaches what was admitted.
12
18
  const planes = createPlaneServer({
13
19
  transport,
14
20
  planes: planeHandlers,
15
- liveLane: (executionId) => {
21
+ liveLane: (executionId, plane) => {
16
22
  const waiting = pending.get(executionId)?.message;
17
- return waiting?.kind === "invoke" ? waiting.scope.id : undefined;
23
+ if (waiting?.kind === "invoke")
24
+ return waiting.scope.id;
25
+ if (waiting?.kind === "file" && (plane === undefined || filePlanes.includes(plane)))
26
+ return waiting.scope.id;
27
+ return undefined;
18
28
  },
19
29
  });
20
30
  let announced;
@@ -26,10 +36,24 @@ export function createHandLink(transport, planeHandlers = {}) {
26
36
  if (waiter === undefined)
27
37
  return;
28
38
  pending.delete(executionId);
39
+ sent.delete(executionId);
29
40
  planes.parentEnded(executionId);
30
41
  waiter.resolve(reply);
31
42
  };
32
43
  const send = (lane, message) => transport.send(lane, encodeRemoteMessage(message));
44
+ const gate = epoch === undefined ? undefined : createEpochGate(epoch, (lane, floor) => send(lane, floor));
45
+ /** Runs `go` once the lane's floor is acked at this epoch (at once without an epoch); a refusal ends the message. */
46
+ const whenOpen = (lane, executionId, go) => {
47
+ if (gate === undefined)
48
+ return go();
49
+ void gate.open(lane).then((refusal) => {
50
+ if (!pending.has(executionId))
51
+ return;
52
+ if (refusal === undefined)
53
+ return go();
54
+ settle(executionId, { kind: "epoch_refused", reason: refusal });
55
+ });
56
+ };
33
57
  transport.onFrame((frame) => {
34
58
  const nested = decodePlaneMessage(frame.payload);
35
59
  if (nested !== undefined)
@@ -41,16 +65,22 @@ export function createHandLink(transport, planeHandlers = {}) {
41
65
  catch {
42
66
  return;
43
67
  }
44
- const ack = (executionId) => void send(frame.lane, { kind: "ack", executionId }).catch(() => undefined);
68
+ const ack = (executionId) => void send(frame.lane, { kind: "ack", executionId, ...stamp }).catch(() => undefined);
45
69
  if (message.kind === "hello") {
46
70
  announced = message;
47
71
  for (const waiter of [...helloWaiters])
48
72
  waiter(message);
73
+ gate?.resend();
49
74
  if (message.durable)
50
- for (const { message: waiting } of pending.values())
51
- void send(waiting.scope.id, waiting).catch(() => undefined);
75
+ for (const { message: waiting } of pending.values()) {
76
+ if (!sent.has(waiting.executionId))
77
+ continue;
78
+ whenOpen(waiting.scope.id, waiting.executionId, () => void send(waiting.scope.id, waiting).catch(() => undefined));
79
+ }
52
80
  return;
53
81
  }
82
+ if (message.kind === "floor_ack" || message.kind === "floor_refused")
83
+ return gate?.answer(frame.lane, message);
54
84
  if (message.kind === "settled") {
55
85
  settle(message.executionId, { kind: "settled", result: message.result });
56
86
  ack(message.executionId);
@@ -63,7 +93,8 @@ export function createHandLink(transport, planeHandlers = {}) {
63
93
  settle(message.executionId, { kind: "refused", reason: message.reason });
64
94
  });
65
95
  return {
66
- dispatch(message, signal) {
96
+ dispatch(unstamped, signal) {
97
+ const message = { ...unstamped, ...stamp };
67
98
  const { executionId } = message;
68
99
  const replied = new Promise((resolve) => {
69
100
  pending.set(executionId, { message, resolve });
@@ -75,15 +106,20 @@ export function createHandLink(transport, planeHandlers = {}) {
75
106
  const onAbort = () => {
76
107
  if (!pending.has(executionId))
77
108
  return;
78
- void send(message.scope.id, { kind: "abort", executionId }).catch(() => undefined);
79
- settle(executionId, { kind: "aborted", sent: true });
109
+ const reached = sent.has(executionId);
110
+ if (reached)
111
+ void send(message.scope.id, { kind: "abort", executionId, ...stamp }).catch(() => undefined);
112
+ settle(executionId, { kind: "aborted", sent: reached });
80
113
  };
81
114
  signal?.addEventListener("abort", onAbort, { once: true });
82
115
  void replied.then(() => signal?.removeEventListener("abort", onAbort));
83
- send(message.scope.id, message).catch((error) => {
84
- settle(executionId, {
85
- kind: "unreachable",
86
- reason: error instanceof Error ? error.message : String(error),
116
+ whenOpen(message.scope.id, executionId, () => {
117
+ sent.add(executionId);
118
+ send(message.scope.id, message).catch((error) => {
119
+ settle(executionId, {
120
+ kind: "unreachable",
121
+ reason: error instanceof Error ? error.message : String(error),
122
+ });
87
123
  });
88
124
  });
89
125
  return replied;
@@ -9,7 +9,7 @@ import type { ExecutionScope } from "./tool-host.ts";
9
9
  * The hand receives the model's raw call (name and arguments, before preparation, validation and hooks) and runs all of
10
10
  * those steps itself. `sessionRef` is what the session chose to say about itself: the hand passes it to nothing.
11
11
  */
12
- export type RemoteHandMessage = RemoteInvoke | RemoteAbort | RemoteAck | RemoteSettled | RemoteTerminal | RemoteRefused | RemoteHello | RemoteFile;
12
+ export type RemoteHandMessage = RemoteInvoke | RemoteAbort | RemoteAck | RemoteSettled | RemoteTerminal | RemoteRefused | RemoteHello | RemoteFloor | RemoteFloorAck | RemoteFloorRefused | RemoteFile;
13
13
  /** The lane a hand announces itself on; execution scope lanes carry everything else. */
14
14
  export declare const HAND_CONTROL_LANE = "hand.control";
15
15
  /**
@@ -33,12 +33,39 @@ export interface RemoteHello {
33
33
  export interface RemoteFile {
34
34
  readonly kind: "file";
35
35
  readonly executionId: string;
36
+ /** The sender's owner epoch, as on an invoke: a file operation is fenced by the same floor (S35). */
37
+ readonly epoch?: number;
36
38
  readonly scope: ExecutionScope;
37
39
  readonly op: DeviceFileOp;
38
40
  readonly args: JsonValue;
39
41
  }
42
+ /**
43
+ * The session's owner at `epoch` asks the hand to fence every lower epoch on this scope lane (brain/hand S35; relay
44
+ * design 4.4, the SP6 `epoch.floor` record). The owner dispatches the lane's calls only after the hand acked exactly
45
+ * its epoch.
46
+ */
47
+ export interface RemoteFloor {
48
+ readonly kind: "floor";
49
+ readonly epoch: number;
50
+ }
51
+ /** The floor in force on the lane: the requested epoch, or a higher one when a newer owner already raised it. */
52
+ export interface RemoteFloorAck {
53
+ readonly kind: "floor_ack";
54
+ readonly floor: number;
55
+ }
56
+ /**
57
+ * Why a hand refused a floor (SP6's refusals, plus `epoch_unsupported` from a hand that keeps no floor): only the
58
+ * scope's owner raises it, by one epoch at a time, and another owner at the floor's epoch is fenced.
59
+ */
60
+ export type EpochRefusal = "peer_unauthorized" | "epoch_fenced" | "epoch_step_exceeded" | "epoch_unsupported";
61
+ export interface RemoteFloorRefused {
62
+ readonly kind: "floor_refused";
63
+ readonly reason: EpochRefusal;
64
+ }
65
+ /** `epoch` on an invoke, abort or ack: the sender's owner epoch; a hand refuses one below the lane's floor. */
40
66
  export interface RemoteInvoke {
41
67
  readonly kind: "invoke";
68
+ readonly epoch?: number;
42
69
  /** Unique per call per session; a hand runs one execution ID at most once. */
43
70
  readonly executionId: string;
44
71
  readonly batchId: string;
@@ -53,11 +80,13 @@ export interface RemoteInvoke {
53
80
  export interface RemoteAbort {
54
81
  readonly kind: "abort";
55
82
  readonly executionId: string;
83
+ readonly epoch?: number;
56
84
  }
57
85
  /** The session has its outcome: the hand may forget it (a later replay is `result_expired`). */
58
86
  export interface RemoteAck {
59
87
  readonly kind: "ack";
60
88
  readonly executionId: string;
89
+ readonly epoch?: number;
61
90
  }
62
91
  /** The reasons a call can end on a hand without a tool result (the endpoint state machine's terminal reasons). */
63
92
  export type RemoteTerminalReason = "cancelled" | "lease_expired" | "hand_restarted" | "uncertain";