@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,141 @@
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
+ export class ExecutorKilledError extends Error {
6
+ constructor(id) {
7
+ super(`executor ${id} was killed`);
8
+ this.name = "ExecutorKilledError";
9
+ }
10
+ }
11
+ function stoppedReply(kind, name) {
12
+ return kind === "blocked" ? { kind, result: `blocked: ${name}` } : { kind };
13
+ }
14
+ /** The reply a re-sent prepare gets back from the ledger's durable `blocked` outcome, as the prepared executor does. */
15
+ function fromStopped(value) {
16
+ if (value === null || typeof value !== "object" || !("kind" in value) || !("name" in value))
17
+ return undefined;
18
+ const { kind, name } = value;
19
+ if (typeof name !== "string" || (kind !== "blocked" && kind !== "batch_abort"))
20
+ return undefined;
21
+ return stoppedReply(kind, name);
22
+ }
23
+ function expectEntry(reply, what) {
24
+ if (reply.status === "applied" || reply.status === "replayed")
25
+ return reply.entry;
26
+ throw new Error(`${what}: unexpected ledger reply ${JSON.stringify(reply)}`);
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 const referenceBatchExecutor = {
34
+ open: async (options) => {
35
+ const { id, store, epoch, now, trace, pause, killed } = options;
36
+ const ledger = createExecutionLedger({ store, epoch, admission: createAdmissionLine() });
37
+ await ledger.recover(now());
38
+ const death = new Promise((_, reject) => killed.addEventListener("abort", () => reject(new ExecutorKilledError(id)), { once: true }));
39
+ death.catch(() => { });
40
+ const alive = () => {
41
+ if (killed.aborted)
42
+ throw new ExecutorKilledError(id);
43
+ };
44
+ const hold = async (executionId, point) => {
45
+ await Promise.race([pause(executionId, point), death]);
46
+ alive();
47
+ };
48
+ const keyOf = (ref) => ({ issuer: ref.issuer, commandId: ref.executionId });
49
+ const apply = (ref, event, actor) => ledger.apply({ key: keyOf(ref), generation: ref.generation, actor: { id: actor }, now: now(), event });
50
+ const stored = async (entry) => {
51
+ const progress = entry.progress;
52
+ if (progress.state === "settled") {
53
+ const stopped = progress.outcome.reason === "blocked" ? fromStopped(progress.outcome.value) : undefined;
54
+ return stopped ?? { kind: "settled", outcome: progress.outcome };
55
+ }
56
+ if (!("call" in progress))
57
+ throw new Error(`no stored prepare reply in state ${progress.state}`);
58
+ return { kind: "prepared", frozenDigest: progress.call.digest };
59
+ };
60
+ const settled = async (ref) => {
61
+ const entry = await ledger.read(keyOf(ref));
62
+ if (entry === undefined)
63
+ return { kind: "unknown_execution" };
64
+ if (entry.progress.state !== "settled")
65
+ throw new Error(`execution ${ref.executionId} is ${entry.progress.state}`);
66
+ return { kind: "settled", outcome: entry.progress.outcome };
67
+ };
68
+ const prepare = async (request) => {
69
+ const { issuer, executionId: commandId, generation, workspace, scope, requestDigest, call } = request;
70
+ const { admittedAt, leaseUntil } = request;
71
+ const admission = {
72
+ issuer,
73
+ commandId,
74
+ executor: id,
75
+ workspace,
76
+ scope,
77
+ generation,
78
+ requestDigest,
79
+ admittedAt,
80
+ leaseUntil,
81
+ };
82
+ const entry = expectEntry(await ledger.admit({ ...admission, reconcilable: false }), "admit");
83
+ if (entry.progress.state !== "admitted")
84
+ return stored(entry);
85
+ expectEntry(await apply(request, { kind: "prepare" }, id), "prepare");
86
+ expectEntry(await apply(request, { kind: "effect" }, id), "effect");
87
+ trace.push(`shim:${commandId}`);
88
+ trace.push(`hook:${commandId}`);
89
+ await hold(commandId, "hook");
90
+ const decision = BATCH_TOOLS[call.name];
91
+ if (decision !== undefined) {
92
+ const block = { kind: "block", value: { kind: decision, name: call.name } };
93
+ return stored(expectEntry(await apply(request, block, id), "block"));
94
+ }
95
+ const frozen = { ...call, digest: `${requestDigest}:frozen` };
96
+ const freeze = { kind: "freeze", call: frozen, awaitingConsent: false };
97
+ return stored(expectEntry(await apply(request, freeze, id), "freeze"));
98
+ };
99
+ const release = async (ref) => {
100
+ const entry = await ledger.read(keyOf(ref));
101
+ if (entry === undefined)
102
+ return { kind: "unknown_execution" };
103
+ if (entry.progress.state === "settled")
104
+ return settled(ref);
105
+ expectEntry(await apply(ref, { kind: "release" }, ref.issuer), "release");
106
+ await hold(ref.executionId, "dispatch");
107
+ const dispatched = expectEntry(await apply(ref, { kind: "dispatch" }, id), "dispatch");
108
+ if (dispatched.progress.state === "dispatched") {
109
+ trace.push(`body:${ref.executionId}`);
110
+ await hold(ref.executionId, "body");
111
+ const value = { executionId: ref.executionId, name: dispatched.progress.call.name };
112
+ trace.push(`done:${ref.executionId}`);
113
+ expectEntry(await apply(ref, { kind: "result", value }, id), "result");
114
+ }
115
+ return settled(ref);
116
+ };
117
+ const abort = async (ref) => {
118
+ if ((await ledger.read(keyOf(ref))) === undefined)
119
+ return { kind: "unknown_execution" };
120
+ const reply = await apply(ref, { kind: "abort" }, ref.issuer);
121
+ if (reply.status === "refused" && reply.reason !== "terminal")
122
+ throw new Error(`abort refused: ${reply.reason}`);
123
+ return settled(ref);
124
+ };
125
+ const once = (run) => {
126
+ const inflight = new Map();
127
+ return (input) => {
128
+ alive();
129
+ const key = JSON.stringify([input.issuer, input.executionId]);
130
+ const running = inflight.get(key);
131
+ if (running !== undefined)
132
+ return running;
133
+ const started = run(input).finally(() => inflight.delete(key));
134
+ inflight.set(key, started);
135
+ return started;
136
+ };
137
+ };
138
+ return { prepare: once(prepare), release: once(release), abort: once(abort) };
139
+ },
140
+ };
141
+ //# sourceMappingURL=batch-executor.js.map
@@ -0,0 +1,36 @@
1
+ import { type BatchCoordinator } from "../coordinator.ts";
2
+ import type { BatchPlan, CallOutcome } from "../coordinator-types.ts";
3
+ import type { BatchCaseAdapters, PausePoint } from "./batch-executor.ts";
4
+ /** A coordinator write named by its step and call: `manifest`, `prepare:a`, `decision`, `release:a`, `outcome:a`. */
5
+ export type BrainKill = {
6
+ readonly label: string;
7
+ readonly at: "before" | "after";
8
+ };
9
+ export declare class BrainKilledError extends Error {
10
+ constructor(label: string);
11
+ }
12
+ export type CallSpec = readonly [executionId: string, executor: string, name?: string, sequential?: "sequential"];
13
+ export declare function batchPlan(batchId: string, calls: readonly CallSpec[]): BatchPlan;
14
+ export declare const resultOf: (executionId: string, name?: string) => CallOutcome;
15
+ export type BatchHarness = Awaited<ReturnType<typeof batchHarness>>;
16
+ /** Two executors (`e1`, `e2`) and one brain, each on its own durable medium, with pausable steps and kill controls. */
17
+ export declare function batchHarness(adapters: BatchCaseAdapters): Promise<{
18
+ trace: string[];
19
+ count: (event: string) => number;
20
+ /** Resolves with every durable brain write so far, at the moment the brain's `label` write becomes durable. */
21
+ written: (label: string) => Promise<readonly string[]>;
22
+ /** Hold `executionId` at `point`: `reached` resolves when the step gets there, `open()` lets it continue. */
23
+ hold: (executionId: string, point: PausePoint) => {
24
+ reached: Promise<void>;
25
+ open: () => void;
26
+ };
27
+ /** A fresh brain process over the brain's durable medium, optionally dying around one of its writes. */
28
+ brain: (dieAt?: BrainKill) => Promise<BatchCoordinator>;
29
+ /** Kill the executor process and start a new one on the same durable medium. */
30
+ restartExecutor: (id: string) => Promise<void>;
31
+ /** Kill the executor and start it on a new, empty medium: every execution it held is lost. */
32
+ loseExecutor: (id: string) => Promise<void>;
33
+ ledgerState: (id: string, executionId: string) => Promise<string | undefined>;
34
+ }>;
35
+ export declare function expectRejects(operation: Promise<unknown>, type: new (...args: never[]) => Error, what: string): Promise<void>;
36
+ //# sourceMappingURL=batch-harness.d.ts.map
@@ -0,0 +1,208 @@
1
+ import { createAdmissionLine } from "../../durable/store-admission.js";
2
+ import { createBatchCoordinator } from "../coordinator.js";
3
+ const ADMITTED_AT = 100;
4
+ const NOW = ADMITTED_AT + 1;
5
+ export class BrainKilledError extends Error {
6
+ constructor(label) {
7
+ super(`brain killed around ${label}`);
8
+ this.name = "BrainKilledError";
9
+ }
10
+ }
11
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
12
+ function labelOf(writes) {
13
+ for (const write of writes) {
14
+ if (write.op !== "append" || write.kind !== "execution.batch")
15
+ continue;
16
+ const data = write.data;
17
+ if (!isObject(data))
18
+ return undefined;
19
+ return typeof data.executionId === "string" ? `${String(data.step)}:${data.executionId}` : String(data.step);
20
+ }
21
+ return undefined;
22
+ }
23
+ function withCommit(store, commit) {
24
+ return {
25
+ readEpoch: () => store.readEpoch(),
26
+ readHead: () => store.readHead(),
27
+ claim: (expected, next) => store.claim(expected, next),
28
+ commit,
29
+ mintId: () => store.mintId(),
30
+ scanRecords: (query) => store.scanRecords(query),
31
+ getDocument: (key) => store.getDocument(key),
32
+ scanDocuments: (prefix) => store.scanDocuments(prefix),
33
+ exportSnapshot: () => store.exportSnapshot(),
34
+ importSnapshot: (epoch, snapshot) => store.importSnapshot(epoch, snapshot),
35
+ };
36
+ }
37
+ /**
38
+ * The brain's store: `onDurable` sees the label of every durable write; with `kill`, the brain dies before that write
39
+ * (nothing of it durable) or after it is durable, and never writes again.
40
+ */
41
+ function brainStore(store, onDurable, kill) {
42
+ let dead = false;
43
+ return withCommit(store, async (epoch, writes, adopt) => {
44
+ const label = labelOf(writes) ?? "";
45
+ if (dead)
46
+ throw new BrainKilledError(label);
47
+ const hit = kill !== undefined && label === kill.label;
48
+ if (hit && kill.at === "before") {
49
+ dead = true;
50
+ throw new BrainKilledError(label);
51
+ }
52
+ const result = await store.commit(epoch, writes, adopt);
53
+ onDurable(label);
54
+ if (hit) {
55
+ dead = true;
56
+ throw new BrainKilledError(label);
57
+ }
58
+ return result;
59
+ });
60
+ }
61
+ function deadAfter(store, killed) {
62
+ return withCommit(store, (epoch, writes, adopt) => {
63
+ if (killed.aborted)
64
+ return Promise.reject(new Error("a killed executor cannot write"));
65
+ return store.commit(epoch, writes, adopt);
66
+ });
67
+ }
68
+ export function batchPlan(batchId, calls) {
69
+ return {
70
+ batchId,
71
+ scope: "scope",
72
+ workspace: "workspace",
73
+ generation: 1,
74
+ admittedAt: ADMITTED_AT,
75
+ leaseUntil: ADMITTED_AT + 60_000,
76
+ calls: calls.map(([executionId, executor, name = "read", sequential]) => ({
77
+ executionId,
78
+ executor,
79
+ name,
80
+ args: { executionId },
81
+ sequential: sequential === "sequential",
82
+ })),
83
+ };
84
+ }
85
+ export const resultOf = (executionId, name = "read") => ({
86
+ kind: "result",
87
+ value: { executionId, name },
88
+ });
89
+ /** Two executors (`e1`, `e2`) and one brain, each on its own durable medium, with pausable steps and kill controls. */
90
+ export async function batchHarness(adapters) {
91
+ const trace = [];
92
+ const gates = new Map();
93
+ const gate = (key) => {
94
+ let found = gates.get(key);
95
+ if (found === undefined) {
96
+ found = { reached: Promise.withResolvers() };
97
+ gates.set(key, found);
98
+ }
99
+ return found;
100
+ };
101
+ const pause = async (executionId, point) => {
102
+ const found = gate(`${executionId}/${point}`);
103
+ found.reached.resolve();
104
+ if (found.open !== undefined)
105
+ await found.open.promise;
106
+ };
107
+ const claimed = async () => {
108
+ const medium = await adapters.store.createMedium();
109
+ await (await adapters.store.open(medium)).claim(0, 1);
110
+ return medium;
111
+ };
112
+ const executors = new Map();
113
+ const start = async (id, medium) => {
114
+ const killed = new AbortController();
115
+ const store = deadAfter(await adapters.store.open(medium), killed.signal);
116
+ const endpoint = await adapters.executor.open({
117
+ id,
118
+ store,
119
+ epoch: 1,
120
+ now: () => NOW,
121
+ trace,
122
+ pause,
123
+ killed: killed.signal,
124
+ });
125
+ executors.set(id, { medium, killed, endpoint });
126
+ };
127
+ const current = (id) => {
128
+ const found = executors.get(id);
129
+ if (found === undefined)
130
+ throw new Error(`no executor ${id}`);
131
+ return found.endpoint;
132
+ };
133
+ const proxy = (id) => ({
134
+ prepare: (request) => current(id).prepare(request),
135
+ release: (ref) => current(id).release(ref),
136
+ abort: (ref) => current(id).abort(ref),
137
+ });
138
+ const kill = (id) => {
139
+ const found = executors.get(id);
140
+ if (found === undefined)
141
+ throw new Error(`no executor ${id}`);
142
+ found.killed.abort();
143
+ return found.medium;
144
+ };
145
+ for (const id of ["e1", "e2"])
146
+ await start(id, await claimed());
147
+ const brainMedium = await claimed();
148
+ const brainWrites = [];
149
+ const writeWaiters = new Map();
150
+ const onDurable = (label) => {
151
+ brainWrites.push(label);
152
+ writeWaiters.get(label)?.resolve([...brainWrites]);
153
+ };
154
+ return {
155
+ trace,
156
+ count: (event) => trace.filter((entry) => entry === event).length,
157
+ /** Resolves with every durable brain write so far, at the moment the brain's `label` write becomes durable. */
158
+ written: (label) => {
159
+ const waiter = Promise.withResolvers();
160
+ writeWaiters.set(label, waiter);
161
+ return waiter.promise;
162
+ },
163
+ /** Hold `executionId` at `point`: `reached` resolves when the step gets there, `open()` lets it continue. */
164
+ hold: (executionId, point) => {
165
+ const found = gate(`${executionId}/${point}`);
166
+ const open = Promise.withResolvers();
167
+ found.open = open;
168
+ return { reached: found.reached.promise, open: () => open.resolve() };
169
+ },
170
+ /** A fresh brain process over the brain's durable medium, optionally dying around one of its writes. */
171
+ brain: async (dieAt) => {
172
+ const opened = await adapters.store.open(brainMedium);
173
+ return createBatchCoordinator({
174
+ issuer: "brain",
175
+ store: brainStore(opened, onDurable, dieAt),
176
+ epoch: 1,
177
+ admission: createAdmissionLine(),
178
+ executor: proxy,
179
+ });
180
+ },
181
+ /** Kill the executor process and start a new one on the same durable medium. */
182
+ restartExecutor: async (id) => start(id, kill(id)),
183
+ /** Kill the executor and start it on a new, empty medium: every execution it held is lost. */
184
+ loseExecutor: async (id) => {
185
+ kill(id);
186
+ await start(id, await claimed());
187
+ },
188
+ ledgerState: async (id, executionId) => {
189
+ const store = await adapters.store.open(executors.get(id)?.medium ?? "");
190
+ const row = await store.getDocument(`execution.ledger:${JSON.stringify(["brain", executionId])}`);
191
+ if (!isObject(row) || !isObject(row.progress))
192
+ return undefined;
193
+ return String(row.progress.state);
194
+ },
195
+ };
196
+ }
197
+ export async function expectRejects(operation, type, what) {
198
+ try {
199
+ await operation;
200
+ }
201
+ catch (error) {
202
+ if (error instanceof type)
203
+ return;
204
+ throw new Error(`${what}: expected ${type.name}, got ${String(error)}`);
205
+ }
206
+ throw new Error(`${what}: expected ${type.name}, but it resolved`);
207
+ }
208
+ //# sourceMappingURL=batch-harness.js.map
@@ -0,0 +1,3 @@
1
+ import type { RegisteredCase } from "../../conformance/registry.ts";
2
+ export declare const BATCH_REGISTRY: readonly RegisteredCase[];
3
+ //# sourceMappingURL=batch-registry.d.ts.map
@@ -0,0 +1,30 @@
1
+ import { KILL_BATCH_DECLARATIONS } from "./kill-batch.js";
2
+ const BATCH_CASES_IMPL = "packages/agent/src/execution/testing/batch-cases.ts";
3
+ const INTRO = "#5416";
4
+ const batchCase = (id, expected) => ({
5
+ id,
6
+ impl: BATCH_CASES_IMPL,
7
+ intro: INTRO,
8
+ adapters: ["store", "executor"],
9
+ expected,
10
+ });
11
+ export const BATCH_REGISTRY = [
12
+ batchCase("BATCH-01", "the brain crashes after the manifest: the same execution ids are re-prepared; nothing had run"),
13
+ batchCase("BATCH-02", "the brain crashes after the prepares: prepare is re-sent, stored replies return, hooks never rerun"),
14
+ batchCase("BATCH-03", "the brain crashes inside a released wave: released calls get a re-sent release, unmarked ready calls are released, the next wave waits"),
15
+ batchCase("BATCH-05", "an executor restart keeps prepared and released calls, and release proceeds"),
16
+ batchCase("BATCH-06", "a lost prepared execution answers unknown_execution and is uncertain; siblings settle"),
17
+ batchCase("BATCH-07", "prepare runs in source order across executors; each release waits for its dependencies' final outcomes"),
18
+ batchCase("BATCH-08", "a batch_abort reply ABORTs the batch: no later prepare, no body, abort re-sent on recovery"),
19
+ batchCase("BATCH-09", "a blocked call is a per-call result; the other calls are released"),
20
+ batchCase("REPLAY-01", "an executor restart during preparation replays like today (X12): placeholder result, never rerun, a reissued call runs once"),
21
+ batchCase("REPLAY-02", "the same beside a prepared sibling: the sibling is aborted unrun, both replay with the placeholder"),
22
+ ...KILL_BATCH_DECLARATIONS.map(({ id, scenario, kill }) => ({
23
+ id,
24
+ impl: "packages/agent/src/execution/testing/kill-batch.ts",
25
+ intro: INTRO,
26
+ adapters: ["store", "executor"],
27
+ expected: `everywhere: kill the brain ${kill.at} its ${kill.label} write (${scenario}); recovery reaches the uncrashed outcomes with stable ids, each step run once`,
28
+ })),
29
+ ];
30
+ //# sourceMappingURL=batch-registry.js.map
@@ -0,0 +1,6 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import { type HandCaseAdapters } from "./hand-harness.ts";
3
+ type HandCase = CaseImplementation<HandCaseAdapters>;
4
+ export declare const FAULT_HAND_CASES: ReadonlyMap<string, HandCase>;
5
+ export {};
6
+ //# sourceMappingURL=fault-hand-cases.d.ts.map
@@ -0,0 +1,70 @@
1
+ import { expectEqual } from "../../durable/testing/store-harness.js";
2
+ import { createCarrierFault, FAULT_PROFILE_NAMES, } from "../../transport/testing/fault-transport.js";
3
+ import { call, openHandRig } from "./hand-harness.js";
4
+ const SCOPES = ["a", "b"];
5
+ const CALLS = 12;
6
+ /** The sends span 360 ms, past the flap profile's second drop (260 ms), so every profile acts while calls are live. */
7
+ const PACE_MS = 30;
8
+ const ids = (scope) => Array.from({ length: CALLS }, (_, index) => `${scope}${index + 1}`);
9
+ const texts = (messages) => messages.map((message) => message.content.map((part) => (part.type === "text" ? part.text : "")).join(""));
10
+ const acted = {
11
+ slow: (stats) => stats.refused > 0,
12
+ lossy: (stats) => stats.lost > 0,
13
+ laggy: (stats) => stats.reordered > 0,
14
+ flap: (stats) => stats.drops >= 2,
15
+ "drop-reattach": (stats) => stats.drops >= 2,
16
+ };
17
+ /**
18
+ * Calls of two scopes sent one by one across the faulted link: every call settles with exactly the result an unfaulted
19
+ * run gives, each body runs once, and each scope's calls start in their lane order.
20
+ */
21
+ const underProfile = (name) => async (adapters) => {
22
+ const stats = { refused: 0, lost: 0, reordered: 0, drops: 0 };
23
+ const rig = await openHandRig(adapters, { placement: "cross-machine", fault: createCarrierFault(name, stats) });
24
+ const what = `FAULT-HAND ${name}`;
25
+ const batches = [];
26
+ for (let index = 0; index < CALLS; index++) {
27
+ for (const scope of SCOPES)
28
+ batches.push(rig.execute(scope, [call(ids(scope)[index] ?? "")], "sequential"));
29
+ await rig.advance(PACE_MS);
30
+ }
31
+ const results = await rig.settle(Promise.all(batches), `${what}: every call settled`);
32
+ expectEqual(results.flatMap(({ messages }) => texts(messages)).sort(), SCOPES.flatMap((scope) => ids(scope).map((id) => `ran:${id}`)).sort(), `${what}: results equal the unfaulted run`);
33
+ for (const scope of SCOPES)
34
+ expectEqual(rig.bodies.filter((body) => body.startsWith(`${scope}:`)), ids(scope).map((id) => `${scope}:${id}`), `${what}: scope ${scope} ran each call once, in lane order`);
35
+ expectEqual(rig.faults, [], `${what}: the hand reported no fault`);
36
+ if (!acted[name](stats))
37
+ throw new Error(`${what}: the profile never acted (${JSON.stringify(stats)})`);
38
+ };
39
+ /**
40
+ * The hand becomes unreachable for far longer than the transport's resume window while several sessions' calls run on
41
+ * it: every dependent call pauses (no outcome is invented and nothing reruns), and after the hand is reachable again each
42
+ * scope's call settles exactly once with its own result.
43
+ */
44
+ const unreachableThenBack = async (adapters) => {
45
+ const rig = await openHandRig(adapters, { placement: "cross-machine" });
46
+ rig.gateBodies();
47
+ const settledScopes = new Set();
48
+ const batches = SCOPES.map((scope) => {
49
+ const batch = rig.execute(scope, [call(`${scope}1`)]);
50
+ void batch.then(() => settledScopes.add(scope));
51
+ return batch;
52
+ });
53
+ await rig.runUntil(() => rig.bodies.length === SCOPES.length, "FAULT-HAND-MULTI-01: every scope's call is running");
54
+ rig.disconnect();
55
+ for (const scope of SCOPES)
56
+ rig.release(`${scope}1`);
57
+ await rig.advance(60_000);
58
+ expectEqual([...settledScopes], [], "FAULT-HAND-MULTI-01: dependent calls pause while the hand is unreachable");
59
+ rig.reconnect();
60
+ const results = await rig.settle(Promise.all(batches), "FAULT-HAND-MULTI-01: every scope resumed after reconnect");
61
+ expectEqual(results.map(({ messages }) => texts(messages)), SCOPES.map((scope) => [`ran:${scope}1`]), "FAULT-HAND-MULTI-01: each scope settled with its own result");
62
+ await rig.advance(5_000);
63
+ expectEqual(rig.bodies, SCOPES.map((scope) => `${scope}:${scope}1`), "FAULT-HAND-MULTI-01: resumed once: no body ran twice");
64
+ expectEqual(rig.faults, [], "FAULT-HAND-MULTI-01: the hand reported no fault");
65
+ };
66
+ export const FAULT_HAND_CASES = new Map([
67
+ ...FAULT_PROFILE_NAMES.map((name, index) => [`FAULT-HAND-0${index + 1}`, underProfile(name)]),
68
+ ["FAULT-HAND-MULTI-01", unreachableThenBack],
69
+ ]);
70
+ //# sourceMappingURL=fault-hand-cases.js.map
@@ -0,0 +1,48 @@
1
+ import type { AgentToolCall, ToolExecutionMode } from "../../types.ts";
2
+ import { type ManualTimers } from "../../durable/testing/manual-timers.ts";
3
+ import type { StoreCaseAdapters } from "../../durable/testing/store-harness.ts";
4
+ import type { CarrierFault, TransportCaseAdapters } from "../../transport/testing/transport-harness.ts";
5
+ import type { ExecutionEntry } from "../ledger-types.ts";
6
+ import { type HandPlacement } from "../remote-tool-host.ts";
7
+ import type { ToolHostResult } from "../tool-host.ts";
8
+ /** What the KILL-HAND, MULTI-HAND and FAULT-HAND cases need from a host: a durable store and a transport. */
9
+ export type HandCaseAdapters = StoreCaseAdapters & TransportCaseAdapters;
10
+ /** Kill the hand at the `commit`-th ledger commit (0-based), before it or once it is durable. */
11
+ export interface KillPoint {
12
+ readonly commit: number;
13
+ readonly at: "before" | "durable";
14
+ }
15
+ export interface HandRig {
16
+ /** Every tool body start, as `<scope>:<toolCallId>`, across all hand processes. */
17
+ readonly bodies: readonly string[];
18
+ /** Faults the hand processes reported (a killed hand reports the kill). */
19
+ readonly faults: readonly unknown[];
20
+ readonly killed: Promise<void>;
21
+ execute(scope: string, calls: readonly AgentToolCall[], mode?: ToolExecutionMode): Promise<ToolHostResult>;
22
+ /** A new hand process on the reopened store and the same link; resolves once it announced itself. */
23
+ restart(): Promise<void>;
24
+ /** Hold every body until `release(toolCallId)`. */
25
+ gateBodies(): void;
26
+ release(toolCallId: string): void;
27
+ /**
28
+ * Lets `ms` of transport time pass in small steps, running the work each due timer starts before the next step, so a
29
+ * check made afterwards sees everything that time could have produced. Cases wait only through this, `settle` and
30
+ * `runUntil`: a bare timer advance fires timers without letting the hand's settle chain run, and an assertion that
31
+ * nothing happened would then pass whether or not the case's precondition held.
32
+ */
33
+ advance(ms: number): Promise<void>;
34
+ /** Advances transport time until `promise` settles; fails past the budget. */
35
+ settle<T>(promise: Promise<T>, what: string, budgetMs?: number): Promise<T>;
36
+ runUntil(done: () => boolean, what: string, budgetMs?: number): Promise<void>;
37
+ /** Drops the carrier between session and hand (the hand becomes unreachable) and attaches it again. */
38
+ disconnect(): void;
39
+ reconnect(): void;
40
+ rows(): Promise<ExecutionEntry[]>;
41
+ }
42
+ export declare function call(id: string): AgentToolCall;
43
+ export declare function openHandRig(adapters: HandCaseAdapters, options: {
44
+ readonly placement: HandPlacement;
45
+ readonly killAt?: KillPoint;
46
+ readonly fault?: (timers: ManualTimers) => CarrierFault;
47
+ }): Promise<HandRig>;
48
+ //# sourceMappingURL=hand-harness.d.ts.map