@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
@@ -0,0 +1,175 @@
1
+ import { createAdmissionLine } from "../../durable/store-admission.js";
2
+ import { resolveToolNameAlias, withToolNameCorrection } from "../../tool-name-alias.js";
3
+ import { createBatchCoordinator } from "../coordinator.js";
4
+ import { createExecutionLedger } from "../ledger.js";
5
+ import { createErrorToolResult, emitToolExecutionEnd, emitToolExecutionUpdate } from "../tool-outcome-events.js";
6
+ import { createPreparedExecutor } from "./executor.js";
7
+ import { toStoreValue } from "./executor-freeze.js";
8
+ import { agentPreparationPipeline } from "./executor-pipeline.js";
9
+ const ISSUER = "loop";
10
+ const EXECUTOR = "local";
11
+ const LEASE_MS = 24 * 60 * 60 * 1000;
12
+ // The ledger admits no call without a workspace, and a loop built with no execution scope has an empty root. The
13
+ // batch's ledger lives only for this batch, so the name only has to be non-empty.
14
+ const NO_WORKSPACE = "in-process";
15
+ /** The scheduler's sequential test, decided before preparation: exact name, then the alias rule; an unresolved name runs in parallel. */
16
+ function isSequential(context, name) {
17
+ const tools = context.tools ?? [];
18
+ const named = resolveToolNameAlias(name, tools.map((tool) => tool.name));
19
+ const tool = tools.find((candidate) => candidate.name === name) ?? tools.find((candidate) => candidate.name === named);
20
+ return tool?.executionMode === "sequential";
21
+ }
22
+ /**
23
+ * Runs one batch through the prepared pipeline (S18b): the batch coordinator prepares every call in source order on the
24
+ * in-process prepared executor, decides once, then releases by dependencies. The loop's events are emitted where
25
+ * today's scheduler emits them; the returned outcomes are the calls that started, in source order. A call's command ID
26
+ * is its block position in the batch, not the model's call ID: a model may repeat a call ID inside one message, and
27
+ * today's scheduler runs each such block as its own call. Each batch runs on its own in-memory ledger.
28
+ */
29
+ export async function runPreparedBatch(request) {
30
+ const { source, calls, context, assistantMessage, emit, signal } = request;
31
+ const store = request.openStore();
32
+ await store.claim(0, 1);
33
+ const admission = createAdmissionLine();
34
+ const base = agentPreparationPipeline(source);
35
+ // Keyed by the call itself: two blocks of one message may share a call ID but never a call.
36
+ const resolved = new Map();
37
+ const prepared = createPreparedExecutor({
38
+ ledger: createExecutionLedger({ store, epoch: 1, admission }),
39
+ executor: EXECUTOR,
40
+ pipeline: { ...base, resolve: async (call) => resolved.get(call) },
41
+ });
42
+ const executionIdOf = (index) => String(index);
43
+ const byExecution = new Map(calls.map((call, index) => [executionIdOf(index), call]));
44
+ // Every map below is keyed by execution ID (the block), never by the model's call ID.
45
+ const renamed = new Map();
46
+ const named = (id, call) => renamed.get(id) ?? call;
47
+ const callOf = (id) => {
48
+ const call = byExecution.get(id);
49
+ if (call === undefined)
50
+ throw new Error(`prepared pipeline: unknown execution ${id}`);
51
+ return call;
52
+ };
53
+ const started = new Set();
54
+ const pending = new Map();
55
+ const finalized = new Map();
56
+ const finish = async (id, outcome) => {
57
+ finalized.set(id, outcome);
58
+ await emitToolExecutionEnd(outcome, emit);
59
+ };
60
+ const aborted = (call) => ({
61
+ toolCall: call,
62
+ result: createErrorToolResult("Operation aborted"),
63
+ isError: true,
64
+ });
65
+ const endpoint = {
66
+ prepare: async (ref) => {
67
+ const id = ref.executionId;
68
+ const call = callOf(id);
69
+ if (signal?.aborted && started.size > 0)
70
+ return { kind: "batch_abort" };
71
+ const tool = call.incomplete === true ? undefined : await base.resolve(call, context);
72
+ resolved.set(call, tool);
73
+ if (tool !== undefined && tool.name !== call.name)
74
+ renamed.set(id, { ...call, name: tool.name });
75
+ await emit({
76
+ type: "tool_execution_start",
77
+ toolCallId: call.id,
78
+ toolName: tool?.name ?? call.name,
79
+ args: call.arguments,
80
+ });
81
+ started.add(id);
82
+ const reply = await prepared.prepare({
83
+ issuer: ISSUER,
84
+ commandId: id,
85
+ generation: ref.generation,
86
+ workspace: ref.workspace,
87
+ scope: ref.scope,
88
+ call,
89
+ assistantMessage,
90
+ context,
91
+ admittedAt: ref.admittedAt,
92
+ leaseUntil: ref.leaseUntil,
93
+ ...(signal === undefined ? {} : { signal }),
94
+ });
95
+ if (signal?.aborted) {
96
+ pending.set(id, aborted(named(id, call)));
97
+ return { kind: "batch_abort" };
98
+ }
99
+ if (reply.kind === "prepared")
100
+ return { kind: "prepared", frozenDigest: reply.call.digest };
101
+ if (reply.kind === "prepared_awaiting_consent")
102
+ return { kind: "prepared_awaiting_consent", frozenDigest: reply.call.digest };
103
+ if (reply.kind === "refused")
104
+ throw new Error(`prepared pipeline refused call ${call.id} (execution ${id}): ${reply.reason}`);
105
+ const result = reply.kind === "blocked" && reply.requestedName !== undefined && tool !== undefined
106
+ ? withToolNameCorrection(reply.result, reply.requestedName, tool.name)
107
+ : reply.result;
108
+ pending.set(id, { toolCall: named(id, call), result, isError: true });
109
+ const value = toStoreValue({ content: result.content ?? [] });
110
+ return reply.kind === "blocked" ? { kind: "blocked", result: value } : { kind: "batch_abort" };
111
+ },
112
+ release: async (ref) => {
113
+ const id = ref.executionId;
114
+ const call = callOf(id);
115
+ const reply = await prepared.release({
116
+ key: { issuer: ISSUER, commandId: id },
117
+ generation: ref.generation,
118
+ actor: { id: ISSUER },
119
+ onUpdateFor: (toolCall) => emitToolExecutionUpdate(toolCall, emit),
120
+ ...(signal === undefined ? {} : { signal }),
121
+ });
122
+ if (reply.kind === "settled") {
123
+ const result = reply.requestedName === undefined
124
+ ? reply.result
125
+ : withToolNameCorrection(reply.result, reply.requestedName, reply.toolCall.name);
126
+ await finish(id, { toolCall: reply.toolCall, result, isError: reply.isError });
127
+ return {
128
+ kind: "settled",
129
+ outcome: {
130
+ reason: "result",
131
+ value: toStoreValue(result.content ?? []),
132
+ hooksRan: true,
133
+ uncertain: false,
134
+ },
135
+ };
136
+ }
137
+ if (reply.kind !== "aborted")
138
+ throw new Error(`prepared pipeline: release ${reply.kind} for call ${call.id} (execution ${id})`);
139
+ await finish(id, signal?.aborted
140
+ ? aborted(named(id, call))
141
+ : { toolCall: named(id, call), result: reply.result, isError: true });
142
+ return { kind: "settled", outcome: { reason: "cancelled", hooksRan: true, uncertain: false } };
143
+ },
144
+ abort: async (ref) => {
145
+ const id = ref.executionId;
146
+ const call = callOf(id);
147
+ if (started.has(id))
148
+ await finish(id, signal?.aborted ? aborted(named(id, call)) : (pending.get(id) ?? aborted(named(id, call))));
149
+ return { kind: "settled", outcome: { reason: "cancelled", hooksRan: false, uncertain: false } };
150
+ },
151
+ };
152
+ const now = Date.now();
153
+ const plan = {
154
+ batchId: crypto.randomUUID(),
155
+ scope: request.scope.id,
156
+ workspace: request.scope.root === "" ? NO_WORKSPACE : request.scope.root,
157
+ generation: 1,
158
+ admittedAt: now,
159
+ leaseUntil: now + LEASE_MS,
160
+ calls: calls.map((call, index) => ({
161
+ executionId: executionIdOf(index),
162
+ executor: EXECUTOR,
163
+ name: call.name,
164
+ args: toStoreValue(call.arguments),
165
+ sequential: isSequential(context, call.name),
166
+ })),
167
+ };
168
+ await createBatchCoordinator({ issuer: ISSUER, store, epoch: 1, admission, executor: () => endpoint }).run(plan);
169
+ return calls.flatMap((_call, index) => {
170
+ const id = executionIdOf(index);
171
+ const outcome = finalized.get(id);
172
+ return started.has(id) && outcome !== undefined ? [outcome] : [];
173
+ });
174
+ }
175
+ //# sourceMappingURL=pipeline-prepared-batch.js.map
@@ -0,0 +1,10 @@
1
+ import type { BatchStoreFactory } from "../../types.ts";
2
+ import type { ToolHost } from "../tool-host.ts";
3
+ import type { PreparationSource } from "./executor-pipeline.ts";
4
+ /**
5
+ * The prepared pipeline as the session's ToolHost (S18b): every model-issued batch runs through the batch coordinator
6
+ * and the prepared executor in this process, with today's events, result messages and source order. A batch the loop
7
+ * runs sequentially runs as consecutive one-call batches, so each call is prepared after the previous one finished.
8
+ */
9
+ export declare function createPreparedToolHost(source: PreparationSource, openStore: BatchStoreFactory): ToolHost;
10
+ //# sourceMappingURL=pipeline-prepared.d.ts.map
@@ -0,0 +1,54 @@
1
+ import { createToolResultMessage, emitToolResultMessage, shouldTerminateToolBatch } from "../tool-outcome-events.js";
2
+ import { runPreparedBatch } from "./pipeline-prepared-batch.js";
3
+ /**
4
+ * The prepared pipeline as the session's ToolHost (S18b): every model-issued batch runs through the batch coordinator
5
+ * and the prepared executor in this process, with today's events, result messages and source order. A batch the loop
6
+ * runs sequentially runs as consecutive one-call batches, so each call is prepared after the previous one finished.
7
+ */
8
+ export function createPreparedToolHost(source, openStore) {
9
+ return {
10
+ async execute(call, options) {
11
+ const { emit, signal, recordWitness, local } = options;
12
+ if (local === undefined)
13
+ throw new Error("the prepared pipeline runs only in the loop's own process");
14
+ if (recordWitness) {
15
+ for (const raw of call.calls) {
16
+ const pending = recordWitness({ pipeline: "prepared", toolCallId: raw.id });
17
+ if (pending)
18
+ await pending;
19
+ }
20
+ }
21
+ const batch = (calls) => runPreparedBatch({
22
+ source,
23
+ openStore,
24
+ calls,
25
+ scope: call.scope,
26
+ context: local.context,
27
+ assistantMessage: local.assistantMessage,
28
+ emit,
29
+ ...(signal === undefined ? {} : { signal }),
30
+ });
31
+ const outcomes = [];
32
+ const messages = [];
33
+ const report = async (finished) => {
34
+ for (const outcome of finished) {
35
+ const message = createToolResultMessage(outcome);
36
+ await emitToolResultMessage(message, emit);
37
+ outcomes.push(outcome);
38
+ messages.push(message);
39
+ }
40
+ };
41
+ if (call.mode === "sequential") {
42
+ for (const raw of call.calls) {
43
+ await report(await batch([raw]));
44
+ if (signal?.aborted)
45
+ break;
46
+ }
47
+ }
48
+ else
49
+ await report(await batch(call.calls));
50
+ return { messages, terminate: shouldTerminateToolBatch(outcomes) };
51
+ },
52
+ };
53
+ }
54
+ //# sourceMappingURL=pipeline-prepared.js.map
@@ -1,10 +1,12 @@
1
- import { DeviceFileError, decodeBase64, encodeBase64, FILE_CHANNEL, FILE_CHANNEL_MAX_BYTES, fileOutcomeOf, } from "./device-files.js";
1
+ import { DeviceFileError, decodeBase64, encodeBase64, FILE_CHANNEL, FILE_CHANNEL_MAX_BYTES, fileOutcomeOf, RUN_CHANNEL, } from "./device-files.js";
2
2
  /** How long an operation waits for the hand's `hello` before answering `unsupported` (C1). */
3
3
  export const HELLO_WAIT_MS = 5000;
4
4
  const GRANT_REFUSALS = new Set(["grant_missing", "grant_expired", "workspace_unknown", "capability_missing"]);
5
5
  function refusalError(reason) {
6
6
  if (GRANT_REFUSALS.has(reason))
7
7
  return new DeviceFileError("refused_by_grant", reason);
8
+ if (reason === "epoch_fenced")
9
+ return new DeviceFileError("refused_by_policy", reason);
8
10
  if (reason === "hand_closed" || reason.startsWith("scope_unavailable"))
9
11
  return new DeviceFileError("hand_unreachable", reason);
10
12
  return new DeviceFileError("protocol", reason);
@@ -34,6 +36,8 @@ function valueOf(reply) {
34
36
  throw new DeviceFileError("hand_unreachable", reply.reason);
35
37
  case "closed":
36
38
  throw new DeviceFileError("hand_unreachable", "the hand link was closed");
39
+ case "epoch_refused":
40
+ throw new DeviceFileError("refused_by_policy", `epoch: ${reply.reason}`);
37
41
  }
38
42
  }
39
43
  /**
@@ -42,12 +46,12 @@ function valueOf(reply) {
42
46
  * before anything is sent; the hand checks the limit again before it reads or writes.
43
47
  */
44
48
  export function createRemoteDeviceFiles(link, scope, mintId) {
45
- const call = async (op, args, signal) => {
49
+ const call = async (op, args, signal, channel = FILE_CHANNEL) => {
46
50
  const hello = await link.hello(HELLO_WAIT_MS, signal);
47
51
  if (signal?.aborted)
48
52
  throw new DeviceFileError("aborted", "the operation was aborted");
49
- if (hello === undefined || !hello.ops.includes(FILE_CHANNEL))
50
- throw new DeviceFileError("unsupported", "the hand serves no file channel");
53
+ if (hello === undefined || !hello.ops.includes(channel))
54
+ throw new DeviceFileError("unsupported", `the hand serves no ${channel} channel`);
51
55
  return valueOf(await link.dispatch({ kind: "file", executionId: mintId(), scope, op, args }, signal));
52
56
  };
53
57
  return {
@@ -79,6 +83,31 @@ export function createRemoteDeviceFiles(link, scope, mintId) {
79
83
  mkdir: async (path, options) => {
80
84
  await call("mkdir", { path }, options?.signal);
81
85
  },
86
+ run: async (request, options) => {
87
+ if (request.stdin !== undefined && request.stdin.byteLength > FILE_CHANNEL_MAX_BYTES)
88
+ throw new DeviceFileError("too_large", "stdin");
89
+ const args = {
90
+ path: request.cwd,
91
+ exe: request.exe,
92
+ argv: [...request.argv],
93
+ env: { ...request.env },
94
+ ...(request.stdin === undefined ? {} : { stdin: encodeBase64(request.stdin) }),
95
+ ...(request.timeoutMs === undefined ? {} : { timeoutMs: request.timeoutMs }),
96
+ activityLock: request.activityLock === true,
97
+ };
98
+ const value = await call("run", args, options?.signal, RUN_CHANNEL);
99
+ if (typeof value !== "object" || value === null || Array.isArray(value))
100
+ throw new DeviceFileError("protocol", "malformed run outcome");
101
+ const { code, signal, stdout, stderr } = value;
102
+ if (typeof stdout !== "string" || typeof stderr !== "string")
103
+ throw new DeviceFileError("protocol", "malformed run outcome");
104
+ return {
105
+ code: typeof code === "number" ? code : null,
106
+ signal: typeof signal === "string" ? signal : null,
107
+ stdout: decodeBase64(stdout),
108
+ stderr,
109
+ };
110
+ },
82
111
  };
83
112
  }
84
113
  //# sourceMappingURL=remote-device-files.js.map
@@ -0,0 +1,19 @@
1
+ import type { RemoteFloor, RemoteFloorAck, RemoteFloorRefused } from "./remote-protocol.ts";
2
+ /**
3
+ * A session's side of the epoch floor (brain/hand S35): an owner at `epoch` dispatches a scope lane's calls only after
4
+ * the hand acked exactly that epoch on the lane. An ack above it means a newer owner holds the session, and a refusal
5
+ * means this sender may not own it; either way the lane never dispatches again.
6
+ */
7
+ export interface EpochGate {
8
+ /** Resolves `undefined` once `lane` may dispatch, or the reason it never will. The first ask sends the floor. */
9
+ open(lane: string): Promise<string | undefined>;
10
+ /** Counts only while the lane waits for an answer; a late or duplicate answer changes nothing. */
11
+ answer(lane: string, message: RemoteFloorAck | RemoteFloorRefused): void;
12
+ /**
13
+ * The hand restarted: sends the floor again on every lane not refused, and each of them waits for its new answer
14
+ * before anything dispatches there again, re-sent calls included.
15
+ */
16
+ resend(): void;
17
+ }
18
+ export declare function createEpochGate(epoch: number, send: (lane: string, floor: RemoteFloor) => Promise<void>): EpochGate;
19
+ //# sourceMappingURL=remote-epoch-gate.d.ts.map
@@ -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) {