@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
@@ -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
@@ -0,0 +1,11 @@
1
+ import type { ToolResultMessage } from "@earendil-works/pi-ai";
2
+ import type { AgentEvent, AgentToolCall, AgentToolCallOutcome, AgentToolResult } from "../types.ts";
3
+ type EventSink = (event: AgentEvent) => Promise<void> | void;
4
+ export declare function createErrorToolResult(message: string): AgentToolResult<unknown>;
5
+ export declare function emitToolExecutionUpdate(toolCall: AgentToolCall, emit: EventSink): (partialResult: AgentToolResult<unknown>) => Promise<void> | void;
6
+ export declare function emitToolExecutionEnd(finalized: AgentToolCallOutcome, emit: EventSink): Promise<void>;
7
+ export declare function createToolResultMessage(finalized: AgentToolCallOutcome): ToolResultMessage;
8
+ export declare function emitToolResultMessage(toolResultMessage: ToolResultMessage, emit: EventSink): Promise<void>;
9
+ export declare function shouldTerminateToolBatch(finalizedCalls: readonly AgentToolCallOutcome[]): boolean;
10
+ export {};
11
+ //# sourceMappingURL=tool-outcome-events.d.ts.map
@@ -0,0 +1,47 @@
1
+ export function createErrorToolResult(message) {
2
+ return {
3
+ content: [{ type: "text", text: message }],
4
+ details: {},
5
+ };
6
+ }
7
+ export function emitToolExecutionUpdate(toolCall, emit) {
8
+ return (partialResult) => emit({
9
+ type: "tool_execution_update",
10
+ toolCallId: toolCall.id,
11
+ toolName: toolCall.name,
12
+ args: toolCall.arguments,
13
+ partialResult,
14
+ });
15
+ }
16
+ export async function emitToolExecutionEnd(finalized, emit) {
17
+ await emit({
18
+ type: "tool_execution_end",
19
+ toolCallId: finalized.toolCall.id,
20
+ toolName: finalized.toolCall.name,
21
+ result: finalized.result,
22
+ isError: finalized.isError,
23
+ });
24
+ }
25
+ export function createToolResultMessage(finalized) {
26
+ return {
27
+ role: "toolResult",
28
+ toolCallId: finalized.toolCall.id,
29
+ toolName: finalized.toolCall.name,
30
+ // Untyped tools (JS extensions) can return results without content; normalize
31
+ // so the null never enters session history or provider payloads.
32
+ content: finalized.result.content ?? [],
33
+ details: finalized.result.details,
34
+ usage: finalized.result.usage,
35
+ ...(finalized.result.addedToolNames?.length ? { addedToolNames: finalized.result.addedToolNames } : {}),
36
+ isError: finalized.isError,
37
+ timestamp: Date.now(),
38
+ };
39
+ }
40
+ export async function emitToolResultMessage(toolResultMessage, emit) {
41
+ await emit({ type: "message_start", message: toolResultMessage });
42
+ await emit({ type: "message_end", message: toolResultMessage });
43
+ }
44
+ export function shouldTerminateToolBatch(finalizedCalls) {
45
+ return finalizedCalls.length > 0 && finalizedCalls.every((finalized) => finalized.result.terminate === true);
46
+ }
47
+ //# sourceMappingURL=tool-outcome-events.js.map
@@ -0,0 +1,25 @@
1
+ import type { DurableStore } from "../durable/store.ts";
2
+ import type { AdmissionLine } from "../durable/store-admission.ts";
3
+ import { type WakeEvent, type WakeInboxRecord, type WakeReceipt } from "./wake-types.ts";
4
+ export interface WakeInboxOptions {
5
+ readonly issuer: string;
6
+ readonly store: DurableStore;
7
+ readonly epoch: number;
8
+ readonly admission: AdmissionLine;
9
+ readonly clock: () => number;
10
+ /** The authenticated hand bound to a scope (design 5.6.6), or undefined for a scope this brain does not own (yet): such a wake is refused unknown_scope and re-offered by the hand. */
11
+ readonly owner: (scope: string) => string | undefined;
12
+ }
13
+ /** The brain side of design 5.6.4: deduplicated by event id, acked only after the commit. */
14
+ export interface WakeInbox {
15
+ /** `sender` is the authenticated hand. The returned `ack` is the `wake_ack` to send; it exists only once committed. */
16
+ receive(sender: string, wake: WakeEvent): Promise<WakeReceipt>;
17
+ /** Hands each committed wake to the loop, then removes it; drains run one at a time, and a crash in between hands the same wake over again, so the consumer is idempotent by event id. */
18
+ drain(consume: (wake: WakeEvent) => Promise<void>): Promise<number>;
19
+ closeScope(scope: string): Promise<void>;
20
+ /** Forgets the event ids of scopes closed longer ago than the retention; the close stays, so a late wake is refused. */
21
+ sweep(): Promise<readonly string[]>;
22
+ read(): Promise<WakeInboxRecord>;
23
+ }
24
+ export declare function createWakeInbox(options: WakeInboxOptions): WakeInbox;
25
+ //# sourceMappingURL=wake-inbox.d.ts.map
@@ -0,0 +1,85 @@
1
+ import { isStoreObject } from "./wake-outbox.js";
2
+ import { WAKE_RETENTION_MS } from "./wake-types.js";
3
+ const KIND = "execution.wake-inbox";
4
+ const EMPTY = { seen: {}, pending: [], closed: {} };
5
+ function decode(value) {
6
+ if (value === undefined)
7
+ return EMPTY;
8
+ if (isStoreObject(value) && isStoreObject(value.seen) && Array.isArray(value.pending) && isStoreObject(value.closed))
9
+ return value;
10
+ throw new Error("corrupt wake inbox record");
11
+ }
12
+ export function createWakeInbox(options) {
13
+ const { issuer, store, epoch, admission, clock, owner } = options;
14
+ const key = `${KIND}:${JSON.stringify([issuer])}`;
15
+ const read = async () => decode(await store.getDocument(key));
16
+ const write = async (record, step, eventId) => {
17
+ await store.commit(epoch, [
18
+ { op: "append", id: store.mintId(), kind: KIND, data: { step, executionId: eventId } },
19
+ { op: "put", key, data: record },
20
+ ], () => { });
21
+ };
22
+ const update = (decide) => admission.admit(async () => decide(await read()));
23
+ let draining = Promise.resolve();
24
+ const drainOnce = async (consume) => {
25
+ let taken = 0;
26
+ for (const wake of (await read()).pending) {
27
+ await consume(wake);
28
+ await update(async (record) => {
29
+ if (!record.pending.some((entry) => entry.eventId === wake.eventId))
30
+ return;
31
+ const pending = record.pending.filter((entry) => entry.eventId !== wake.eventId);
32
+ await write({ ...record, pending }, "take", wake.eventId);
33
+ });
34
+ taken += 1;
35
+ }
36
+ return taken;
37
+ };
38
+ return {
39
+ read,
40
+ receive: (sender, wake) => update(async (record) => {
41
+ const bound = owner(wake.scope);
42
+ if (bound === undefined)
43
+ return { kind: "refused", eventId: wake.eventId, reason: "unknown_scope" };
44
+ if (bound !== sender)
45
+ return { kind: "refused", eventId: wake.eventId, reason: "not_scope_hand" };
46
+ const seen = record.seen[wake.scope] ?? [];
47
+ if (seen.includes(wake.eventId))
48
+ return { kind: "ack", eventId: wake.eventId, duplicate: true };
49
+ if (record.closed[wake.scope] !== undefined)
50
+ return { kind: "refused", eventId: wake.eventId, reason: "scope_closed" };
51
+ await write({
52
+ ...record,
53
+ seen: { ...record.seen, [wake.scope]: [...seen, wake.eventId] },
54
+ pending: [...record.pending, wake],
55
+ }, "commit", wake.eventId);
56
+ return { kind: "ack", eventId: wake.eventId, duplicate: false };
57
+ }),
58
+ drain: (consume) => {
59
+ const run = draining.then(() => drainOnce(consume));
60
+ draining = run.catch(() => undefined);
61
+ return run;
62
+ },
63
+ closeScope: (scope) => update(async (record) => {
64
+ if (record.closed[scope] !== undefined)
65
+ return;
66
+ await write({ ...record, closed: { ...record.closed, [scope]: clock() } }, "close", null);
67
+ }),
68
+ sweep: () => update(async (record) => {
69
+ const now = clock();
70
+ const gone = Object.entries(record.closed)
71
+ .filter(([scope, closedAt]) => now > closedAt + WAKE_RETENTION_MS && record.seen[scope] !== undefined)
72
+ .map(([scope]) => scope);
73
+ if (gone.length === 0)
74
+ return [];
75
+ const drop = new Set(gone);
76
+ await write({
77
+ seen: Object.fromEntries(Object.entries(record.seen).filter(([scope]) => !drop.has(scope))),
78
+ pending: record.pending,
79
+ closed: record.closed,
80
+ }, "sweep", null);
81
+ return gone;
82
+ }),
83
+ };
84
+ }
85
+ //# sourceMappingURL=wake-inbox.js.map
@@ -0,0 +1,30 @@
1
+ import type { DurableStore, StoreValue } from "../durable/store.ts";
2
+ import type { AdmissionLine } from "../durable/store-admission.ts";
3
+ import { type WakeEvent, type WakeReceipt } from "./wake-types.ts";
4
+ export interface WakeOutboxOptions {
5
+ /** The hand this outbox belongs to; every event id it mints starts with it. */
6
+ readonly hand: string;
7
+ readonly store: DurableStore;
8
+ readonly epoch: number;
9
+ readonly admission: AdmissionLine;
10
+ readonly clock: () => number;
11
+ }
12
+ /** The hand side of design 5.6.4: a wake is durable before it is sent and removed only by its `wake_ack`. */
13
+ export interface WakeOutbox {
14
+ /** Commits the wake and returns it; the caller sends it (or a later `reoffer` does). */
15
+ offer(wake: Omit<WakeEvent, "eventId">): Promise<WakeEvent>;
16
+ /** Sends every un-acked wake in offer order (on reconnect) but those refused for good (not_scope_hand, scope_closed); a failed send or an unknown scope leaves it pending for the next re-offer. */
17
+ reoffer(send: (wake: WakeEvent) => Promise<WakeReceipt>): Promise<number>;
18
+ /** Applies one brain answer: an ack removes the wake; a refusal keeps it for retention and stops its re-offers. Idempotent. */
19
+ receipt(receipt: WakeReceipt): Promise<void>;
20
+ /** The scope closed: its un-acked wakes are kept until `closedAt + WAKE_RETENTION_MS`. */
21
+ closeScope(scope: string): Promise<void>;
22
+ /** Drops the wakes past retention, each with a logged `wake_expired` record; returns their ids. */
23
+ sweep(): Promise<readonly string[]>;
24
+ pending(): Promise<readonly WakeEvent[]>;
25
+ }
26
+ export declare const isStoreObject: (value: StoreValue | undefined) => value is {
27
+ readonly [key: string]: StoreValue;
28
+ };
29
+ export declare function createWakeOutbox(options: WakeOutboxOptions): WakeOutbox;
30
+ //# sourceMappingURL=wake-outbox.d.ts.map
@@ -0,0 +1,87 @@
1
+ import { WAKE_RETENTION_MS } from "./wake-types.js";
2
+ const KIND = "execution.wake-outbox";
3
+ const EMPTY = { pending: [], refused: {}, closed: {} };
4
+ export const isStoreObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
5
+ function decode(value) {
6
+ if (value === undefined)
7
+ return EMPTY;
8
+ if (isStoreObject(value) &&
9
+ Array.isArray(value.pending) &&
10
+ isStoreObject(value.refused) &&
11
+ isStoreObject(value.closed))
12
+ return value;
13
+ throw new Error("corrupt wake outbox record");
14
+ }
15
+ export function createWakeOutbox(options) {
16
+ const { hand, store, epoch, admission, clock } = options;
17
+ const key = `${KIND}:${JSON.stringify([hand])}`;
18
+ const read = async () => decode(await store.getDocument(key));
19
+ const write = async (record, step, eventId, extra = []) => {
20
+ const data = { step, eventId };
21
+ await store.commit(epoch, [
22
+ { op: "append", id: store.mintId(), kind: KIND, data },
23
+ ...extra.map((data) => ({
24
+ op: "append",
25
+ id: store.mintId(),
26
+ kind: "execution.wake-expired",
27
+ data,
28
+ })),
29
+ { op: "put", key, data: record },
30
+ ], () => { });
31
+ };
32
+ const update = (decide) => admission.admit(async () => decide(await read()));
33
+ const receipt = (answer) => update(async (record) => {
34
+ if (!record.pending.some((wake) => wake.eventId === answer.eventId))
35
+ return;
36
+ if (answer.kind === "refused") {
37
+ // The scope may not be bound yet (a brain restart, a bind racing this outbox): only a refusal that cannot change
38
+ // is recorded and stops the re-offers.
39
+ if (answer.reason === "unknown_scope" || record.refused[answer.eventId] === answer.reason)
40
+ return;
41
+ await write({ ...record, refused: { ...record.refused, [answer.eventId]: answer.reason } }, "refused", answer.eventId);
42
+ return;
43
+ }
44
+ const pending = record.pending.filter((wake) => wake.eventId !== answer.eventId);
45
+ const { [answer.eventId]: _settled, ...refused } = record.refused;
46
+ await write({ ...record, pending, refused }, "ack", answer.eventId);
47
+ });
48
+ return {
49
+ offer: (wake) => update(async (record) => {
50
+ const event = { ...wake, eventId: `${hand}:${store.mintId()}` };
51
+ await write({ ...record, pending: [...record.pending, event] }, "offer", event.eventId);
52
+ return event;
53
+ }),
54
+ reoffer: async (send) => {
55
+ let sent = 0;
56
+ const record = await read();
57
+ for (const wake of record.pending) {
58
+ if (record.refused[wake.eventId] !== undefined)
59
+ continue;
60
+ await receipt(await send(wake));
61
+ sent += 1;
62
+ }
63
+ return sent;
64
+ },
65
+ receipt,
66
+ closeScope: (scope) => update(async (record) => {
67
+ if (record.closed[scope] !== undefined)
68
+ return;
69
+ await write({ ...record, closed: { ...record.closed, [scope]: clock() } }, "close", null);
70
+ }),
71
+ sweep: () => update(async (record) => {
72
+ const now = clock();
73
+ const expired = record.pending.filter((wake) => {
74
+ const closedAt = record.closed[wake.scope];
75
+ return closedAt !== undefined && now > closedAt + WAKE_RETENTION_MS;
76
+ });
77
+ if (expired.length === 0)
78
+ return [];
79
+ const gone = new Set(expired.map((wake) => wake.eventId));
80
+ const refused = Object.fromEntries(Object.entries(record.refused).filter(([eventId]) => !gone.has(eventId)));
81
+ await write({ ...record, pending: record.pending.filter((wake) => !gone.has(wake.eventId)), refused }, "sweep", null, expired.map((wake) => ({ reason: "wake_expired", eventId: wake.eventId, scope: wake.scope })));
82
+ return [...gone];
83
+ }),
84
+ pending: async () => (await read()).pending,
85
+ };
86
+ }
87
+ //# sourceMappingURL=wake-outbox.js.map
@@ -0,0 +1,45 @@
1
+ import type { StoreValue } from "../durable/store.ts";
2
+ /** Design 5.6.4: an un-acked wake lives until its scope closes plus this long, then it is dropped as `wake_expired`. */
3
+ export declare const WAKE_RETENTION_MS: number;
4
+ /** One durable wake from a hand to the brain that owns its scope. `eventId` is unique per hand and stable on re-offer. */
5
+ export type WakeEvent = {
6
+ readonly eventId: string;
7
+ readonly scope: string;
8
+ readonly source: string;
9
+ readonly payload: StoreValue;
10
+ };
11
+ export type WakeRefusal = "not_scope_hand" | "unknown_scope" | "scope_closed";
12
+ /** What the brain answers a wake: `ack` only after the inbox commit; a refusal commits nothing and is never acked. */
13
+ export type WakeReceipt = {
14
+ readonly kind: "ack";
15
+ readonly eventId: string;
16
+ readonly duplicate: boolean;
17
+ } | {
18
+ readonly kind: "refused";
19
+ readonly eventId: string;
20
+ readonly reason: WakeRefusal;
21
+ };
22
+ export type WakeOutboxRecord = {
23
+ readonly pending: readonly WakeEvent[];
24
+ /** Pending wakes the brain refused for good, by event id: kept for retention, never re-offered. */
25
+ readonly refused: {
26
+ readonly [eventId: string]: WakeRefusal;
27
+ };
28
+ /** Scopes the hand closed, with the close time that starts their retention. */
29
+ readonly closed: {
30
+ readonly [scope: string]: number;
31
+ };
32
+ };
33
+ export type WakeInboxRecord = {
34
+ /** Every committed event id per scope: a re-offer is a duplicate, never a second wake. */
35
+ readonly seen: {
36
+ readonly [scope: string]: readonly string[];
37
+ };
38
+ /** Committed and not yet taken by the brain's loop, in commit order. */
39
+ readonly pending: readonly WakeEvent[];
40
+ /** Scopes the brain closed, with the close time; kept after their seen ids are dropped, so a late wake is refused. */
41
+ readonly closed: {
42
+ readonly [scope: string]: number;
43
+ };
44
+ };
45
+ //# sourceMappingURL=wake-types.d.ts.map
@@ -0,0 +1,3 @@
1
+ /** Design 5.6.4: an un-acked wake lives until its scope closes plus this long, then it is dropped as `wake_expired`. */
2
+ export const WAKE_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
3
+ //# sourceMappingURL=wake-types.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,13 @@
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 passes its arguments
7
+ * through unchanged; `run` owns the harness's own signal, updates and error semantics.
8
+ */
9
+ export declare function runOnPreparedToolHost<T>(toolCall: AgentToolCall, scopeId: string, recordWitness: WitnessSink | undefined, run: (args: unknown) => Promise<{
10
+ readonly outcome: T;
11
+ readonly result: AgentToolResult<unknown>;
12
+ }>): Promise<T>;
13
+ //# sourceMappingURL=tool-host-call.d.ts.map
@@ -0,0 +1,55 @@
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 passes its arguments
28
+ * through unchanged; `run` owns the harness's own signal, updates and error semantics.
29
+ */
30
+ export async function runOnPreparedToolHost(toolCall, scopeId, recordWitness, run) {
31
+ let settled;
32
+ const body = {
33
+ name: toolCall.name,
34
+ label: toolCall.name,
35
+ description: toolCall.name,
36
+ parameters: CLEARED_ARGUMENTS,
37
+ execute: async (_toolCallId, args) => {
38
+ const { outcome, result } = await run(args);
39
+ settled = { outcome };
40
+ return result;
41
+ },
42
+ };
43
+ await createPreparedToolHost({ afterToolFreeze: noPreflightCarry, removedToolHints: {} }, openMemoryBatchStore).execute({ scope: { id: scopeId, root: "" }, calls: [toolCall], mode: "sequential" }, {
44
+ emit: () => undefined,
45
+ ...(recordWitness === undefined ? {} : { recordWitness }),
46
+ local: {
47
+ context: { systemPrompt: "", messages: [], tools: [body] },
48
+ assistantMessage: issuingMessage(toolCall),
49
+ },
50
+ });
51
+ if (settled === undefined)
52
+ throw new Error(`agent harness: the prepared host ran no body for ${toolCall.name}`);
53
+ return settled.outcome;
54
+ }
55
+ //# 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,5 +1,6 @@
1
1
  import { validateToolArguments } from "@earendil-works/pi-ai";
2
2
  import { withAbortSignal } from "../context.js";
3
+ import { runOnPreparedToolHost } from "./tool-host-call.js";
3
4
  function createErrorToolResult(message) {
4
5
  return {
5
6
  content: [{ type: "text", text: message }],
@@ -53,27 +54,41 @@ export function applyBeforeToolDecision(prepared, decision) {
53
54
  }
54
55
  }
55
56
  /** Execute one cleared external tool effect, converting expected tool throws to error output. */
56
- export function executeToolCall(call, gate, onUpdate, toolContext, invocation, context) {
57
+ export function executeToolCall(call, gate, onUpdate, toolContext, invocation, context, recordWitness) {
57
58
  let acceptingUpdates = true;
58
59
  return gate.admit(async () => {
59
60
  const admittedContext = withAbortSignal(gate.signal, context);
60
61
  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
- }
62
+ // The harness already prepared, validated and hooked this call, so the host gets only its identity and cleared
63
+ // arguments: a stream flag such as `incomplete` would make the host refuse it before the body runs.
64
+ const toolCall = {
65
+ type: "toolCall",
66
+ id: call.toolCall.id,
67
+ name: call.toolCall.name,
68
+ arguments: call.args,
69
+ };
70
+ // The body receives the host's frozen copy of the arguments (a JSON-value round trip): identical for the JSON
71
+ // arguments a tool takes; a non-JSON value (NaN, Infinity, -0, a Date) would not survive it.
72
+ return runOnPreparedToolHost(toolCall, invocation.invocationId, recordWitness, async (args) => {
73
+ let executed;
74
+ try {
75
+ const result = await call.tool.execute(call.toolCall.id, args, (partial, options) => {
76
+ if (acceptingUpdates)
77
+ onUpdate(partial, options);
78
+ }, toolContext, invocation, admittedContext);
79
+ executed = { result, isError: false };
80
+ }
81
+ catch (error) {
82
+ executed = {
83
+ result: createErrorToolResult(error instanceof Error ? error.message : String(error)),
84
+ isError: true,
85
+ };
86
+ }
87
+ finally {
88
+ acceptingUpdates = false;
89
+ }
90
+ return { outcome: executed, result: executed.result };
91
+ });
77
92
  });
78
93
  }
79
94
  /** 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 {
package/dist/index.d.ts CHANGED
@@ -3,13 +3,38 @@ 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 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";
14
+ export { createErrorToolResult, createToolResultMessage, emitToolExecutionEnd, emitToolExecutionUpdate, emitToolResultMessage, shouldTerminateToolBatch, } from "./execution/tool-outcome-events.ts";
15
+ export { createAdmissionLine } from "./durable/store-admission.ts";
16
+ export { createMemoryStoreMedium, openMemoryStore } from "./durable/store-memory.ts";
17
+ export { createBatchCoordinator } from "./execution/coordinator.ts";
18
+ export type { BatchExecutor, BatchPlan } from "./execution/coordinator-types.ts";
19
+ export { createExecutionLedger } from "./execution/ledger.ts";
11
20
  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";
21
+ export { createHandEpochFence, EPOCH_FLOOR_MAX_STEP, type FloorRaise, HAND_SELF_SENDER, type HandEpochFence, type HandEpochFenceOptions, } from "./execution/remote-epoch.ts";
22
+ 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, RUN_CHANNEL, fileOutcomeOf, } from "./execution/device-files.ts";
23
+ export { HELLO_WAIT_MS } from "./execution/remote-device-files.ts";
24
+ export { fileRefusal, fileResult } from "./execution/remote-file-call.ts";
25
+ export { createModelPlaneClient, decodeModelPlaneRequest, MODEL_PLANE, type ModelPlaneRequest, serveModelPlane, } from "./execution/plane-model.ts";
26
+ export { createLoopToolHost, createSessionPlaneClient, createSplitToolHost, decodeSessionPlaneRequest, loopSideToolNames, SESSION_PLANE, type SessionPlaneRequest, serveSessionPlane, } from "./execution/plane-session.ts";
27
+ export { admitChainCall, CHAIN_COUNT_LIMIT, CHAIN_ORIGIN, ChainCountLimitError, decodeChainCount, nextChainCount, } from "./execution/chain-count.ts";
28
+ export { decodePlaneMessage, encodePlaneMessage, type NestedRequest, type PlaneHandler, type PlaneMessage, PlaneRefusedError, } from "./execution/plane.ts";
29
+ export { createLoopHookHost, type LoopHookHost, type LoopHookHostOptions, LoopHookFailedError, LoopHookRestartedError, } from "./execution/loop-hook-host.ts";
30
+ export { type LoopHookHand, type LoopHookHandOptions, type LoopHookPoint, type LoopHookRunner, serveLoopHooks, } from "./execution/loop-hook-host-hand.ts";
12
31
  export { createRemoteToolHost, type HandPlacement, type RemoteToolHostOptions } from "./execution/remote-tool-host.ts";
32
+ export { canonicalJson } from "./execution/canonical-digest.ts";
33
+ export { toStoreValue } from "./execution/prepared/executor-freeze.ts";
34
+ export type { ConsentClassifier } from "./execution/prepared/executor-types.ts";
35
+ export { openMemoryBatchStore } from "./execution/prepared/memory-batch-store.ts";
36
+ export { BatchStoreMissingError, noPreflightCarry, PreflightCarryMissingError } from "./execution/tool-host.ts";
37
+ export { createPreparedToolHost } from "./execution/prepared/pipeline-prepared.ts";
13
38
  export { type CarrierLink, createInProcessNetwork, type InProcessNetwork } from "./transport/in-process-carrier.ts";
14
39
  export { type LocalEndpoint, localEndpoint } from "./transport/local-endpoint.ts";
15
40
  export { createReliableTransport, type ReliableTransportOptions } from "./transport/reliable-transport.ts";
@@ -40,6 +65,6 @@ export * from "./response-timing.ts";
40
65
  export * from "./search/index.ts";
41
66
  export { setDefaultStreamFn } from "./stream-fn.ts";
42
67
  export { prepareToolArguments } from "./tool-arguments.ts";
43
- export { resolveToolNameAlias } from "./tool-name-alias.ts";
68
+ export { resolveToolNameAlias, withToolNameCorrection } from "./tool-name-alias.ts";
44
69
  export * from "./types.ts";
45
70
  //# sourceMappingURL=index.d.ts.map