@code-yeongyu/senpi-agent-core 2026.11.3-3 → 2026.11.5-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 (167) hide show
  1. package/dist/agent-loop.js +20 -186
  2. package/dist/agent.d.ts +4 -0
  3. package/dist/agent.js +4 -0
  4. package/dist/conformance/index.d.ts +30 -0
  5. package/dist/conformance/index.js +21 -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 +20 -18
  9. package/dist/egress/types.d.ts +102 -0
  10. package/dist/egress/types.js +7 -0
  11. package/dist/execution/canonical-digest.d.ts +10 -0
  12. package/dist/execution/canonical-digest.js +20 -0
  13. package/dist/execution/canonical-json.d.ts +3 -0
  14. package/dist/execution/canonical-json.js +12 -0
  15. package/dist/execution/chain-count.d.ts +26 -0
  16. package/dist/execution/chain-count.js +45 -0
  17. package/dist/execution/coordinator-codec.js +13 -2
  18. package/dist/execution/coordinator-consent.d.ts +29 -0
  19. package/dist/execution/coordinator-consent.js +63 -0
  20. package/dist/execution/coordinator-plan.d.ts +1 -2
  21. package/dist/execution/coordinator-plan.js +4 -17
  22. package/dist/execution/coordinator-sequential.d.ts +15 -0
  23. package/dist/execution/coordinator-sequential.js +34 -0
  24. package/dist/execution/coordinator-types.d.ts +45 -0
  25. package/dist/execution/coordinator.d.ts +3 -1
  26. package/dist/execution/coordinator.js +35 -3
  27. package/dist/execution/device-files-node.d.ts +8 -0
  28. package/dist/execution/device-files-node.js +150 -0
  29. package/dist/execution/device-files.d.ts +109 -0
  30. package/dist/execution/device-files.js +124 -0
  31. package/dist/execution/ledger-types.d.ts +3 -1
  32. package/dist/execution/ledger.d.ts +9 -3
  33. package/dist/execution/ledger.js +8 -2
  34. package/dist/execution/loop-hook-host-hand.d.ts +33 -0
  35. package/dist/execution/loop-hook-host-hand.js +71 -0
  36. package/dist/execution/loop-hook-host-protocol.d.ts +46 -0
  37. package/dist/execution/loop-hook-host-protocol.js +47 -0
  38. package/dist/execution/loop-hook-host.d.ts +40 -0
  39. package/dist/execution/loop-hook-host.js +87 -0
  40. package/dist/execution/nested-codec.d.ts +5 -0
  41. package/dist/execution/nested-codec.js +41 -0
  42. package/dist/execution/nested-types.d.ts +92 -0
  43. package/dist/execution/nested-types.js +3 -0
  44. package/dist/execution/nested.d.ts +48 -0
  45. package/dist/execution/nested.js +206 -0
  46. package/dist/execution/plane-model.d.ts +33 -0
  47. package/dist/execution/plane-model.js +80 -0
  48. package/dist/execution/plane-session.d.ts +56 -0
  49. package/dist/execution/plane-session.js +178 -0
  50. package/dist/execution/plane.d.ts +75 -0
  51. package/dist/execution/plane.js +172 -0
  52. package/dist/execution/prepared/executor-body.d.ts +22 -0
  53. package/dist/execution/prepared/executor-body.js +73 -0
  54. package/dist/execution/prepared/executor-freeze.d.ts +17 -0
  55. package/dist/execution/prepared/executor-freeze.js +42 -0
  56. package/dist/execution/prepared/executor-pipeline.d.ts +11 -0
  57. package/dist/execution/prepared/executor-pipeline.js +26 -0
  58. package/dist/execution/prepared/executor-types.d.ts +131 -0
  59. package/dist/execution/prepared/executor-types.js +2 -0
  60. package/dist/execution/prepared/executor.d.ts +8 -0
  61. package/dist/execution/prepared/executor.js +261 -0
  62. package/dist/execution/prepared/memory-batch-store.d.ts +4 -0
  63. package/dist/execution/prepared/memory-batch-store.js +4 -0
  64. package/dist/execution/prepared/pipeline-prepared-batch.d.ts +27 -0
  65. package/dist/execution/prepared/pipeline-prepared-batch.js +175 -0
  66. package/dist/execution/prepared/pipeline-prepared.d.ts +10 -0
  67. package/dist/execution/prepared/pipeline-prepared.js +54 -0
  68. package/dist/execution/remote-device-files.d.ts +12 -0
  69. package/dist/execution/remote-device-files.js +113 -0
  70. package/dist/execution/remote-epoch-gate.d.ts +19 -0
  71. package/dist/execution/remote-epoch-gate.js +46 -0
  72. package/dist/execution/remote-epoch.d.ts +53 -0
  73. package/dist/execution/remote-epoch.js +74 -0
  74. package/dist/execution/remote-executor.d.ts +17 -0
  75. package/dist/execution/remote-executor.js +70 -18
  76. package/dist/execution/remote-file-call.d.ts +14 -0
  77. package/dist/execution/remote-file-call.js +31 -0
  78. package/dist/execution/remote-hand-ledger.d.ts +11 -3
  79. package/dist/execution/remote-hand-ledger.js +31 -15
  80. package/dist/execution/remote-link.d.ts +41 -0
  81. package/dist/execution/remote-link.js +153 -0
  82. package/dist/execution/remote-protocol.d.ts +50 -4
  83. package/dist/execution/remote-protocol.js +48 -2
  84. package/dist/execution/remote-tool-host.d.ts +23 -3
  85. package/dist/execution/remote-tool-host.js +25 -64
  86. package/dist/execution/scope-lifecycle.d.ts +81 -0
  87. package/dist/execution/scope-lifecycle.js +173 -0
  88. package/dist/execution/testing/batch-executor.js +32 -3
  89. package/dist/execution/testing/batch-harness.d.ts +25 -3
  90. package/dist/execution/testing/batch-harness.js +83 -5
  91. package/dist/execution/testing/cancel-cases.d.ts +8 -0
  92. package/dist/execution/testing/cancel-cases.js +64 -0
  93. package/dist/execution/testing/consent-cases.d.ts +14 -0
  94. package/dist/execution/testing/consent-cases.js +66 -0
  95. package/dist/execution/testing/epoch-cases.d.ts +8 -0
  96. package/dist/execution/testing/epoch-cases.js +84 -0
  97. package/dist/execution/testing/epoch-harness.d.ts +47 -0
  98. package/dist/execution/testing/epoch-harness.js +172 -0
  99. package/dist/execution/testing/epoch-registry.d.ts +3 -0
  100. package/dist/execution/testing/epoch-registry.js +17 -0
  101. package/dist/execution/testing/hand-harness.d.ts +3 -0
  102. package/dist/execution/testing/hand-harness.js +27 -22
  103. package/dist/execution/testing/hand-registry.d.ts +3 -0
  104. package/dist/execution/testing/hand-registry.js +20 -0
  105. package/dist/execution/testing/kill-epoch.d.ts +9 -0
  106. package/dist/execution/testing/kill-epoch.js +71 -0
  107. package/dist/execution/testing/kill-hook.d.ts +14 -0
  108. package/dist/execution/testing/kill-hook.js +117 -0
  109. package/dist/execution/testing/kill-nest.d.ts +6 -0
  110. package/dist/execution/testing/kill-nest.js +55 -0
  111. package/dist/execution/testing/kill-wakex.d.ts +6 -0
  112. package/dist/execution/testing/kill-wakex.js +81 -0
  113. package/dist/execution/testing/lifecycle-cases.d.ts +9 -0
  114. package/dist/execution/testing/lifecycle-cases.js +60 -0
  115. package/dist/execution/testing/lifecycle-registry.d.ts +3 -0
  116. package/dist/execution/testing/lifecycle-registry.js +19 -0
  117. package/dist/execution/testing/multi-epoch-cases.d.ts +4 -0
  118. package/dist/execution/testing/multi-epoch-cases.js +29 -0
  119. package/dist/execution/testing/multi-lifecycle-cases.d.ts +4 -0
  120. package/dist/execution/testing/multi-lifecycle-cases.js +34 -0
  121. package/dist/execution/testing/multi-seq-cases.d.ts +4 -0
  122. package/dist/execution/testing/multi-seq-cases.js +46 -0
  123. package/dist/execution/testing/nest-cases.d.ts +39 -0
  124. package/dist/execution/testing/nest-cases.js +181 -0
  125. package/dist/execution/testing/nest-registry.d.ts +3 -0
  126. package/dist/execution/testing/nest-registry.js +27 -0
  127. package/dist/execution/testing/scope-cases.d.ts +6 -0
  128. package/dist/execution/testing/scope-cases.js +49 -0
  129. package/dist/execution/testing/seq-cases.d.ts +6 -0
  130. package/dist/execution/testing/seq-cases.js +71 -0
  131. package/dist/execution/testing/seq-registry.d.ts +3 -0
  132. package/dist/execution/testing/seq-registry.js +32 -0
  133. package/dist/execution/testing/wake-exec-cases.d.ts +20 -0
  134. package/dist/execution/testing/wake-exec-cases.js +147 -0
  135. package/dist/execution/testing/wake-registry.d.ts +3 -0
  136. package/dist/execution/testing/wake-registry.js +26 -0
  137. package/dist/execution/tool-host.d.ts +23 -3
  138. package/dist/execution/tool-host.js +18 -1
  139. package/dist/execution/tool-outcome-events.d.ts +11 -0
  140. package/dist/execution/tool-outcome-events.js +47 -0
  141. package/dist/execution/wake-inbox.d.ts +25 -0
  142. package/dist/execution/wake-inbox.js +85 -0
  143. package/dist/execution/wake-outbox.d.ts +30 -0
  144. package/dist/execution/wake-outbox.js +87 -0
  145. package/dist/execution/wake-types.d.ts +45 -0
  146. package/dist/execution/wake-types.js +3 -0
  147. package/dist/harness/agent-harness.d.ts +6 -0
  148. package/dist/harness/execution/tool-host-call.d.ts +13 -0
  149. package/dist/harness/execution/tool-host-call.js +55 -0
  150. package/dist/harness/execution/tools.d.ts +2 -1
  151. package/dist/harness/execution/tools.js +32 -17
  152. package/dist/harness/runtime/drive/tools.js +1 -1
  153. package/dist/harness/runtime/harness.js +1 -0
  154. package/dist/harness/runtime/types.d.ts +1 -0
  155. package/dist/index.d.ts +27 -2
  156. package/dist/index.js +24 -1
  157. package/dist/node.d.ts +1 -0
  158. package/dist/node.js +1 -0
  159. package/dist/public-entry.d.ts +10 -0
  160. package/dist/public-entry.js +23 -0
  161. package/dist/step-commit.d.ts +24 -0
  162. package/dist/step-commit.js +24 -0
  163. package/dist/tool-name-alias.d.ts +1 -7
  164. package/dist/tool-name-alias.js +0 -17
  165. package/dist/transport/testing/multi-cases.js +8 -8
  166. package/dist/types.d.ts +37 -1
  167. package/package.json +3 -3
@@ -0,0 +1,178 @@
1
+ import { PlaneRefusedError } from "./plane.js";
2
+ import { createPreparedToolHost } from "./prepared/pipeline-prepared.js";
3
+ import { BatchStoreMissingError, PreflightCarryMissingError, } from "./tool-host.js";
4
+ /**
5
+ * The session plane (brain/hand split, S32): tools that act on the session (todo, thread tools, task/subagent spawn,
6
+ * `ask_user`, and the other built-ins declared `runs: "brain"`) run where the loop runs. A model call to one of them
7
+ * never reaches the hand, and a hand-run tool that needs one asks the brain that owns its call on this plane.
8
+ */
9
+ export const SESSION_PLANE = "session";
10
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11
+ /** Parses a request body, keeping only the fields of {@link SessionPlaneRequest}; refuses a malformed one. */
12
+ export function decodeSessionPlaneRequest(body) {
13
+ if (!isRecord(body) || typeof body.tool !== "string" || body.tool.length === 0)
14
+ throw new PlaneRefusedError("malformed_request: tool");
15
+ if (!isRecord(body.arguments))
16
+ throw new PlaneRefusedError("malformed_request: arguments");
17
+ return { tool: body.tool, arguments: body.arguments };
18
+ }
19
+ /** The registered tools a split session runs loop-side: exactly those declared `runs: "brain"`. */
20
+ export function loopSideToolNames(tools) {
21
+ const names = new Set();
22
+ for (const tool of tools)
23
+ if (tool.runs === "brain")
24
+ names.add(tool.name);
25
+ return names;
26
+ }
27
+ /**
28
+ * The brain's session plane: runs one loop-side tool call with the session's own tools and returns its result. A tool
29
+ * that is not loop-side is refused `not_loop_side`: a hand's tools never run on the brain through this plane.
30
+ */
31
+ export function serveSessionPlane(options) {
32
+ return async (body, signal) => {
33
+ const request = decodeSessionPlaneRequest(body);
34
+ if (!options.loopSide.has(request.tool))
35
+ throw new Error(`not_loop_side: ${request.tool}`);
36
+ const result = await options.run(request, signal);
37
+ return JSON.parse(JSON.stringify(result));
38
+ };
39
+ }
40
+ /** A hand's client for the session plane, over the running call's nested requests. */
41
+ export function createSessionPlaneClient(nested) {
42
+ return {
43
+ async call(request, signal) {
44
+ const reply = await nested(SESSION_PLANE, JSON.parse(JSON.stringify(request)), signal);
45
+ if (!isRecord(reply) || !Array.isArray(reply.content))
46
+ throw new PlaneRefusedError("malformed_reply");
47
+ return reply;
48
+ },
49
+ };
50
+ }
51
+ /**
52
+ * The loop's own pipeline as a ToolHost (the prepared pipeline a fused session runs), for a split session's loop-side
53
+ * calls. It reads `agent`'s hooks and batch store at each batch, so hooks installed after it was made still apply.
54
+ */
55
+ export function createLoopToolHost(agent) {
56
+ return {
57
+ execute(call, options) {
58
+ const { batchStoreFactory, afterToolFreeze } = agent;
59
+ if (batchStoreFactory === undefined)
60
+ throw new BatchStoreMissingError();
61
+ if (afterToolFreeze === undefined)
62
+ throw new PreflightCarryMissingError();
63
+ return createPreparedToolHost({ ...pick(agent), afterToolFreeze }, batchStoreFactory).execute(call, options);
64
+ },
65
+ };
66
+ }
67
+ function pick(agent) {
68
+ return {
69
+ resolveUnknownToolCall: agent.resolveUnknownToolCall,
70
+ beforeToolCall: agent.beforeToolCall,
71
+ afterToolCall: agent.afterToolCall,
72
+ removedToolHints: agent.removedToolHints,
73
+ };
74
+ }
75
+ /**
76
+ * Splits a batch into stages run one after another, each a set of same-side segments run at once; `owner[i]` is the
77
+ * segment that runs call `i`. `parallel` keeps the loop's dependency order (`batchDependencies`): a sequential call is a
78
+ * stage of its own, so it waits for every earlier call and every later call waits for it; the calls between two
79
+ * sequential calls share one stage. Otherwise each run of same-side calls is a stage.
80
+ */
81
+ function stagesOf(calls, sideOf, isSequential, parallel) {
82
+ const stages = [];
83
+ const segments = [];
84
+ const owner = [];
85
+ let open = false;
86
+ for (const call of calls) {
87
+ const side = sideOf(call);
88
+ const barrier = parallel && isSequential(call);
89
+ const stage = stages.at(-1);
90
+ const joinable = open && !barrier && stage !== undefined && (parallel || stage[0]?.side === side);
91
+ if (!joinable)
92
+ stages.push([]);
93
+ const current = stages.at(-1) ?? [];
94
+ let segment = current.find((entry) => entry.side === side);
95
+ if (segment === undefined) {
96
+ segment = { side, calls: [] };
97
+ current.push(segment);
98
+ segments.push(segment);
99
+ }
100
+ segment.calls.push(call);
101
+ owner.push(segments.indexOf(segment));
102
+ open = !barrier;
103
+ }
104
+ return { stages, segments, owner };
105
+ }
106
+ /** Items per call ID in arrival order (a batch may repeat an ID, senpi#5796). */
107
+ function queueBy(items, idOf) {
108
+ const queues = new Map();
109
+ for (const item of items) {
110
+ const queue = queues.get(idOf(item)) ?? [];
111
+ queue.push(item);
112
+ queues.set(idOf(item), queue);
113
+ }
114
+ return queues;
115
+ }
116
+ /** Passes every event through except tool result messages, which it holds in `held` as start/end pairs. */
117
+ function holdingResults(emit, held) {
118
+ return (event) => {
119
+ if ((event.type !== "message_start" && event.type !== "message_end") || event.message.role !== "toolResult")
120
+ return emit(event);
121
+ const { toolCallId } = event.message;
122
+ const open = event.type === "message_end" ? held.findLast((entry) => entry.toolCallId === toolCallId) : undefined;
123
+ if (open !== undefined && open.events.at(-1)?.type === "message_start")
124
+ open.events.push(event);
125
+ else
126
+ held.push({ toolCallId, events: [event] });
127
+ };
128
+ }
129
+ /**
130
+ * The ToolHost of a split session: each call to a loop-side tool runs on `loop` (the session's own pipeline, in its
131
+ * process) and every other call on `hand`. A batch of one side goes to that host whole. A mixed batch keeps the mode:
132
+ * `parallel` runs both sides at once and emits the result messages in source order once both finished, as the fused
133
+ * pipeline does; `sequential` runs each run of same-side calls in source order and starts none after an abort. Results come
134
+ * back in the model's source order and the batch terminates only when every call asked to.
135
+ */
136
+ export function createSplitToolHost(options) {
137
+ const sideOf = (call) => (options.loopSide(call.name) ? "loop" : "hand");
138
+ const isSequential = (call) => options.isSequential(call.name);
139
+ const hostOf = (side) => (side === "loop" ? options.loop : options.hand);
140
+ return {
141
+ async execute(call, hostOptions) {
142
+ const parallel = call.mode === "parallel";
143
+ const { stages, segments, owner } = stagesOf(call.calls, sideOf, isSequential, parallel);
144
+ const [only] = segments;
145
+ if (segments.every((segment) => segment.side === only?.side))
146
+ return hostOf(only?.side ?? "hand").execute(call, hostOptions);
147
+ const held = segments.map(() => []);
148
+ const run = async (segment) => {
149
+ const index = segments.indexOf(segment);
150
+ results[index] = await hostOf(segment.side).execute({ ...call, calls: segment.calls }, parallel ? { ...hostOptions, emit: holdingResults(hostOptions.emit, held[index] ?? []) } : hostOptions);
151
+ };
152
+ const results = segments.map(() => undefined);
153
+ for (const stage of stages) {
154
+ await Promise.all(stage.map(run));
155
+ if (hostOptions.signal?.aborted)
156
+ break;
157
+ }
158
+ const messages = results.map((result) => queueBy(result?.messages ?? [], (message) => message.toolCallId));
159
+ const events = held.map((entries) => queueBy(entries, (entry) => entry.toolCallId));
160
+ const ordered = [];
161
+ for (const [index, raw] of call.calls.entries()) {
162
+ const segment = owner[index] ?? -1;
163
+ for (const event of events[segment]?.get(raw.id)?.shift()?.events ?? [])
164
+ await hostOptions.emit(event);
165
+ const message = messages[segment]?.get(raw.id)?.shift();
166
+ if (message !== undefined)
167
+ ordered.push(message);
168
+ }
169
+ const ran = results.filter((result) => (result?.messages.length ?? 0) > 0);
170
+ return {
171
+ messages: ordered,
172
+ // As the fused pipeline: only segments whose calls ran decide; a batch where nothing ran does not terminate.
173
+ terminate: ran.length > 0 && ran.every((result) => result.terminate),
174
+ };
175
+ },
176
+ };
177
+ }
178
+ //# sourceMappingURL=plane-session.js.map
@@ -0,0 +1,75 @@
1
+ import type { JsonValue } from "@earendil-works/pi-ai";
2
+ import type { Transport } from "../transport/transport.ts";
3
+ /**
4
+ * Nested requests from a hand back to the brain that owns the running call (brain/hand split, design 5.6.3): a
5
+ * model-backed tool's completion (S31) and, later, session-plane work. A request travels on its parent call's own scope
6
+ * lane and names that parent; the brain admits it only while the parent is live on that lane, and it is never sent
7
+ * hand-to-hand. The bodies are a plane's own payloads; this layer only carries, admits, deduplicates and cancels them.
8
+ */
9
+ export type PlaneMessage = PlaneRequest | PlaneAbort | PlaneReply | PlaneRefused;
10
+ interface PlaneAddress {
11
+ /** The execution ID of the call the request is nested in. */
12
+ readonly parent: string;
13
+ /** Unique per parent; a replayed request with the same ID gets the same answer and is served once. */
14
+ readonly childRequestId: string;
15
+ }
16
+ export interface PlaneRequest extends PlaneAddress {
17
+ readonly kind: "plane.request";
18
+ readonly plane: string;
19
+ readonly body: JsonValue;
20
+ }
21
+ export interface PlaneAbort extends PlaneAddress {
22
+ readonly kind: "plane.abort";
23
+ }
24
+ export interface PlaneReply extends PlaneAddress {
25
+ readonly kind: "plane.reply";
26
+ readonly body: JsonValue;
27
+ }
28
+ /**
29
+ * The brain did not serve the request. `parent_terminal`: its parent is not a live call; `scope_lane_mismatch`: it came
30
+ * on another scope's lane; `plane_unavailable`: the brain serves no such plane; `plane_failed: ...`: the plane's
31
+ * handler failed.
32
+ */
33
+ export interface PlaneRefused extends PlaneAddress {
34
+ readonly kind: "plane.refused";
35
+ readonly reason: string;
36
+ }
37
+ /** Serves one plane on the brain. `signal` aborts when the request or its parent call is aborted or ends. */
38
+ export type PlaneHandler = (body: JsonValue, signal: AbortSignal) => Promise<JsonValue>;
39
+ /** What a running call on a hand uses to ask the brain that owns it. Rejects with {@link PlaneRefusedError}. */
40
+ export type NestedRequest = (plane: string, body: JsonValue, signal?: AbortSignal) => Promise<JsonValue>;
41
+ export declare class PlaneRefusedError extends Error {
42
+ readonly reason: string;
43
+ constructor(reason: string);
44
+ }
45
+ export declare function encodePlaneMessage(message: PlaneMessage): Uint8Array;
46
+ /** Parses one frame payload as a plane message; anything else (a tool-call message included) is `undefined`. */
47
+ export declare function decodePlaneMessage(payload: Uint8Array): PlaneMessage | undefined;
48
+ /**
49
+ * The brain's side: admits a request (and an abort) only while its parent is a live call on the lane it came on, serves each
50
+ * (parent, child request) once and answers a replay from the stored answer, and aborts a parent's open requests when
51
+ * the parent ends. Answers are kept for the parent's life only.
52
+ */
53
+ export declare function createPlaneServer(options: {
54
+ readonly transport: Transport;
55
+ readonly planes: Readonly<Record<string, PlaneHandler>>;
56
+ /**
57
+ * The lane of the live parent with this execution ID that may host a request on `plane`, or `undefined` once it ended
58
+ * (or never existed, or may not host that plane). `plane` is absent for an abort of a request already admitted.
59
+ */
60
+ readonly liveLane: (executionId: string, plane?: string) => string | undefined;
61
+ }): {
62
+ receive(lane: string, message: PlaneMessage): void;
63
+ parentEnded(executionId: string): void;
64
+ };
65
+ /** The hand's side: issues a running call's nested requests on its lane and fails them all once the call ends. */
66
+ export declare function createPlaneClient(options: {
67
+ readonly transport: Transport;
68
+ readonly mintId?: () => string;
69
+ }): {
70
+ requestFor(parent: string, lane: string, parentSignal: AbortSignal): NestedRequest;
71
+ receive(message: PlaneMessage): void;
72
+ parentEnded(parent: string): void;
73
+ };
74
+ export {};
75
+ //# sourceMappingURL=plane.d.ts.map
@@ -0,0 +1,172 @@
1
+ export class PlaneRefusedError extends Error {
2
+ constructor(reason) {
3
+ super(`The brain refused this request: ${reason}`);
4
+ this.name = "PlaneRefusedError";
5
+ this.reason = reason;
6
+ }
7
+ }
8
+ const KINDS = ["plane.request", "plane.abort", "plane.reply", "plane.refused"];
9
+ const encoder = new TextEncoder();
10
+ const decoder = new TextDecoder();
11
+ export function encodePlaneMessage(message) {
12
+ return encoder.encode(JSON.stringify(message));
13
+ }
14
+ const isRecord = (value) => typeof value === "object" && value !== null;
15
+ const isId = (value) => typeof value === "string" && value.length > 0;
16
+ /** Parses one frame payload as a plane message; anything else (a tool-call message included) is `undefined`. */
17
+ export function decodePlaneMessage(payload) {
18
+ let value;
19
+ try {
20
+ value = JSON.parse(decoder.decode(payload));
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ if (!isRecord(value) || !KINDS.includes(value.kind))
26
+ return undefined;
27
+ if (!isId(value.parent) || !isId(value.childRequestId))
28
+ return undefined;
29
+ const address = { parent: value.parent, childRequestId: value.childRequestId };
30
+ switch (value.kind) {
31
+ case "plane.request":
32
+ return isId(value.plane) && "body" in value
33
+ ? { kind: "plane.request", ...address, plane: value.plane, body: value.body }
34
+ : undefined;
35
+ case "plane.abort":
36
+ return { kind: "plane.abort", ...address };
37
+ case "plane.reply":
38
+ return "body" in value ? { kind: "plane.reply", ...address, body: value.body } : undefined;
39
+ default:
40
+ return typeof value.reason === "string"
41
+ ? { kind: "plane.refused", ...address, reason: value.reason }
42
+ : undefined;
43
+ }
44
+ }
45
+ /**
46
+ * The brain's side: admits a request (and an abort) only while its parent is a live call on the lane it came on, serves each
47
+ * (parent, child request) once and answers a replay from the stored answer, and aborts a parent's open requests when
48
+ * the parent ends. Answers are kept for the parent's life only.
49
+ */
50
+ export function createPlaneServer(options) {
51
+ const served = new Map();
52
+ const send = (lane, message) => void options.transport.send(lane, encodePlaneMessage(message)).catch(() => undefined);
53
+ const serve = (lane, request) => {
54
+ const { parent, childRequestId } = request;
55
+ const refuse = (reason) => send(lane, { kind: "plane.refused", parent, childRequestId, reason });
56
+ const parentLane = options.liveLane(parent, request.plane);
57
+ if (parentLane === undefined)
58
+ return refuse("parent_terminal");
59
+ if (parentLane !== lane)
60
+ return refuse("scope_lane_mismatch");
61
+ const children = served.get(parent) ?? new Map();
62
+ served.set(parent, children);
63
+ const known = children.get(childRequestId);
64
+ if (known !== undefined) {
65
+ if (known.answer !== undefined)
66
+ send(lane, known.answer);
67
+ return;
68
+ }
69
+ const handler = Object.hasOwn(options.planes, request.plane) ? options.planes[request.plane] : undefined;
70
+ if (handler === undefined)
71
+ return refuse("plane_unavailable");
72
+ const entry = { controller: new AbortController() };
73
+ children.set(childRequestId, entry);
74
+ void handler(request.body, entry.controller.signal)
75
+ .then((body) => ({ kind: "plane.reply", parent, childRequestId, body }), (error) => ({
76
+ kind: "plane.refused",
77
+ parent,
78
+ childRequestId,
79
+ reason: `plane_failed: ${error instanceof Error ? error.message : String(error)}`,
80
+ }))
81
+ .then((answer) => {
82
+ if (served.get(parent)?.get(childRequestId) !== entry)
83
+ return;
84
+ entry.answer = answer;
85
+ send(lane, answer);
86
+ });
87
+ };
88
+ return {
89
+ receive(lane, message) {
90
+ if (message.kind === "plane.request")
91
+ serve(lane, message);
92
+ else if (message.kind === "plane.abort" && options.liveLane(message.parent) === lane)
93
+ served.get(message.parent)?.get(message.childRequestId)?.controller.abort();
94
+ },
95
+ parentEnded(executionId) {
96
+ const children = served.get(executionId);
97
+ served.delete(executionId);
98
+ for (const entry of children?.values() ?? [])
99
+ entry.controller.abort();
100
+ },
101
+ };
102
+ }
103
+ /** The hand's side: issues a running call's nested requests on its lane and fails them all once the call ends. */
104
+ export function createPlaneClient(options) {
105
+ const mintId = options.mintId ?? (() => crypto.randomUUID());
106
+ const waiting = new Map();
107
+ const live = new Set();
108
+ return {
109
+ requestFor(parent, lane, parentSignal) {
110
+ live.add(parent);
111
+ return (plane, body, signal) => new Promise((resolve, reject) => {
112
+ if (!live.has(parent) || parentSignal.aborted || signal?.aborted)
113
+ return reject(new PlaneRefusedError("parent_terminal"));
114
+ const childRequestId = mintId();
115
+ const children = waiting.get(parent) ?? new Map();
116
+ waiting.set(parent, children);
117
+ const abort = () => {
118
+ if (!children.delete(childRequestId))
119
+ return;
120
+ void options.transport
121
+ .send(lane, encodePlaneMessage({ kind: "plane.abort", parent, childRequestId }))
122
+ .catch(() => undefined);
123
+ reject(new Error("Operation aborted"));
124
+ };
125
+ const release = () => {
126
+ parentSignal.removeEventListener("abort", abort);
127
+ signal?.removeEventListener("abort", abort);
128
+ };
129
+ children.set(childRequestId, {
130
+ resolve: (value) => {
131
+ release();
132
+ resolve(value);
133
+ },
134
+ reject: (error) => {
135
+ release();
136
+ reject(error);
137
+ },
138
+ });
139
+ parentSignal.addEventListener("abort", abort, { once: true });
140
+ signal?.addEventListener("abort", abort, { once: true });
141
+ const request = { kind: "plane.request", parent, childRequestId, plane, body };
142
+ options.transport.send(lane, encodePlaneMessage(request)).catch((error) => {
143
+ if (!children.delete(childRequestId))
144
+ return;
145
+ release();
146
+ reject(new PlaneRefusedError(`brain_unreachable: ${error instanceof Error ? error.message : String(error)}`));
147
+ });
148
+ });
149
+ },
150
+ receive(message) {
151
+ if (message.kind !== "plane.reply" && message.kind !== "plane.refused")
152
+ return;
153
+ const children = waiting.get(message.parent);
154
+ const waiter = children?.get(message.childRequestId);
155
+ if (waiter === undefined)
156
+ return;
157
+ children?.delete(message.childRequestId);
158
+ if (message.kind === "plane.reply")
159
+ waiter.resolve(message.body);
160
+ else
161
+ waiter.reject(new PlaneRefusedError(message.reason));
162
+ },
163
+ parentEnded(parent) {
164
+ live.delete(parent);
165
+ const children = waiting.get(parent);
166
+ waiting.delete(parent);
167
+ for (const waiter of children?.values() ?? [])
168
+ waiter.reject(new PlaneRefusedError("parent_terminal"));
169
+ },
170
+ };
171
+ }
172
+ //# sourceMappingURL=plane.js.map
@@ -0,0 +1,22 @@
1
+ import type { AgentContext, AgentTool, AgentToolCall, AgentToolResult, AgentToolUpdateCallback } from "../../types.ts";
2
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
3
+ import type { PreparationPipeline } from "./executor-types.ts";
4
+ /** What release needs from preparation; it lives in memory with the executor that prepared the call. */
5
+ export interface PreparedBody {
6
+ readonly tool: AgentTool;
7
+ readonly toolCall: AgentToolCall;
8
+ readonly args: unknown;
9
+ readonly assistantMessage: AssistantMessage;
10
+ readonly context: AgentContext;
11
+ /** The model's own name when it resolved to another tool; today's result carries a correction notice for it. */
12
+ readonly requestedName?: string;
13
+ }
14
+ export interface BodyOutcome {
15
+ readonly result: AgentToolResult<unknown>;
16
+ readonly isError: boolean;
17
+ }
18
+ export declare function errorResult(message: string): AgentToolResult<unknown>;
19
+ export declare function messageOf(error: unknown): string;
20
+ export declare function runBody(body: PreparedBody, signal: AbortSignal | undefined, onUpdate: AgentToolUpdateCallback<unknown>): Promise<BodyOutcome>;
21
+ export declare function finalizeBody(body: PreparedBody, executed: BodyOutcome, pipeline: PreparationPipeline, signal: AbortSignal | undefined): Promise<BodyOutcome>;
22
+ //# sourceMappingURL=executor-body.d.ts.map
@@ -0,0 +1,73 @@
1
+ export function errorResult(message) {
2
+ return { content: [{ type: "text", text: message }], details: {} };
3
+ }
4
+ export function messageOf(error) {
5
+ return error instanceof Error ? error.message : String(error);
6
+ }
7
+ const ABORTED = Symbol("aborted");
8
+ // Today's body semantics (agent-loop `executePreparedToolCall`): an abort releases the wait even when the tool never
9
+ // settles, and updates stop at settlement.
10
+ export async function runBody(body, signal, onUpdate) {
11
+ const updates = [];
12
+ let accepting = true;
13
+ try {
14
+ const execution = body.tool.execute(body.toolCall.id, body.args, signal, (partial) => {
15
+ if (accepting)
16
+ updates.push(Promise.resolve(onUpdate(partial)));
17
+ });
18
+ const aborted = signal === undefined
19
+ ? undefined
20
+ : new Promise((resolve) => {
21
+ if (signal.aborted)
22
+ resolve(ABORTED);
23
+ else
24
+ signal.addEventListener("abort", () => resolve(ABORTED), { once: true });
25
+ });
26
+ const settled = aborted ? await Promise.race([execution, aborted]) : await execution;
27
+ accepting = false;
28
+ await Promise.all(updates);
29
+ if (settled === ABORTED) {
30
+ void Promise.resolve(execution).catch(() => undefined);
31
+ return { result: errorResult("Tool execution aborted"), isError: true };
32
+ }
33
+ return { result: settled, isError: settled.isError === true };
34
+ }
35
+ catch (error) {
36
+ accepting = false;
37
+ await Promise.all(updates);
38
+ return { result: errorResult(messageOf(error)), isError: true };
39
+ }
40
+ }
41
+ // Today's after-hook merge (agent-loop `finalizeExecutedToolCall`), field by field.
42
+ export async function finalizeBody(body, executed, pipeline, signal) {
43
+ const { result, isError } = executed;
44
+ try {
45
+ const after = await pipeline.afterToolCall({
46
+ assistantMessage: body.assistantMessage,
47
+ toolCall: body.toolCall,
48
+ args: body.args,
49
+ result,
50
+ isError,
51
+ context: body.context,
52
+ }, signal);
53
+ if (!after)
54
+ return executed;
55
+ const structuredContent = after.structuredContent ?? (after.content ? undefined : result.structuredContent);
56
+ const merged = {
57
+ ...result,
58
+ content: after.content ?? result.content,
59
+ details: after.details ?? result.details,
60
+ usage: after.usage ?? result.usage,
61
+ terminate: after.terminate ?? result.terminate,
62
+ };
63
+ if (structuredContent === undefined)
64
+ delete merged.structuredContent;
65
+ else
66
+ merged.structuredContent = structuredContent;
67
+ return { result: merged, isError: after.isError ?? isError };
68
+ }
69
+ catch (error) {
70
+ return { result: errorResult(messageOf(error)), isError: true };
71
+ }
72
+ }
73
+ //# sourceMappingURL=executor-body.js.map
@@ -0,0 +1,17 @@
1
+ import type { StoreValue } from "../../durable/store.ts";
2
+ import type { AgentToolResult } from "../../types.ts";
3
+ import type { FrozenCall } from "../ledger-types.ts";
4
+ import type { PrepareReply } from "./executor-types.ts";
5
+ /** Tool arguments and results are JSON on every model and wire path; a round trip drops what JSON cannot carry. */
6
+ export declare function toStoreValue(value: unknown): StoreValue;
7
+ /** The call after the whole `tool_call` chain, detached from every object a handler or caller still holds. */
8
+ export declare function freezeCall(name: string, args: unknown): Promise<FrozenCall>;
9
+ /** The durable record of a settled body: what the issuer commits before ACK. Details stay in the in-process reply. */
10
+ export declare function resultValue(result: AgentToolResult<unknown>, isError: boolean, requestedName?: string): StoreValue;
11
+ export type StoppedReply = Extract<PrepareReply, {
12
+ readonly kind: "blocked" | "batch_abort";
13
+ }>;
14
+ /** A preparation that ended without a frozen call, as the ledger's durable `blocked` outcome value. */
15
+ export declare function stoppedValue(reply: StoppedReply): StoreValue;
16
+ export declare function stoppedReply(value: StoreValue): StoppedReply | undefined;
17
+ //# sourceMappingURL=executor-freeze.d.ts.map
@@ -0,0 +1,42 @@
1
+ import { canonicalDigest } from "../canonical-digest.js";
2
+ import { errorResult } from "./executor-body.js";
3
+ /** Tool arguments and results are JSON on every model and wire path; a round trip drops what JSON cannot carry. */
4
+ export function toStoreValue(value) {
5
+ const json = JSON.stringify(value);
6
+ return json === undefined ? null : JSON.parse(json);
7
+ }
8
+ /** The call after the whole `tool_call` chain, detached from every object a handler or caller still holds. */
9
+ export async function freezeCall(name, args) {
10
+ const frozenArgs = toStoreValue(args);
11
+ return { name, args: frozenArgs, digest: await canonicalDigest({ name, args: frozenArgs }) };
12
+ }
13
+ /** The durable record of a settled body: what the issuer commits before ACK. Details stay in the in-process reply. */
14
+ export function resultValue(result, isError, requestedName) {
15
+ return toStoreValue({ content: result.content ?? [], isError, requestedName });
16
+ }
17
+ /** A preparation that ended without a frozen call, as the ledger's durable `blocked` outcome value. */
18
+ export function stoppedValue(reply) {
19
+ const text = (reply.result.content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("");
20
+ const requestedName = reply.kind === "blocked" ? reply.requestedName : undefined;
21
+ return toStoreValue({ kind: reply.kind, text, terminate: reply.result.terminate === true, requestedName });
22
+ }
23
+ /** The reply a re-sent prepare gets back from a durable `blocked` outcome; undefined for a value this module never wrote. */
24
+ function isRecord(value) {
25
+ return value !== null && typeof value === "object" && !Array.isArray(value);
26
+ }
27
+ export function stoppedReply(value) {
28
+ if (!isRecord(value))
29
+ return undefined;
30
+ const { kind, text, terminate, requestedName } = value;
31
+ if (typeof text !== "string" || typeof terminate !== "boolean")
32
+ return undefined;
33
+ const result = errorResult(text);
34
+ if (terminate)
35
+ result.terminate = true;
36
+ if (kind === "batch_abort")
37
+ return { kind, result };
38
+ if (kind !== "blocked")
39
+ return undefined;
40
+ return typeof requestedName === "string" ? { kind, result, requestedName } : { kind, result };
41
+ }
42
+ //# sourceMappingURL=executor-freeze.js.map
@@ -0,0 +1,11 @@
1
+ import type { AgentLoopConfig } from "../../types.ts";
2
+ import type { PreparationPipeline } from "./executor-types.ts";
3
+ /** What preparation reads from an agent or a loop config, at call time. */
4
+ export type PreparationSource = Pick<AgentLoopConfig, "resolveUnknownToolCall" | "beforeToolCall" | "afterToolCall" | "removedToolHints"> & Required<Pick<AgentLoopConfig, "afterToolFreeze">>;
5
+ /**
6
+ * The preparation steps an agent's loop runs today, read from the agent at call time: its resolver (lazy activation),
7
+ * its `beforeToolCall` / `afterToolCall` (the session's `tool_call` and `tool_result` chains) and its removed-tool
8
+ * hints. Building this pipeline installs nothing on the agent.
9
+ */
10
+ export declare function agentPreparationPipeline(agent: PreparationSource): PreparationPipeline;
11
+ //# sourceMappingURL=executor-pipeline.d.ts.map
@@ -0,0 +1,26 @@
1
+ import { resolveToolNameAlias } from "../../tool-name-alias.js";
2
+ /**
3
+ * The preparation steps an agent's loop runs today, read from the agent at call time: its resolver (lazy activation),
4
+ * its `beforeToolCall` / `afterToolCall` (the session's `tool_call` and `tool_result` chains) and its removed-tool
5
+ * hints. Building this pipeline installs nothing on the agent.
6
+ */
7
+ export function agentPreparationPipeline(agent) {
8
+ return {
9
+ resolve: async (call, context) => {
10
+ const tools = context.tools ?? [];
11
+ const exact = tools.find((tool) => tool.name === call.name);
12
+ if (exact)
13
+ return exact;
14
+ const resolved = await agent.resolveUnknownToolCall?.(call.name, context);
15
+ if (resolved)
16
+ return resolved;
17
+ const aliased = resolveToolNameAlias(call.name, tools.map((tool) => tool.name));
18
+ return tools.find((tool) => tool.name === aliased);
19
+ },
20
+ beforeToolCall: async (context, signal) => agent.beforeToolCall?.(context, signal),
21
+ afterToolCall: async (context, signal) => agent.afterToolCall?.(context, signal),
22
+ removedToolHint: (name) => agent.removedToolHints?.[name],
23
+ afterFreeze: (prepared, frozen) => agent.afterToolFreeze(prepared, frozen),
24
+ };
25
+ }
26
+ //# sourceMappingURL=executor-pipeline.js.map