@code-yeongyu/senpi-agent-core 2026.11.4-2 → 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 (100) 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 +7 -0
  5. package/dist/conformance/index.js +4 -0
  6. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  7. package/dist/conformance/loop-core-manifest.js +17 -0
  8. package/dist/conformance/registry.js +11 -17
  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/chain-count.d.ts +26 -0
  14. package/dist/execution/chain-count.js +45 -0
  15. package/dist/execution/coordinator-plan.d.ts +1 -2
  16. package/dist/execution/coordinator-plan.js +4 -17
  17. package/dist/execution/device-files-node.js +39 -1
  18. package/dist/execution/device-files.d.ts +30 -1
  19. package/dist/execution/device-files.js +38 -1
  20. package/dist/execution/ledger-types.d.ts +3 -1
  21. package/dist/execution/ledger.d.ts +9 -3
  22. package/dist/execution/ledger.js +8 -2
  23. package/dist/execution/loop-hook-host-hand.d.ts +33 -0
  24. package/dist/execution/loop-hook-host-hand.js +71 -0
  25. package/dist/execution/loop-hook-host-protocol.d.ts +46 -0
  26. package/dist/execution/loop-hook-host-protocol.js +47 -0
  27. package/dist/execution/loop-hook-host.d.ts +40 -0
  28. package/dist/execution/loop-hook-host.js +87 -0
  29. package/dist/execution/plane-session.d.ts +56 -0
  30. package/dist/execution/plane-session.js +178 -0
  31. package/dist/execution/plane.d.ts +5 -2
  32. package/dist/execution/plane.js +1 -1
  33. package/dist/execution/prepared/executor-body.d.ts +22 -0
  34. package/dist/execution/prepared/executor-body.js +73 -0
  35. package/dist/execution/prepared/executor-freeze.d.ts +17 -0
  36. package/dist/execution/prepared/executor-freeze.js +42 -0
  37. package/dist/execution/prepared/executor-pipeline.d.ts +11 -0
  38. package/dist/execution/prepared/executor-pipeline.js +26 -0
  39. package/dist/execution/prepared/executor-types.d.ts +131 -0
  40. package/dist/execution/prepared/executor-types.js +2 -0
  41. package/dist/execution/prepared/executor.d.ts +8 -0
  42. package/dist/execution/prepared/executor.js +261 -0
  43. package/dist/execution/prepared/memory-batch-store.d.ts +4 -0
  44. package/dist/execution/prepared/memory-batch-store.js +4 -0
  45. package/dist/execution/prepared/pipeline-prepared-batch.d.ts +27 -0
  46. package/dist/execution/prepared/pipeline-prepared-batch.js +175 -0
  47. package/dist/execution/prepared/pipeline-prepared.d.ts +10 -0
  48. package/dist/execution/prepared/pipeline-prepared.js +54 -0
  49. package/dist/execution/remote-device-files.js +33 -4
  50. package/dist/execution/remote-epoch-gate.d.ts +19 -0
  51. package/dist/execution/remote-epoch-gate.js +46 -0
  52. package/dist/execution/remote-epoch.d.ts +53 -0
  53. package/dist/execution/remote-epoch.js +74 -0
  54. package/dist/execution/remote-executor.d.ts +8 -1
  55. package/dist/execution/remote-executor.js +24 -6
  56. package/dist/execution/remote-file-call.js +1 -0
  57. package/dist/execution/remote-hand-ledger.d.ts +11 -3
  58. package/dist/execution/remote-hand-ledger.js +31 -15
  59. package/dist/execution/remote-link.d.ts +6 -1
  60. package/dist/execution/remote-link.js +50 -14
  61. package/dist/execution/remote-protocol.d.ts +30 -1
  62. package/dist/execution/remote-protocol.js +30 -0
  63. package/dist/execution/remote-tool-host.d.ts +12 -0
  64. package/dist/execution/remote-tool-host.js +3 -1
  65. package/dist/execution/testing/epoch-cases.d.ts +8 -0
  66. package/dist/execution/testing/epoch-cases.js +84 -0
  67. package/dist/execution/testing/epoch-harness.d.ts +47 -0
  68. package/dist/execution/testing/epoch-harness.js +172 -0
  69. package/dist/execution/testing/epoch-registry.d.ts +3 -0
  70. package/dist/execution/testing/epoch-registry.js +17 -0
  71. package/dist/execution/testing/hand-harness.d.ts +3 -0
  72. package/dist/execution/testing/hand-harness.js +27 -22
  73. package/dist/execution/testing/hand-registry.d.ts +3 -0
  74. package/dist/execution/testing/hand-registry.js +20 -0
  75. package/dist/execution/testing/kill-epoch.d.ts +9 -0
  76. package/dist/execution/testing/kill-epoch.js +71 -0
  77. package/dist/execution/testing/kill-hook.d.ts +14 -0
  78. package/dist/execution/testing/kill-hook.js +117 -0
  79. package/dist/execution/testing/multi-epoch-cases.d.ts +4 -0
  80. package/dist/execution/testing/multi-epoch-cases.js +29 -0
  81. package/dist/execution/tool-host.d.ts +13 -1
  82. package/dist/execution/tool-host.js +18 -1
  83. package/dist/harness/agent-harness.d.ts +6 -0
  84. package/dist/harness/execution/tool-host-call.d.ts +13 -0
  85. package/dist/harness/execution/tool-host-call.js +55 -0
  86. package/dist/harness/execution/tools.d.ts +2 -1
  87. package/dist/harness/execution/tools.js +32 -17
  88. package/dist/harness/runtime/drive/tools.js +1 -1
  89. package/dist/harness/runtime/harness.js +1 -0
  90. package/dist/harness/runtime/types.d.ts +1 -0
  91. package/dist/index.d.ts +16 -2
  92. package/dist/index.js +14 -1
  93. package/dist/public-entry.d.ts +10 -0
  94. package/dist/public-entry.js +23 -0
  95. package/dist/step-commit.d.ts +24 -0
  96. package/dist/step-commit.js +24 -0
  97. package/dist/tool-name-alias.d.ts +1 -7
  98. package/dist/tool-name-alias.js +0 -17
  99. package/dist/types.d.ts +37 -1
  100. 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
@@ -53,8 +53,11 @@ export declare function decodePlaneMessage(payload: Uint8Array): PlaneMessage |
53
53
  export declare function createPlaneServer(options: {
54
54
  readonly transport: Transport;
55
55
  readonly planes: Readonly<Record<string, PlaneHandler>>;
56
- /** The lane of the live call with this execution ID, or `undefined` once it ended (or never existed). */
57
- readonly liveLane: (executionId: string) => string | undefined;
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;
58
61
  }): {
59
62
  receive(lane: string, message: PlaneMessage): void;
60
63
  parentEnded(executionId: string): void;
@@ -53,7 +53,7 @@ export function createPlaneServer(options) {
53
53
  const serve = (lane, request) => {
54
54
  const { parent, childRequestId } = request;
55
55
  const refuse = (reason) => send(lane, { kind: "plane.refused", parent, childRequestId, reason });
56
- const parentLane = options.liveLane(parent);
56
+ const parentLane = options.liveLane(parent, request.plane);
57
57
  if (parentLane === undefined)
58
58
  return refuse("parent_terminal");
59
59
  if (parentLane !== lane)
@@ -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
@@ -0,0 +1,131 @@
1
+ import type { AfterToolCallContext, AfterToolCallResult, AgentContext, AgentTool, AgentToolCall, AgentToolResult, AgentToolUpdateCallback, BeforeToolCallContext, BeforeToolCallResult } from "../../types.ts";
2
+ import type { ExecutionEntry, ExecutionKey, FrozenCall } from "../ledger-types.ts";
3
+ import type { ExecutionLedger } from "../ledger.ts";
4
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
5
+ /** Today's per-call steps, as the executor runs them; the executor owns their order and the ledger around them. */
6
+ export interface PreparationPipeline {
7
+ /** Exact name, then the host resolver (which may activate a lazy tool), then the alias rule. */
8
+ resolve(call: AgentToolCall, context: AgentContext): Promise<AgentTool | undefined>;
9
+ /** The ordered `tool_call` chain; PreToolUse is one handler in it. */
10
+ beforeToolCall(context: BeforeToolCallContext, signal?: AbortSignal): Promise<BeforeToolCallResult | undefined>;
11
+ afterToolCall(context: AfterToolCallContext, signal?: AbortSignal): Promise<AfterToolCallResult | undefined>;
12
+ removedToolHint(name: string): string | undefined;
13
+ /**
14
+ * Called once per call after its freeze is recorded and before its body is stored: carries the facts the
15
+ * `tool_call` preflight attached to the prepared arguments object over to the frozen copy the tool will execute
16
+ * (senpi#5795). Synchronous and must never throw: a throw here would turn into a block after the freeze.
17
+ */
18
+ afterFreeze(prepared: unknown, frozen: unknown): void;
19
+ }
20
+ export interface PreparedExecutorOptions {
21
+ readonly ledger: ExecutionLedger;
22
+ /** The executor's authenticated identity: the actor of every executor-side ledger event. */
23
+ readonly executor: string;
24
+ readonly pipeline: PreparationPipeline;
25
+ readonly clock?: () => number;
26
+ /**
27
+ * Gate B for a cross-machine executor (design 5.6.1): a frozen call that differs from what Gate A authorized and
28
+ * needs consent waits for an approval of its frozen digest. Absent on fused and split-local executors (K3): no wait.
29
+ */
30
+ readonly consent?: ConsentClassifier;
31
+ }
32
+ /** The engine's own permission classification of a call, without prompting anyone. */
33
+ export interface ConsentClassifier {
34
+ needsConsent(call: {
35
+ readonly name: string;
36
+ readonly args: unknown;
37
+ }): boolean;
38
+ }
39
+ export interface PrepareRequest {
40
+ readonly issuer: string;
41
+ readonly generation: number;
42
+ readonly workspace: string;
43
+ readonly scope: string;
44
+ /** The model's raw call; its id is the execution's command id unless `commandId` names another. */
45
+ readonly call: AgentToolCall;
46
+ /** The execution's command id when the call's own id cannot be one: the model may repeat a call id in one message. */
47
+ readonly commandId?: string;
48
+ readonly assistantMessage: AssistantMessage;
49
+ readonly context: AgentContext;
50
+ /** Issuer-minted with the call, so a re-sent prepare matches its admission exactly. */
51
+ readonly admittedAt: number;
52
+ readonly leaseUntil: number;
53
+ readonly reconcilable?: boolean;
54
+ readonly signal?: AbortSignal;
55
+ /** The raw request digest Gate A approved, if the brain asked; an identical frozen call needs no second approval. */
56
+ readonly authorizedDigest?: string;
57
+ }
58
+ /** `requestedName` is set when the model's name resolved to another tool; the caller adds today's notice. */
59
+ export type PrepareReply = {
60
+ readonly kind: "prepared";
61
+ readonly call: FrozenCall;
62
+ readonly requestedName?: string;
63
+ } | {
64
+ readonly kind: "prepared_awaiting_consent";
65
+ readonly call: FrozenCall;
66
+ readonly requestedName?: string;
67
+ } | {
68
+ readonly kind: "blocked";
69
+ readonly result: AgentToolResult<unknown>;
70
+ readonly requestedName?: string;
71
+ } | {
72
+ readonly kind: "batch_abort";
73
+ readonly result: AgentToolResult<unknown>;
74
+ } | {
75
+ readonly kind: "refused";
76
+ readonly reason: string;
77
+ };
78
+ export interface ReleaseRequest {
79
+ readonly key: ExecutionKey;
80
+ readonly generation: number;
81
+ /** Verified identity of the releasing issuer, supplied by the endpoint. */
82
+ readonly actor: {
83
+ readonly id: string;
84
+ };
85
+ readonly signal?: AbortSignal;
86
+ readonly onUpdate?: AgentToolUpdateCallback<unknown>;
87
+ /** Like `onUpdate`, built from the prepared call it updates (renamed and prepared as the body runs it); wins over it. */
88
+ readonly onUpdateFor?: (toolCall: AgentToolCall) => AgentToolUpdateCallback<unknown>;
89
+ }
90
+ export type ReleaseReply = {
91
+ readonly kind: "settled";
92
+ readonly toolCall: AgentToolCall;
93
+ readonly result: AgentToolResult<unknown>;
94
+ readonly isError: boolean;
95
+ /** Set when the model's name resolved to another tool; the caller adds today's correction notice. */
96
+ readonly requestedName?: string;
97
+ } | {
98
+ readonly kind: "aborted";
99
+ readonly result: AgentToolResult<unknown>;
100
+ } | {
101
+ readonly kind: "replayed";
102
+ readonly entry: ExecutionEntry;
103
+ } | {
104
+ readonly kind: "refused";
105
+ readonly reason: string;
106
+ };
107
+ export interface ConsentRequest {
108
+ readonly key: ExecutionKey;
109
+ readonly generation: number;
110
+ /** Verified identity of the issuer applying the approval, supplied by the endpoint. */
111
+ readonly actor: {
112
+ readonly id: string;
113
+ };
114
+ /** The approval binds this frozen call; an approval of anything else is refused. */
115
+ readonly frozenDigest: string;
116
+ }
117
+ export type ConsentReply = {
118
+ readonly kind: "prepared";
119
+ } | {
120
+ readonly kind: "replayed";
121
+ readonly entry: ExecutionEntry;
122
+ } | {
123
+ readonly kind: "refused";
124
+ readonly reason: string;
125
+ };
126
+ export interface PreparedExecutor {
127
+ prepare(request: PrepareRequest): Promise<PrepareReply>;
128
+ release(request: ReleaseRequest): Promise<ReleaseReply>;
129
+ consent(request: ConsentRequest): Promise<ConsentReply>;
130
+ }
131
+ //# sourceMappingURL=executor-types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=executor-types.js.map
@@ -0,0 +1,8 @@
1
+ import type { PreparedExecutor, PreparedExecutorOptions } from "./executor-types.ts";
2
+ /**
3
+ * The prepared executor (design 5.6.1): PREPARE persists effect_possible, runs today's resolution, shim, validation
4
+ * and `tool_call` chain once, and freezes the result; RELEASE dispatches the frozen call at most once and runs the
5
+ * after-hook once. Nothing here is installed on a session; a caller builds one and drives it.
6
+ */
7
+ export declare function createPreparedExecutor(options: PreparedExecutorOptions): PreparedExecutor;
8
+ //# sourceMappingURL=executor.d.ts.map