@code-yeongyu/senpi-agent-core 2026.11.3-1 → 2026.11.3-3

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 (51) hide show
  1. package/dist/conformance/index.d.ts +14 -0
  2. package/dist/conformance/index.js +8 -0
  3. package/dist/conformance/registry.js +22 -0
  4. package/dist/execution/coordinator-codec.d.ts +5 -0
  5. package/dist/execution/coordinator-codec.js +93 -0
  6. package/dist/execution/coordinator-plan.d.ts +33 -0
  7. package/dist/execution/coordinator-plan.js +106 -0
  8. package/dist/execution/coordinator-types.d.ts +116 -0
  9. package/dist/execution/coordinator-types.js +2 -0
  10. package/dist/execution/coordinator.d.ts +25 -0
  11. package/dist/execution/coordinator.js +132 -0
  12. package/dist/execution/grant-verify.d.ts +70 -0
  13. package/dist/execution/grant-verify.js +87 -0
  14. package/dist/execution/ledger-codec.js +1 -0
  15. package/dist/execution/ledger-transition.js +8 -0
  16. package/dist/execution/ledger-types.d.ts +10 -0
  17. package/dist/execution/ledger.d.ts +2 -0
  18. package/dist/execution/ledger.js +1 -0
  19. package/dist/execution/remote-executor.d.ts +64 -0
  20. package/dist/execution/remote-executor.js +159 -0
  21. package/dist/execution/remote-hand-ledger.d.ts +40 -0
  22. package/dist/execution/remote-hand-ledger.js +137 -0
  23. package/dist/execution/remote-protocol.d.ts +87 -0
  24. package/dist/execution/remote-protocol.js +88 -0
  25. package/dist/execution/remote-tool-host.d.ts +29 -0
  26. package/dist/execution/remote-tool-host.js +155 -0
  27. package/dist/execution/testing/batch-cases.d.ts +6 -0
  28. package/dist/execution/testing/batch-cases.js +210 -0
  29. package/dist/execution/testing/batch-executor.d.ts +34 -0
  30. package/dist/execution/testing/batch-executor.js +141 -0
  31. package/dist/execution/testing/batch-harness.d.ts +36 -0
  32. package/dist/execution/testing/batch-harness.js +208 -0
  33. package/dist/execution/testing/batch-registry.d.ts +3 -0
  34. package/dist/execution/testing/batch-registry.js +30 -0
  35. package/dist/execution/testing/fault-hand-cases.d.ts +6 -0
  36. package/dist/execution/testing/fault-hand-cases.js +70 -0
  37. package/dist/execution/testing/hand-harness.d.ts +48 -0
  38. package/dist/execution/testing/hand-harness.js +136 -0
  39. package/dist/execution/testing/kill-batch.d.ts +12 -0
  40. package/dist/execution/testing/kill-batch.js +70 -0
  41. package/dist/execution/testing/kill-hand.d.ts +16 -0
  42. package/dist/execution/testing/kill-hand.js +75 -0
  43. package/dist/execution/testing/ledger-cases.js +9 -0
  44. package/dist/execution/testing/multi-hand-cases.d.ts +6 -0
  45. package/dist/execution/testing/multi-hand-cases.js +44 -0
  46. package/dist/execution/testing/prep-cases.d.ts +57 -0
  47. package/dist/execution/testing/prep-cases.js +89 -0
  48. package/dist/harness/env/nodejs.js +4 -0
  49. package/dist/index.d.ts +9 -0
  50. package/dist/index.js +8 -0
  51. package/package.json +3 -3
@@ -0,0 +1,87 @@
1
+ import type { ImageContent, JsonValue, TextContent } from "@earendil-works/pi-ai";
2
+ import type { AgentToolResult } from "../types.ts";
3
+ import type { ExecutionScope } from "./tool-host.ts";
4
+ /**
5
+ * The wire messages between a session's remote ToolHost and the hand that runs its tool calls (brain/hand split, S27a).
6
+ * One transport lane per execution scope; a transport never inspects these payloads.
7
+ *
8
+ * The hand receives the model's raw call (name and arguments, before preparation, validation and hooks) and runs all of
9
+ * those steps itself. `sessionRef` is what the session chose to say about itself: the hand passes it to nothing.
10
+ */
11
+ export type RemoteHandMessage = RemoteInvoke | RemoteAbort | RemoteAck | RemoteSettled | RemoteTerminal | RemoteRefused | RemoteHello;
12
+ /** The lane a hand announces itself on; execution scope lanes carry everything else. */
13
+ export declare const HAND_CONTROL_LANE = "hand.control";
14
+ /**
15
+ * A hand with a durable record announces itself when it (re)starts, after re-sending the outcomes the session has not
16
+ * acknowledged. The session then re-sends every call still waiting: the record answers a call it already holds, and
17
+ * runs only a call whose admission never became durable (nothing of it ran).
18
+ */
19
+ export interface RemoteHello {
20
+ readonly kind: "hello";
21
+ readonly instance: string;
22
+ }
23
+ export interface RemoteInvoke {
24
+ readonly kind: "invoke";
25
+ /** Unique per call per session; a hand runs one execution ID at most once. */
26
+ readonly executionId: string;
27
+ readonly batchId: string;
28
+ /** Position in the batch, in the model's source order. */
29
+ readonly index: number;
30
+ readonly scope: ExecutionScope;
31
+ readonly toolCallId: string;
32
+ readonly name: string;
33
+ readonly arguments: unknown;
34
+ readonly sessionRef?: string;
35
+ }
36
+ export interface RemoteAbort {
37
+ readonly kind: "abort";
38
+ readonly executionId: string;
39
+ }
40
+ /** The session has its outcome: the hand may forget it (a later replay is `result_expired`). */
41
+ export interface RemoteAck {
42
+ readonly kind: "ack";
43
+ readonly executionId: string;
44
+ }
45
+ /** The reasons a call can end on a hand without a tool result (the endpoint state machine's terminal reasons). */
46
+ export type RemoteTerminalReason = "cancelled" | "lease_expired" | "hand_restarted" | "uncertain";
47
+ /**
48
+ * The call ended without a tool result, for example because the hand restarted while it ran. `uncertain` says its
49
+ * effects may have happened; `hooksRan` says its `tool_call` handlers may have run. It is never run again.
50
+ */
51
+ export interface RemoteTerminal {
52
+ readonly kind: "terminal";
53
+ readonly executionId: string;
54
+ readonly reason: RemoteTerminalReason;
55
+ readonly uncertain: boolean;
56
+ readonly hooksRan: boolean;
57
+ }
58
+ /** The call ran to an outcome on the hand (an `isError` result included: a blocked, invalid or failing call). */
59
+ export interface RemoteSettled {
60
+ readonly kind: "settled";
61
+ readonly executionId: string;
62
+ readonly result: RemoteToolResult;
63
+ }
64
+ /** The hand refused the call before anything ran (duplicate execution, scope binding, an unopenable scope). */
65
+ export interface RemoteRefused {
66
+ readonly kind: "refused";
67
+ readonly executionId: string;
68
+ readonly reason: string;
69
+ }
70
+ /** The serializable part of an {@link AgentToolResult}. */
71
+ export interface RemoteToolResult {
72
+ readonly content: (TextContent | ImageContent)[];
73
+ readonly details: JsonValue | undefined;
74
+ readonly isError: boolean;
75
+ readonly structuredContent?: JsonValue;
76
+ readonly terminate?: boolean;
77
+ readonly addedToolNames?: readonly string[];
78
+ }
79
+ export declare class RemoteProtocolError extends Error {
80
+ constructor(message: string);
81
+ }
82
+ export declare function encodeRemoteMessage(message: RemoteHandMessage): Uint8Array;
83
+ /** Parses one frame payload. Anything that is not exactly one of the messages is refused; nothing guesses. */
84
+ export declare function decodeRemoteMessage(payload: Uint8Array): RemoteHandMessage;
85
+ /** What a hand sends back for a tool result, keeping only what crosses the wire. */
86
+ export declare function toRemoteToolResult(result: AgentToolResult<unknown>): RemoteToolResult;
87
+ //# sourceMappingURL=remote-protocol.d.ts.map
@@ -0,0 +1,88 @@
1
+ /** The lane a hand announces itself on; execution scope lanes carry everything else. */
2
+ export const HAND_CONTROL_LANE = "hand.control";
3
+ export class RemoteProtocolError extends Error {
4
+ constructor(message) {
5
+ super(`remote_protocol: ${message}`);
6
+ this.name = "RemoteProtocolError";
7
+ }
8
+ }
9
+ const TERMINAL_REASONS = ["cancelled", "lease_expired", "hand_restarted", "uncertain"];
10
+ const encoder = new TextEncoder();
11
+ const decoder = new TextDecoder();
12
+ export function encodeRemoteMessage(message) {
13
+ return encoder.encode(JSON.stringify(message));
14
+ }
15
+ const isRecord = (value) => typeof value === "object" && value !== null;
16
+ const isString = (value) => typeof value === "string" && value.length > 0;
17
+ /** Parses one frame payload. Anything that is not exactly one of the messages is refused; nothing guesses. */
18
+ export function decodeRemoteMessage(payload) {
19
+ let value;
20
+ try {
21
+ value = JSON.parse(decoder.decode(payload));
22
+ }
23
+ catch {
24
+ throw new RemoteProtocolError("payload is not JSON");
25
+ }
26
+ if (isRecord(value) && value.kind === "hello") {
27
+ if (!isString(value.instance))
28
+ throw new RemoteProtocolError("malformed hello");
29
+ return { kind: "hello", instance: value.instance };
30
+ }
31
+ if (!isRecord(value) || !isString(value.executionId))
32
+ throw new RemoteProtocolError("no execution ID");
33
+ switch (value.kind) {
34
+ case "invoke": {
35
+ const scope = value.scope;
36
+ if (!isString(value.batchId) ||
37
+ typeof value.index !== "number" ||
38
+ !Number.isSafeInteger(value.index) ||
39
+ value.index < 0 ||
40
+ !isRecord(scope) ||
41
+ !isString(scope.id) ||
42
+ typeof scope.root !== "string" ||
43
+ !isString(value.toolCallId) ||
44
+ !isString(value.name) ||
45
+ (value.sessionRef !== undefined && typeof value.sessionRef !== "string"))
46
+ throw new RemoteProtocolError("malformed invoke");
47
+ return value;
48
+ }
49
+ case "abort":
50
+ return value;
51
+ case "ack":
52
+ return value;
53
+ case "terminal":
54
+ if (!TERMINAL_REASONS.includes(value.reason) ||
55
+ typeof value.uncertain !== "boolean" ||
56
+ typeof value.hooksRan !== "boolean")
57
+ throw new RemoteProtocolError("malformed terminal outcome");
58
+ return value;
59
+ case "settled": {
60
+ const result = value.result;
61
+ if (!isRecord(result) || !Array.isArray(result.content) || typeof result.isError !== "boolean")
62
+ throw new RemoteProtocolError("malformed result");
63
+ return value;
64
+ }
65
+ case "refused":
66
+ if (typeof value.reason !== "string")
67
+ throw new RemoteProtocolError("malformed refusal");
68
+ return value;
69
+ default:
70
+ throw new RemoteProtocolError("unknown message kind");
71
+ }
72
+ }
73
+ /** The JSON form a value takes on the wire (what the session receives), so a result's types say what arrives. */
74
+ function asJson(value) {
75
+ return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
76
+ }
77
+ /** What a hand sends back for a tool result, keeping only what crosses the wire. */
78
+ export function toRemoteToolResult(result) {
79
+ return {
80
+ content: result.content ?? [],
81
+ details: asJson(result.details),
82
+ isError: result.isError === true,
83
+ ...(result.structuredContent === undefined ? {} : { structuredContent: result.structuredContent }),
84
+ ...(result.terminate === undefined ? {} : { terminate: result.terminate }),
85
+ ...(result.addedToolNames?.length ? { addedToolNames: [...result.addedToolNames] } : {}),
86
+ };
87
+ }
88
+ //# sourceMappingURL=remote-protocol.js.map
@@ -0,0 +1,29 @@
1
+ import type { Transport } from "../transport/transport.ts";
2
+ import type { ToolHost } from "./tool-host.ts";
3
+ /**
4
+ * Where the hand runs relative to the session. It decides what a call that ended without a result (the hand restarted
5
+ * while it ran) looks like to the model, and is always stated, never inferred:
6
+ * - `split-local`: one machine. Recovery equals today's: the call gets today's placeholder result and is not run again.
7
+ * - `cross-machine`: the endpoint contract. The call is reported as uncertain, never run again.
8
+ */
9
+ export type HandPlacement = "split-local" | "cross-machine";
10
+ export interface RemoteToolHostOptions {
11
+ /** The session's end of the link to the hand; lanes are execution scope IDs. */
12
+ readonly transport: Transport;
13
+ readonly placement: HandPlacement;
14
+ /** What the session says about itself; the hand never acts on it (R16). */
15
+ readonly sessionRef?: string;
16
+ readonly mintId?: () => string;
17
+ }
18
+ /**
19
+ * The ToolHost that runs a session's tool calls on a hand (brain/hand split, S27a). The hand resolves, prepares,
20
+ * validates, runs the extensions' `tool_call`/`tool_result` handlers (permission checks among them) and executes each
21
+ * call; this host keeps the loop's side: tool events, the batch's ordering, a forwarded abort and the result messages in
22
+ * source order. A call whose send is refused (the transport closed) becomes an error result, never a retry. The one
23
+ * re-send is on a hand's `hello` (it restarted with its durable record): every call still waiting is sent again, and
24
+ * the hand answers each one its record already holds instead of running it a second time.
25
+ */
26
+ export declare function createRemoteToolHost(options: RemoteToolHostOptions): ToolHost & {
27
+ close(): void;
28
+ };
29
+ //# sourceMappingURL=remote-tool-host.d.ts.map
@@ -0,0 +1,155 @@
1
+ import { TOOL_RESULT_PLACEHOLDER } from "@earendil-works/pi-ai";
2
+ import { decodeRemoteMessage, encodeRemoteMessage, } from "./remote-protocol.js";
3
+ function errorResult(text) {
4
+ return { content: [{ type: "text", text }], details: {}, isError: true };
5
+ }
6
+ function terminalResult(placement, terminal) {
7
+ if (placement === "split-local")
8
+ return { content: [{ type: "text", text: TOOL_RESULT_PLACEHOLDER }], details: {}, isError: false };
9
+ const { reason, uncertain, hooksRan } = terminal;
10
+ const effects = uncertain ? "Its effects are uncertain." : "It had no effect.";
11
+ return {
12
+ content: [
13
+ { type: "text", text: `The tool call ended without a result (${reason}) and was not run again. ${effects}` },
14
+ ],
15
+ details: { outcome: reason, uncertain, hooksRan },
16
+ isError: true,
17
+ };
18
+ }
19
+ /**
20
+ * The ToolHost that runs a session's tool calls on a hand (brain/hand split, S27a). The hand resolves, prepares,
21
+ * validates, runs the extensions' `tool_call`/`tool_result` handlers (permission checks among them) and executes each
22
+ * call; this host keeps the loop's side: tool events, the batch's ordering, a forwarded abort and the result messages in
23
+ * source order. A call whose send is refused (the transport closed) becomes an error result, never a retry. The one
24
+ * re-send is on a hand's `hello` (it restarted with its durable record): every call still waiting is sent again, and
25
+ * the hand answers each one its record already holds instead of running it a second time.
26
+ */
27
+ export function createRemoteToolHost(options) {
28
+ const { transport } = options;
29
+ const mintId = options.mintId ?? (() => crypto.randomUUID());
30
+ const pending = new Map();
31
+ const settle = (executionId, result) => {
32
+ const waiter = pending.get(executionId);
33
+ if (waiter === undefined)
34
+ return;
35
+ pending.delete(executionId);
36
+ waiter.resolve(result);
37
+ };
38
+ transport.onFrame((frame) => {
39
+ let message;
40
+ try {
41
+ message = decodeRemoteMessage(frame.payload);
42
+ }
43
+ catch {
44
+ return;
45
+ }
46
+ const ack = (executionId) => void transport.send(frame.lane, encodeRemoteMessage({ kind: "ack", executionId })).catch(() => undefined);
47
+ if (message.kind === "hello") {
48
+ for (const { invoke } of pending.values())
49
+ void transport.send(invoke.scope.id, encodeRemoteMessage(invoke)).catch(() => undefined);
50
+ return;
51
+ }
52
+ if (message.kind === "settled") {
53
+ settle(message.executionId, message.result);
54
+ ack(message.executionId);
55
+ }
56
+ else if (message.kind === "terminal") {
57
+ settle(message.executionId, terminalResult(options.placement, message));
58
+ ack(message.executionId);
59
+ }
60
+ else if (message.kind === "refused")
61
+ settle(message.executionId, errorResult(`The hand refused this tool call: ${message.reason}`));
62
+ });
63
+ const dispatch = (invoke, signal) => {
64
+ const settled = new Promise((resolve) => {
65
+ pending.set(invoke.executionId, { invoke, resolve });
66
+ });
67
+ if (signal?.aborted)
68
+ settle(invoke.executionId, errorResult("Operation aborted"));
69
+ else {
70
+ const onAbort = () => {
71
+ if (!pending.has(invoke.executionId))
72
+ return;
73
+ void transport
74
+ .send(invoke.scope.id, encodeRemoteMessage({ kind: "abort", executionId: invoke.executionId }))
75
+ .catch(() => undefined);
76
+ settle(invoke.executionId, errorResult("Tool execution aborted"));
77
+ };
78
+ signal?.addEventListener("abort", onAbort, { once: true });
79
+ void settled.then(() => signal?.removeEventListener("abort", onAbort));
80
+ transport.send(invoke.scope.id, encodeRemoteMessage(invoke)).catch((error) => {
81
+ const reason = error instanceof Error ? error.message : String(error);
82
+ settle(invoke.executionId, errorResult(`The hand is unreachable: ${reason}`));
83
+ });
84
+ }
85
+ return { settled };
86
+ };
87
+ return {
88
+ async execute(call, hostOptions) {
89
+ const { emit, signal } = hostOptions;
90
+ const batchId = mintId();
91
+ const invokeOf = (raw, index) => ({
92
+ kind: "invoke",
93
+ executionId: mintId(),
94
+ batchId,
95
+ index,
96
+ scope: call.scope,
97
+ toolCallId: raw.id,
98
+ name: raw.name,
99
+ arguments: raw.arguments,
100
+ ...(options.sessionRef === undefined ? {} : { sessionRef: options.sessionRef }),
101
+ });
102
+ const finish = async (raw, result) => {
103
+ await emit({
104
+ type: "tool_execution_end",
105
+ toolCallId: raw.id,
106
+ toolName: raw.name,
107
+ result,
108
+ isError: result.isError,
109
+ });
110
+ return result;
111
+ };
112
+ const outcomes = [];
113
+ for (const [index, raw] of call.calls.entries()) {
114
+ await emit({ type: "tool_execution_start", toolCallId: raw.id, toolName: raw.name, args: raw.arguments });
115
+ const outcome = dispatch(invokeOf(raw, index), signal).settled.then((result) => finish(raw, result));
116
+ outcomes.push(outcome);
117
+ if (call.mode === "sequential") {
118
+ await outcome;
119
+ if (signal?.aborted)
120
+ break;
121
+ }
122
+ }
123
+ const results = await Promise.all(outcomes);
124
+ const messages = [];
125
+ for (const [index, result] of results.entries()) {
126
+ const raw = call.calls[index];
127
+ if (raw === undefined)
128
+ continue;
129
+ const message = {
130
+ role: "toolResult",
131
+ toolCallId: raw.id,
132
+ toolName: raw.name,
133
+ content: result.content,
134
+ details: result.details,
135
+ ...(result.addedToolNames?.length ? { addedToolNames: [...result.addedToolNames] } : {}),
136
+ isError: result.isError,
137
+ timestamp: Date.now(),
138
+ };
139
+ await emit({ type: "message_start", message });
140
+ await emit({ type: "message_end", message });
141
+ messages.push(message);
142
+ }
143
+ return {
144
+ messages,
145
+ terminate: results.length > 0 && results.every((result) => result.terminate === true),
146
+ };
147
+ },
148
+ close() {
149
+ for (const executionId of [...pending.keys()])
150
+ settle(executionId, errorResult("The hand link was closed before the call settled"));
151
+ transport.close();
152
+ },
153
+ };
154
+ }
155
+ //# sourceMappingURL=remote-tool-host.js.map
@@ -0,0 +1,6 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import type { BatchCaseAdapters } from "./batch-executor.ts";
3
+ type BatchCase = CaseImplementation<BatchCaseAdapters>;
4
+ export declare const BATCH_CASES: ReadonlyMap<string, BatchCase>;
5
+ export {};
6
+ //# sourceMappingURL=batch-cases.d.ts.map
@@ -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