@code-yeongyu/senpi-agent-core 2026.11.3-2 → 2026.11.4-2

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 (118) hide show
  1. package/dist/agent-loop.js +7 -47
  2. package/dist/conformance/index.d.ts +37 -0
  3. package/dist/conformance/index.js +25 -0
  4. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  5. package/dist/conformance/loop-core-manifest.js +1 -0
  6. package/dist/conformance/registry.js +31 -1
  7. package/dist/execution/canonical-json.d.ts +3 -0
  8. package/dist/execution/canonical-json.js +12 -0
  9. package/dist/execution/coordinator-codec.d.ts +5 -0
  10. package/dist/execution/coordinator-codec.js +104 -0
  11. package/dist/execution/coordinator-consent.d.ts +29 -0
  12. package/dist/execution/coordinator-consent.js +63 -0
  13. package/dist/execution/coordinator-plan.d.ts +33 -0
  14. package/dist/execution/coordinator-plan.js +106 -0
  15. package/dist/execution/coordinator-sequential.d.ts +15 -0
  16. package/dist/execution/coordinator-sequential.js +34 -0
  17. package/dist/execution/coordinator-types.d.ts +161 -0
  18. package/dist/execution/coordinator-types.js +2 -0
  19. package/dist/execution/coordinator.d.ts +27 -0
  20. package/dist/execution/coordinator.js +164 -0
  21. package/dist/execution/device-files-node.d.ts +8 -0
  22. package/dist/execution/device-files-node.js +112 -0
  23. package/dist/execution/device-files.d.ts +80 -0
  24. package/dist/execution/device-files.js +87 -0
  25. package/dist/execution/grant-verify.d.ts +70 -0
  26. package/dist/execution/grant-verify.js +87 -0
  27. package/dist/execution/ledger.d.ts +2 -0
  28. package/dist/execution/ledger.js +1 -0
  29. package/dist/execution/nested-codec.d.ts +5 -0
  30. package/dist/execution/nested-codec.js +41 -0
  31. package/dist/execution/nested-types.d.ts +92 -0
  32. package/dist/execution/nested-types.js +3 -0
  33. package/dist/execution/nested.d.ts +48 -0
  34. package/dist/execution/nested.js +206 -0
  35. package/dist/execution/plane-model.d.ts +33 -0
  36. package/dist/execution/plane-model.js +80 -0
  37. package/dist/execution/plane.d.ts +72 -0
  38. package/dist/execution/plane.js +172 -0
  39. package/dist/execution/remote-device-files.d.ts +12 -0
  40. package/dist/execution/remote-device-files.js +84 -0
  41. package/dist/execution/remote-executor.d.ts +74 -0
  42. package/dist/execution/remote-executor.js +193 -0
  43. package/dist/execution/remote-file-call.d.ts +14 -0
  44. package/dist/execution/remote-file-call.js +30 -0
  45. package/dist/execution/remote-hand-ledger.d.ts +40 -0
  46. package/dist/execution/remote-hand-ledger.js +137 -0
  47. package/dist/execution/remote-link.d.ts +36 -0
  48. package/dist/execution/remote-link.js +117 -0
  49. package/dist/execution/remote-protocol.d.ts +104 -0
  50. package/dist/execution/remote-protocol.js +104 -0
  51. package/dist/execution/remote-tool-host.d.ts +37 -0
  52. package/dist/execution/remote-tool-host.js +114 -0
  53. package/dist/execution/scope-lifecycle.d.ts +81 -0
  54. package/dist/execution/scope-lifecycle.js +173 -0
  55. package/dist/execution/testing/batch-cases.d.ts +6 -0
  56. package/dist/execution/testing/batch-cases.js +210 -0
  57. package/dist/execution/testing/batch-executor.d.ts +34 -0
  58. package/dist/execution/testing/batch-executor.js +170 -0
  59. package/dist/execution/testing/batch-harness.d.ts +58 -0
  60. package/dist/execution/testing/batch-harness.js +286 -0
  61. package/dist/execution/testing/batch-registry.d.ts +3 -0
  62. package/dist/execution/testing/batch-registry.js +30 -0
  63. package/dist/execution/testing/cancel-cases.d.ts +8 -0
  64. package/dist/execution/testing/cancel-cases.js +64 -0
  65. package/dist/execution/testing/consent-cases.d.ts +14 -0
  66. package/dist/execution/testing/consent-cases.js +66 -0
  67. package/dist/execution/testing/fault-hand-cases.d.ts +6 -0
  68. package/dist/execution/testing/fault-hand-cases.js +70 -0
  69. package/dist/execution/testing/hand-harness.d.ts +48 -0
  70. package/dist/execution/testing/hand-harness.js +136 -0
  71. package/dist/execution/testing/kill-batch.d.ts +12 -0
  72. package/dist/execution/testing/kill-batch.js +70 -0
  73. package/dist/execution/testing/kill-hand.d.ts +16 -0
  74. package/dist/execution/testing/kill-hand.js +75 -0
  75. package/dist/execution/testing/kill-nest.d.ts +6 -0
  76. package/dist/execution/testing/kill-nest.js +55 -0
  77. package/dist/execution/testing/kill-wakex.d.ts +6 -0
  78. package/dist/execution/testing/kill-wakex.js +81 -0
  79. package/dist/execution/testing/lifecycle-cases.d.ts +9 -0
  80. package/dist/execution/testing/lifecycle-cases.js +60 -0
  81. package/dist/execution/testing/lifecycle-registry.d.ts +3 -0
  82. package/dist/execution/testing/lifecycle-registry.js +19 -0
  83. package/dist/execution/testing/multi-hand-cases.d.ts +6 -0
  84. package/dist/execution/testing/multi-hand-cases.js +44 -0
  85. package/dist/execution/testing/multi-lifecycle-cases.d.ts +4 -0
  86. package/dist/execution/testing/multi-lifecycle-cases.js +34 -0
  87. package/dist/execution/testing/multi-seq-cases.d.ts +4 -0
  88. package/dist/execution/testing/multi-seq-cases.js +46 -0
  89. package/dist/execution/testing/nest-cases.d.ts +39 -0
  90. package/dist/execution/testing/nest-cases.js +181 -0
  91. package/dist/execution/testing/nest-registry.d.ts +3 -0
  92. package/dist/execution/testing/nest-registry.js +27 -0
  93. package/dist/execution/testing/scope-cases.d.ts +6 -0
  94. package/dist/execution/testing/scope-cases.js +49 -0
  95. package/dist/execution/testing/seq-cases.d.ts +6 -0
  96. package/dist/execution/testing/seq-cases.js +71 -0
  97. package/dist/execution/testing/seq-registry.d.ts +3 -0
  98. package/dist/execution/testing/seq-registry.js +32 -0
  99. package/dist/execution/testing/wake-exec-cases.d.ts +20 -0
  100. package/dist/execution/testing/wake-exec-cases.js +147 -0
  101. package/dist/execution/testing/wake-registry.d.ts +3 -0
  102. package/dist/execution/testing/wake-registry.js +26 -0
  103. package/dist/execution/tool-host.d.ts +10 -2
  104. package/dist/execution/tool-outcome-events.d.ts +11 -0
  105. package/dist/execution/tool-outcome-events.js +47 -0
  106. package/dist/execution/wake-inbox.d.ts +25 -0
  107. package/dist/execution/wake-inbox.js +85 -0
  108. package/dist/execution/wake-outbox.d.ts +30 -0
  109. package/dist/execution/wake-outbox.js +87 -0
  110. package/dist/execution/wake-types.d.ts +45 -0
  111. package/dist/execution/wake-types.js +3 -0
  112. package/dist/harness/env/nodejs.js +4 -0
  113. package/dist/index.d.ts +21 -1
  114. package/dist/index.js +19 -1
  115. package/dist/node.d.ts +1 -0
  116. package/dist/node.js +1 -0
  117. package/dist/transport/testing/multi-cases.js +8 -8
  118. package/package.json +3 -3
@@ -0,0 +1,210 @@
1
+ import { TOOL_RESULT_PLACEHOLDER } from "@earendil-works/pi-ai";
2
+ import { expectEqual } from "../../durable/testing/store-harness.js";
3
+ import { interruptedReplayText } from "../coordinator-plan.js";
4
+ import { ExecutorKilledError } from "./batch-executor.js";
5
+ import { BrainKilledError, batchHarness, batchPlan, expectRejects, resultOf, } from "./batch-harness.js";
6
+ function ranOnce(h, ids, steps, what) {
7
+ for (const id of ids)
8
+ for (const step of steps)
9
+ expectEqual(h.count(`${step}:${id}`), 1, `${what}: ${step}:${id}`);
10
+ }
11
+ function before(h, first, second, what) {
12
+ const a = h.trace.indexOf(first);
13
+ const b = h.trace.indexOf(second);
14
+ if (a < 0 || b < 0 || a > b)
15
+ throw new Error(`${what}: expected ${first} before ${second} in ${h.trace.join(",")}`);
16
+ }
17
+ const crashAfterManifest = async (adapters) => {
18
+ const h = await batchHarness(adapters);
19
+ const plan = batchPlan("batch-01", [
20
+ ["a", "e1"],
21
+ ["b", "e2"],
22
+ ]);
23
+ await expectRejects((await h.brain({ label: "manifest", at: "after" })).run(plan), BrainKilledError, "kill");
24
+ expectEqual(h.trace, [], "nothing has run after the manifest alone");
25
+ const result = await (await h.brain()).run(plan);
26
+ expectEqual(result, { decision: "RELEASE", outcomes: [resultOf("a"), resultOf("b")] }, "re-prepared and run");
27
+ ranOnce(h, ["a", "b"], ["shim", "hook", "body"], "the same execution ids, each step once");
28
+ expectEqual(await h.ledgerState("e1", "a"), "settled", "the endpoint row carries the manifest's execution id");
29
+ };
30
+ const crashAfterPrepares = async (adapters) => {
31
+ const h = await batchHarness(adapters);
32
+ const plan = batchPlan("batch-02", [
33
+ ["a", "e1"],
34
+ ["b", "e2"],
35
+ ]);
36
+ await expectRejects((await h.brain({ label: "decision", at: "before" })).run(plan), BrainKilledError, "kill");
37
+ expectEqual(h.trace, ["shim:a", "hook:a", "shim:b", "hook:b"], "both prepared, no body before the decision");
38
+ const result = await (await h.brain()).run(plan);
39
+ expectEqual(result.outcomes, [resultOf("a"), resultOf("b")], "the stored prepare replies decide RELEASE");
40
+ ranOnce(h, ["a", "b"], ["shim", "hook", "body"], "hooks never rerun");
41
+ };
42
+ const crashInsideFirstWave = async (adapters) => {
43
+ const h = await batchHarness(adapters);
44
+ const plan = batchPlan("batch-03", [
45
+ ["a", "e1"],
46
+ ["b", "e2"],
47
+ ["c", "e1", "read", "sequential"],
48
+ ]);
49
+ const bodyA = h.hold("a", "body");
50
+ await expectRejects((await h.brain({ label: "release:b", at: "before" })).run(plan), BrainKilledError, "kill");
51
+ await bodyA.reached;
52
+ const settledB = h.written("outcome:b");
53
+ const resumed = (await h.brain()).run(plan);
54
+ const writes = await settledB;
55
+ expectEqual(writes.includes("release:c"), false, "the next wave is not released while wave 0 is unsettled");
56
+ bodyA.open();
57
+ expectEqual((await resumed).outcomes, [resultOf("a"), resultOf("b"), resultOf("c")], "every call settles");
58
+ ranOnce(h, ["a", "b", "c"], ["hook", "body"], "a re-sent release never reruns a body");
59
+ before(h, "body:b", "done:a", "the unmarked wave-0 call is released beside the re-sent one");
60
+ before(h, "done:a", "body:c", "wave 1 waits for a");
61
+ before(h, "done:b", "body:c", "wave 1 waits for b");
62
+ };
63
+ const executorRestartKeepsPrepared = async (adapters) => {
64
+ const h = await batchHarness(adapters);
65
+ const plan = batchPlan("batch-05", [
66
+ ["a", "e1"],
67
+ ["b", "e1", "read", "sequential"],
68
+ ]);
69
+ const dispatchA = h.hold("a", "dispatch");
70
+ const brain = await h.brain();
71
+ const first = brain.run(plan);
72
+ await dispatchA.reached;
73
+ await h.restartExecutor("e1");
74
+ await expectRejects(first, ExecutorKilledError, "the release in flight is lost with the executor");
75
+ expectEqual(await h.ledgerState("e1", "a"), "released", "released survives the restart");
76
+ expectEqual(await h.ledgerState("e1", "b"), "prepared", "prepared survives the restart");
77
+ dispatchA.open();
78
+ expectEqual((await brain.run(plan)).outcomes, [resultOf("a"), resultOf("b")], "release proceeds");
79
+ ranOnce(h, ["a", "b"], ["hook", "body"], "nothing is prepared or run twice");
80
+ };
81
+ const lostPreparedExecution = async (adapters) => {
82
+ const h = await batchHarness(adapters);
83
+ const plan = batchPlan("batch-06", [
84
+ ["a", "e1"],
85
+ ["b", "e2"],
86
+ ]);
87
+ await expectRejects((await h.brain({ label: "decision", at: "after" })).run(plan), BrainKilledError, "kill");
88
+ await h.loseExecutor("e1");
89
+ const { outcomes } = await (await h.brain()).run(plan);
90
+ const lost = { kind: "interrupted", reason: "unknown_execution", uncertain: true };
91
+ expectEqual(outcomes, [lost, resultOf("b")], "a lost prepared execution is uncertain; the sibling settles");
92
+ expectEqual(h.count("body:a"), 0, "the lost call never runs");
93
+ expectEqual(interruptedReplayText(lost), TOOL_RESULT_PLACEHOLDER, "it replays with today's placeholder");
94
+ };
95
+ const wavesAcrossExecutors = async (adapters) => {
96
+ const h = await batchHarness(adapters);
97
+ const plan = batchPlan("batch-07", [
98
+ ["a", "e1"],
99
+ ["b", "e2"],
100
+ ["s", "e1", "read", "sequential"],
101
+ ["d", "e2"],
102
+ ]);
103
+ const hookA = h.hold("a", "hook");
104
+ const [bodyA, bodyB] = [h.hold("a", "body"), h.hold("b", "body")];
105
+ const run = (await h.brain()).run(plan);
106
+ await hookA.reached;
107
+ expectEqual(h.count("shim:b"), 0, "b is prepared only after a's prepare reply");
108
+ hookA.open();
109
+ await Promise.all([bodyA.reached, bodyB.reached]);
110
+ const settledB = h.written("outcome:b");
111
+ bodyB.open();
112
+ const writes = await settledB;
113
+ expectEqual(writes.includes("release:s"), false, "the sequential call is not released while the wave runs");
114
+ bodyA.open();
115
+ expectEqual((await run).outcomes, ["a", "b", "s", "d"].map((id) => resultOf(id)), "every call settles");
116
+ for (const [first, second] of [
117
+ ["shim:a", "shim:b"],
118
+ ["shim:b", "shim:s"],
119
+ ["shim:s", "shim:d"],
120
+ ])
121
+ before(h, first, second, "prepare runs in source order across executors");
122
+ for (const [first, second] of [
123
+ ["done:a", "body:s"],
124
+ ["done:b", "body:s"],
125
+ ["done:s", "body:d"],
126
+ ])
127
+ before(h, first, second, "a release waits for its dependencies' final outcomes");
128
+ const chain = batchPlan("batch-07-blocked-link", [
129
+ ["s1", "e1", "read", "sequential"],
130
+ ["s2", "e2", "deny", "sequential"],
131
+ ["s3", "e1", "read", "sequential"],
132
+ ["p", "e2"],
133
+ ]);
134
+ const last = h.written("outcome:p");
135
+ const blocked = { kind: "blocked", result: "blocked: deny" };
136
+ expectEqual((await (await h.brain()).run(chain)).outcomes, [resultOf("s1"), blocked, resultOf("s3"), resultOf("p")], "a blocked link settles as blocked; the chain runs");
137
+ const order = await last;
138
+ for (const [finished, released] of [
139
+ ["outcome:s1", "release:s3"],
140
+ ["outcome:s3", "release:p"],
141
+ ]) {
142
+ const [a, b] = [order.indexOf(finished), order.indexOf(released)];
143
+ if (a < 0 || b < 0 || a > b)
144
+ throw new Error(`a blocked link still waits on its own dependencies: ${finished} before ${released}`);
145
+ }
146
+ };
147
+ const batchAbort = async (adapters) => {
148
+ const h = await batchHarness(adapters);
149
+ const plan = batchPlan("batch-08", [
150
+ ["a", "e1"],
151
+ ["b", "e2", "stop"],
152
+ ["c", "e1"],
153
+ ]);
154
+ await expectRejects((await h.brain({ label: "decision", at: "after" })).run(plan), BrainKilledError, "kill");
155
+ const result = await (await h.brain()).run(plan);
156
+ const notRun = { kind: "not_run", cause: "batch_abort" };
157
+ expectEqual(result, { decision: "ABORT", outcomes: [notRun, notRun, notRun] }, "ABORT ends every call");
158
+ expectEqual(h.count("shim:c"), 0, "no call after the batch_abort reply is prepared");
159
+ expectEqual(["body:a", "body:b"].map(h.count), [0, 0], "no body runs");
160
+ expectEqual(await h.ledgerState("e1", "a"), "settled", "the re-sent abort ends the prepared call");
161
+ };
162
+ const blockedBesideReleased = async (adapters) => {
163
+ const h = await batchHarness(adapters);
164
+ const plan = batchPlan("batch-09", [
165
+ ["a", "e1", "deny"],
166
+ ["b", "e2"],
167
+ ["c", "e1", "read", "sequential"],
168
+ ]);
169
+ const result = await (await h.brain()).run(plan);
170
+ const blocked = { kind: "blocked", result: "blocked: deny" };
171
+ expectEqual(result, { decision: "RELEASE", outcomes: [blocked, resultOf("b"), resultOf("c")] }, "others run");
172
+ expectEqual(h.count("body:a"), 0, "a blocked call's body never runs");
173
+ expectEqual(await h.ledgerState("e1", "a"), "settled", "the blocked call's endpoint is closed");
174
+ };
175
+ async function replayInterruptedPreparation(adapters, withPreparedSibling) {
176
+ const h = await batchHarness(adapters);
177
+ const ids = withPreparedSibling ? ["a", "b"] : ["b"];
178
+ const plan = batchPlan(`replay-${ids.length}`, ids.map((id) => [id, "e1"]));
179
+ const hookB = h.hold("b", "hook");
180
+ const brain = await h.brain();
181
+ const first = brain.run(plan);
182
+ await hookB.reached;
183
+ await h.restartExecutor("e1");
184
+ await expectRejects(first, ExecutorKilledError, "the executor died during preparation");
185
+ const { decision, outcomes } = await brain.run(plan);
186
+ const interrupted = { kind: "interrupted", reason: "hand_restarted", uncertain: true };
187
+ const sibling = { kind: "not_run", cause: "interrupted_preparation" };
188
+ expectEqual(decision, "ABORT", "unreleased calls are aborted");
189
+ expectEqual(outcomes, withPreparedSibling ? [sibling, interrupted] : [interrupted], "outcomes");
190
+ expectEqual(outcomes.map(interruptedReplayText), ids.map(() => TOOL_RESULT_PLACEHOLDER), "today's placeholder");
191
+ ranOnce(h, ids, ["shim", "hook"], "preparation never runs again");
192
+ expectEqual(ids.map((id) => h.count(`body:${id}`)), ids.map(() => 0), "no body runs");
193
+ const again = ids.map((id) => `${id}-again`);
194
+ const reissued = await brain.run(batchPlan(`${plan.batchId}-again`, again.map((id) => [id, "e1"])));
195
+ expectEqual(reissued.outcomes, again.map((id) => resultOf(id)), "a reissued call runs afresh");
196
+ ranOnce(h, again, ["shim", "hook", "body"], "exactly once");
197
+ }
198
+ export const BATCH_CASES = new Map([
199
+ ["BATCH-01", crashAfterManifest],
200
+ ["BATCH-02", crashAfterPrepares],
201
+ ["BATCH-03", crashInsideFirstWave],
202
+ ["BATCH-05", executorRestartKeepsPrepared],
203
+ ["BATCH-06", lostPreparedExecution],
204
+ ["BATCH-07", wavesAcrossExecutors],
205
+ ["BATCH-08", batchAbort],
206
+ ["BATCH-09", blockedBesideReleased],
207
+ ["REPLAY-01", (adapters) => replayInterruptedPreparation(adapters, false)],
208
+ ["REPLAY-02", (adapters) => replayInterruptedPreparation(adapters, true)],
209
+ ]);
210
+ //# sourceMappingURL=batch-cases.js.map
@@ -0,0 +1,34 @@
1
+ import type { DurableStore } from "../../durable/store.ts";
2
+ import type { StoreCaseAdapters } from "../../durable/testing/store-harness.ts";
3
+ import type { BatchExecutor } from "../coordinator-types.ts";
4
+ /** Where a test can hold an execution: inside the `tool_call` chain, between release and dispatch, inside the body. */
5
+ export type PausePoint = "hook" | "dispatch" | "body";
6
+ export interface ExecutorOpenOptions {
7
+ readonly id: string;
8
+ /** The executor's own durable store, already claimed at `epoch`. */
9
+ readonly store: DurableStore;
10
+ readonly epoch: number;
11
+ readonly now: () => number;
12
+ /** Survives restarts: `shim:<id>`, `hook:<id>`, `body:<id>`, `done:<id>`, each appended when the step runs. */
13
+ readonly trace: string[];
14
+ readonly pause: (executionId: string, point: PausePoint) => Promise<void>;
15
+ /** Aborted when the executor process is killed; a killed executor never writes or answers again. */
16
+ readonly killed: AbortSignal;
17
+ }
18
+ /** The `executor` adapter: opens an executor endpoint over a store, recovering its durable executions first. */
19
+ export interface BatchExecutorConformanceAdapter {
20
+ open(options: ExecutorOpenOptions): Promise<BatchExecutor>;
21
+ }
22
+ export type BatchCaseAdapters = StoreCaseAdapters & {
23
+ readonly executor: BatchExecutorConformanceAdapter;
24
+ };
25
+ export declare class ExecutorKilledError extends Error {
26
+ constructor(id: string);
27
+ }
28
+ /**
29
+ * A reference executor over the execution ledger: preparation runs a scripted shim and `tool_call` chain once, the
30
+ * body runs once from the frozen call, and every answer is read back from durable state, so a re-sent message never
31
+ * reruns a step.
32
+ */
33
+ export declare const referenceBatchExecutor: BatchExecutorConformanceAdapter;
34
+ //# sourceMappingURL=batch-executor.d.ts.map
@@ -0,0 +1,170 @@
1
+ import { createAdmissionLine } from "../../durable/store-admission.js";
2
+ import { createExecutionLedger } from "../ledger.js";
3
+ /** What the scripted `tool_call` chain decides for a tool name; unknown names are allowed. */
4
+ const BATCH_TOOLS = { deny: "blocked", stop: "batch_abort" };
5
+ /**
6
+ * Tools whose body needs consent (design 5.6.1). `gated`'s shim changes the call, so its frozen call always differs
7
+ * from the raw one; `ask`'s shim keeps it, so a Gate A approval of the raw digest also covers the frozen call.
8
+ */
9
+ const CONSENT_TOOLS = new Set(["gated", "ask"]);
10
+ const frozenDigestOf = (name, requestDigest) => name === "ask" ? requestDigest : `${requestDigest}:frozen`;
11
+ export class ExecutorKilledError extends Error {
12
+ constructor(id) {
13
+ super(`executor ${id} was killed`);
14
+ this.name = "ExecutorKilledError";
15
+ }
16
+ }
17
+ function stoppedReply(kind, name) {
18
+ return kind === "blocked" ? { kind, result: `blocked: ${name}` } : { kind };
19
+ }
20
+ /** The reply a re-sent prepare gets back from the ledger's durable `blocked` outcome, as the prepared executor does. */
21
+ function fromStopped(value) {
22
+ if (value === null || typeof value !== "object" || !("kind" in value) || !("name" in value))
23
+ return undefined;
24
+ const { kind, name } = value;
25
+ if (typeof name !== "string" || (kind !== "blocked" && kind !== "batch_abort"))
26
+ return undefined;
27
+ return stoppedReply(kind, name);
28
+ }
29
+ function expectEntry(reply, what) {
30
+ if (reply.status === "applied" || reply.status === "replayed")
31
+ return reply.entry;
32
+ throw new Error(`${what}: unexpected ledger reply ${JSON.stringify(reply)}`);
33
+ }
34
+ /**
35
+ * A reference executor over the execution ledger: preparation runs a scripted shim and `tool_call` chain once, the
36
+ * body runs once from the frozen call, and every answer is read back from durable state, so a re-sent message never
37
+ * reruns a step.
38
+ */
39
+ export const referenceBatchExecutor = {
40
+ open: async (options) => {
41
+ const { id, store, epoch, now, trace, pause, killed } = options;
42
+ const ledger = createExecutionLedger({ store, epoch, admission: createAdmissionLine() });
43
+ await ledger.recover(now());
44
+ const death = new Promise((_, reject) => killed.addEventListener("abort", () => reject(new ExecutorKilledError(id)), { once: true }));
45
+ death.catch(() => { });
46
+ const alive = () => {
47
+ if (killed.aborted)
48
+ throw new ExecutorKilledError(id);
49
+ };
50
+ const hold = async (executionId, point) => {
51
+ await Promise.race([pause(executionId, point), death]);
52
+ alive();
53
+ };
54
+ const keyOf = (ref) => ({ issuer: ref.issuer, commandId: ref.executionId });
55
+ const apply = (ref, event, actor) => ledger.apply({ key: keyOf(ref), generation: ref.generation, actor: { id: actor }, now: now(), event });
56
+ const stored = async (entry) => {
57
+ const progress = entry.progress;
58
+ if (progress.state === "settled") {
59
+ const stopped = progress.outcome.reason === "blocked" ? fromStopped(progress.outcome.value) : undefined;
60
+ return stopped ?? { kind: "settled", outcome: progress.outcome };
61
+ }
62
+ if (!("call" in progress))
63
+ throw new Error(`no stored prepare reply in state ${progress.state}`);
64
+ if (progress.state === "prepared_awaiting_consent")
65
+ return { kind: "prepared_awaiting_consent", frozenDigest: progress.call.digest };
66
+ return { kind: "prepared", frozenDigest: progress.call.digest };
67
+ };
68
+ const settled = async (ref) => {
69
+ const entry = await ledger.read(keyOf(ref));
70
+ if (entry === undefined)
71
+ return { kind: "unknown_execution" };
72
+ if (entry.progress.state !== "settled")
73
+ throw new Error(`execution ${ref.executionId} is ${entry.progress.state}`);
74
+ return { kind: "settled", outcome: entry.progress.outcome };
75
+ };
76
+ const prepare = async (request) => {
77
+ const { issuer, executionId: commandId, generation, workspace, scope, requestDigest, call } = request;
78
+ const { admittedAt, leaseUntil } = request;
79
+ const admission = {
80
+ issuer,
81
+ commandId,
82
+ executor: id,
83
+ workspace,
84
+ scope,
85
+ generation,
86
+ requestDigest,
87
+ admittedAt,
88
+ leaseUntil,
89
+ };
90
+ const entry = expectEntry(await ledger.admit({ ...admission, reconcilable: false }), "admit");
91
+ if (entry.progress.state !== "admitted")
92
+ return stored(entry);
93
+ expectEntry(await apply(request, { kind: "prepare" }, id), "prepare");
94
+ expectEntry(await apply(request, { kind: "effect" }, id), "effect");
95
+ trace.push(`shim:${commandId}`);
96
+ trace.push(`hook:${commandId}`);
97
+ await hold(commandId, "hook");
98
+ const decision = BATCH_TOOLS[call.name];
99
+ if (decision !== undefined) {
100
+ const block = { kind: "block", value: { kind: decision, name: call.name } };
101
+ return stored(expectEntry(await apply(request, block, id), "block"));
102
+ }
103
+ const frozen = { ...call, digest: frozenDigestOf(call.name, requestDigest) };
104
+ const awaitingConsent = CONSENT_TOOLS.has(call.name) && request.authorizedDigest !== frozen.digest;
105
+ const freeze = { kind: "freeze", call: frozen, awaitingConsent };
106
+ return stored(expectEntry(await apply(request, freeze, id), "freeze"));
107
+ };
108
+ const release = async (ref) => {
109
+ const entry = await ledger.read(keyOf(ref));
110
+ if (entry === undefined)
111
+ return { kind: "unknown_execution" };
112
+ if (entry.progress.state === "settled")
113
+ return settled(ref);
114
+ expectEntry(await apply(ref, { kind: "release" }, ref.issuer), "release");
115
+ await hold(ref.executionId, "dispatch");
116
+ const dispatched = expectEntry(await apply(ref, { kind: "dispatch" }, id), "dispatch");
117
+ if (dispatched.progress.state === "dispatched") {
118
+ trace.push(`body:${ref.executionId}`);
119
+ await hold(ref.executionId, "body");
120
+ const value = { executionId: ref.executionId, name: dispatched.progress.call.name };
121
+ trace.push(`done:${ref.executionId}`);
122
+ expectEntry(await apply(ref, { kind: "result", value }, id), "result");
123
+ }
124
+ return settled(ref);
125
+ };
126
+ const abort = async (ref) => {
127
+ if ((await ledger.read(keyOf(ref))) === undefined)
128
+ return { kind: "unknown_execution" };
129
+ const reply = await apply(ref, { kind: "abort" }, ref.issuer);
130
+ if (reply.status === "refused" && reply.reason !== "terminal")
131
+ throw new Error(`abort refused: ${reply.reason}`);
132
+ return settled(ref);
133
+ };
134
+ const consent = async (ref, frozenDigest) => {
135
+ const entry = await ledger.read(keyOf(ref));
136
+ if (entry === undefined)
137
+ return { kind: "unknown_execution" };
138
+ if ("call" in entry.progress && entry.progress.call.digest !== frozenDigest)
139
+ throw new Error(`consent for ${ref.executionId} names another frozen call`);
140
+ const reply = await apply(ref, { kind: "consent" }, ref.issuer);
141
+ if (reply.status === "refused" && reply.reason !== "terminal" && reply.reason !== "invalid_transition")
142
+ throw new Error(`consent refused: ${reply.reason}`);
143
+ const after = await ledger.read(keyOf(ref));
144
+ return after?.progress.state === "prepared" ? { kind: "prepared" } : settled(ref);
145
+ };
146
+ const once = (run) => {
147
+ const inflight = new Map();
148
+ return (input) => {
149
+ alive();
150
+ const key = JSON.stringify([input.issuer, input.executionId]);
151
+ const running = inflight.get(key);
152
+ if (running !== undefined)
153
+ return running;
154
+ const started = run(input).finally(() => inflight.delete(key));
155
+ inflight.set(key, started);
156
+ return started;
157
+ };
158
+ };
159
+ return {
160
+ prepare: once(prepare),
161
+ release: once(release),
162
+ abort: once(abort),
163
+ consent: (ref, frozenDigest) => {
164
+ alive();
165
+ return consent(ref, frozenDigest);
166
+ },
167
+ };
168
+ },
169
+ };
170
+ //# sourceMappingURL=batch-executor.js.map
@@ -0,0 +1,58 @@
1
+ import type { StoreValue } from "../../durable/store.ts";
2
+ import { type BatchCoordinator } from "../coordinator.ts";
3
+ import { type NestedAdmissionControl } from "../nested.ts";
4
+ import { type ScopeLifecycle } from "../scope-lifecycle.ts";
5
+ import { type WakeInbox } from "../wake-inbox.ts";
6
+ import { type WakeOutbox } from "../wake-outbox.ts";
7
+ import type { BatchConsent, BatchExecutor, BatchPlan, CallOutcome } from "../coordinator-types.ts";
8
+ import type { BatchCaseAdapters, PausePoint } from "./batch-executor.ts";
9
+ /** A coordinator write named by its step and call: `manifest`, `prepare:a`, `decision`, `release:a`, `outcome:a`. */
10
+ export type BrainKill = {
11
+ readonly label: string;
12
+ readonly at: "before" | "after";
13
+ };
14
+ export declare class BrainKilledError extends Error {
15
+ constructor(label: string);
16
+ }
17
+ export type CallSpec = readonly [executionId: string, executor: string, name?: string, sequential?: "sequential"];
18
+ export declare function batchPlan(batchId: string, calls: readonly CallSpec[]): BatchPlan;
19
+ export declare const resultOf: (executionId: string, name?: string) => CallOutcome;
20
+ export type BatchHarness = Awaited<ReturnType<typeof batchHarness>>;
21
+ /** Two executors (`e1`, `e2`) and one brain, each on its own durable medium, with pausable steps and kill controls. */
22
+ export declare function batchHarness(adapters: BatchCaseAdapters): Promise<{
23
+ trace: string[];
24
+ count: (event: string) => number;
25
+ /** Resolves with every durable brain write so far, at the moment the brain's `label` write becomes durable. */
26
+ written: (label: string) => Promise<readonly string[]>;
27
+ /** Hold `executionId` at `point`: `reached` resolves when the step gets there, `open()` lets it continue. */
28
+ hold: (executionId: string, point: PausePoint) => {
29
+ reached: Promise<void>;
30
+ open: () => void;
31
+ };
32
+ /**
33
+ * A fresh brain process over the brain's durable medium, optionally dying around one of its writes. Two issuers
34
+ * on one harness are two sessions' brains sharing the executors.
35
+ */
36
+ brain: (dieAt?: BrainKill, issuer?: string, consent?: BatchConsent) => Promise<BatchCoordinator>;
37
+ /** The brain's nested admission over the same durable medium, optionally dying around one of its writes. */
38
+ nested: (dieAt?: BrainKill, issuer?: string) => Promise<NestedAdmissionControl>;
39
+ /** A hand's durable wake outbox on its own medium (one per hand), optionally dying around one of its writes. */
40
+ wakeOutbox: (hand: string, dieAt?: BrainKill) => Promise<WakeOutbox>;
41
+ /** The endpoint's scope lifecycle on its own medium, optionally dying around one of its writes. */
42
+ scopes: (idleTtlMs: number, dieAt?: BrainKill) => Promise<ScopeLifecycle>;
43
+ /** The `wake_expired` records a hand's outbox logged, in log order. */
44
+ wakeLog: (hand: string) => Promise<readonly StoreValue[]>;
45
+ /** The brain's wake inbox over its medium; `owner` binds each scope to its authenticated hand. */
46
+ wakeInbox: (owner: (scope: string) => string | undefined, dieAt?: BrainKill) => Promise<WakeInbox>;
47
+ /** Moves every executor's clock: a lease that ends before the new time is expired on the next ledger event. */
48
+ advance: (ms: number) => void;
49
+ /** The executor proxy for `id`, as the brain reaches it (a late approval goes through it). */
50
+ executor: (id: string) => BatchExecutor;
51
+ /** Kill the executor process and start a new one on the same durable medium. */
52
+ restartExecutor: (id: string) => Promise<void>;
53
+ /** Kill the executor and start it on a new, empty medium: every execution it held is lost. */
54
+ loseExecutor: (id: string) => Promise<void>;
55
+ ledgerState: (id: string, executionId: string) => Promise<string | undefined>;
56
+ }>;
57
+ export declare function expectRejects(operation: Promise<unknown>, type: new (...args: never[]) => Error, what: string): Promise<void>;
58
+ //# sourceMappingURL=batch-harness.d.ts.map