@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
@@ -1,2 +1,19 @@
1
- export {};
1
+ /** The loop had a tool batch to run on its default pipeline but no `batchStoreFactory`; it refuses instead of guessing a store. */
2
+ export class BatchStoreMissingError extends Error {
3
+ constructor() {
4
+ super("agent loop: no batchStoreFactory configured for the prepared pipeline; pass one (or a toolHost)");
5
+ this.code = "batch_store_missing";
6
+ this.name = "BatchStoreMissingError";
7
+ }
8
+ }
9
+ /** The loop had a tool batch to run on its default pipeline but no `afterToolFreeze`; it refuses instead of dropping preflight facts. */
10
+ export class PreflightCarryMissingError extends Error {
11
+ constructor() {
12
+ super("agent loop: no afterToolFreeze configured for the prepared pipeline; pass one (or a toolHost)");
13
+ this.code = "preflight_carry_missing";
14
+ this.name = "PreflightCarryMissingError";
15
+ }
16
+ }
17
+ /** The package entry's default `afterToolFreeze`: for hosts whose `beforeToolCall` binds nothing to the arguments object. */
18
+ export function noPreflightCarry(_prepared, _frozen) { }
2
19
  //# sourceMappingURL=tool-host.js.map
@@ -1,5 +1,6 @@
1
1
  import type { JsonRepresentation } from "@earendil-works/chord";
2
2
  import type { Api, AssistantMessage, AssistantMessageEvent, AssistantMessageFrame, DeferredHandle, ImageContent, Message, Model, Models, RetryPolicy, ToolResultMessage, Usage } from "@earendil-works/pi-ai";
3
+ import type { ExecutionPipelineWitness } from "../execution/tool-host.ts";
3
4
  import type { AgentMessage, AgentToolResult, QueueMode, ThinkingLevel } from "../types.ts";
4
5
  import type { BranchPreparation, BranchSummaryResult } from "./compaction/branch-summarization.ts";
5
6
  import type { CompactionPreparation, CompactionSettings, CompactResult } from "./compaction/compaction.ts";
@@ -632,6 +633,11 @@ export interface AgentHarnessOptions<TContext extends object | undefined = objec
632
633
  toolExecution?: "sequential" | "parallel";
633
634
  toProviderMessages?: (messages: AgentMessage[], context: Context) => Message[] | Promise<Message[]>;
634
635
  entryProjectors?: Record<string, EntryProjector>;
636
+ /**
637
+ * Receives `{ pipeline: "prepared", toolCallId }` for every tool call whose body runs, as `Agent.onExecutionPipeline`
638
+ * does. A callback that throws fails that tool call, as on `Agent`.
639
+ */
640
+ onExecutionPipeline?: (witness: ExecutionPipelineWitness) => void | Promise<void>;
635
641
  }
636
642
  export interface AgentLane {
637
643
  readonly name: string;
@@ -0,0 +1,14 @@
1
+ import { type ExecutionPipelineWitness } from "../../execution/tool-host.ts";
2
+ import type { AgentToolCall, AgentToolResult } from "../../types.ts";
3
+ export type WitnessSink = (witness: ExecutionPipelineWitness) => Promise<void> | void;
4
+ /**
5
+ * Runs one cleared harness call's body on the in-process prepared ToolHost (S19c), as a one-call batch on its own
6
+ * in-memory ledger. The harness already prepared, validated and hooked the call, so the host's schema passes its
7
+ * arguments through. The host records a JSON copy of them, but `run` executes the body on the cleared arguments object
8
+ * itself, as before the host (senpi#5861); it owns the harness's own signal, updates and error semantics.
9
+ */
10
+ export declare function runOnPreparedToolHost<T>(toolCall: AgentToolCall, scopeId: string, recordWitness: WitnessSink | undefined, run: () => Promise<{
11
+ readonly outcome: T;
12
+ readonly result: AgentToolResult<unknown>;
13
+ }>): Promise<T>;
14
+ //# sourceMappingURL=tool-host-call.d.ts.map
@@ -0,0 +1,56 @@
1
+ import { Type } from "typebox";
2
+ import { openMemoryBatchStore } from "../../execution/prepared/memory-batch-store.js";
3
+ import { createPreparedToolHost } from "../../execution/prepared/pipeline-prepared.js";
4
+ import { noPreflightCarry } from "../../execution/tool-host.js";
5
+ const CLEARED_ARGUMENTS = Type.Unknown();
6
+ function issuingMessage(toolCall) {
7
+ return {
8
+ role: "assistant",
9
+ content: [toolCall],
10
+ api: "agent-harness",
11
+ provider: "agent-harness",
12
+ model: "agent-harness",
13
+ usage: {
14
+ input: 0,
15
+ output: 0,
16
+ cacheRead: 0,
17
+ cacheWrite: 0,
18
+ totalTokens: 0,
19
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
20
+ },
21
+ stopReason: "toolUse",
22
+ timestamp: Date.now(),
23
+ };
24
+ }
25
+ /**
26
+ * Runs one cleared harness call's body on the in-process prepared ToolHost (S19c), as a one-call batch on its own
27
+ * in-memory ledger. The harness already prepared, validated and hooked the call, so the host's schema passes its
28
+ * arguments through. The host records a JSON copy of them, but `run` executes the body on the cleared arguments object
29
+ * itself, as before the host (senpi#5861); it owns the harness's own signal, updates and error semantics.
30
+ */
31
+ export async function runOnPreparedToolHost(toolCall, scopeId, recordWitness, run) {
32
+ let settled;
33
+ const body = {
34
+ name: toolCall.name,
35
+ label: toolCall.name,
36
+ description: toolCall.name,
37
+ parameters: CLEARED_ARGUMENTS,
38
+ execute: async () => {
39
+ const { outcome, result } = await run();
40
+ settled = { outcome };
41
+ return result;
42
+ },
43
+ };
44
+ await createPreparedToolHost({ afterToolFreeze: noPreflightCarry, removedToolHints: {} }, openMemoryBatchStore).execute({ scope: { id: scopeId, root: "" }, calls: [toolCall], mode: "sequential" }, {
45
+ emit: () => undefined,
46
+ ...(recordWitness === undefined ? {} : { recordWitness }),
47
+ local: {
48
+ context: { systemPrompt: "", messages: [], tools: [body] },
49
+ assistantMessage: issuingMessage(toolCall),
50
+ },
51
+ });
52
+ if (settled === undefined)
53
+ throw new Error(`agent harness: the prepared host ran no body for ${toolCall.name}`);
54
+ return settled.outcome;
55
+ }
56
+ //# sourceMappingURL=tool-host-call.js.map
@@ -4,6 +4,7 @@ import { type Context } from "../context.ts";
4
4
  import type { JsonValue } from "../session/types.ts";
5
5
  import type { AgentHarnessTool, AgentHarnessToolInvocation, AgentHarnessToolUpdateCallback } from "../types.ts";
6
6
  import type { Gate } from "./effect-gate.ts";
7
+ import { type WitnessSink } from "./tool-host-call.ts";
7
8
  /** A tool call whose tool exists and whose prepared arguments passed validation. */
8
9
  export interface PreparedToolCall<TContext extends object | undefined> {
9
10
  toolCall: AgentToolCall;
@@ -57,7 +58,7 @@ export declare function prepareToolCall<TContext extends object | undefined>(cal
57
58
  /** Apply an explicit hook decision and revalidate replacement arguments. */
58
59
  export declare function applyBeforeToolDecision<TContext extends object | undefined>(prepared: PreparedToolCall<TContext>, decision: BeforeToolDecision | undefined): ClearedToolCall<TContext> | ImmediateToolOutcome;
59
60
  /** Execute one cleared external tool effect, converting expected tool throws to error output. */
60
- export declare function executeToolCall<TContext extends object | undefined>(call: ClearedToolCall<TContext>, gate: Gate, onUpdate: AgentHarnessToolUpdateCallback<unknown>, toolContext: TContext, invocation: AgentHarnessToolInvocation, context: Context): Promise<ExecutedToolCall>;
61
+ export declare function executeToolCall<TContext extends object | undefined>(call: ClearedToolCall<TContext>, gate: Gate, onUpdate: AgentHarnessToolUpdateCallback<unknown>, toolContext: TContext, invocation: AgentHarnessToolInvocation, context: Context, recordWitness?: WitnessSink): Promise<ExecutedToolCall>;
61
62
  /** Apply an after-tool patch field by field. */
62
63
  export declare function finalizeToolCall<TContext extends object | undefined>(call: ClearedToolCall<TContext>, executed: ExecutedToolCall, patch: AfterToolPatch | undefined): FinalizedToolCall;
63
64
  /** Reconstruct the canonical tool result represented by a staged transcript message. */
@@ -1,11 +1,23 @@
1
1
  import { validateToolArguments } from "@earendil-works/pi-ai";
2
+ import { toStoreValue } from "../../execution/prepared/executor-freeze.js";
2
3
  import { withAbortSignal } from "../context.js";
4
+ import { runOnPreparedToolHost } from "./tool-host-call.js";
3
5
  function createErrorToolResult(message) {
4
6
  return {
5
7
  content: [{ type: "text", text: message }],
6
8
  details: undefined,
7
9
  };
8
10
  }
11
+ // Arguments the host cannot record as JSON (a BigInt, a cycle) settle as a tool error before the body (senpi#5861).
12
+ function unrecordableArguments(args) {
13
+ try {
14
+ toStoreValue(args);
15
+ return undefined;
16
+ }
17
+ catch (error) {
18
+ return `Tool arguments are not JSON: ${error instanceof Error ? error.message : String(error)}`;
19
+ }
20
+ }
9
21
  function immediateError(toolCall, message, terminate = false) {
10
22
  return {
11
23
  kind: "immediate",
@@ -53,27 +65,43 @@ export function applyBeforeToolDecision(prepared, decision) {
53
65
  }
54
66
  }
55
67
  /** Execute one cleared external tool effect, converting expected tool throws to error output. */
56
- export function executeToolCall(call, gate, onUpdate, toolContext, invocation, context) {
68
+ export function executeToolCall(call, gate, onUpdate, toolContext, invocation, context, recordWitness) {
57
69
  let acceptingUpdates = true;
58
70
  return gate.admit(async () => {
59
71
  const admittedContext = withAbortSignal(gate.signal, context);
60
72
  admittedContext.abortSignal?.throwIfAborted();
61
- try {
62
- const result = await call.tool.execute(call.toolCall.id, call.args, (partial, options) => {
63
- if (acceptingUpdates)
64
- onUpdate(partial, options);
65
- }, toolContext, invocation, admittedContext);
66
- return { result, isError: false };
67
- }
68
- catch (error) {
69
- return {
70
- result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
71
- isError: true,
72
- };
73
- }
74
- finally {
75
- acceptingUpdates = false;
76
- }
73
+ const unrecordable = unrecordableArguments(call.args);
74
+ if (unrecordable !== undefined)
75
+ return { result: createErrorToolResult(unrecordable), isError: true };
76
+ // The harness already prepared, validated and hooked this call, so the host gets only its identity and cleared
77
+ // arguments: a stream flag such as `incomplete` would make the host refuse it before the body runs.
78
+ const toolCall = {
79
+ type: "toolCall",
80
+ id: call.toolCall.id,
81
+ name: call.toolCall.name,
82
+ arguments: call.args,
83
+ };
84
+ // The host records a JSON copy of the arguments; the body and after_tool share the cleared arguments object itself.
85
+ return runOnPreparedToolHost(toolCall, invocation.invocationId, recordWitness, async () => {
86
+ let executed;
87
+ try {
88
+ const result = await call.tool.execute(call.toolCall.id, call.args, (partial, options) => {
89
+ if (acceptingUpdates)
90
+ onUpdate(partial, options);
91
+ }, toolContext, invocation, admittedContext);
92
+ executed = { result, isError: false };
93
+ }
94
+ catch (error) {
95
+ executed = {
96
+ result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
97
+ isError: true,
98
+ };
99
+ }
100
+ finally {
101
+ acceptingUpdates = false;
102
+ }
103
+ return { outcome: executed, result: executed.result };
104
+ });
77
105
  });
78
106
  }
79
107
  /** Apply an after-tool patch field by field. */
@@ -262,7 +262,7 @@ async function performToolInvocation(lane, drive, batch, call, cleared, toolCont
262
262
  publishUpdate(partial);
263
263
  if (options?.checkpoint === true)
264
264
  progress.write(partial);
265
- }, toolContext, capability.invocation, drive.context);
265
+ }, toolContext, capability.invocation, drive.context, lane.readConfig().onExecutionPipeline);
266
266
  }
267
267
  catch (error) {
268
268
  capability.expire();
@@ -39,6 +39,7 @@ export class Harness {
39
39
  systemPrompt: options.systemPrompt,
40
40
  toProviderMessages: options.toProviderMessages ?? ((messages) => convertToLlm(messages)),
41
41
  entryProjectors: options.entryProjectors ?? {},
42
+ ...(options.onExecutionPipeline === undefined ? {} : { onExecutionPipeline: options.onExecutionPipeline }),
42
43
  },
43
44
  };
44
45
  for (const [name, state] of restored)
@@ -23,6 +23,7 @@ export interface Config<TContext extends object | undefined> {
23
23
  readonly systemPrompt: AgentHarnessOptions<TContext>["systemPrompt"];
24
24
  readonly toProviderMessages: NonNullable<AgentHarnessOptions<TContext>["toProviderMessages"]>;
25
25
  readonly entryProjectors: Readonly<NonNullable<AgentHarnessOptions<TContext>["entryProjectors"]>>;
26
+ readonly onExecutionPipeline?: AgentHarnessOptions<TContext>["onExecutionPipeline"];
26
27
  }
27
28
  /** The current durable state owned by one lane. */
28
29
  export interface LaneState {
@@ -15,7 +15,7 @@ export function createReadTool(options = { folder: selectedReadFolder }) {
15
15
  return {
16
16
  name: "read",
17
17
  label: "read",
18
- description: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,
18
+ description: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp; bmp only when an imageProcessor is configured). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete. A .js or .json file of 100+ lines read without offset/limit may come back folded: bodies are replaced by markers and a footer lists the offset/limit ranges to reread; markers are not source, so reread those ranges before quoting or editing them.`,
19
19
  parameters: readSchema,
20
20
  async execute(_toolCallId, { path, offset, limit }, _onUpdate, { env }, _invocation, context) {
21
21
  const absolutePath = await resolveReadToolPath(env, path, context);
package/dist/index.d.ts CHANGED
@@ -3,24 +3,41 @@ export type { AttributeValue, ExactTelemetryAttributes, InferEventAttributes, In
3
3
  export { createTypedSpanStarter, defineTelemetrySchema, InMemoryTelemetryContext, NOOP_TELEMETRY_CONTEXT, } from "@earendil-works/pi-telemetry";
4
4
  export * from "./agent.ts";
5
5
  export * from "./agent-loop.ts";
6
+ export * from "./egress/types.ts";
7
+ export { isStepCommitError, StepCommitError, type StepCommitFailure } from "./step-commit.ts";
8
+ export { Agent, agentLoop, agentLoopContinue, runAgentLoop, runAgentLoopContinue } from "./public-entry.ts";
6
9
  export { createInternalAgentChannel, type InternalAgentChannel, type OrderedAgentRecord } from "./internal-events.ts";
7
10
  export { EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC, ProviderRetryWatchdogAbortError } from "./assistant-terminal-state.ts";
8
11
  export { createRemoteExecutor, type HandCall, type HandScope, type OpenHandScope, type RemoteExecutor, type RemoteExecutorOptions, } from "./execution/remote-executor.ts";
9
12
  export { createHandLedger, type HandAdmission, type HandLedger, type HandLedgerOptions, } from "./execution/remote-hand-ledger.ts";
10
- export { decodeRemoteMessage, encodeRemoteMessage, HAND_CONTROL_LANE, type RemoteAbort, type RemoteAck, type RemoteHandMessage, type RemoteFile, type RemoteHello, type RemoteInvoke, type RemoteRefused, type RemoteSettled, RemoteProtocolError, type RemoteTerminal, type RemoteTerminalReason, type RemoteToolResult, } from "./execution/remote-protocol.ts";
13
+ export { decodeRemoteMessage, encodeRemoteMessage, HAND_CONTROL_LANE, type RemoteAbort, type EpochRefusal, type RemoteAck, type RemoteHandMessage, type RemoteFile, type RemoteHello, type RemoteInvoke, type RemoteFloor, type RemoteFloorAck, type RemoteFloorRefused, type RemoteRefused, type RemoteSettled, RemoteProtocolError, type RemoteTerminal, type RemoteTerminalReason, type RemoteToolResult, } from "./execution/remote-protocol.ts";
11
14
  export { createErrorToolResult, createToolResultMessage, emitToolExecutionEnd, emitToolExecutionUpdate, emitToolResultMessage, shouldTerminateToolBatch, } from "./execution/tool-outcome-events.ts";
12
15
  export { createAdmissionLine } from "./durable/store-admission.ts";
16
+ export type { SessionHandle, SessionHeader, StoredEntry, StoredSession, SyncSessionHandle, } from "./durable/session-store.ts";
17
+ export { openSessionStore, openSyncSessionStore, SessionStoreError } from "./durable/session-store.ts";
18
+ export type { SyncCommit, SyncCommitStore } from "./durable/store.ts";
13
19
  export { createMemoryStoreMedium, openMemoryStore } from "./durable/store-memory.ts";
14
20
  export { createBatchCoordinator } from "./execution/coordinator.ts";
15
21
  export type { BatchExecutor, BatchPlan } from "./execution/coordinator-types.ts";
16
22
  export { createExecutionLedger } from "./execution/ledger.ts";
17
23
  export { authorize, createGrantVerifier, DEFAULT_WORKSPACE, type GrantRefusal, type GrantRow, type GrantSnapshot, type GrantVerdict, type GrantVerifier, type GrantVerifierOptions, HAND_CAPABILITY, type HandAuthority, type WorkspaceRoot, } from "./execution/grant-verify.ts";
18
- export { base64Length, DEVICE_FILE_OPS, type DeviceFileArgs, DeviceFileError, type DeviceFileErrorCode, type DeviceFileOp, type DeviceFileOptions, type DeviceFileOutcome, type DeviceFiles, type DeviceFileStat, decodeBase64, decodeDeviceFileArgs, encodeBase64, FILE_CHANNEL, FILE_CHANNEL_MAX_BYTES, fileOutcomeOf, } from "./execution/device-files.ts";
24
+ export { createHandEpochFence, EPOCH_FLOOR_MAX_STEP, type FloorRaise, HAND_SELF_SENDER, type HandEpochFence, type HandEpochFenceOptions, } from "./execution/remote-epoch.ts";
25
+ export { base64Length, DEVICE_FILE_OPS, type DeviceFileArgs, DeviceFileError, type DeviceFileErrorCode, type DeviceFileOp, type DeviceFileOptions, type DeviceRunRequest, type DeviceRunResult, type DeviceFileOutcome, type DeviceFiles, type DeviceFileStat, decodeBase64, decodeDeviceFileArgs, encodeBase64, FILE_CHANNEL, FILE_CHANNEL_MAX_BYTES, isLocalDeviceFiles, LOCAL_DEVICE_FILES, RUN_CHANNEL, fileOutcomeOf, } from "./execution/device-files.ts";
19
26
  export { HELLO_WAIT_MS } from "./execution/remote-device-files.ts";
20
27
  export { fileRefusal, fileResult } from "./execution/remote-file-call.ts";
21
28
  export { createModelPlaneClient, decodeModelPlaneRequest, MODEL_PLANE, type ModelPlaneRequest, serveModelPlane, } from "./execution/plane-model.ts";
29
+ export { createLoopToolHost, createSessionPlaneClient, createSplitToolHost, decodeSessionPlaneRequest, loopSideToolNames, SESSION_PLANE, type SessionPlaneRequest, serveSessionPlane, } from "./execution/plane-session.ts";
30
+ export { admitChainCall, CHAIN_COUNT_LIMIT, CHAIN_ORIGIN, ChainCountLimitError, decodeChainCount, nextChainCount, } from "./execution/chain-count.ts";
22
31
  export { decodePlaneMessage, encodePlaneMessage, type NestedRequest, type PlaneHandler, type PlaneMessage, PlaneRefusedError, } from "./execution/plane.ts";
32
+ export { createLoopHookHost, type LoopHookHost, type LoopHookHostOptions, LoopHookFailedError, LoopHookRestartedError, } from "./execution/loop-hook-host.ts";
33
+ export { type LoopHookHand, type LoopHookHandOptions, type LoopHookPoint, type LoopHookRunner, serveLoopHooks, } from "./execution/loop-hook-host-hand.ts";
23
34
  export { createRemoteToolHost, type HandPlacement, type RemoteToolHostOptions } from "./execution/remote-tool-host.ts";
35
+ export { canonicalJson } from "./execution/canonical-digest.ts";
36
+ export { toStoreValue } from "./execution/prepared/executor-freeze.ts";
37
+ export type { ConsentClassifier } from "./execution/prepared/executor-types.ts";
38
+ export { openMemoryBatchStore } from "./execution/prepared/memory-batch-store.ts";
39
+ export { BatchStoreMissingError, noPreflightCarry, PreflightCarryMissingError } from "./execution/tool-host.ts";
40
+ export { createPreparedToolHost } from "./execution/prepared/pipeline-prepared.ts";
24
41
  export { type CarrierLink, createInProcessNetwork, type InProcessNetwork } from "./transport/in-process-carrier.ts";
25
42
  export { type LocalEndpoint, localEndpoint } from "./transport/local-endpoint.ts";
26
43
  export { createReliableTransport, type ReliableTransportOptions } from "./transport/reliable-transport.ts";
package/dist/index.js CHANGED
@@ -2,6 +2,9 @@ export { uuidv7 } from "@earendil-works/pi-ai";
2
2
  export { createTypedSpanStarter, defineTelemetrySchema, InMemoryTelemetryContext, NOOP_TELEMETRY_CONTEXT, } from "@earendil-works/pi-telemetry";
3
3
  export * from "./agent.js";
4
4
  export * from "./agent-loop.js";
5
+ export * from "./egress/types.js";
6
+ export { isStepCommitError, StepCommitError } from "./step-commit.js";
7
+ export { Agent, agentLoop, agentLoopContinue, runAgentLoop, runAgentLoopContinue } from "./public-entry.js";
5
8
  export { createInternalAgentChannel } from "./internal-events.js";
6
9
  export { EMPTY_TOOL_USE_DEMOTION_DIAGNOSTIC, ProviderRetryWatchdogAbortError } from "./assistant-terminal-state.js";
7
10
  export { createRemoteExecutor, } from "./execution/remote-executor.js";
@@ -9,16 +12,27 @@ export { createHandLedger, } from "./execution/remote-hand-ledger.js";
9
12
  export { decodeRemoteMessage, encodeRemoteMessage, HAND_CONTROL_LANE, RemoteProtocolError, } from "./execution/remote-protocol.js";
10
13
  export { createErrorToolResult, createToolResultMessage, emitToolExecutionEnd, emitToolExecutionUpdate, emitToolResultMessage, shouldTerminateToolBatch, } from "./execution/tool-outcome-events.js";
11
14
  export { createAdmissionLine } from "./durable/store-admission.js";
15
+ export { openSessionStore, openSyncSessionStore, SessionStoreError } from "./durable/session-store.js";
12
16
  export { createMemoryStoreMedium, openMemoryStore } from "./durable/store-memory.js";
13
17
  export { createBatchCoordinator } from "./execution/coordinator.js";
14
18
  export { createExecutionLedger } from "./execution/ledger.js";
15
19
  export { authorize, createGrantVerifier, DEFAULT_WORKSPACE, HAND_CAPABILITY, } from "./execution/grant-verify.js";
16
- export { base64Length, DEVICE_FILE_OPS, DeviceFileError, decodeBase64, decodeDeviceFileArgs, encodeBase64, FILE_CHANNEL, FILE_CHANNEL_MAX_BYTES, fileOutcomeOf, } from "./execution/device-files.js";
20
+ export { createHandEpochFence, EPOCH_FLOOR_MAX_STEP, HAND_SELF_SENDER, } from "./execution/remote-epoch.js";
21
+ export { base64Length, DEVICE_FILE_OPS, DeviceFileError, decodeBase64, decodeDeviceFileArgs, encodeBase64, FILE_CHANNEL, FILE_CHANNEL_MAX_BYTES, isLocalDeviceFiles, LOCAL_DEVICE_FILES, RUN_CHANNEL, fileOutcomeOf, } from "./execution/device-files.js";
17
22
  export { HELLO_WAIT_MS } from "./execution/remote-device-files.js";
18
23
  export { fileRefusal, fileResult } from "./execution/remote-file-call.js";
19
24
  export { createModelPlaneClient, decodeModelPlaneRequest, MODEL_PLANE, serveModelPlane, } from "./execution/plane-model.js";
25
+ export { createLoopToolHost, createSessionPlaneClient, createSplitToolHost, decodeSessionPlaneRequest, loopSideToolNames, SESSION_PLANE, serveSessionPlane, } from "./execution/plane-session.js";
26
+ export { admitChainCall, CHAIN_COUNT_LIMIT, CHAIN_ORIGIN, ChainCountLimitError, decodeChainCount, nextChainCount, } from "./execution/chain-count.js";
20
27
  export { decodePlaneMessage, encodePlaneMessage, PlaneRefusedError, } from "./execution/plane.js";
28
+ export { createLoopHookHost, LoopHookFailedError, LoopHookRestartedError, } from "./execution/loop-hook-host.js";
29
+ export { serveLoopHooks, } from "./execution/loop-hook-host-hand.js";
21
30
  export { createRemoteToolHost } from "./execution/remote-tool-host.js";
31
+ export { canonicalJson } from "./execution/canonical-digest.js";
32
+ export { toStoreValue } from "./execution/prepared/executor-freeze.js";
33
+ export { openMemoryBatchStore } from "./execution/prepared/memory-batch-store.js";
34
+ export { BatchStoreMissingError, noPreflightCarry, PreflightCarryMissingError } from "./execution/tool-host.js";
35
+ export { createPreparedToolHost } from "./execution/prepared/pipeline-prepared.js";
22
36
  export { createInProcessNetwork } from "./transport/in-process-carrier.js";
23
37
  export { localEndpoint } from "./transport/local-endpoint.js";
24
38
  export { createReliableTransport } from "./transport/reliable-transport.js";
@@ -0,0 +1,10 @@
1
+ import { Agent as LoopAgent, type AgentOptions } from "./agent.ts";
2
+ import { agentLoop as loopAgentLoop, agentLoopContinue as loopAgentLoopContinue, runAgentLoop as loopRunAgentLoop, runAgentLoopContinue as loopRunAgentLoopContinue } from "./agent-loop.ts";
3
+ export declare class Agent extends LoopAgent {
4
+ constructor(options: AgentOptions);
5
+ }
6
+ export declare const agentLoop: typeof loopAgentLoop;
7
+ export declare const agentLoopContinue: typeof loopAgentLoopContinue;
8
+ export declare const runAgentLoop: typeof loopRunAgentLoop;
9
+ export declare const runAgentLoopContinue: typeof loopRunAgentLoopContinue;
10
+ //# sourceMappingURL=public-entry.d.ts.map
@@ -0,0 +1,23 @@
1
+ import { Agent as LoopAgent } from "./agent.js";
2
+ import { agentLoop as loopAgentLoop, agentLoopContinue as loopAgentLoopContinue, runAgentLoop as loopRunAgentLoop, runAgentLoopContinue as loopRunAgentLoopContinue, } from "./agent-loop.js";
3
+ import { openMemoryBatchStore } from "./execution/prepared/memory-batch-store.js";
4
+ import { noPreflightCarry } from "./execution/tool-host.js";
5
+ // The package entry's loop and Agent: the loop core builds no store (senpi#4996), so the entry supplies a fresh in-memory
6
+ // store per batch unless the caller passes its own factory or ToolHost. External callers need no new argument.
7
+ function withBatchStore(config) {
8
+ return {
9
+ ...config,
10
+ batchStoreFactory: config.batchStoreFactory ?? openMemoryBatchStore,
11
+ afterToolFreeze: config.afterToolFreeze ?? noPreflightCarry,
12
+ };
13
+ }
14
+ export class Agent extends LoopAgent {
15
+ constructor(options) {
16
+ super(withBatchStore(options));
17
+ }
18
+ }
19
+ export const agentLoop = (prompts, context, config, signal, streamFn) => loopAgentLoop(prompts, context, withBatchStore(config), signal, streamFn);
20
+ export const agentLoopContinue = (context, config, signal, streamFn) => loopAgentLoopContinue(context, withBatchStore(config), signal, streamFn);
21
+ export const runAgentLoop = (prompts, context, config, emit, signal, streamFn) => loopRunAgentLoop(prompts, context, withBatchStore(config), emit, signal, streamFn);
22
+ export const runAgentLoopContinue = (context, config, emit, signal, streamFn) => loopRunAgentLoopContinue(context, withBatchStore(config), emit, signal, streamFn);
23
+ //# sourceMappingURL=public-entry.js.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The durable step commit a hosted brain host installs through `AgentLoopConfig.commitStep`.
3
+ *
4
+ * Fused and split-local assemblies never set `commitStep` and never construct a `StepCommitError`;
5
+ * only a hosted host's commit implementation (and its conformance harness) does. The error is branded
6
+ * with a registry symbol so a value built by a second copy of this package (version skew, a bundler
7
+ * duplicate) is still recognised: callers check it with `isStepCommitError`, never `instanceof`.
8
+ */
9
+ export type StepCommitFailure = "already_committed" | "fenced" | "generation" | "epoch_unverified" | "storage_unavailable" | "ambiguous_unresolved";
10
+ declare const STEP_COMMIT_BRAND: unique symbol;
11
+ /** A hosted step commit failed; the step's message is not durable and must not be acted on. */
12
+ export declare class StepCommitError extends Error {
13
+ readonly name: "StepCommitError";
14
+ readonly [STEP_COMMIT_BRAND]: true;
15
+ readonly stepId: string;
16
+ readonly code: StepCommitFailure;
17
+ constructor(stepId: string, code: StepCommitFailure, options?: {
18
+ readonly cause?: unknown;
19
+ });
20
+ }
21
+ /** True for a `StepCommitError` from any copy of this package; false for look-alikes without the brand. */
22
+ export declare function isStepCommitError(value: unknown): value is StepCommitError;
23
+ export {};
24
+ //# sourceMappingURL=step-commit.d.ts.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The durable step commit a hosted brain host installs through `AgentLoopConfig.commitStep`.
3
+ *
4
+ * Fused and split-local assemblies never set `commitStep` and never construct a `StepCommitError`;
5
+ * only a hosted host's commit implementation (and its conformance harness) does. The error is branded
6
+ * with a registry symbol so a value built by a second copy of this package (version skew, a bundler
7
+ * duplicate) is still recognised: callers check it with `isStepCommitError`, never `instanceof`.
8
+ */
9
+ const STEP_COMMIT_BRAND = Symbol.for("senpi.StepCommitError");
10
+ /** A hosted step commit failed; the step's message is not durable and must not be acted on. */
11
+ export class StepCommitError extends Error {
12
+ constructor(stepId, code, options) {
13
+ super(`step commit failed: ${code}`, options);
14
+ this.name = "StepCommitError";
15
+ this.stepId = stepId;
16
+ this.code = code;
17
+ Object.defineProperty(this, STEP_COMMIT_BRAND, { value: true, enumerable: false, writable: false });
18
+ }
19
+ }
20
+ /** True for a `StepCommitError` from any copy of this package; false for look-alikes without the brand. */
21
+ export function isStepCommitError(value) {
22
+ return typeof value === "object" && value !== null && Reflect.get(value, STEP_COMMIT_BRAND) === true;
23
+ }
24
+ //# sourceMappingURL=step-commit.js.map
@@ -1,4 +1,4 @@
1
- import type { AgentContext, AgentLoopConfig, AgentTool, AgentToolCall, AgentToolResult } from "./types.ts";
1
+ import type { AgentToolResult } from "./types.ts";
2
2
  /**
3
3
  * A model can call a tool by a name it was never registered under: recased,
4
4
  * under a gateway namespace (`mcp__<id>__<Name>`, any case), or without the
@@ -7,11 +7,5 @@ import type { AgentContext, AgentLoopConfig, AgentTool, AgentToolCall, AgentTool
7
7
  */
8
8
  export declare function resolveToolNameAlias(requested: string, available: Iterable<string>): string | undefined;
9
9
  export declare function toolNameCorrectionNotice(requested: string, resolved: string): string;
10
- /**
11
- * Find the tool a call will run, resolving an unknown name through the host
12
- * resolver and then the alias rule. Runs before `tool_execution_start` so every
13
- * event names the tool that executes, never the name the model mistyped.
14
- */
15
- export declare function resolveCallTool(currentContext: AgentContext, toolCall: AgentToolCall, config: AgentLoopConfig): Promise<AgentTool | undefined>;
16
10
  export declare function withToolNameCorrection(result: AgentToolResult<unknown>, requestedName: string, resolvedName: string): AgentToolResult<unknown>;
17
11
  //# sourceMappingURL=tool-name-alias.d.ts.map
@@ -11,23 +11,6 @@ export function resolveToolNameAlias(requested, available) {
11
11
  export function toolNameCorrectionNotice(requested, resolved) {
12
12
  return `[auto-corrected] no tool is named "${requested}"; ran "${resolved}". Call tools by their exact listed name.`;
13
13
  }
14
- /**
15
- * Find the tool a call will run, resolving an unknown name through the host
16
- * resolver and then the alias rule. Runs before `tool_execution_start` so every
17
- * event names the tool that executes, never the name the model mistyped.
18
- */
19
- export async function resolveCallTool(currentContext, toolCall, config) {
20
- if (toolCall.incomplete === true)
21
- return undefined;
22
- const exact = currentContext.tools?.find((candidate) => candidate.name === toolCall.name);
23
- if (exact)
24
- return exact;
25
- const resolved = await config.resolveUnknownToolCall?.(toolCall.name, currentContext);
26
- if (resolved)
27
- return resolved;
28
- const aliasedName = resolveToolNameAlias(toolCall.name, (currentContext.tools ?? []).map((candidate) => candidate.name));
29
- return currentContext.tools?.find((candidate) => candidate.name === aliasedName);
30
- }
31
14
  export function withToolNameCorrection(result, requestedName, resolvedName) {
32
15
  return {
33
16
  ...result,
package/dist/types.d.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  import type { Api, AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream, CursorExecHandlers, ImageContent, JsonValue, Message, Model, ProviderDiagnostic, SimpleStreamOptions, TextContent, ThinkingSelection, Tool, ToolResultMessage, TranscriptContext, Usage } from "@earendil-works/pi-ai";
2
2
  import type { Static, TSchema } from "typebox";
3
+ import type { DurableStore } from "./durable/store.ts";
3
4
  import type { ExecutionPipelineWitness, ExecutionScope, ToolHost } from "./execution/tool-host.ts";
5
+ /**
6
+ * Opens a new, empty store for one tool batch, which the batch claims at epoch 1. A batch never reuses another's
7
+ * store: a call's command ID is the model's call ID, and providers reuse those across turns.
8
+ */
9
+ export type BatchStoreFactory = () => DurableStore;
4
10
  export type { ExecutionPipelineWitness, ExecutionScope, ToolHost, ToolHostCall, ToolHostOptions, ToolHostResult, } from "./execution/tool-host.ts";
5
11
  /**
6
12
  * Stream function used by the agent loop. `Models.streamSimple` satisfies
@@ -135,6 +141,16 @@ export type AgentTurnDecision = {
135
141
  * with the current context. Error and aborted responses remain hard exits.
136
142
  */
137
143
  export type FinishTurn = (turn: AgentTurnContext, signal?: AbortSignal) => AgentTurnDecision | void | Promise<AgentTurnDecision | undefined> | Promise<void>;
144
+ /** One model step as the loop finished it: its terminal assistant message and the provider tool results emitted for it. */
145
+ export interface StepCommit {
146
+ readonly message: AssistantMessage;
147
+ readonly providerToolResults: readonly ToolResultMessage[];
148
+ }
149
+ /**
150
+ * Makes one finished model step durable before the loop acts on it. A rejection leaves the loop with no further
151
+ * events and no tool dispatch for that step.
152
+ */
153
+ export type StepCommitFn = (step: StepCommit) => Promise<void>;
138
154
  /** Replacement runtime state used by the agent loop before starting another provider request. */
139
155
  export interface AgentLoopTurnUpdate {
140
156
  /** Context for the next provider request. */
@@ -263,6 +279,12 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
263
279
  * hard exits.
264
280
  */
265
281
  finishTurn?: FinishTurn;
282
+ /**
283
+ * Called once per model step, after the step's provider tool results are emitted and before the loop decides
284
+ * whether the turn ends or dispatches tools; it covers success and terminal-failure messages alike. Unset on
285
+ * every local assembly; a hosted brain host sets it to commit the step durably.
286
+ */
287
+ commitStep?: StepCommitFn;
266
288
  /**
267
289
  * Called immediately before every conversational provider request, including the first.
268
290
  * Pending messages have already been appended. The returned context, model, and thinking level
@@ -324,8 +346,22 @@ export interface AgentLoopConfig extends SimpleStreamOptions {
324
346
  * Default: "parallel"
325
347
  */
326
348
  toolExecution?: ToolExecutionMode;
327
- /** Unprepared batch boundary. Omitted selects the existing in-process legacy scheduler. */
349
+ /** Unprepared batch boundary. Omitted selects the prepared pipeline (batch coordinator + prepared executor) in this process. */
328
350
  toolHost?: ToolHost;
351
+ /**
352
+ * Opens each batch's execution ledger for the default (prepared) pipeline. The loop builds no store itself: with no
353
+ * `toolHost` and no factory, a tool batch fails closed with `BatchStoreMissingError`. The package entry's `Agent` and
354
+ * `agentLoop` default it to `openMemoryBatchStore`.
355
+ */
356
+ batchStoreFactory?: BatchStoreFactory;
357
+ /**
358
+ * Runs once per call on the prepared pipeline, after the call is frozen and before it executes, with the arguments
359
+ * object `beforeToolCall` saw and the frozen copy the tool will receive. A host whose `beforeToolCall` binds facts to
360
+ * that object (an approval, a symbol property) moves them here. Synchronous and must not throw. With no `toolHost`
361
+ * and no hook, a tool batch fails closed with `PreflightCarryMissingError`; the package entry's `Agent` and
362
+ * `agentLoop` default it to `noPreflightCarry` (senpi#5795).
363
+ */
364
+ afterToolFreeze?: (prepared: unknown, frozen: unknown) => void;
329
365
  executionScope?: ExecutionScope;
330
366
  onExecutionPipeline?: (witness: ExecutionPipelineWitness) => Promise<void> | void;
331
367
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@code-yeongyu/senpi-agent-core",
3
- "version": "2026.11.4-2",
3
+ "version": "2026.11.6-1",
4
4
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -72,8 +72,8 @@
72
72
  },
73
73
  "dependencies": {
74
74
  "@earendil-works/chord": "0.99.1",
75
- "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.4-2",
76
- "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.11.4-2",
75
+ "@earendil-works/pi-ai": "npm:@code-yeongyu/senpi-ai@2026.11.6-1",
76
+ "@earendil-works/pi-telemetry": "npm:@code-yeongyu/senpi-telemetry@2026.11.6-1",
77
77
  "diff": "9.0.0",
78
78
  "ignore": "7.0.9",
79
79
  "typebox": "1.3.34",