@code-yeongyu/senpi-agent-core 2026.11.4-2 → 2026.11.6-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/agent-loop.js +14 -140
  2. package/dist/agent.d.ts +4 -0
  3. package/dist/agent.js +4 -0
  4. package/dist/conformance/index.d.ts +12 -1
  5. package/dist/conformance/index.js +6 -0
  6. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  7. package/dist/conformance/loop-core-manifest.js +18 -0
  8. package/dist/conformance/registry.js +11 -17
  9. package/dist/durable/session-store.d.ts +42 -0
  10. package/dist/durable/session-store.js +124 -0
  11. package/dist/durable/store-memory.d.ts +2 -2
  12. package/dist/durable/store-memory.js +36 -34
  13. package/dist/durable/store.d.ts +9 -0
  14. package/dist/durable/testing/store-harness.d.ts +1 -0
  15. package/dist/durable/testing/store-harness.js +1 -0
  16. package/dist/durable/testing/sync-commit-cases.d.ts +20 -0
  17. package/dist/durable/testing/sync-commit-cases.js +89 -0
  18. package/dist/egress/types.d.ts +102 -0
  19. package/dist/egress/types.js +7 -0
  20. package/dist/execution/canonical-digest.d.ts +10 -0
  21. package/dist/execution/canonical-digest.js +20 -0
  22. package/dist/execution/chain-count.d.ts +26 -0
  23. package/dist/execution/chain-count.js +45 -0
  24. package/dist/execution/coordinator-plan.d.ts +1 -2
  25. package/dist/execution/coordinator-plan.js +4 -17
  26. package/dist/execution/device-files-node.js +40 -1
  27. package/dist/execution/device-files.d.ts +39 -1
  28. package/dist/execution/device-files.js +48 -1
  29. package/dist/execution/ledger-types.d.ts +3 -1
  30. package/dist/execution/ledger.d.ts +9 -3
  31. package/dist/execution/ledger.js +8 -2
  32. package/dist/execution/loop-hook-host-hand.d.ts +33 -0
  33. package/dist/execution/loop-hook-host-hand.js +71 -0
  34. package/dist/execution/loop-hook-host-protocol.d.ts +46 -0
  35. package/dist/execution/loop-hook-host-protocol.js +47 -0
  36. package/dist/execution/loop-hook-host.d.ts +40 -0
  37. package/dist/execution/loop-hook-host.js +87 -0
  38. package/dist/execution/plane-session.d.ts +56 -0
  39. package/dist/execution/plane-session.js +178 -0
  40. package/dist/execution/plane.d.ts +5 -2
  41. package/dist/execution/plane.js +1 -1
  42. package/dist/execution/prepared/executor-body.d.ts +22 -0
  43. package/dist/execution/prepared/executor-body.js +73 -0
  44. package/dist/execution/prepared/executor-freeze.d.ts +22 -0
  45. package/dist/execution/prepared/executor-freeze.js +55 -0
  46. package/dist/execution/prepared/executor-pipeline.d.ts +11 -0
  47. package/dist/execution/prepared/executor-pipeline.js +26 -0
  48. package/dist/execution/prepared/executor-types.d.ts +131 -0
  49. package/dist/execution/prepared/executor-types.js +2 -0
  50. package/dist/execution/prepared/executor.d.ts +8 -0
  51. package/dist/execution/prepared/executor.js +260 -0
  52. package/dist/execution/prepared/memory-batch-store.d.ts +4 -0
  53. package/dist/execution/prepared/memory-batch-store.js +4 -0
  54. package/dist/execution/prepared/pipeline-prepared-batch.d.ts +27 -0
  55. package/dist/execution/prepared/pipeline-prepared-batch.js +175 -0
  56. package/dist/execution/prepared/pipeline-prepared.d.ts +10 -0
  57. package/dist/execution/prepared/pipeline-prepared.js +54 -0
  58. package/dist/execution/remote-device-files.js +33 -4
  59. package/dist/execution/remote-epoch-gate.d.ts +19 -0
  60. package/dist/execution/remote-epoch-gate.js +46 -0
  61. package/dist/execution/remote-epoch.d.ts +53 -0
  62. package/dist/execution/remote-epoch.js +74 -0
  63. package/dist/execution/remote-executor.d.ts +8 -1
  64. package/dist/execution/remote-executor.js +24 -6
  65. package/dist/execution/remote-file-call.js +1 -0
  66. package/dist/execution/remote-hand-ledger.d.ts +11 -3
  67. package/dist/execution/remote-hand-ledger.js +31 -15
  68. package/dist/execution/remote-link.d.ts +6 -1
  69. package/dist/execution/remote-link.js +50 -14
  70. package/dist/execution/remote-protocol.d.ts +30 -1
  71. package/dist/execution/remote-protocol.js +30 -0
  72. package/dist/execution/remote-tool-host.d.ts +12 -0
  73. package/dist/execution/remote-tool-host.js +3 -1
  74. package/dist/execution/testing/epoch-cases.d.ts +8 -0
  75. package/dist/execution/testing/epoch-cases.js +84 -0
  76. package/dist/execution/testing/epoch-harness.d.ts +47 -0
  77. package/dist/execution/testing/epoch-harness.js +172 -0
  78. package/dist/execution/testing/epoch-registry.d.ts +3 -0
  79. package/dist/execution/testing/epoch-registry.js +17 -0
  80. package/dist/execution/testing/hand-harness.d.ts +5 -0
  81. package/dist/execution/testing/hand-harness.js +57 -24
  82. package/dist/execution/testing/hand-registry.d.ts +3 -0
  83. package/dist/execution/testing/hand-registry.js +20 -0
  84. package/dist/execution/testing/kill-epoch.d.ts +9 -0
  85. package/dist/execution/testing/kill-epoch.js +71 -0
  86. package/dist/execution/testing/kill-hook.d.ts +14 -0
  87. package/dist/execution/testing/kill-hook.js +117 -0
  88. package/dist/execution/testing/multi-epoch-cases.d.ts +4 -0
  89. package/dist/execution/testing/multi-epoch-cases.js +29 -0
  90. package/dist/execution/testing/multi-hand-cases.js +1 -1
  91. package/dist/execution/tool-host.d.ts +16 -1
  92. package/dist/execution/tool-host.js +18 -1
  93. package/dist/harness/agent-harness.d.ts +6 -0
  94. package/dist/harness/execution/tool-host-call.d.ts +14 -0
  95. package/dist/harness/execution/tool-host-call.js +56 -0
  96. package/dist/harness/execution/tools.d.ts +2 -1
  97. package/dist/harness/execution/tools.js +45 -17
  98. package/dist/harness/runtime/drive/tools.js +1 -1
  99. package/dist/harness/runtime/harness.js +1 -0
  100. package/dist/harness/runtime/types.d.ts +1 -0
  101. package/dist/harness/tools/read.js +1 -1
  102. package/dist/index.d.ts +19 -2
  103. package/dist/index.js +15 -1
  104. package/dist/public-entry.d.ts +10 -0
  105. package/dist/public-entry.js +23 -0
  106. package/dist/step-commit.d.ts +24 -0
  107. package/dist/step-commit.js +24 -0
  108. package/dist/tool-name-alias.d.ts +1 -7
  109. package/dist/tool-name-alias.js +0 -17
  110. package/dist/types.d.ts +37 -1
  111. package/package.json +3 -3
@@ -0,0 +1,172 @@
1
+ import { createAdmissionLine } from "../../durable/store-admission.js";
2
+ import { createManualTimers } from "../../durable/testing/manual-timers.js";
3
+ import { claimedStore } from "../../durable/testing/store-cases.js";
4
+ import { createInProcessNetwork } from "../../transport/in-process-carrier.js";
5
+ import { localEndpoint } from "../../transport/local-endpoint.js";
6
+ import { createGrantVerifier } from "../grant-verify.js";
7
+ import { createExecutionLedger } from "../ledger.js";
8
+ import { createHandEpochFence, EPOCH_FLOOR_PREFIX } from "../remote-epoch.js";
9
+ import { createRemoteExecutor } from "../remote-executor.js";
10
+ import { createHandLedger } from "../remote-hand-ledger.js";
11
+ import { createRemoteToolHost } from "../remote-tool-host.js";
12
+ import { transportPump } from "./hand-harness.js";
13
+ const LEASE_MS = 3_600_000;
14
+ const HAND = "hand";
15
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16
+ const field = (write, name) => {
17
+ const data = write.op === "delete" ? undefined : write.data;
18
+ return isRecord(data) ? data[name] : undefined;
19
+ };
20
+ export const floorCommit = (scope, epoch) => (writes) => writes.some((write) => write.op === "put" && write.key === `${EPOCH_FLOOR_PREFIX}${scope}` && field(write, "epoch") === epoch);
21
+ /** The ledger commit of `event` for a call `brain` sent (execution IDs are minted as `<brain>-<n>`). */
22
+ export const stepCommit = (brain, event) => (writes) => writes.some((write) => write.op === "append" &&
23
+ field(write, "event") === event &&
24
+ String(field(write, "commandId")).startsWith(`${brain}-`));
25
+ /** A hand process's store: holds and kills act on whole commits; after a kill every call fails, as in a dead process. */
26
+ function processStore(inner, holds, kill) {
27
+ let dead = false;
28
+ const alive = () => {
29
+ if (dead)
30
+ throw new Error("the hand was killed");
31
+ };
32
+ const die = (at) => {
33
+ dead = true;
34
+ kill?.die();
35
+ throw new Error(`hand killed ${at} the matched commit`);
36
+ };
37
+ let killArmed = kill !== undefined;
38
+ const live = (read) => async (...args) => {
39
+ alive();
40
+ return read(...args);
41
+ };
42
+ return {
43
+ readEpoch: live(() => inner.readEpoch()),
44
+ readHead: live(() => inner.readHead()),
45
+ claim: live((expected, next) => inner.claim(expected, next)),
46
+ mintId: () => inner.mintId(),
47
+ scanRecords: live((query) => inner.scanRecords(query)),
48
+ getDocument: live((key) => inner.getDocument(key)),
49
+ scanDocuments: live((prefix) => inner.scanDocuments(prefix)),
50
+ exportSnapshot: live(() => inner.exportSnapshot()),
51
+ importSnapshot: live((epoch, snapshot) => inner.importSnapshot(epoch, snapshot)),
52
+ async commit(epoch, writes, adopt) {
53
+ alive();
54
+ const index = holds.findIndex((hold) => hold.match(writes));
55
+ const hold = index < 0 ? undefined : holds.splice(index, 1)[0];
56
+ if (hold !== undefined) {
57
+ hold.reached.resolve();
58
+ await hold.gate.promise;
59
+ alive();
60
+ }
61
+ const killing = killArmed && kill !== undefined && kill.match(writes);
62
+ if (!killing)
63
+ return inner.commit(epoch, writes, adopt);
64
+ killArmed = false;
65
+ if (kill.at === "before")
66
+ return die("before");
67
+ await inner.commit(epoch, writes, () => { });
68
+ return die("once durable");
69
+ },
70
+ };
71
+ }
72
+ /**
73
+ * One hand process reached by several brains, each over its own link with its own executor (a peer link per brain),
74
+ * sharing the hand's store, ledger and epoch fence: what a session sees when it moves from one brain to another.
75
+ */
76
+ export async function openEpochRig(adapters, options) {
77
+ const timers = createManualTimers(1_000);
78
+ const pump = transportPump(timers);
79
+ const network = createInProcessNetwork({ schedule: (deliver) => void timers.setTimer(deliver, 0) });
80
+ const verifier = createGrantVerifier({ self: HAND, workspaces: [{ root: "/work" }], canonicalize: (path) => path });
81
+ verifier.install({
82
+ rv: 1,
83
+ expiresAt: Number.MAX_SAFE_INTEGER,
84
+ grants: options.brains.map(({ name }) => ({
85
+ holder: name,
86
+ target: HAND,
87
+ workspace: "omo",
88
+ capability: "execute",
89
+ })),
90
+ });
91
+ const handSides = new Map();
92
+ const hosts = new Map();
93
+ for (const { name, epoch } of options.brains) {
94
+ const sessionSide = adapters.transport.createSide(timers);
95
+ const handSide = adapters.transport.createSide(timers);
96
+ const endpoint = localEndpoint(adapters.platform, `epoch-${name}`, "/run/senpi-conformance");
97
+ network.listen(endpoint, handSide);
98
+ network.dial(endpoint, sessionSide).connect();
99
+ handSides.set(name, handSide);
100
+ let minted = 0;
101
+ const placement = options.placement ?? "cross-machine";
102
+ hosts.set(name, createRemoteToolHost({ transport: sessionSide, placement, epoch, mintId: () => `${name}-${minted++}` }));
103
+ }
104
+ const { medium } = await claimedStore(adapters.store);
105
+ const owners = new Map();
106
+ const bodies = [];
107
+ const faults = [];
108
+ const holds = [];
109
+ const killed = Promise.withResolvers();
110
+ const startHand = async (store) => {
111
+ const admission = createAdmissionLine();
112
+ const ledger = createExecutionLedger({ store, epoch: 1, admission });
113
+ const hand = createHandLedger({
114
+ ledger,
115
+ executor: HAND,
116
+ issuer: "session",
117
+ workspace: "workspace",
118
+ now: timers.now,
119
+ leaseMs: LEASE_MS,
120
+ });
121
+ const fence = createHandEpochFence({
122
+ ownerOf: (scope) => owners.get(scope),
123
+ durable: { store, epoch: 1, admission },
124
+ });
125
+ const executors = options.brains.map(({ name }) => {
126
+ const transport = handSides.get(name);
127
+ if (transport === undefined)
128
+ throw new Error(`no link for ${name}`);
129
+ return createRemoteExecutor({
130
+ authority: { kind: "peer", peer: name, verifier },
131
+ transport,
132
+ ledger: hand,
133
+ fence,
134
+ openScope: async (scope) => ({
135
+ run: async (handCall) => {
136
+ bodies.push(`${scope.id}:${handCall.toolCallId}`);
137
+ return { content: [{ type: "text", text: `ran:${handCall.toolCallId}` }], details: {} };
138
+ },
139
+ isSequential: () => false,
140
+ dispose: async () => { },
141
+ }),
142
+ onFault: (error) => faults.push(error),
143
+ });
144
+ });
145
+ await pump.settle(Promise.all(executors.map(({ ready }) => ready)), "every link's executor is ready");
146
+ };
147
+ const kill = options.kill === undefined ? undefined : { ...options.kill, die: () => killed.resolve() };
148
+ await startHand(processStore(await adapters.store.open(medium), holds, kill));
149
+ const reader = async () => adapters.store.open(medium);
150
+ return {
151
+ ...pump,
152
+ bodies,
153
+ faults,
154
+ killed: killed.promise,
155
+ execute(brain, scope, calls) {
156
+ const host = hosts.get(brain);
157
+ if (host === undefined)
158
+ throw new Error(`no brain ${brain}`);
159
+ return host.execute({ scope: { id: scope, root: `/work/${scope}` }, calls, mode: "parallel" }, { emit: () => { } });
160
+ },
161
+ setOwner: (scope, brain) => void owners.set(scope, brain),
162
+ hold(match) {
163
+ const hold = { match, reached: Promise.withResolvers(), gate: Promise.withResolvers() };
164
+ holds.push(hold);
165
+ return { reached: hold.reached.promise, release: () => hold.gate.resolve() };
166
+ },
167
+ restart: async () => startHand(processStore(await reader(), holds, undefined)),
168
+ rows: async () => createExecutionLedger({ store: await reader(), epoch: 1, admission: createAdmissionLine() }).scan(),
169
+ floor: async (scope) => (await reader()).getDocument(`${EPOCH_FLOOR_PREFIX}${scope}`),
170
+ };
171
+ }
172
+ //# sourceMappingURL=epoch-harness.js.map
@@ -0,0 +1,3 @@
1
+ import type { RegisteredCase } from "../../conformance/registry.ts";
2
+ export declare const EPOCH_REGISTRY: readonly RegisteredCase[];
3
+ //# sourceMappingURL=epoch-registry.d.ts.map
@@ -0,0 +1,17 @@
1
+ import { KILL_EPOCH_DECLARATIONS } from "./kill-epoch.js";
2
+ const epochCase = (id, impl, expected) => ({
3
+ id,
4
+ impl,
5
+ intro: "#5729",
6
+ adapters: ["store", "transport", "executor"],
7
+ expected,
8
+ });
9
+ const EPOCH_IMPL = "packages/agent/src/execution/testing/epoch-cases.ts";
10
+ export const EPOCH_REGISTRY = [
11
+ epochCase("EPOCH-01", EPOCH_IMPL, "a barrier holding the floor ACK while the new owner dispatches: 0 effects, then once"),
12
+ epochCase("EPOCH-02", EPOCH_IMPL, "two concurrent CAS claims: exactly one owner; only its calls run"),
13
+ epochCase("EPOCH-03", EPOCH_IMPL, "an old owner's delayed prepare, release or invoke after the new owner's first call is refused"),
14
+ epochCase("MULTI-EPOCH-01", "packages/agent/src/execution/testing/multi-epoch-cases.ts", "one session's epoch bump leaves the other sessions' scopes on the hand untouched"),
15
+ ...KILL_EPOCH_DECLARATIONS.map(({ id, expected }) => epochCase(id, "packages/agent/src/execution/testing/kill-epoch.ts", expected)),
16
+ ];
17
+ //# sourceMappingURL=epoch-registry.js.map
@@ -34,12 +34,17 @@ export interface HandRig {
34
34
  /** Advances transport time until `promise` settles; fails past the budget. */
35
35
  settle<T>(promise: Promise<T>, what: string, budgetMs?: number): Promise<T>;
36
36
  runUntil(done: () => boolean, what: string, budgetMs?: number): Promise<void>;
37
+ /** As `runUntil`, for a condition that needs an asynchronous read (the hand's durable rows). */
38
+ waitFor(done: () => Promise<boolean>, what: string, budgetMs?: number): Promise<void>;
37
39
  /** Drops the carrier between session and hand (the hand becomes unreachable) and attaches it again. */
38
40
  disconnect(): void;
39
41
  reconnect(): void;
40
42
  rows(): Promise<ExecutionEntry[]>;
41
43
  }
42
44
  export declare function call(id: string): AgentToolCall;
45
+ export type TransportPump = Pick<HandRig, "advance" | "settle" | "runUntil" | "waitFor">;
46
+ /** Steps transport time on `timers` the way every hand rig waits (see {@link HandRig.advance}). */
47
+ export declare function transportPump(timers: ManualTimers): TransportPump;
43
48
  export declare function openHandRig(adapters: HandCaseAdapters, options: {
44
49
  readonly placement: HandPlacement;
45
50
  readonly killAt?: KillPoint;
@@ -9,13 +9,65 @@ import { createHandLedger } from "../remote-hand-ledger.js";
9
9
  import { createRemoteToolHost } from "../remote-tool-host.js";
10
10
  const TICK_MS = 5;
11
11
  const LEASE_MS = 3_600_000;
12
+ // A store may confirm a write only after I/O (a Durable Object commit awaits `storage.sync()`; the async-store
13
+ // conformance run takes three `setTimeout(0)` hops per write), and microtasks alone never let that write land
14
+ // between two clock steps. One event-loop turn per step is not enough either: a write that needs several hops
15
+ // lands one hop per 5 ms tick while a fault profile's own timers keep re-arming ahead of it, and `settle` burns
16
+ // its whole transport budget (senpi#6114). A step therefore takes a fixed number of event-loop turns. The count
17
+ // is measured, not derived (an immediate turn and a timer hop are not one-to-one): on the FAULT-HAND cases over
18
+ // the async store, 2 turns per step still fails, 4 passes every run, and 8 is 4 with the same margin again.
19
+ // `setImmediate` is the turn: each one runs after the loop's timers and I/O phases, so a pending `setTimeout(0)`
20
+ // hop lands between two of them, and it costs microseconds where `setTimeout(0)` costs its 1 ms clamp, which over
21
+ // the 120,000 ticks of a 600 s transport budget is the difference between a 0.3 s and a 150 s case. Where the
22
+ // host has no `setImmediate`, each turn is a timer turn. An adapter whose write takes more hops than this must
23
+ // raise the count here; the rig cannot observe a quiet loop from inside it.
24
+ const IO_TURNS_PER_STEP = 8;
25
+ const ioTurn = () => new Promise((resolve) => typeof setImmediate === "function" ? void setImmediate(resolve) : void setTimeout(resolve, 0));
12
26
  const drain = async () => {
13
- for (let turn = 0; turn < 32; turn++)
14
- await Promise.resolve();
27
+ for (let io = 0; io < IO_TURNS_PER_STEP; io++) {
28
+ await ioTurn();
29
+ for (let turn = 0; turn < 32; turn++)
30
+ await Promise.resolve();
31
+ }
15
32
  };
16
33
  export function call(id) {
17
34
  return { type: "toolCall", id, name: "probe", arguments: { id } };
18
35
  }
36
+ /** Steps transport time on `timers` the way every hand rig waits (see {@link HandRig.advance}). */
37
+ export function transportPump(timers) {
38
+ const pump = async (stop, ms) => {
39
+ const end = timers.now() + ms;
40
+ await drain();
41
+ while (!stop() && timers.now() < end) {
42
+ await timers.advanceTo(Math.min(end, timers.now() + TICK_MS));
43
+ await drain();
44
+ }
45
+ };
46
+ const runUntil = async (done, what, budgetMs = 600_000) => {
47
+ await pump(done, budgetMs);
48
+ if (!done())
49
+ throw new Error(`${what}: not reached within ${budgetMs} ms of transport time`);
50
+ };
51
+ const settle = async (promise, what, budgetMs = 600_000) => {
52
+ let outcome;
53
+ promise.then((value) => void (outcome = { value }), (error) => void (outcome = { error }));
54
+ await runUntil(() => outcome !== undefined, what, budgetMs);
55
+ if (outcome === undefined || "error" in outcome)
56
+ throw outcome?.error;
57
+ return outcome.value;
58
+ };
59
+ const waitFor = async (done, what, budgetMs = 600_000) => {
60
+ const end = timers.now() + budgetMs;
61
+ await drain();
62
+ while (!(await done())) {
63
+ if (timers.now() >= end)
64
+ throw new Error(`${what}: not reached within ${budgetMs} ms of transport time`);
65
+ await timers.advanceTo(Math.min(end, timers.now() + TICK_MS));
66
+ await drain();
67
+ }
68
+ };
69
+ return { advance: (ms) => pump(() => false, ms), settle, runUntil, waitFor };
70
+ }
19
71
  export async function openHandRig(adapters, options) {
20
72
  const timers = createManualTimers(1_000);
21
73
  const network = createInProcessNetwork({ schedule: (deliver) => void timers.setTimer(deliver, 0) });
@@ -83,29 +135,9 @@ export async function openHandRig(adapters, options) {
83
135
  let current = await adapters.store.open(medium, { onWritePoint: killing });
84
136
  await startHand(current).ready;
85
137
  const host = createRemoteToolHost({ transport: sessionSide, placement: options.placement });
86
- const pump = async (stop, ms) => {
87
- const end = timers.now() + ms;
88
- await drain();
89
- while (!stop() && timers.now() < end) {
90
- await timers.advanceTo(Math.min(end, timers.now() + TICK_MS));
91
- await drain();
92
- }
93
- };
94
- const runUntil = async (done, what, budgetMs = 600_000) => {
95
- await pump(done, budgetMs);
96
- if (!done())
97
- throw new Error(`${what}: not reached within ${budgetMs} ms of transport time`);
98
- };
99
- const settle = async (promise, what, budgetMs = 600_000) => {
100
- let outcome;
101
- promise.then((value) => void (outcome = { value }), (error) => void (outcome = { error }));
102
- await runUntil(() => outcome !== undefined, what, budgetMs);
103
- if (outcome === undefined || "error" in outcome)
104
- throw outcome?.error;
105
- return outcome.value;
106
- };
138
+ const { advance, settle, runUntil, waitFor } = transportPump(timers);
107
139
  return {
108
- advance: (ms) => pump(() => false, ms),
140
+ advance,
109
141
  bodies,
110
142
  faults,
111
143
  killed: killed.promise,
@@ -124,6 +156,7 @@ export async function openHandRig(adapters, options) {
124
156
  },
125
157
  settle,
126
158
  runUntil,
159
+ waitFor,
127
160
  disconnect: () => link.drop(),
128
161
  reconnect: () => link.connect(),
129
162
  rows: async () => createExecutionLedger({
@@ -0,0 +1,3 @@
1
+ import type { RegisteredCase } from "../../conformance/registry.ts";
2
+ export declare const HAND_REGISTRY: readonly RegisteredCase[];
3
+ //# sourceMappingURL=hand-registry.d.ts.map
@@ -0,0 +1,20 @@
1
+ import { KILL_HAND_DECLARATIONS } from "./kill-hand.js";
2
+ const HAND_INTRO = "#5482";
3
+ const handCase = (id, impl, expected) => ({
4
+ id,
5
+ impl,
6
+ intro: HAND_INTRO,
7
+ adapters: ["store", "transport", "executor"],
8
+ expected,
9
+ });
10
+ const KILL_HAND_IMPL = "packages/agent/src/execution/testing/kill-hand.ts";
11
+ const MULTI_HAND_IMPL = "packages/agent/src/execution/testing/multi-hand-cases.ts";
12
+ const FAULT_HAND_IMPL = "packages/agent/src/execution/testing/fault-hand-cases.ts";
13
+ export const HAND_REGISTRY = [
14
+ ...KILL_HAND_DECLARATIONS.map(({ id, expected }) => handCase(id, KILL_HAND_IMPL, expected)),
15
+ handCase("MULTI-HAND-01", MULTI_HAND_IMPL, "N scopes batch at once on one hand; each scope's calls start in lane order"),
16
+ handCase("MULTI-KILL-01", MULTI_HAND_IMPL, "cross-machine: a hand killed with several scopes in flight; each ends hand_restarted, uncertain, never rerun"),
17
+ ...["slow", "lossy", "laggy", "flap", "drop-reattach"].map((profile, index) => handCase(`FAULT-HAND-0${index + 1}`, FAULT_HAND_IMPL, `${profile} profile: every call settles with its unfaulted result, runs once, per-scope order kept`)),
18
+ handCase("FAULT-HAND-MULTI-01", FAULT_HAND_IMPL, "hand unreachable past the resume window: dependent calls pause, then each scope resumes exactly once"),
19
+ ];
20
+ //# sourceMappingURL=hand-registry.js.map
@@ -0,0 +1,9 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import { type HandCaseAdapters } from "./hand-harness.ts";
3
+ export interface KillEpochDeclaration {
4
+ readonly id: string;
5
+ readonly expected: string;
6
+ }
7
+ export declare const KILL_EPOCH_DECLARATIONS: readonly KillEpochDeclaration[];
8
+ export declare const KILL_EPOCH_CASES: ReadonlyMap<string, CaseImplementation<HandCaseAdapters>>;
9
+ //# sourceMappingURL=kill-epoch.d.ts.map
@@ -0,0 +1,71 @@
1
+ import { expectEqual } from "../../durable/testing/store-harness.js";
2
+ import { texts } from "./epoch-cases.js";
3
+ import { floorCommit, openEpochRig, stepCommit } from "./epoch-harness.js";
4
+ import { call } from "./hand-harness.js";
5
+ const OLD = { name: "brain-old", epoch: 1 };
6
+ const NEW = { name: "brain-new", epoch: 2 };
7
+ const FENCED = "the old owner stays fenced";
8
+ const POINTS = [
9
+ {
10
+ id: "KILL-EPOCH-01-B",
11
+ match: floorCommit("s", NEW.epoch),
12
+ at: "before",
13
+ floorAfterKill: OLD.epoch,
14
+ newCallRuns: true,
15
+ expected: `kill before the floor raise is durable: no ACK; the re-sent floor is acked after restart, the new call runs once, ${FENCED}`,
16
+ },
17
+ {
18
+ id: "KILL-EPOCH-01-D",
19
+ match: floorCommit("s", NEW.epoch),
20
+ at: "durable",
21
+ floorAfterKill: NEW.epoch,
22
+ newCallRuns: true,
23
+ expected: `kill once the floor is durable, before its ACK: the restarted hand holds the floor, the new call runs once, ${FENCED}`,
24
+ },
25
+ {
26
+ id: "KILL-EPOCH-02-B",
27
+ match: stepCommit(NEW.name, "admit"),
28
+ at: "before",
29
+ floorAfterKill: NEW.epoch,
30
+ newCallRuns: true,
31
+ expected: `kill after the ACK, before the new owner's first call is recorded: the floor survives, the call runs once, ${FENCED}`,
32
+ },
33
+ {
34
+ id: "KILL-EPOCH-02-D",
35
+ match: stepCommit(NEW.name, "admit"),
36
+ at: "durable",
37
+ floorAfterKill: NEW.epoch,
38
+ newCallRuns: false,
39
+ expected: `kill once the new owner's first call is recorded: the floor survives, the call ends hand_restarted and never runs, ${FENCED}`,
40
+ },
41
+ ];
42
+ const cases = POINTS.map((point) => {
43
+ const run = async (adapters) => {
44
+ const what = point.id;
45
+ const rig = await openEpochRig(adapters, { brains: [OLD, NEW], kill: { match: point.match, at: point.at } });
46
+ rig.setOwner("s", OLD.name);
47
+ await rig.settle(rig.execute(OLD.name, "s", [call("c0")]), `${what}: the old owner's first call`);
48
+ rig.setOwner("s", NEW.name);
49
+ const moved = rig.execute(NEW.name, "s", [call("c1")]);
50
+ await rig.settle(rig.killed, `${what}: the kill point fired`);
51
+ expectEqual(await rig.floor("s"), { epoch: point.floorAfterKill, owner: point.floorAfterKill === NEW.epoch ? NEW.name : OLD.name }, `${what}: the floor durable at the kill`);
52
+ await rig.restart();
53
+ const result = await rig.settle(moved, `${what}: the new owner's call`);
54
+ if (point.newCallRuns)
55
+ expectEqual(texts(result), ["ran:c1"], `${what}: the new owner's call ran`);
56
+ else
57
+ expectEqual(result.messages[0]?.details, { outcome: "hand_restarted", uncertain: false, hooksRan: false }, `${what}: the recorded call ended hand_restarted, not uncertain`);
58
+ const delayed = await rig.settle(rig.execute(OLD.name, "s", [call("c2")]), `${what}: a delayed old-owner call`);
59
+ expectEqual(delayed.messages[0]?.isError, true, `${what}: the old owner's delayed call is refused`);
60
+ await rig.advance(200);
61
+ expectEqual(rig.bodies, point.newCallRuns ? ["s:c0", "s:c1"] : ["s:c0"], `${what}: tool body runs`);
62
+ expectEqual((await rig.rows()).map(({ commandId, progress }) => [commandId, progress.state]), [
63
+ ["brain-new-1", "acked"],
64
+ ["brain-old-1", "acked"],
65
+ ], `${what}: one durable record per call that reached the ledger, acknowledged`);
66
+ };
67
+ return { declaration: { id: point.id, expected: point.expected }, run };
68
+ });
69
+ export const KILL_EPOCH_DECLARATIONS = cases.map(({ declaration }) => declaration);
70
+ export const KILL_EPOCH_CASES = new Map(cases.map(({ declaration, run }) => [declaration.id, run]));
71
+ //# sourceMappingURL=kill-epoch.js.map
@@ -0,0 +1,14 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import type { TransportCaseAdapters } from "../../transport/testing/transport-harness.ts";
3
+ import { type LoopHookPoint } from "../loop-hook-host-hand.ts";
4
+ /** Where the kill lands: a point of the call on the hand, or after the loop host committed the reply. */
5
+ type KillAt = LoopHookPoint | "committed";
6
+ export interface KillHookDeclaration {
7
+ readonly id: string;
8
+ readonly at: KillAt;
9
+ readonly expected: string;
10
+ }
11
+ export declare const KILL_HOOK_DECLARATIONS: readonly KillHookDeclaration[];
12
+ export declare const KILL_HOOK_CASES: ReadonlyMap<string, CaseImplementation<TransportCaseAdapters>>;
13
+ export {};
14
+ //# sourceMappingURL=kill-hook.d.ts.map
@@ -0,0 +1,117 @@
1
+ import { createManualTimers } from "../../durable/testing/manual-timers.js";
2
+ import { expectEqual } from "../../durable/testing/store-harness.js";
3
+ import { createInProcessNetwork } from "../../transport/in-process-carrier.js";
4
+ import { localEndpoint } from "../../transport/local-endpoint.js";
5
+ import { createLoopHookHost, LoopHookRestartedError } from "../loop-hook-host.js";
6
+ import { serveLoopHooks } from "../loop-hook-host-hand.js";
7
+ /**
8
+ * KILL-HOOK (brain/hand split S33): the user's machine is killed around one forwarded hook call and its reply, then a new
9
+ * process starts on the same link. Each case declares what the loop host's turn sees: the hook result (and exactly one
10
+ * provider request carrying it), or a restarted call that is never run again and issues no provider request. These
11
+ * placements only exist where the hook host is engaged (a hosted loop, or any loop away from the user's machine); a
12
+ * fused or split-local session never forwards its hooks.
13
+ */
14
+ const LANE = "loop-hooks:session";
15
+ const TICK_MS = 5;
16
+ const KILLS = [
17
+ { at: "received", outcome: "result", runs: 1 },
18
+ { at: "started", outcome: "restarted", runs: 0 },
19
+ { at: "ran", outcome: "restarted", runs: 1 },
20
+ { at: "replied", outcome: "result", runs: 1 },
21
+ { at: "committed", outcome: "result", runs: 1 },
22
+ ];
23
+ const WHERE = {
24
+ received: "after the hand received the hook call, before it started it",
25
+ started: "after the hand said it started the hooks, before they ran",
26
+ ran: "after the hooks ran, before the hand sent the reply",
27
+ replied: "after the hand sent the reply, before the loop host committed it",
28
+ committed: "after the loop host committed the reply, before the provider request",
29
+ };
30
+ const expectedOf = ({ at, outcome, runs }) => {
31
+ const result = outcome === "result"
32
+ ? "the turn gets the hook result and issues exactly one provider request with it"
33
+ : "the call ends restarted (uncertain), is never sent again, and no provider request is issued";
34
+ return `cross-machine and hosted: kill ${WHERE[at]}; ${result}; the hooks ran ${runs === 0 ? "never" : "once"}`;
35
+ };
36
+ const drain = async () => {
37
+ for (let turn = 0; turn < 32; turn++)
38
+ await Promise.resolve();
39
+ };
40
+ async function runKillCase(adapters, kill, what) {
41
+ const timers = createManualTimers(1_000);
42
+ const network = createInProcessNetwork({ schedule: (deliver) => void timers.setTimer(deliver, 0) });
43
+ const loopSide = adapters.transport.createSide(timers);
44
+ const handSide = adapters.transport.createSide(timers);
45
+ const endpoint = localEndpoint(adapters.platform, "loop-hook-conformance", "/run/senpi-conformance");
46
+ network.listen(endpoint, handSide);
47
+ network.dial(endpoint, loopSide).connect();
48
+ const runs = [];
49
+ const requests = [];
50
+ const killed = Promise.withResolvers();
51
+ const startHand = (killAt) => serveLoopHooks({
52
+ transport: handSide,
53
+ lane: LANE,
54
+ run: async (event, payload) => {
55
+ runs.push(event);
56
+ return { context: `hook saw ${JSON.stringify(payload)}` };
57
+ },
58
+ onPoint: (point) => {
59
+ if (point !== killAt)
60
+ return;
61
+ killed.resolve();
62
+ throw new Error(`hand killed ${point}`);
63
+ },
64
+ });
65
+ const until = async (done, label) => {
66
+ const end = timers.now() + 600_000;
67
+ await drain();
68
+ while (!done() && timers.now() < end) {
69
+ await timers.advanceTo(timers.now() + TICK_MS);
70
+ await drain();
71
+ }
72
+ if (!done())
73
+ throw new Error(`${what}: ${label} not reached`);
74
+ };
75
+ let hand = startHand(kill.at === "committed" ? undefined : kill.at);
76
+ const host = createLoopHookHost({ transport: loopSide, lane: LANE });
77
+ let outcome;
78
+ host.run("before_agent_start", { prompt: "go" }).then(async (result) => {
79
+ if (kill.at === "committed") {
80
+ hand.close();
81
+ killed.resolve();
82
+ hand = startHand();
83
+ }
84
+ requests.push(result);
85
+ outcome = { result };
86
+ }, (error) => void (outcome = { error }));
87
+ let didKill = false;
88
+ void killed.promise.then(() => void (didKill = true));
89
+ await until(() => didKill, "the kill point fired");
90
+ if (kill.at !== "committed")
91
+ hand = startHand();
92
+ await until(() => outcome !== undefined, "the turn got the hook call's outcome");
93
+ // Let any second dispatch the restart could cause surface before the run count is checked.
94
+ for (let step = 0; step < 40; step++) {
95
+ await timers.advanceTo(timers.now() + TICK_MS);
96
+ await drain();
97
+ }
98
+ if (kill.outcome === "result") {
99
+ expectEqual(outcome !== undefined && "result" in outcome ? outcome.result : outcome, { context: 'hook saw {"prompt":"go"}' }, `${what}: the hook result`);
100
+ expectEqual(requests.length, 1, `${what}: provider requests`);
101
+ }
102
+ else {
103
+ expectEqual(outcome !== undefined && "error" in outcome && outcome.error instanceof LoopHookRestartedError, true, `${what}: the call ended restarted`);
104
+ expectEqual(requests.length, 0, `${what}: provider requests`);
105
+ }
106
+ expectEqual(runs.length, kill.runs, `${what}: hook runs`);
107
+ expectEqual(host.waiting(), [], `${what}: nothing left waiting`);
108
+ }
109
+ const cases = KILLS.map((kill, index) => {
110
+ const id = `KILL-HOOK-${String(index + 1).padStart(2, "0")}`;
111
+ const declaration = { id, at: kill.at, expected: expectedOf(kill) };
112
+ const run = (adapters) => runKillCase(adapters, kill, `${id} (${kill.at})`);
113
+ return { declaration, run };
114
+ });
115
+ export const KILL_HOOK_DECLARATIONS = cases.map(({ declaration }) => declaration);
116
+ export const KILL_HOOK_CASES = new Map(cases.map(({ declaration, run }) => [declaration.id, run]));
117
+ //# sourceMappingURL=kill-hook.js.map
@@ -0,0 +1,4 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import { type HandCaseAdapters } from "./hand-harness.ts";
3
+ export declare const MULTI_EPOCH_CASES: ReadonlyMap<string, CaseImplementation<HandCaseAdapters>>;
4
+ //# sourceMappingURL=multi-epoch-cases.d.ts.map
@@ -0,0 +1,29 @@
1
+ import { expectEqual } from "../../durable/testing/store-harness.js";
2
+ import { texts } from "./epoch-cases.js";
3
+ import { openEpochRig } from "./epoch-harness.js";
4
+ import { call } from "./hand-harness.js";
5
+ const SCOPES = ["a", "b", "c"];
6
+ /** Z2: one session moves (its scope's floor rises); the other sessions' scopes on the same hand keep running. */
7
+ const oneSessionMoves = async (adapters) => {
8
+ const rig = await openEpochRig(adapters, {
9
+ brains: [
10
+ { name: "brain-old", epoch: 1 },
11
+ { name: "brain-new", epoch: 2 },
12
+ ],
13
+ });
14
+ for (const scope of SCOPES)
15
+ rig.setOwner(scope, "brain-old");
16
+ await rig.settle(Promise.all(SCOPES.map((scope) => rig.execute("brain-old", scope, [call(`${scope}1`)]))), "MULTI-EPOCH-01: every scope ran on the old owner");
17
+ rig.setOwner("a", "brain-new");
18
+ const moved = await rig.settle(rig.execute("brain-new", "a", [call("a2")]), "MULTI-EPOCH-01: scope a moved");
19
+ expectEqual(texts(moved), ["ran:a2"], "MULTI-EPOCH-01: the moved scope runs on its new owner");
20
+ const after = await rig.settle(Promise.all(SCOPES.map((scope) => rig.execute("brain-old", scope, [call(`${scope}3`)]))), "MULTI-EPOCH-01: the old owner's next calls");
21
+ expectEqual(after.map(texts), [["The hand refused this tool call: epoch_fenced"], ["ran:b3"], ["ran:c3"]], "MULTI-EPOCH-01: only the moved scope fences the old owner; the others run untouched");
22
+ for (const scope of ["b", "c"])
23
+ expectEqual(await rig.floor(scope), { epoch: 1, owner: "brain-old" }, `MULTI-EPOCH-01: scope ${scope}'s floor`);
24
+ expectEqual([...rig.bodies].sort(), ["a1", "a2", "b1", "b3", "c1", "c3"].map((id) => `${id.charAt(0)}:${id}`), "MULTI-EPOCH-01: every scope's calls ran once; the fenced one never ran");
25
+ };
26
+ export const MULTI_EPOCH_CASES = new Map([
27
+ ["MULTI-EPOCH-01", oneSessionMoves],
28
+ ]);
29
+ //# sourceMappingURL=multi-epoch-cases.js.map
@@ -34,7 +34,7 @@ const killWithScopesInFlight = async (adapters) => {
34
34
  const results = await rig.settle(Promise.all(batches), "MULTI-KILL-01: every scope got its outcome");
35
35
  expectEqual(results.map(({ messages }) => messages.map((message) => message.details)), SCOPES.map(() => [{ outcome: "hand_restarted", uncertain: true, hooksRan: true }]), "MULTI-KILL-01: each scope's call ended hand_restarted, uncertain");
36
36
  expectEqual(rig.bodies, SCOPES.map((scope) => `${scope}:${scope}1`), "MULTI-KILL-01: no call ran twice");
37
- await rig.advance(200);
37
+ await rig.waitFor(async () => (await rig.rows()).every((row) => row.progress.state === "acked"), "MULTI-KILL-01: every call's record acknowledged");
38
38
  expectEqual((await rig.rows()).map((row) => row.progress.state), SCOPES.map(() => "acked"), "MULTI-KILL-01: one durable record per call, acknowledged");
39
39
  };
40
40
  export const MULTI_HAND_CASES = new Map([
@@ -1,5 +1,6 @@
1
1
  import type { AssistantMessage, ToolResultMessage } from "@earendil-works/pi-ai";
2
2
  import type { AgentContext, AgentEvent, AgentToolCall, ToolExecutionMode } from "../types.ts";
3
+ import type { DeviceFiles } from "./device-files.ts";
3
4
  /** Brain-minted identity and execution root; the executor treats the identity as opaque. */
4
5
  export interface ExecutionScope {
5
6
  readonly id: string;
@@ -12,7 +13,7 @@ export interface ToolHostCall {
12
13
  readonly mode: ToolExecutionMode;
13
14
  }
14
15
  export interface ExecutionPipelineWitness {
15
- readonly pipeline: "legacy" | "prepared";
16
+ readonly pipeline: "prepared";
16
17
  readonly toolCallId: string;
17
18
  }
18
19
  export interface ToolHostResult {
@@ -34,7 +35,21 @@ export interface ToolHostOptions {
34
35
  readonly assistantMessage: AssistantMessage;
35
36
  };
36
37
  }
38
+ /** The loop had a tool batch to run on its default pipeline but no `batchStoreFactory`; it refuses instead of guessing a store. */
39
+ export declare class BatchStoreMissingError extends Error {
40
+ readonly code = "batch_store_missing";
41
+ constructor();
42
+ }
43
+ /** The loop had a tool batch to run on its default pipeline but no `afterToolFreeze`; it refuses instead of dropping preflight facts. */
44
+ export declare class PreflightCarryMissingError extends Error {
45
+ readonly code = "preflight_carry_missing";
46
+ constructor();
47
+ }
48
+ /** The package entry's default `afterToolFreeze`: for hosts whose `beforeToolCall` binds nothing to the arguments object. */
49
+ export declare function noPreflightCarry(_prepared: unknown, _frozen: unknown): void;
37
50
  export interface ToolHost {
38
51
  execute(call: ToolHostCall, options: ToolHostOptions): Promise<ToolHostResult>;
52
+ /** The files of the device this host runs calls on, for `scope` (S40); absent: the loop's own machine. */
53
+ deviceFiles?(scope: ExecutionScope): DeviceFiles;
39
54
  }
40
55
  //# sourceMappingURL=tool-host.d.ts.map