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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/agent-loop.js +14 -140
  2. package/dist/agent.d.ts +4 -0
  3. package/dist/agent.js +4 -0
  4. package/dist/conformance/index.d.ts +12 -1
  5. package/dist/conformance/index.js +6 -0
  6. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  7. package/dist/conformance/loop-core-manifest.js +18 -0
  8. package/dist/conformance/registry.js +11 -17
  9. package/dist/durable/session-store.d.ts +42 -0
  10. package/dist/durable/session-store.js +124 -0
  11. package/dist/durable/store-memory.d.ts +2 -2
  12. package/dist/durable/store-memory.js +36 -34
  13. package/dist/durable/store.d.ts +9 -0
  14. package/dist/durable/testing/store-harness.d.ts +1 -0
  15. package/dist/durable/testing/store-harness.js +1 -0
  16. package/dist/durable/testing/sync-commit-cases.d.ts +20 -0
  17. package/dist/durable/testing/sync-commit-cases.js +89 -0
  18. package/dist/egress/types.d.ts +102 -0
  19. package/dist/egress/types.js +7 -0
  20. package/dist/execution/canonical-digest.d.ts +10 -0
  21. package/dist/execution/canonical-digest.js +20 -0
  22. package/dist/execution/chain-count.d.ts +26 -0
  23. package/dist/execution/chain-count.js +45 -0
  24. package/dist/execution/coordinator-plan.d.ts +1 -2
  25. package/dist/execution/coordinator-plan.js +4 -17
  26. package/dist/execution/device-files-node.js +40 -1
  27. package/dist/execution/device-files.d.ts +39 -1
  28. package/dist/execution/device-files.js +48 -1
  29. package/dist/execution/ledger-types.d.ts +3 -1
  30. package/dist/execution/ledger.d.ts +9 -3
  31. package/dist/execution/ledger.js +8 -2
  32. package/dist/execution/loop-hook-host-hand.d.ts +33 -0
  33. package/dist/execution/loop-hook-host-hand.js +71 -0
  34. package/dist/execution/loop-hook-host-protocol.d.ts +46 -0
  35. package/dist/execution/loop-hook-host-protocol.js +47 -0
  36. package/dist/execution/loop-hook-host.d.ts +40 -0
  37. package/dist/execution/loop-hook-host.js +87 -0
  38. package/dist/execution/plane-session.d.ts +56 -0
  39. package/dist/execution/plane-session.js +178 -0
  40. package/dist/execution/plane.d.ts +5 -2
  41. package/dist/execution/plane.js +1 -1
  42. package/dist/execution/prepared/executor-body.d.ts +22 -0
  43. package/dist/execution/prepared/executor-body.js +73 -0
  44. package/dist/execution/prepared/executor-freeze.d.ts +22 -0
  45. package/dist/execution/prepared/executor-freeze.js +55 -0
  46. package/dist/execution/prepared/executor-pipeline.d.ts +11 -0
  47. package/dist/execution/prepared/executor-pipeline.js +26 -0
  48. package/dist/execution/prepared/executor-types.d.ts +131 -0
  49. package/dist/execution/prepared/executor-types.js +2 -0
  50. package/dist/execution/prepared/executor.d.ts +8 -0
  51. package/dist/execution/prepared/executor.js +260 -0
  52. package/dist/execution/prepared/memory-batch-store.d.ts +4 -0
  53. package/dist/execution/prepared/memory-batch-store.js +4 -0
  54. package/dist/execution/prepared/pipeline-prepared-batch.d.ts +27 -0
  55. package/dist/execution/prepared/pipeline-prepared-batch.js +175 -0
  56. package/dist/execution/prepared/pipeline-prepared.d.ts +10 -0
  57. package/dist/execution/prepared/pipeline-prepared.js +54 -0
  58. package/dist/execution/remote-device-files.js +33 -4
  59. package/dist/execution/remote-epoch-gate.d.ts +19 -0
  60. package/dist/execution/remote-epoch-gate.js +46 -0
  61. package/dist/execution/remote-epoch.d.ts +53 -0
  62. package/dist/execution/remote-epoch.js +74 -0
  63. package/dist/execution/remote-executor.d.ts +8 -1
  64. package/dist/execution/remote-executor.js +24 -6
  65. package/dist/execution/remote-file-call.js +1 -0
  66. package/dist/execution/remote-hand-ledger.d.ts +11 -3
  67. package/dist/execution/remote-hand-ledger.js +31 -15
  68. package/dist/execution/remote-link.d.ts +6 -1
  69. package/dist/execution/remote-link.js +50 -14
  70. package/dist/execution/remote-protocol.d.ts +30 -1
  71. package/dist/execution/remote-protocol.js +30 -0
  72. package/dist/execution/remote-tool-host.d.ts +12 -0
  73. package/dist/execution/remote-tool-host.js +3 -1
  74. package/dist/execution/testing/epoch-cases.d.ts +8 -0
  75. package/dist/execution/testing/epoch-cases.js +84 -0
  76. package/dist/execution/testing/epoch-harness.d.ts +47 -0
  77. package/dist/execution/testing/epoch-harness.js +172 -0
  78. package/dist/execution/testing/epoch-registry.d.ts +3 -0
  79. package/dist/execution/testing/epoch-registry.js +17 -0
  80. package/dist/execution/testing/hand-harness.d.ts +5 -0
  81. package/dist/execution/testing/hand-harness.js +57 -24
  82. package/dist/execution/testing/hand-registry.d.ts +3 -0
  83. package/dist/execution/testing/hand-registry.js +20 -0
  84. package/dist/execution/testing/kill-epoch.d.ts +9 -0
  85. package/dist/execution/testing/kill-epoch.js +71 -0
  86. package/dist/execution/testing/kill-hook.d.ts +14 -0
  87. package/dist/execution/testing/kill-hook.js +117 -0
  88. package/dist/execution/testing/multi-epoch-cases.d.ts +4 -0
  89. package/dist/execution/testing/multi-epoch-cases.js +29 -0
  90. package/dist/execution/testing/multi-hand-cases.js +1 -1
  91. package/dist/execution/tool-host.d.ts +16 -1
  92. package/dist/execution/tool-host.js +18 -1
  93. package/dist/harness/agent-harness.d.ts +6 -0
  94. package/dist/harness/execution/tool-host-call.d.ts +14 -0
  95. package/dist/harness/execution/tool-host-call.js +56 -0
  96. package/dist/harness/execution/tools.d.ts +2 -1
  97. package/dist/harness/execution/tools.js +45 -17
  98. package/dist/harness/runtime/drive/tools.js +1 -1
  99. package/dist/harness/runtime/harness.js +1 -0
  100. package/dist/harness/runtime/types.d.ts +1 -0
  101. package/dist/harness/tools/read.js +1 -1
  102. package/dist/index.d.ts +19 -2
  103. package/dist/index.js +15 -1
  104. package/dist/public-entry.d.ts +10 -0
  105. package/dist/public-entry.js +23 -0
  106. package/dist/step-commit.d.ts +24 -0
  107. package/dist/step-commit.js +24 -0
  108. package/dist/tool-name-alias.d.ts +1 -7
  109. package/dist/tool-name-alias.js +0 -17
  110. package/dist/types.d.ts +37 -1
  111. package/package.json +3 -3
@@ -0,0 +1,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,22 @@
1
+ import type { StoreValue } from "../../durable/store.ts";
2
+ import type { FrozenCall } from "../ledger-types.ts";
3
+ import { type BodyOutcome } from "./executor-body.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
+ /**
10
+ * A settled body and its durable record. Content JSON cannot carry (an untyped tool breaking the content contract) settles
11
+ * the call as a tool error naming the problem, never as a rejection of the whole release (senpi#5864).
12
+ */
13
+ export declare function recordedResult(outcome: BodyOutcome, requestedName: string | undefined): BodyOutcome & {
14
+ readonly value: StoreValue;
15
+ };
16
+ export type StoppedReply = Extract<PrepareReply, {
17
+ readonly kind: "blocked" | "batch_abort";
18
+ }>;
19
+ /** A preparation that ended without a frozen call, as the ledger's durable `blocked` outcome value. */
20
+ export declare function stoppedValue(reply: StoppedReply): StoreValue;
21
+ export declare function stoppedReply(value: StoreValue): StoppedReply | undefined;
22
+ //# sourceMappingURL=executor-freeze.d.ts.map
@@ -0,0 +1,55 @@
1
+ import { canonicalDigest } from "../canonical-digest.js";
2
+ import { errorResult, messageOf } 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
+ function resultValue(result, isError, requestedName) {
15
+ return toStoreValue({ content: result.content ?? [], isError, requestedName });
16
+ }
17
+ /**
18
+ * A settled body and its durable record. Content JSON cannot carry (an untyped tool breaking the content contract) settles
19
+ * the call as a tool error naming the problem, never as a rejection of the whole release (senpi#5864).
20
+ */
21
+ export function recordedResult(outcome, requestedName) {
22
+ try {
23
+ return { ...outcome, value: resultValue(outcome.result, outcome.isError, requestedName) };
24
+ }
25
+ catch (error) {
26
+ const result = errorResult(`Tool result content is not JSON: ${messageOf(error)}`);
27
+ return { result, isError: true, value: resultValue(result, true, requestedName) };
28
+ }
29
+ }
30
+ /** A preparation that ended without a frozen call, as the ledger's durable `blocked` outcome value. */
31
+ export function stoppedValue(reply) {
32
+ const text = (reply.result.content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("");
33
+ const requestedName = reply.kind === "blocked" ? reply.requestedName : undefined;
34
+ return toStoreValue({ kind: reply.kind, text, terminate: reply.result.terminate === true, requestedName });
35
+ }
36
+ /** The reply a re-sent prepare gets back from a durable `blocked` outcome; undefined for a value this module never wrote. */
37
+ function isRecord(value) {
38
+ return value !== null && typeof value === "object" && !Array.isArray(value);
39
+ }
40
+ export function stoppedReply(value) {
41
+ if (!isRecord(value))
42
+ return undefined;
43
+ const { kind, text, terminate, requestedName } = value;
44
+ if (typeof text !== "string" || typeof terminate !== "boolean")
45
+ return undefined;
46
+ const result = errorResult(text);
47
+ if (terminate)
48
+ result.terminate = true;
49
+ if (kind === "batch_abort")
50
+ return { kind, result };
51
+ if (kind !== "blocked")
52
+ return undefined;
53
+ return typeof requestedName === "string" ? { kind, result, requestedName } : { kind, result };
54
+ }
55
+ //# 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
@@ -0,0 +1,260 @@
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, recordedResult, 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, value } = recordedResult(await finalizeBody(body, executed, pipeline, signal), body.requestedName);
159
+ const recorded = await step(key, generation, { kind: "result", value });
160
+ for (const memo of [bodies, preparations, releases])
161
+ memo.delete(keyId(key));
162
+ // A cancel or lease expiry that settled first stays terminal; the late body result is audit only.
163
+ if (recorded.status === "replayed")
164
+ return { kind: "replayed", entry: recorded.entry };
165
+ if (recorded.status !== "applied")
166
+ return refusal(recorded);
167
+ const named = body.requestedName === undefined ? {} : { requestedName: body.requestedName };
168
+ return { kind: "settled", toolCall: body.toolCall, result, isError, ...named };
169
+ }
170
+ // Every release reaches the ledger with its own actor and generation before any memo is read or written, so a
171
+ // wrong actor or an old generation is refused there and can never answer, or block, the issuer's own release.
172
+ async function release(request) {
173
+ const { key, generation } = request;
174
+ const released = await ledger.apply({
175
+ key,
176
+ generation,
177
+ actor: request.actor,
178
+ now: clock(),
179
+ event: { kind: "release" },
180
+ });
181
+ if (released.status === "refused")
182
+ return released.reason === "terminal" ? terminalRow(key) : refusal(released);
183
+ if (released.status === "result_expired")
184
+ return refusal(released);
185
+ const id = keyId(key);
186
+ const pending = releases.get(id);
187
+ if (pending !== undefined)
188
+ return pending;
189
+ const body = bodies.get(id);
190
+ if (body === undefined)
191
+ return { kind: "refused", reason: "not_prepared" };
192
+ // Today's loop never starts a body once the run is aborted; the call stays released for the issuer's abort.
193
+ if (request.signal?.aborted)
194
+ return { kind: "aborted", result: errorResult("Operation aborted") };
195
+ const reply = runReleased(request, body);
196
+ releases.set(id, reply);
197
+ void reply.catch(() => releases.get(id) === reply && releases.delete(id));
198
+ return reply;
199
+ }
200
+ // An approval reaches the ledger as the issuer's own `consent` event and only for the frozen call it names; a lease
201
+ // that ran out first settles the call `lease_expired`, so the approval answers with that terminal row.
202
+ async function consent(request) {
203
+ const entry = await ledger.read(request.key);
204
+ if (entry === undefined)
205
+ return { kind: "refused", reason: "not_found" };
206
+ if ("call" in entry.progress && entry.progress.call.digest !== request.frozenDigest)
207
+ return { kind: "refused", reason: "frozen_digest_mismatch" };
208
+ const reply = await ledger.apply({
209
+ key: request.key,
210
+ generation: request.generation,
211
+ actor: request.actor,
212
+ now: clock(),
213
+ event: { kind: "consent" },
214
+ });
215
+ if (reply.status === "applied" && reply.entry.progress.state === "prepared")
216
+ return { kind: "prepared" };
217
+ // The issuer's re-sent approval (the brain restarted before recording the first reply) finds the call prepared.
218
+ if (reply.status === "refused" && reply.reason === "invalid_transition" && entry.progress.state === "prepared")
219
+ return { kind: "prepared" };
220
+ if (reply.status === "applied" || reply.status === "replayed")
221
+ return { kind: "replayed", entry: reply.entry };
222
+ if (reply.status === "refused" && reply.reason === "terminal") {
223
+ const terminal = await ledger.read(request.key);
224
+ return terminal === undefined
225
+ ? { kind: "refused", reason: "not_found" }
226
+ : { kind: "replayed", entry: terminal };
227
+ }
228
+ return refusal(reply);
229
+ }
230
+ return {
231
+ consent,
232
+ prepare: async (request) => {
233
+ const { name, arguments: args, incomplete, errorMessage } = request.call;
234
+ const requestDigest = await canonicalDigest(toStoreValue({ name, args, incomplete, errorMessage }));
235
+ const admission = JSON.stringify([
236
+ request.generation,
237
+ request.workspace,
238
+ request.scope,
239
+ requestDigest,
240
+ request.admittedAt,
241
+ request.leaseUntil,
242
+ request.reconcilable ?? false,
243
+ ]);
244
+ const id = keyId(keyOf(request));
245
+ const pending = preparations.get(id);
246
+ if (pending !== undefined && pending.admission === admission)
247
+ return pending.reply;
248
+ if (pending !== undefined)
249
+ return { kind: "refused", reason: "identity_conflict" };
250
+ const reply = prepareOnce(request, requestDigest);
251
+ preparations.set(id, { admission, reply });
252
+ // Only a prepared call keeps its memo (release needs it); every other reply is durable or retryable.
253
+ const forget = () => preparations.get(id)?.reply === reply && preparations.delete(id);
254
+ void reply.then((settled) => settled.kind === "prepared" || settled.kind === "prepared_awaiting_consent" || forget(), forget);
255
+ return reply;
256
+ },
257
+ release,
258
+ };
259
+ }
260
+ //# 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