@code-yeongyu/senpi-agent-core 2026.11.4-2 → 2026.11.6-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 (111) 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 +12 -1
  5. package/dist/conformance/index.js +6 -0
  6. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  7. package/dist/conformance/loop-core-manifest.js +18 -0
  8. package/dist/conformance/registry.js +11 -17
  9. package/dist/durable/session-store.d.ts +42 -0
  10. package/dist/durable/session-store.js +124 -0
  11. package/dist/durable/store-memory.d.ts +2 -2
  12. package/dist/durable/store-memory.js +36 -34
  13. package/dist/durable/store.d.ts +9 -0
  14. package/dist/durable/testing/store-harness.d.ts +1 -0
  15. package/dist/durable/testing/store-harness.js +1 -0
  16. package/dist/durable/testing/sync-commit-cases.d.ts +20 -0
  17. package/dist/durable/testing/sync-commit-cases.js +89 -0
  18. package/dist/egress/types.d.ts +102 -0
  19. package/dist/egress/types.js +7 -0
  20. package/dist/execution/canonical-digest.d.ts +10 -0
  21. package/dist/execution/canonical-digest.js +20 -0
  22. package/dist/execution/chain-count.d.ts +26 -0
  23. package/dist/execution/chain-count.js +45 -0
  24. package/dist/execution/coordinator-plan.d.ts +1 -2
  25. package/dist/execution/coordinator-plan.js +4 -17
  26. package/dist/execution/device-files-node.js +40 -1
  27. package/dist/execution/device-files.d.ts +39 -1
  28. package/dist/execution/device-files.js +48 -1
  29. package/dist/execution/ledger-types.d.ts +3 -1
  30. package/dist/execution/ledger.d.ts +9 -3
  31. package/dist/execution/ledger.js +8 -2
  32. package/dist/execution/loop-hook-host-hand.d.ts +33 -0
  33. package/dist/execution/loop-hook-host-hand.js +71 -0
  34. package/dist/execution/loop-hook-host-protocol.d.ts +46 -0
  35. package/dist/execution/loop-hook-host-protocol.js +47 -0
  36. package/dist/execution/loop-hook-host.d.ts +40 -0
  37. package/dist/execution/loop-hook-host.js +87 -0
  38. package/dist/execution/plane-session.d.ts +56 -0
  39. package/dist/execution/plane-session.js +178 -0
  40. package/dist/execution/plane.d.ts +5 -2
  41. package/dist/execution/plane.js +1 -1
  42. package/dist/execution/prepared/executor-body.d.ts +22 -0
  43. package/dist/execution/prepared/executor-body.js +73 -0
  44. package/dist/execution/prepared/executor-freeze.d.ts +22 -0
  45. package/dist/execution/prepared/executor-freeze.js +55 -0
  46. package/dist/execution/prepared/executor-pipeline.d.ts +11 -0
  47. package/dist/execution/prepared/executor-pipeline.js +26 -0
  48. package/dist/execution/prepared/executor-types.d.ts +131 -0
  49. package/dist/execution/prepared/executor-types.js +2 -0
  50. package/dist/execution/prepared/executor.d.ts +8 -0
  51. package/dist/execution/prepared/executor.js +260 -0
  52. package/dist/execution/prepared/memory-batch-store.d.ts +4 -0
  53. package/dist/execution/prepared/memory-batch-store.js +4 -0
  54. package/dist/execution/prepared/pipeline-prepared-batch.d.ts +27 -0
  55. package/dist/execution/prepared/pipeline-prepared-batch.js +175 -0
  56. package/dist/execution/prepared/pipeline-prepared.d.ts +10 -0
  57. package/dist/execution/prepared/pipeline-prepared.js +54 -0
  58. package/dist/execution/remote-device-files.js +33 -4
  59. package/dist/execution/remote-epoch-gate.d.ts +19 -0
  60. package/dist/execution/remote-epoch-gate.js +46 -0
  61. package/dist/execution/remote-epoch.d.ts +53 -0
  62. package/dist/execution/remote-epoch.js +74 -0
  63. package/dist/execution/remote-executor.d.ts +8 -1
  64. package/dist/execution/remote-executor.js +24 -6
  65. package/dist/execution/remote-file-call.js +1 -0
  66. package/dist/execution/remote-hand-ledger.d.ts +11 -3
  67. package/dist/execution/remote-hand-ledger.js +31 -15
  68. package/dist/execution/remote-link.d.ts +6 -1
  69. package/dist/execution/remote-link.js +50 -14
  70. package/dist/execution/remote-protocol.d.ts +30 -1
  71. package/dist/execution/remote-protocol.js +30 -0
  72. package/dist/execution/remote-tool-host.d.ts +12 -0
  73. package/dist/execution/remote-tool-host.js +3 -1
  74. package/dist/execution/testing/epoch-cases.d.ts +8 -0
  75. package/dist/execution/testing/epoch-cases.js +84 -0
  76. package/dist/execution/testing/epoch-harness.d.ts +47 -0
  77. package/dist/execution/testing/epoch-harness.js +172 -0
  78. package/dist/execution/testing/epoch-registry.d.ts +3 -0
  79. package/dist/execution/testing/epoch-registry.js +17 -0
  80. package/dist/execution/testing/hand-harness.d.ts +5 -0
  81. package/dist/execution/testing/hand-harness.js +57 -24
  82. package/dist/execution/testing/hand-registry.d.ts +3 -0
  83. package/dist/execution/testing/hand-registry.js +20 -0
  84. package/dist/execution/testing/kill-epoch.d.ts +9 -0
  85. package/dist/execution/testing/kill-epoch.js +71 -0
  86. package/dist/execution/testing/kill-hook.d.ts +14 -0
  87. package/dist/execution/testing/kill-hook.js +117 -0
  88. package/dist/execution/testing/multi-epoch-cases.d.ts +4 -0
  89. package/dist/execution/testing/multi-epoch-cases.js +29 -0
  90. package/dist/execution/testing/multi-hand-cases.js +1 -1
  91. package/dist/execution/tool-host.d.ts +16 -1
  92. package/dist/execution/tool-host.js +18 -1
  93. package/dist/harness/agent-harness.d.ts +6 -0
  94. package/dist/harness/execution/tool-host-call.d.ts +14 -0
  95. package/dist/harness/execution/tool-host-call.js +56 -0
  96. package/dist/harness/execution/tools.d.ts +2 -1
  97. package/dist/harness/execution/tools.js +45 -17
  98. package/dist/harness/runtime/drive/tools.js +1 -1
  99. package/dist/harness/runtime/harness.js +1 -0
  100. package/dist/harness/runtime/types.d.ts +1 -0
  101. package/dist/harness/tools/read.js +1 -1
  102. package/dist/index.d.ts +19 -2
  103. package/dist/index.js +15 -1
  104. package/dist/public-entry.d.ts +10 -0
  105. package/dist/public-entry.js +23 -0
  106. package/dist/step-commit.d.ts +24 -0
  107. package/dist/step-commit.js +24 -0
  108. package/dist/tool-name-alias.d.ts +1 -7
  109. package/dist/tool-name-alias.js +0 -17
  110. package/dist/types.d.ts +37 -1
  111. package/package.json +3 -3
@@ -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";
@@ -8,6 +8,12 @@ export class RemoteProtocolError extends Error {
8
8
  }
9
9
  }
10
10
  const TERMINAL_REASONS = ["cancelled", "lease_expired", "hand_restarted", "uncertain"];
11
+ const EPOCH_REFUSALS = [
12
+ "peer_unauthorized",
13
+ "epoch_fenced",
14
+ "epoch_step_exceeded",
15
+ "epoch_unsupported",
16
+ ];
11
17
  const encoder = new TextEncoder();
12
18
  const decoder = new TextDecoder();
13
19
  export function encodeRemoteMessage(message) {
@@ -15,6 +21,25 @@ export function encodeRemoteMessage(message) {
15
21
  }
16
22
  const isRecord = (value) => typeof value === "object" && value !== null;
17
23
  const isString = (value) => typeof value === "string" && value.length > 0;
24
+ const isEpoch = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
25
+ function decodeFloorMessage(value) {
26
+ switch (value.kind) {
27
+ case "floor":
28
+ if (!isEpoch(value.epoch))
29
+ throw new RemoteProtocolError("malformed floor");
30
+ return { kind: "floor", epoch: value.epoch };
31
+ case "floor_ack":
32
+ if (!isEpoch(value.floor))
33
+ throw new RemoteProtocolError("malformed floor ack");
34
+ return { kind: "floor_ack", floor: value.floor };
35
+ case "floor_refused":
36
+ if (!EPOCH_REFUSALS.includes(value.reason))
37
+ throw new RemoteProtocolError("malformed floor refusal");
38
+ return { kind: "floor_refused", reason: value.reason };
39
+ default:
40
+ return undefined;
41
+ }
42
+ }
18
43
  /** Parses one frame payload. Anything that is not exactly one of the messages is refused; nothing guesses. */
19
44
  export function decodeRemoteMessage(payload) {
20
45
  let value;
@@ -34,8 +59,13 @@ export function decodeRemoteMessage(payload) {
34
59
  throw new RemoteProtocolError("malformed hello");
35
60
  return { kind: "hello", instance, durable: durable ?? true, ops: ops ?? [] };
36
61
  }
62
+ const floor = isRecord(value) ? decodeFloorMessage(value) : undefined;
63
+ if (floor !== undefined)
64
+ return floor;
37
65
  if (!isRecord(value) || !isString(value.executionId))
38
66
  throw new RemoteProtocolError("no execution ID");
67
+ if (value.epoch !== undefined && !isEpoch(value.epoch))
68
+ throw new RemoteProtocolError("malformed epoch");
39
69
  switch (value.kind) {
40
70
  case "invoke": {
41
71
  const scope = value.scope;
@@ -22,6 +22,18 @@ export interface RemoteToolHostOptions {
22
22
  * `plane_unavailable`.
23
23
  */
24
24
  readonly planes?: Readonly<Record<string, PlaneHandler>>;
25
+ /**
26
+ * The planes a pending device file operation (S40) may host, on its own lane: a two-sided extension's forwarded tool
27
+ * events (S29), so its handler runs on the loop's copy for a file operation as for a tool call. Absent: none, so
28
+ * every nested request under a file operation is refused `parent_terminal`.
29
+ */
30
+ readonly filePlanes?: readonly string[];
31
+ /**
32
+ * The session's owner epoch (brain/hand S35). With it, each scope lane first raises the hand's floor to this epoch
33
+ * and dispatches only after the hand acked exactly it; every invoke, file operation, abort and ack carries it.
34
+ * Without it, nothing about epochs is sent (a session that never moves).
35
+ */
36
+ readonly epoch?: number;
25
37
  }
26
38
  /**
27
39
  * The ToolHost that runs a session's tool calls on a hand (brain/hand split, S27a). The hand resolves, prepares,
@@ -26,7 +26,7 @@ function terminalResult(placement, terminal) {
26
26
  */
27
27
  export function createRemoteToolHost(options) {
28
28
  const mintId = options.mintId ?? (() => crypto.randomUUID());
29
- const link = createHandLink(options.transport, options.planes ?? {});
29
+ const link = createHandLink(options.transport, options.planes ?? {}, options.filePlanes ?? [], options.epoch);
30
30
  const resultOf = (reply) => {
31
31
  switch (reply.kind) {
32
32
  case "settled":
@@ -41,6 +41,8 @@ export function createRemoteToolHost(options) {
41
41
  return errorResult(`The hand is unreachable: ${reply.reason}`);
42
42
  case "closed":
43
43
  return errorResult("The hand link was closed before the call settled");
44
+ case "epoch_refused":
45
+ return errorResult(`The hand refused this session's epoch: ${reply.reason}`);
44
46
  }
45
47
  };
46
48
  const dispatch = (invoke, signal) => ({
@@ -0,0 +1,8 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import type { ToolHostResult } from "../tool-host.ts";
3
+ import { type HandCaseAdapters } from "./hand-harness.ts";
4
+ type EpochCase = CaseImplementation<HandCaseAdapters>;
5
+ export declare const texts: ({ messages }: ToolHostResult) => string[];
6
+ export declare const EPOCH_CASES: ReadonlyMap<string, EpochCase>;
7
+ export {};
8
+ //# sourceMappingURL=epoch-cases.d.ts.map
@@ -0,0 +1,84 @@
1
+ import { expectEqual } from "../../durable/testing/store-harness.js";
2
+ import { floorCommit, openEpochRig, stepCommit } from "./epoch-harness.js";
3
+ import { call } from "./hand-harness.js";
4
+ export const texts = ({ messages }) => messages.map((message) => message.content.map((part) => (part.type === "text" ? part.text : "")).join(""));
5
+ const OLD = { name: "brain-old", epoch: 1 };
6
+ const NEW = { name: "brain-new", epoch: 2 };
7
+ /** SC-MOVE step 1: while the hand's floor ACK is held, the new owner's call has no effect, then runs once. */
8
+ const floorAckBarrier = async (adapters) => {
9
+ const rig = await openEpochRig(adapters, { brains: [OLD, NEW] });
10
+ rig.setOwner("s", OLD.name);
11
+ const before = await rig.settle(rig.execute(OLD.name, "s", [call("c0")]), "EPOCH-01: the first owner's call");
12
+ expectEqual(texts(before), ["ran:c0"], "EPOCH-01: the first owner runs on its floor");
13
+ rig.setOwner("s", NEW.name);
14
+ const barrier = rig.hold(floorCommit("s", NEW.epoch));
15
+ const moved = rig.execute(NEW.name, "s", [call("c1")]);
16
+ await rig.settle(barrier.reached, "EPOCH-01: the new owner's floor reached the hand's store");
17
+ await rig.advance(2_000);
18
+ expectEqual(rig.bodies, ["s:c0"], "EPOCH-01: nothing of the new owner's call ran while its floor ACK was held");
19
+ expectEqual((await rig.rows()).length, 1, "EPOCH-01: the new owner's call was not even recorded");
20
+ barrier.release();
21
+ expectEqual(texts(await rig.settle(moved, "EPOCH-01: the new owner's call")), ["ran:c1"], "EPOCH-01: result");
22
+ expectEqual(rig.bodies, ["s:c0", "s:c1"], "EPOCH-01: the new owner's call ran exactly once after the ACK");
23
+ };
24
+ /** SC-MOVE step 2: two brains claim the session at once; exactly one wins, and only the winner's calls run. */
25
+ const concurrentClaims = async (adapters) => {
26
+ const first = { name: "brain-first", epoch: 1 };
27
+ const rivals = [
28
+ { name: "brain-a", epoch: 2 },
29
+ { name: "brain-b", epoch: 2 },
30
+ ];
31
+ const rig = await openEpochRig(adapters, { brains: [first, ...rivals] });
32
+ rig.setOwner("s", first.name);
33
+ await rig.settle(rig.execute(first.name, "s", [call("c0")]), "EPOCH-02: the first owner's call");
34
+ const session = await adapters.store.createMedium();
35
+ const opened = await Promise.all([0, 1, 2].map(() => adapters.store.open(session)));
36
+ const [owner, ...claimants] = opened;
37
+ await owner?.claim(0, 1);
38
+ const claims = await Promise.allSettled(claimants.map((store) => store.claim(1, 2)));
39
+ const won = rivals.filter((_, index) => claims[index]?.status === "fulfilled");
40
+ expectEqual(won.length, 1, "EPOCH-02: exactly one of two concurrent CAS claims wins");
41
+ const winner = won[0] ?? rivals[0];
42
+ const loser = rivals.find((rival) => rival !== winner) ?? rivals[1];
43
+ if (winner === undefined || loser === undefined)
44
+ throw new Error("EPOCH-02: no rivals");
45
+ rig.setOwner("s", winner.name);
46
+ const [ran, refused] = await rig.settle(Promise.all([rig.execute(winner.name, "s", [call("cw")]), rig.execute(loser.name, "s", [call("cl")])]), "EPOCH-02: both claimants' calls");
47
+ expectEqual(texts(ran), ["ran:cw"], "EPOCH-02: the winner's call runs");
48
+ expectEqual([texts(refused), refused.messages[0]?.isError], [["The hand refused this session's epoch: peer_unauthorized"], true], "EPOCH-02: the loser's floor is refused and its call is never sent");
49
+ expectEqual(rig.bodies, ["s:c0", "s:cw"], "EPOCH-02: only the winner's call ran");
50
+ };
51
+ /** SC-MOVE step 3: an old owner's delayed walk (prepare, release) and a delayed invoke after the move are refused. */
52
+ const delayedOldOwner = async (adapters) => {
53
+ const rig = await openEpochRig(adapters, { brains: [OLD, NEW] });
54
+ rig.setOwner("s", OLD.name);
55
+ await rig.settle(rig.execute(OLD.name, "s", [call("c0")]), "EPOCH-03: the old owner's first call");
56
+ const prepare = rig.hold(stepCommit(OLD.name, "prepare"));
57
+ const delayed = rig.execute(OLD.name, "s", [call("c2")]);
58
+ await rig.settle(prepare.reached, "EPOCH-03: the old owner's delayed call is mid-walk");
59
+ rig.setOwner("s", NEW.name);
60
+ const moved = rig.execute(NEW.name, "s", [call("c1")]);
61
+ await rig.advance(2_000);
62
+ prepare.release();
63
+ expectEqual(texts(await rig.settle(moved, "EPOCH-03: the new owner's call")), ["ran:c1"], "EPOCH-03: new owner");
64
+ expectEqual(texts(await rig.settle(delayed, "EPOCH-03: the old owner's mid-walk call")), ["The hand refused this tool call: epoch_fenced"], "EPOCH-03: the old owner's walk is refused at its next step");
65
+ const late = await rig.settle(rig.execute(OLD.name, "s", [call("c3")]), "EPOCH-03: a delayed old-owner invoke");
66
+ expectEqual(texts(late), ["The hand refused this tool call: epoch_fenced"], "EPOCH-03: a delayed invoke is fenced");
67
+ await rig.advance(200);
68
+ const rows = await rig.rows();
69
+ expectEqual(rig.bodies, ["s:c0", "s:c1"], "EPOCH-03: no old-owner call ran after the move");
70
+ expectEqual(rows.map(({ commandId, progress }) => [
71
+ commandId,
72
+ progress.state === "settled" ? progress.outcome.reason : progress.state,
73
+ ]), [
74
+ ["brain-new-1", "acked"],
75
+ ["brain-old-1", "acked"],
76
+ ["brain-old-3", "cancelled"],
77
+ ], "EPOCH-03: the fenced walk's record is cancelled, never dispatched; the delayed invoke left no record");
78
+ };
79
+ export const EPOCH_CASES = new Map([
80
+ ["EPOCH-01", floorAckBarrier],
81
+ ["EPOCH-02", concurrentClaims],
82
+ ["EPOCH-03", delayedOldOwner],
83
+ ]);
84
+ //# sourceMappingURL=epoch-cases.js.map
@@ -0,0 +1,47 @@
1
+ import type { AgentToolCall } from "../../types.ts";
2
+ import type { StoreValue, StoreWrite } from "../../durable/store.ts";
3
+ import type { ExecutionEntry } from "../ledger-types.ts";
4
+ import { type HandPlacement } from "../remote-tool-host.ts";
5
+ import type { ToolHostResult } from "../tool-host.ts";
6
+ import { type HandCaseAdapters, type TransportPump } from "./hand-harness.ts";
7
+ export type CommitMatch = (writes: readonly StoreWrite[]) => boolean;
8
+ export interface EpochBrainSpec {
9
+ /** The brain principal: its link's authenticated peer and the name `ownerOf` answers. */
10
+ readonly name: string;
11
+ readonly epoch: number;
12
+ }
13
+ export interface EpochRig extends TransportPump {
14
+ /** Every tool body start, as `<scope>:<toolCallId>`, across all hand processes. */
15
+ readonly bodies: readonly string[];
16
+ readonly faults: readonly unknown[];
17
+ readonly killed: Promise<void>;
18
+ execute(brain: string, scope: string, calls: readonly AgentToolCall[]): Promise<ToolHostResult>;
19
+ /** Moves `scope` to `brain` in the hand's placement record (what `ownerOf` answers). */
20
+ setOwner(scope: string, brain: string): void;
21
+ /** Holds the next commit `match` picks until `release()`; `reached` settles when it arrives. */
22
+ hold(match: CommitMatch): {
23
+ readonly reached: Promise<void>;
24
+ release(): void;
25
+ };
26
+ /** A new hand process on the reopened store; every link's executor announces itself. */
27
+ restart(): Promise<void>;
28
+ rows(): Promise<ExecutionEntry[]>;
29
+ /** The floor persisted for `scope` (read from a fresh store instance), or `undefined`. */
30
+ floor(scope: string): Promise<StoreValue | undefined>;
31
+ }
32
+ export declare const floorCommit: (scope: string, epoch: number) => CommitMatch;
33
+ /** The ledger commit of `event` for a call `brain` sent (execution IDs are minted as `<brain>-<n>`). */
34
+ export declare const stepCommit: (brain: string, event: string) => CommitMatch;
35
+ /**
36
+ * One hand process reached by several brains, each over its own link with its own executor (a peer link per brain),
37
+ * sharing the hand's store, ledger and epoch fence: what a session sees when it moves from one brain to another.
38
+ */
39
+ export declare function openEpochRig(adapters: HandCaseAdapters, options: {
40
+ readonly brains: readonly EpochBrainSpec[];
41
+ readonly placement?: HandPlacement;
42
+ readonly kill?: {
43
+ readonly match: CommitMatch;
44
+ readonly at: "before" | "durable";
45
+ };
46
+ }): Promise<EpochRig>;
47
+ //# sourceMappingURL=epoch-harness.d.ts.map