@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,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
@@ -0,0 +1,261 @@
1
+ import { prepareAgentToolCall } from "../../agent-loop.js";
2
+ import { canonicalDigest } from "../canonical-digest.js";
3
+ import { errorResult, finalizeBody, messageOf, runBody } from "./executor-body.js";
4
+ import { freezeCall, resultValue, stoppedReply, stoppedValue, toStoreValue, } from "./executor-freeze.js";
5
+ const keyId = ({ issuer, commandId }) => JSON.stringify([issuer, commandId]);
6
+ const keyOf = (request) => ({
7
+ issuer: request.issuer,
8
+ commandId: request.commandId ?? request.call.id,
9
+ });
10
+ function refusal(reply) {
11
+ return { kind: "refused", reason: reply.status === "refused" ? reply.reason : reply.status };
12
+ }
13
+ // Today's message for a call the response cut off (agent-loop `createIncompleteToolCallErrorMessage`).
14
+ function incompleteMessage(name, errorMessage) {
15
+ if (errorMessage !== undefined) {
16
+ return `${errorMessage}${errorMessage.endsWith(".") ? "" : "."} Re-issue the tool call with complete arguments.`;
17
+ }
18
+ return `Tool call "${name}" was not executed: the response ended before the tool call was complete because it hit the output token limit. Re-issue the tool call with complete arguments.`;
19
+ }
20
+ /** A durable row that already passed admission: answer from it and never run preparation again. */
21
+ function fromRow(entry) {
22
+ const progress = entry.progress;
23
+ if (progress.state === "prepared_awaiting_consent")
24
+ return { kind: "prepared_awaiting_consent", call: progress.call };
25
+ if ("call" in progress)
26
+ return { kind: "prepared", call: progress.call };
27
+ if (progress.state !== "settled")
28
+ return { kind: "refused", reason: progress.state };
29
+ const outcome = progress.outcome;
30
+ if (outcome.reason !== "blocked")
31
+ return { kind: "refused", reason: "terminal" };
32
+ return stoppedReply(outcome.value) ?? { kind: "refused", reason: "corrupt_blocked_outcome" };
33
+ }
34
+ /**
35
+ * The prepared executor (design 5.6.1): PREPARE persists effect_possible, runs today's resolution, shim, validation
36
+ * and `tool_call` chain once, and freezes the result; RELEASE dispatches the frozen call at most once and runs the
37
+ * after-hook once. Nothing here is installed on a session; a caller builds one and drives it.
38
+ */
39
+ export function createPreparedExecutor(options) {
40
+ const { ledger, executor, pipeline } = options;
41
+ const clock = options.clock ?? Date.now;
42
+ const preparations = new Map();
43
+ const bodies = new Map();
44
+ const releases = new Map();
45
+ const step = (key, generation, event) => ledger.apply({ key, generation, actor: { id: executor }, now: clock(), event });
46
+ // A preparation that ends without a frozen call is terminal and durable, so a re-sent prepare (also from a new
47
+ // executor process after restart) gets this reply back instead of a restart-recovered `hand_restarted`.
48
+ async function stop(key, generation, reply) {
49
+ const recorded = await step(key, generation, { kind: "block", value: stoppedValue(reply) });
50
+ if (recorded.status === "applied")
51
+ return reply;
52
+ return recorded.status === "replayed" ? fromRow(recorded.entry) : refusal(recorded);
53
+ }
54
+ async function prepareOnce(request, requestDigest) {
55
+ const { call, generation, signal } = request;
56
+ const key = keyOf(request);
57
+ const admitted = await ledger.admit({
58
+ ...key,
59
+ executor,
60
+ workspace: request.workspace,
61
+ scope: request.scope,
62
+ generation,
63
+ requestDigest,
64
+ admittedAt: request.admittedAt,
65
+ leaseUntil: request.leaseUntil,
66
+ reconcilable: request.reconcilable ?? false,
67
+ });
68
+ if (admitted.status === "replayed")
69
+ return fromRow(admitted.entry);
70
+ if (admitted.status !== "applied")
71
+ return refusal(admitted);
72
+ const preparing = await step(key, generation, { kind: "prepare" });
73
+ if (preparing.status !== "applied")
74
+ return refusal(preparing);
75
+ if (call.incomplete === true) {
76
+ return stop(key, generation, {
77
+ kind: "blocked",
78
+ result: errorResult(incompleteMessage(call.name, call.errorMessage)),
79
+ });
80
+ }
81
+ const effect = await step(key, generation, { kind: "effect" });
82
+ if (effect.status !== "applied")
83
+ return refusal(effect);
84
+ let tool;
85
+ try {
86
+ tool = await pipeline.resolve(call, request.context);
87
+ }
88
+ catch (error) {
89
+ return stop(key, generation, { kind: "blocked", result: errorResult(messageOf(error)) });
90
+ }
91
+ if (!tool) {
92
+ const hint = pipeline.removedToolHint(call.name);
93
+ const text = hint === undefined ? `Tool ${call.name} not found` : `Tool ${call.name} not found. ${hint}`;
94
+ return stop(key, generation, { kind: "blocked", result: errorResult(text) });
95
+ }
96
+ const requestedName = tool.name === call.name ? undefined : call.name;
97
+ const named = requestedName === undefined ? {} : { requestedName };
98
+ try {
99
+ const prepared = prepareAgentToolCall(tool, requestedName === undefined ? call : { ...call, name: tool.name });
100
+ const before = await pipeline.beforeToolCall({
101
+ assistantMessage: request.assistantMessage,
102
+ toolCall: prepared.toolCall,
103
+ args: prepared.args,
104
+ context: request.context,
105
+ }, signal);
106
+ if (signal?.aborted)
107
+ return stop(key, generation, { kind: "batch_abort", result: errorResult("Operation aborted") });
108
+ if (before?.block) {
109
+ const result = errorResult(before.reason || "Tool execution was blocked");
110
+ if (before.terminate === true)
111
+ result.terminate = true;
112
+ return stop(key, generation, { kind: "blocked", result, ...named });
113
+ }
114
+ const frozen = await freezeCall(tool.name, prepared.args);
115
+ // Gate A approved this exact request; it covers the frozen call only when preparation left the call unchanged.
116
+ const covered = request.authorizedDigest === requestDigest &&
117
+ (await freezeCall(call.name, toStoreValue(call.arguments))).digest === frozen.digest;
118
+ const awaitingConsent = options.consent !== undefined &&
119
+ !covered &&
120
+ options.consent.needsConsent({ name: frozen.name, args: frozen.args });
121
+ const freeze = await step(key, generation, { kind: "freeze", call: frozen, awaitingConsent });
122
+ if (freeze.status !== "applied")
123
+ return refusal(freeze);
124
+ pipeline.afterFreeze(prepared.args, frozen.args);
125
+ bodies.set(keyId(key), {
126
+ ...named,
127
+ tool,
128
+ toolCall: prepared.toolCall,
129
+ args: frozen.args,
130
+ assistantMessage: request.assistantMessage,
131
+ context: request.context,
132
+ });
133
+ return { kind: awaitingConsent ? "prepared_awaiting_consent" : "prepared", call: frozen, ...named };
134
+ }
135
+ catch (error) {
136
+ return stop(key, generation, { kind: "blocked", result: errorResult(messageOf(error)), ...named });
137
+ }
138
+ }
139
+ async function terminalRow(key) {
140
+ const entry = await ledger.read(key);
141
+ if (entry === undefined)
142
+ return { kind: "refused", reason: "not_found" };
143
+ const progress = entry.progress;
144
+ // A blocked call never had a body: release on it is refused, not replayed.
145
+ if (progress.state === "settled" && progress.outcome.reason === "blocked")
146
+ return { kind: "refused", reason: "blocked" };
147
+ return { kind: "replayed", entry };
148
+ }
149
+ async function runReleased(request, body) {
150
+ const { key, generation, signal } = request;
151
+ const dispatched = await step(key, generation, { kind: "dispatch" });
152
+ if (dispatched.status === "replayed")
153
+ return { kind: "replayed", entry: dispatched.entry };
154
+ if (dispatched.status !== "applied" || dispatched.entry.progress.state !== "dispatched") {
155
+ return refusal(dispatched);
156
+ }
157
+ const executed = await runBody(body, signal, request.onUpdateFor?.(body.toolCall) ?? request.onUpdate ?? (() => { }));
158
+ const { result, isError } = await finalizeBody(body, executed, pipeline, signal);
159
+ const value = resultValue(result, isError, body.requestedName);
160
+ const recorded = await step(key, generation, { kind: "result", value });
161
+ for (const memo of [bodies, preparations, releases])
162
+ memo.delete(keyId(key));
163
+ // A cancel or lease expiry that settled first stays terminal; the late body result is audit only.
164
+ if (recorded.status === "replayed")
165
+ return { kind: "replayed", entry: recorded.entry };
166
+ if (recorded.status !== "applied")
167
+ return refusal(recorded);
168
+ const named = body.requestedName === undefined ? {} : { requestedName: body.requestedName };
169
+ return { kind: "settled", toolCall: body.toolCall, result, isError, ...named };
170
+ }
171
+ // Every release reaches the ledger with its own actor and generation before any memo is read or written, so a
172
+ // wrong actor or an old generation is refused there and can never answer, or block, the issuer's own release.
173
+ async function release(request) {
174
+ const { key, generation } = request;
175
+ const released = await ledger.apply({
176
+ key,
177
+ generation,
178
+ actor: request.actor,
179
+ now: clock(),
180
+ event: { kind: "release" },
181
+ });
182
+ if (released.status === "refused")
183
+ return released.reason === "terminal" ? terminalRow(key) : refusal(released);
184
+ if (released.status === "result_expired")
185
+ return refusal(released);
186
+ const id = keyId(key);
187
+ const pending = releases.get(id);
188
+ if (pending !== undefined)
189
+ return pending;
190
+ const body = bodies.get(id);
191
+ if (body === undefined)
192
+ return { kind: "refused", reason: "not_prepared" };
193
+ // Today's loop never starts a body once the run is aborted; the call stays released for the issuer's abort.
194
+ if (request.signal?.aborted)
195
+ return { kind: "aborted", result: errorResult("Operation aborted") };
196
+ const reply = runReleased(request, body);
197
+ releases.set(id, reply);
198
+ void reply.catch(() => releases.get(id) === reply && releases.delete(id));
199
+ return reply;
200
+ }
201
+ // An approval reaches the ledger as the issuer's own `consent` event and only for the frozen call it names; a lease
202
+ // that ran out first settles the call `lease_expired`, so the approval answers with that terminal row.
203
+ async function consent(request) {
204
+ const entry = await ledger.read(request.key);
205
+ if (entry === undefined)
206
+ return { kind: "refused", reason: "not_found" };
207
+ if ("call" in entry.progress && entry.progress.call.digest !== request.frozenDigest)
208
+ return { kind: "refused", reason: "frozen_digest_mismatch" };
209
+ const reply = await ledger.apply({
210
+ key: request.key,
211
+ generation: request.generation,
212
+ actor: request.actor,
213
+ now: clock(),
214
+ event: { kind: "consent" },
215
+ });
216
+ if (reply.status === "applied" && reply.entry.progress.state === "prepared")
217
+ return { kind: "prepared" };
218
+ // The issuer's re-sent approval (the brain restarted before recording the first reply) finds the call prepared.
219
+ if (reply.status === "refused" && reply.reason === "invalid_transition" && entry.progress.state === "prepared")
220
+ return { kind: "prepared" };
221
+ if (reply.status === "applied" || reply.status === "replayed")
222
+ return { kind: "replayed", entry: reply.entry };
223
+ if (reply.status === "refused" && reply.reason === "terminal") {
224
+ const terminal = await ledger.read(request.key);
225
+ return terminal === undefined
226
+ ? { kind: "refused", reason: "not_found" }
227
+ : { kind: "replayed", entry: terminal };
228
+ }
229
+ return refusal(reply);
230
+ }
231
+ return {
232
+ consent,
233
+ prepare: async (request) => {
234
+ const { name, arguments: args, incomplete, errorMessage } = request.call;
235
+ const requestDigest = await canonicalDigest(toStoreValue({ name, args, incomplete, errorMessage }));
236
+ const admission = JSON.stringify([
237
+ request.generation,
238
+ request.workspace,
239
+ request.scope,
240
+ requestDigest,
241
+ request.admittedAt,
242
+ request.leaseUntil,
243
+ request.reconcilable ?? false,
244
+ ]);
245
+ const id = keyId(keyOf(request));
246
+ const pending = preparations.get(id);
247
+ if (pending !== undefined && pending.admission === admission)
248
+ return pending.reply;
249
+ if (pending !== undefined)
250
+ return { kind: "refused", reason: "identity_conflict" };
251
+ const reply = prepareOnce(request, requestDigest);
252
+ preparations.set(id, { admission, reply });
253
+ // Only a prepared call keeps its memo (release needs it); every other reply is durable or retryable.
254
+ const forget = () => preparations.get(id)?.reply === reply && preparations.delete(id);
255
+ void reply.then((settled) => settled.kind === "prepared" || settled.kind === "prepared_awaiting_consent" || forget(), forget);
256
+ return reply;
257
+ },
258
+ release,
259
+ };
260
+ }
261
+ //# sourceMappingURL=executor.js.map
@@ -0,0 +1,4 @@
1
+ import type { BatchStoreFactory } from "../../types.ts";
2
+ /** A batch ledger that lives only in this process for the batch's duration: the in-process (fused) placement. */
3
+ export declare const openMemoryBatchStore: BatchStoreFactory;
4
+ //# sourceMappingURL=memory-batch-store.d.ts.map
@@ -0,0 +1,4 @@
1
+ import { createMemoryStoreMedium, openMemoryStore } from "../../durable/store-memory.js";
2
+ /** A batch ledger that lives only in this process for the batch's duration: the in-process (fused) placement. */
3
+ export const openMemoryBatchStore = () => openMemoryStore(createMemoryStoreMedium());
4
+ //# sourceMappingURL=memory-batch-store.js.map
@@ -0,0 +1,27 @@
1
+ import type { AgentContext, AgentEvent, AgentToolCall, AgentToolCallOutcome, BatchStoreFactory } from "../../types.ts";
2
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
3
+ import { type PreparationSource } from "./executor-pipeline.ts";
4
+ type Emit = (event: AgentEvent) => Promise<void> | void;
5
+ export interface PreparedBatchRequest {
6
+ readonly source: PreparationSource;
7
+ readonly calls: readonly AgentToolCall[];
8
+ readonly scope: {
9
+ readonly id: string;
10
+ readonly root: string;
11
+ };
12
+ readonly context: AgentContext;
13
+ readonly assistantMessage: AssistantMessage;
14
+ readonly emit: Emit;
15
+ readonly signal?: AbortSignal;
16
+ readonly openStore: BatchStoreFactory;
17
+ }
18
+ /**
19
+ * Runs one batch through the prepared pipeline (S18b): the batch coordinator prepares every call in source order on the
20
+ * in-process prepared executor, decides once, then releases by dependencies. The loop's events are emitted where
21
+ * today's scheduler emits them; the returned outcomes are the calls that started, in source order. A call's command ID
22
+ * is its block position in the batch, not the model's call ID: a model may repeat a call ID inside one message, and
23
+ * today's scheduler runs each such block as its own call. Each batch runs on its own in-memory ledger.
24
+ */
25
+ export declare function runPreparedBatch(request: PreparedBatchRequest): Promise<AgentToolCallOutcome[]>;
26
+ export {};
27
+ //# sourceMappingURL=pipeline-prepared-batch.d.ts.map
@@ -0,0 +1,175 @@
1
+ import { createAdmissionLine } from "../../durable/store-admission.js";
2
+ import { resolveToolNameAlias, withToolNameCorrection } from "../../tool-name-alias.js";
3
+ import { createBatchCoordinator } from "../coordinator.js";
4
+ import { createExecutionLedger } from "../ledger.js";
5
+ import { createErrorToolResult, emitToolExecutionEnd, emitToolExecutionUpdate } from "../tool-outcome-events.js";
6
+ import { createPreparedExecutor } from "./executor.js";
7
+ import { toStoreValue } from "./executor-freeze.js";
8
+ import { agentPreparationPipeline } from "./executor-pipeline.js";
9
+ const ISSUER = "loop";
10
+ const EXECUTOR = "local";
11
+ const LEASE_MS = 24 * 60 * 60 * 1000;
12
+ // The ledger admits no call without a workspace, and a loop built with no execution scope has an empty root. The
13
+ // batch's ledger lives only for this batch, so the name only has to be non-empty.
14
+ const NO_WORKSPACE = "in-process";
15
+ /** The scheduler's sequential test, decided before preparation: exact name, then the alias rule; an unresolved name runs in parallel. */
16
+ function isSequential(context, name) {
17
+ const tools = context.tools ?? [];
18
+ const named = resolveToolNameAlias(name, tools.map((tool) => tool.name));
19
+ const tool = tools.find((candidate) => candidate.name === name) ?? tools.find((candidate) => candidate.name === named);
20
+ return tool?.executionMode === "sequential";
21
+ }
22
+ /**
23
+ * Runs one batch through the prepared pipeline (S18b): the batch coordinator prepares every call in source order on the
24
+ * in-process prepared executor, decides once, then releases by dependencies. The loop's events are emitted where
25
+ * today's scheduler emits them; the returned outcomes are the calls that started, in source order. A call's command ID
26
+ * is its block position in the batch, not the model's call ID: a model may repeat a call ID inside one message, and
27
+ * today's scheduler runs each such block as its own call. Each batch runs on its own in-memory ledger.
28
+ */
29
+ export async function runPreparedBatch(request) {
30
+ const { source, calls, context, assistantMessage, emit, signal } = request;
31
+ const store = request.openStore();
32
+ await store.claim(0, 1);
33
+ const admission = createAdmissionLine();
34
+ const base = agentPreparationPipeline(source);
35
+ // Keyed by the call itself: two blocks of one message may share a call ID but never a call.
36
+ const resolved = new Map();
37
+ const prepared = createPreparedExecutor({
38
+ ledger: createExecutionLedger({ store, epoch: 1, admission }),
39
+ executor: EXECUTOR,
40
+ pipeline: { ...base, resolve: async (call) => resolved.get(call) },
41
+ });
42
+ const executionIdOf = (index) => String(index);
43
+ const byExecution = new Map(calls.map((call, index) => [executionIdOf(index), call]));
44
+ // Every map below is keyed by execution ID (the block), never by the model's call ID.
45
+ const renamed = new Map();
46
+ const named = (id, call) => renamed.get(id) ?? call;
47
+ const callOf = (id) => {
48
+ const call = byExecution.get(id);
49
+ if (call === undefined)
50
+ throw new Error(`prepared pipeline: unknown execution ${id}`);
51
+ return call;
52
+ };
53
+ const started = new Set();
54
+ const pending = new Map();
55
+ const finalized = new Map();
56
+ const finish = async (id, outcome) => {
57
+ finalized.set(id, outcome);
58
+ await emitToolExecutionEnd(outcome, emit);
59
+ };
60
+ const aborted = (call) => ({
61
+ toolCall: call,
62
+ result: createErrorToolResult("Operation aborted"),
63
+ isError: true,
64
+ });
65
+ const endpoint = {
66
+ prepare: async (ref) => {
67
+ const id = ref.executionId;
68
+ const call = callOf(id);
69
+ if (signal?.aborted && started.size > 0)
70
+ return { kind: "batch_abort" };
71
+ const tool = call.incomplete === true ? undefined : await base.resolve(call, context);
72
+ resolved.set(call, tool);
73
+ if (tool !== undefined && tool.name !== call.name)
74
+ renamed.set(id, { ...call, name: tool.name });
75
+ await emit({
76
+ type: "tool_execution_start",
77
+ toolCallId: call.id,
78
+ toolName: tool?.name ?? call.name,
79
+ args: call.arguments,
80
+ });
81
+ started.add(id);
82
+ const reply = await prepared.prepare({
83
+ issuer: ISSUER,
84
+ commandId: id,
85
+ generation: ref.generation,
86
+ workspace: ref.workspace,
87
+ scope: ref.scope,
88
+ call,
89
+ assistantMessage,
90
+ context,
91
+ admittedAt: ref.admittedAt,
92
+ leaseUntil: ref.leaseUntil,
93
+ ...(signal === undefined ? {} : { signal }),
94
+ });
95
+ if (signal?.aborted) {
96
+ pending.set(id, aborted(named(id, call)));
97
+ return { kind: "batch_abort" };
98
+ }
99
+ if (reply.kind === "prepared")
100
+ return { kind: "prepared", frozenDigest: reply.call.digest };
101
+ if (reply.kind === "prepared_awaiting_consent")
102
+ return { kind: "prepared_awaiting_consent", frozenDigest: reply.call.digest };
103
+ if (reply.kind === "refused")
104
+ throw new Error(`prepared pipeline refused ${call.id}: ${reply.reason}`);
105
+ const result = reply.kind === "blocked" && reply.requestedName !== undefined && tool !== undefined
106
+ ? withToolNameCorrection(reply.result, reply.requestedName, tool.name)
107
+ : reply.result;
108
+ pending.set(id, { toolCall: named(id, call), result, isError: true });
109
+ const value = toStoreValue({ content: result.content ?? [] });
110
+ return reply.kind === "blocked" ? { kind: "blocked", result: value } : { kind: "batch_abort" };
111
+ },
112
+ release: async (ref) => {
113
+ const id = ref.executionId;
114
+ const call = callOf(id);
115
+ const reply = await prepared.release({
116
+ key: { issuer: ISSUER, commandId: id },
117
+ generation: ref.generation,
118
+ actor: { id: ISSUER },
119
+ onUpdateFor: (toolCall) => emitToolExecutionUpdate(toolCall, emit),
120
+ ...(signal === undefined ? {} : { signal }),
121
+ });
122
+ if (reply.kind === "settled") {
123
+ const result = reply.requestedName === undefined
124
+ ? reply.result
125
+ : withToolNameCorrection(reply.result, reply.requestedName, reply.toolCall.name);
126
+ await finish(id, { toolCall: reply.toolCall, result, isError: reply.isError });
127
+ return {
128
+ kind: "settled",
129
+ outcome: {
130
+ reason: "result",
131
+ value: toStoreValue(result.content ?? []),
132
+ hooksRan: true,
133
+ uncertain: false,
134
+ },
135
+ };
136
+ }
137
+ if (reply.kind !== "aborted")
138
+ throw new Error(`prepared pipeline: release ${reply.kind} for ${call.id}`);
139
+ await finish(id, signal?.aborted
140
+ ? aborted(named(id, call))
141
+ : { toolCall: named(id, call), result: reply.result, isError: true });
142
+ return { kind: "settled", outcome: { reason: "cancelled", hooksRan: true, uncertain: false } };
143
+ },
144
+ abort: async (ref) => {
145
+ const id = ref.executionId;
146
+ const call = callOf(id);
147
+ if (started.has(id))
148
+ await finish(id, signal?.aborted ? aborted(named(id, call)) : (pending.get(id) ?? aborted(named(id, call))));
149
+ return { kind: "settled", outcome: { reason: "cancelled", hooksRan: false, uncertain: false } };
150
+ },
151
+ };
152
+ const now = Date.now();
153
+ const plan = {
154
+ batchId: crypto.randomUUID(),
155
+ scope: request.scope.id,
156
+ workspace: request.scope.root === "" ? NO_WORKSPACE : request.scope.root,
157
+ generation: 1,
158
+ admittedAt: now,
159
+ leaseUntil: now + LEASE_MS,
160
+ calls: calls.map((call, index) => ({
161
+ executionId: executionIdOf(index),
162
+ executor: EXECUTOR,
163
+ name: call.name,
164
+ args: toStoreValue(call.arguments),
165
+ sequential: isSequential(context, call.name),
166
+ })),
167
+ };
168
+ await createBatchCoordinator({ issuer: ISSUER, store, epoch: 1, admission, executor: () => endpoint }).run(plan);
169
+ return calls.flatMap((_call, index) => {
170
+ const id = executionIdOf(index);
171
+ const outcome = finalized.get(id);
172
+ return started.has(id) && outcome !== undefined ? [outcome] : [];
173
+ });
174
+ }
175
+ //# sourceMappingURL=pipeline-prepared-batch.js.map
@@ -0,0 +1,10 @@
1
+ import type { BatchStoreFactory } from "../../types.ts";
2
+ import type { ToolHost } from "../tool-host.ts";
3
+ import type { PreparationSource } from "./executor-pipeline.ts";
4
+ /**
5
+ * The prepared pipeline as the session's ToolHost (S18b): every model-issued batch runs through the batch coordinator
6
+ * and the prepared executor in this process, with today's events, result messages and source order. A batch the loop
7
+ * runs sequentially runs as consecutive one-call batches, so each call is prepared after the previous one finished.
8
+ */
9
+ export declare function createPreparedToolHost(source: PreparationSource, openStore: BatchStoreFactory): ToolHost;
10
+ //# sourceMappingURL=pipeline-prepared.d.ts.map