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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/agent-loop.js +14 -140
  2. package/dist/agent.d.ts +4 -0
  3. package/dist/agent.js +4 -0
  4. package/dist/conformance/index.d.ts +7 -0
  5. package/dist/conformance/index.js +4 -0
  6. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  7. package/dist/conformance/loop-core-manifest.js +17 -0
  8. package/dist/conformance/registry.js +11 -17
  9. package/dist/egress/types.d.ts +102 -0
  10. package/dist/egress/types.js +7 -0
  11. package/dist/execution/canonical-digest.d.ts +10 -0
  12. package/dist/execution/canonical-digest.js +20 -0
  13. package/dist/execution/chain-count.d.ts +26 -0
  14. package/dist/execution/chain-count.js +45 -0
  15. package/dist/execution/coordinator-plan.d.ts +1 -2
  16. package/dist/execution/coordinator-plan.js +4 -17
  17. package/dist/execution/device-files-node.js +39 -1
  18. package/dist/execution/device-files.d.ts +30 -1
  19. package/dist/execution/device-files.js +38 -1
  20. package/dist/execution/ledger-types.d.ts +3 -1
  21. package/dist/execution/ledger.d.ts +9 -3
  22. package/dist/execution/ledger.js +8 -2
  23. package/dist/execution/loop-hook-host-hand.d.ts +33 -0
  24. package/dist/execution/loop-hook-host-hand.js +71 -0
  25. package/dist/execution/loop-hook-host-protocol.d.ts +46 -0
  26. package/dist/execution/loop-hook-host-protocol.js +47 -0
  27. package/dist/execution/loop-hook-host.d.ts +40 -0
  28. package/dist/execution/loop-hook-host.js +87 -0
  29. package/dist/execution/plane-session.d.ts +56 -0
  30. package/dist/execution/plane-session.js +178 -0
  31. package/dist/execution/plane.d.ts +5 -2
  32. package/dist/execution/plane.js +1 -1
  33. package/dist/execution/prepared/executor-body.d.ts +22 -0
  34. package/dist/execution/prepared/executor-body.js +73 -0
  35. package/dist/execution/prepared/executor-freeze.d.ts +17 -0
  36. package/dist/execution/prepared/executor-freeze.js +42 -0
  37. package/dist/execution/prepared/executor-pipeline.d.ts +11 -0
  38. package/dist/execution/prepared/executor-pipeline.js +26 -0
  39. package/dist/execution/prepared/executor-types.d.ts +131 -0
  40. package/dist/execution/prepared/executor-types.js +2 -0
  41. package/dist/execution/prepared/executor.d.ts +8 -0
  42. package/dist/execution/prepared/executor.js +261 -0
  43. package/dist/execution/prepared/memory-batch-store.d.ts +4 -0
  44. package/dist/execution/prepared/memory-batch-store.js +4 -0
  45. package/dist/execution/prepared/pipeline-prepared-batch.d.ts +27 -0
  46. package/dist/execution/prepared/pipeline-prepared-batch.js +175 -0
  47. package/dist/execution/prepared/pipeline-prepared.d.ts +10 -0
  48. package/dist/execution/prepared/pipeline-prepared.js +54 -0
  49. package/dist/execution/remote-device-files.js +33 -4
  50. package/dist/execution/remote-epoch-gate.d.ts +19 -0
  51. package/dist/execution/remote-epoch-gate.js +46 -0
  52. package/dist/execution/remote-epoch.d.ts +53 -0
  53. package/dist/execution/remote-epoch.js +74 -0
  54. package/dist/execution/remote-executor.d.ts +8 -1
  55. package/dist/execution/remote-executor.js +24 -6
  56. package/dist/execution/remote-file-call.js +1 -0
  57. package/dist/execution/remote-hand-ledger.d.ts +11 -3
  58. package/dist/execution/remote-hand-ledger.js +31 -15
  59. package/dist/execution/remote-link.d.ts +6 -1
  60. package/dist/execution/remote-link.js +50 -14
  61. package/dist/execution/remote-protocol.d.ts +30 -1
  62. package/dist/execution/remote-protocol.js +30 -0
  63. package/dist/execution/remote-tool-host.d.ts +12 -0
  64. package/dist/execution/remote-tool-host.js +3 -1
  65. package/dist/execution/testing/epoch-cases.d.ts +8 -0
  66. package/dist/execution/testing/epoch-cases.js +84 -0
  67. package/dist/execution/testing/epoch-harness.d.ts +47 -0
  68. package/dist/execution/testing/epoch-harness.js +172 -0
  69. package/dist/execution/testing/epoch-registry.d.ts +3 -0
  70. package/dist/execution/testing/epoch-registry.js +17 -0
  71. package/dist/execution/testing/hand-harness.d.ts +3 -0
  72. package/dist/execution/testing/hand-harness.js +27 -22
  73. package/dist/execution/testing/hand-registry.d.ts +3 -0
  74. package/dist/execution/testing/hand-registry.js +20 -0
  75. package/dist/execution/testing/kill-epoch.d.ts +9 -0
  76. package/dist/execution/testing/kill-epoch.js +71 -0
  77. package/dist/execution/testing/kill-hook.d.ts +14 -0
  78. package/dist/execution/testing/kill-hook.js +117 -0
  79. package/dist/execution/testing/multi-epoch-cases.d.ts +4 -0
  80. package/dist/execution/testing/multi-epoch-cases.js +29 -0
  81. package/dist/execution/tool-host.d.ts +13 -1
  82. package/dist/execution/tool-host.js +18 -1
  83. package/dist/harness/agent-harness.d.ts +6 -0
  84. package/dist/harness/execution/tool-host-call.d.ts +13 -0
  85. package/dist/harness/execution/tool-host-call.js +55 -0
  86. package/dist/harness/execution/tools.d.ts +2 -1
  87. package/dist/harness/execution/tools.js +32 -17
  88. package/dist/harness/runtime/drive/tools.js +1 -1
  89. package/dist/harness/runtime/harness.js +1 -0
  90. package/dist/harness/runtime/types.d.ts +1 -0
  91. package/dist/index.d.ts +16 -2
  92. package/dist/index.js +14 -1
  93. package/dist/public-entry.d.ts +10 -0
  94. package/dist/public-entry.js +23 -0
  95. package/dist/step-commit.d.ts +24 -0
  96. package/dist/step-commit.js +24 -0
  97. package/dist/tool-name-alias.d.ts +1 -7
  98. package/dist/tool-name-alias.js +0 -17
  99. package/dist/types.d.ts +37 -1
  100. package/package.json +3 -3
@@ -9,8 +9,10 @@ import { internalProgressSink } from "./internal-events.js";
9
9
  import { getDefaultStreamFn, withEmptyAssistantRecovery } from "./stream-fn.js";
10
10
  import { createTransportLiveness, StreamKeepAliveTimeoutError } from "./stream-keepalive.js";
11
11
  import { prepareAgentToolCallArguments } from "./tool-arguments.js";
12
- import { resolveCallTool, withToolNameCorrection } from "./tool-name-alias.js";
13
- import { createErrorToolResult, createToolResultMessage, emitToolExecutionEnd, emitToolExecutionUpdate, emitToolResultMessage, shouldTerminateToolBatch, } from "./execution/tool-outcome-events.js";
12
+ import { withToolNameCorrection } from "./tool-name-alias.js";
13
+ import { createPreparedToolHost } from "./execution/prepared/pipeline-prepared.js";
14
+ import { BatchStoreMissingError, PreflightCarryMissingError } from "./execution/tool-host.js";
15
+ import { createErrorToolResult, createToolResultMessage, emitToolExecutionEnd, emitToolResultMessage, } from "./execution/tool-outcome-events.js";
14
16
  /**
15
17
  * Start an agent loop with a new prompt message.
16
18
  * The prompt is added to the context and events are emitted for it.
@@ -208,6 +210,8 @@ async function runLoop(initialContext, newMessages, initialConfig, signal, emit,
208
210
  newMessages.push(result);
209
211
  toolResults.push(result);
210
212
  }
213
+ if (config.commitStep)
214
+ await config.commitStep({ message, providerToolResults });
211
215
  if (shouldTerminateAssistantTurn(message)) {
212
216
  // Hard exit: the decision is ignored, but the hook still sees the finished turn before turn_end.
213
217
  await config.finishTurn?.({ message, toolResults, context: currentContext, newMessages }, signal);
@@ -926,23 +930,7 @@ async function executeToolCalls(currentContext, assistantMessage, config, signal
926
930
  // channel and its result buffered; running it again would duplicate a
927
931
  // side-effecting tool.
928
932
  const toolCalls = assistantMessage.content.filter((c) => c.type === "toolCall" && !isCursorExecResolved(c));
929
- const host = config.toolHost ?? {
930
- execute: async (call, options) => {
931
- // Only yield when a witness sink is configured and returns a promise: an unconditional `await` adds a
932
- // microtask per call and reorders lifecycle vs message events against today's fused path (EQ E03).
933
- const recordWitness = options.recordWitness;
934
- if (recordWitness) {
935
- for (const raw of call.calls) {
936
- const pending = recordWitness({ pipeline: "legacy", toolCallId: raw.id });
937
- if (pending)
938
- await pending;
939
- }
940
- }
941
- return call.mode === "sequential"
942
- ? executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, options.signal, options.emit)
943
- : executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, options.signal, options.emit);
944
- },
945
- };
933
+ const host = config.toolHost ?? defaultToolHost();
946
934
  return host.execute({
947
935
  scope: config.executionScope ?? { id: crypto.randomUUID(), root: "" },
948
936
  calls: toolCalls,
@@ -953,128 +941,14 @@ async function executeToolCalls(currentContext, assistantMessage, config, signal
953
941
  recordWitness: config.onExecutionPipeline,
954
942
  local: { context: currentContext, assistantMessage },
955
943
  });
956
- }
957
- async function executeToolCallsSequential(currentContext, assistantMessage, toolCalls, config, signal, emit) {
958
- const finalizedCalls = [];
959
- const messages = [];
960
- for (const toolCall of toolCalls) {
961
- const tool = await resolveCallTool(currentContext, toolCall, config);
962
- await emit({
963
- type: "tool_execution_start",
964
- toolCallId: toolCall.id,
965
- toolName: tool?.name ?? toolCall.name,
966
- args: toolCall.arguments,
967
- });
968
- const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, tool, config, signal);
969
- let finalized;
970
- if (preparation.kind === "immediate") {
971
- finalized = {
972
- toolCall: preparation.toolCall,
973
- result: preparation.result,
974
- isError: preparation.isError,
975
- };
976
- }
977
- else {
978
- const executed = await executePreparedToolCall(preparation, signal, emitToolExecutionUpdate(preparation.toolCall, emit));
979
- finalized = await finalizeExecutedToolCall(currentContext, assistantMessage, preparation, executed, config, signal);
980
- }
981
- await emitToolExecutionEnd(finalized, emit);
982
- const toolResultMessage = createToolResultMessage(finalized);
983
- await emitToolResultMessage(toolResultMessage, emit);
984
- finalizedCalls.push(finalized);
985
- messages.push(toolResultMessage);
986
- if (signal?.aborted) {
987
- break;
988
- }
989
- }
990
- return {
991
- messages,
992
- terminate: shouldTerminateToolBatch(finalizedCalls),
993
- };
994
- }
995
- async function executeToolCallsParallel(currentContext, assistantMessage, toolCalls, config, signal, emit) {
996
- const finalizedCalls = [];
997
- const preparedCalls = [];
998
- let lastSequentialCall;
999
- let currentParallelWave = [];
1000
- for (const toolCall of toolCalls) {
1001
- const tool = await resolveCallTool(currentContext, toolCall, config);
1002
- await emit({
1003
- type: "tool_execution_start",
1004
- toolCallId: toolCall.id,
1005
- toolName: tool?.name ?? toolCall.name,
1006
- args: toolCall.arguments,
1007
- });
1008
- const preparation = await prepareToolCall(currentContext, assistantMessage, toolCall, tool, config, signal);
1009
- const isSequential = isSequentialToolCall(currentContext, preparation.toolCall);
1010
- const dependencies = isSequential
1011
- ? [...(lastSequentialCall ? [lastSequentialCall] : []), ...currentParallelWave]
1012
- : lastSequentialCall
1013
- ? [lastSequentialCall]
1014
- : [];
1015
- preparedCalls.push({ preparation, isSequential, dependencies });
1016
- if (isSequential) {
1017
- // Dependencies are assigned in the second phase after all preflight hooks
1018
- // have completed, so a later preflight abort vetoes every execution.
1019
- lastSequentialCall = undefined;
1020
- currentParallelWave = [];
1021
- }
1022
- else {
1023
- currentParallelWave.push(Promise.resolve(undefined));
1024
- }
1025
- if (signal?.aborted) {
1026
- break;
1027
- }
1028
- }
1029
- let previousSequential;
1030
- let previousWave = [];
1031
- for (const { preparation, isSequential } of preparedCalls) {
1032
- const dependencies = isSequential
1033
- ? [...(previousSequential ? [previousSequential] : []), ...previousWave]
1034
- : previousSequential
1035
- ? [previousSequential]
1036
- : [];
1037
- const finalizedCall = (async () => {
1038
- await Promise.all(dependencies);
1039
- const finalized = signal?.aborted
1040
- ? { toolCall: preparation.toolCall, result: createErrorToolResult("Operation aborted"), isError: true }
1041
- : await runPreparedToolCall(currentContext, assistantMessage, preparation, config, signal, emit);
1042
- await emitToolExecutionEnd(finalized, emit);
1043
- return finalized;
1044
- })();
1045
- finalizedCalls.push(finalizedCall);
1046
- if (isSequential) {
1047
- previousSequential = finalizedCall;
1048
- previousWave = [];
1049
- }
1050
- else
1051
- previousWave.push(finalizedCall);
944
+ function defaultToolHost() {
945
+ if (config.batchStoreFactory === undefined)
946
+ throw new BatchStoreMissingError();
947
+ const afterToolFreeze = config.afterToolFreeze;
948
+ if (afterToolFreeze === undefined)
949
+ throw new PreflightCarryMissingError();
950
+ return createPreparedToolHost({ ...config, afterToolFreeze }, config.batchStoreFactory);
1052
951
  }
1053
- const orderedFinalizedCalls = await Promise.all(finalizedCalls);
1054
- const messages = [];
1055
- for (const finalized of orderedFinalizedCalls) {
1056
- const toolResultMessage = createToolResultMessage(finalized);
1057
- await emitToolResultMessage(toolResultMessage, emit);
1058
- messages.push(toolResultMessage);
1059
- }
1060
- return {
1061
- messages,
1062
- terminate: shouldTerminateToolBatch(orderedFinalizedCalls),
1063
- };
1064
- }
1065
- async function runPreparedToolCall(currentContext, assistantMessage, preparation, config, signal, emit) {
1066
- if (preparation.kind === "immediate") {
1067
- return {
1068
- toolCall: preparation.toolCall,
1069
- result: preparation.result,
1070
- isError: preparation.isError,
1071
- };
1072
- }
1073
- const executed = await executePreparedToolCall(preparation, signal, emitToolExecutionUpdate(preparation.toolCall, emit));
1074
- return finalizeExecutedToolCall(currentContext, assistantMessage, preparation, executed, config, signal);
1075
- }
1076
- function isSequentialToolCall(currentContext, toolCall) {
1077
- return currentContext.tools?.find((tool) => tool.name === toolCall.name)?.executionMode === "sequential";
1078
952
  }
1079
953
  export { prepareAgentToolCallArguments };
1080
954
  export function prepareAgentToolCall(tool, toolCall) {
package/dist/agent.d.ts CHANGED
@@ -38,6 +38,8 @@ export interface AgentOptions {
38
38
  maxRetryDelayMs?: number;
39
39
  toolExecution?: ToolExecutionMode;
40
40
  toolHost?: AgentLoopConfig["toolHost"];
41
+ batchStoreFactory?: AgentLoopConfig["batchStoreFactory"];
42
+ afterToolFreeze?: AgentLoopConfig["afterToolFreeze"];
41
43
  executionScope?: AgentLoopConfig["executionScope"];
42
44
  onExecutionPipeline?: AgentLoopConfig["onExecutionPipeline"];
43
45
  removedToolHints?: Record<string, string>;
@@ -117,6 +119,8 @@ export declare class Agent {
117
119
  /** Tool execution strategy for assistant messages that contain multiple tool calls. */
118
120
  toolExecution: ToolExecutionMode;
119
121
  toolHost?: AgentLoopConfig["toolHost"];
122
+ batchStoreFactory?: AgentLoopConfig["batchStoreFactory"];
123
+ afterToolFreeze?: AgentLoopConfig["afterToolFreeze"];
120
124
  executionScope: NonNullable<AgentLoopConfig["executionScope"]>;
121
125
  getExecutionScope?: () => NonNullable<AgentLoopConfig["executionScope"]>;
122
126
  onExecutionPipeline?: AgentLoopConfig["onExecutionPipeline"];
package/dist/agent.js CHANGED
@@ -168,6 +168,8 @@ export class Agent {
168
168
  this.maxRetryDelayMs = runtimeOptions.maxRetryDelayMs;
169
169
  this.toolExecution = runtimeOptions.toolExecution ?? "parallel";
170
170
  this.toolHost = runtimeOptions.toolHost;
171
+ this.batchStoreFactory = runtimeOptions.batchStoreFactory;
172
+ this.afterToolFreeze = runtimeOptions.afterToolFreeze;
171
173
  this.executionScope = runtimeOptions.executionScope ?? { id: crypto.randomUUID(), root: "" };
172
174
  this.onExecutionPipeline = runtimeOptions.onExecutionPipeline;
173
175
  this.removedToolHints = runtimeOptions.removedToolHints ?? {};
@@ -489,6 +491,8 @@ export class Agent {
489
491
  cursorExecHandlers: this.cursorExecHandlers,
490
492
  toolExecution: this.toolExecution,
491
493
  toolHost: this.toolHost,
494
+ batchStoreFactory: this.batchStoreFactory,
495
+ afterToolFreeze: this.afterToolFreeze,
492
496
  executionScope: this.getExecutionScope?.() ?? this.executionScope,
493
497
  onExecutionPipeline: this.onExecutionPipeline,
494
498
  removedToolHints: this.removedToolHints,
@@ -8,6 +8,7 @@ export type { SuiteHashEntry } from "./suite-hash.ts";
8
8
  export { computeSuiteHash, sha256Hex } from "./suite-hash.ts";
9
9
  export type { CommitResult, DurableStore, DurableStoreErrorCode, DurableStoreOptions, RecordScan, StoreDocument, StoreOperation, StoreRecord, StoreSnapshot, StoreValue, StoreWrite, StoreWritePoint, } from "../durable/store.ts";
10
10
  export { DurableStoreError } from "../durable/store.ts";
11
+ export type { AdmissionLine } from "../durable/store-admission.ts";
11
12
  export type { KillDeclaration } from "../durable/testing/kill-store.ts";
12
13
  export { KILL_STORE_CASES, KILL_STORE_DECLARATIONS } from "../durable/testing/kill-store.ts";
13
14
  export { STORE_CASES } from "../durable/testing/store-cases.ts";
@@ -44,10 +45,16 @@ export type { ExecutionLedger } from "../execution/ledger.ts";
44
45
  export type { ExecutionAdmission, ExecutionCommand, ExecutionEntry, ExecutionEvent, ExecutionKey, ExecutionOutcome, ExecutionProgress, FrozenCall, LedgerReply, } from "../execution/ledger-types.ts";
45
46
  export { LEDGER_CASES } from "../execution/testing/ledger-cases.ts";
46
47
  export { KILL_LEDGER_CASES, KILL_LEDGER_DECLARATIONS } from "../execution/testing/kill-ledger.ts";
48
+ export { EPOCH_CASES } from "../execution/testing/epoch-cases.ts";
47
49
  export { FAULT_HAND_CASES } from "../execution/testing/fault-hand-cases.ts";
48
50
  export type { HandCaseAdapters } from "../execution/testing/hand-harness.ts";
49
51
  export type { KillHandDeclaration } from "../execution/testing/kill-hand.ts";
50
52
  export { KILL_HAND_CASES, KILL_HAND_DECLARATIONS } from "../execution/testing/kill-hand.ts";
53
+ export type { KillEpochDeclaration } from "../execution/testing/kill-epoch.ts";
54
+ export { KILL_EPOCH_CASES, KILL_EPOCH_DECLARATIONS } from "../execution/testing/kill-epoch.ts";
55
+ export { MULTI_EPOCH_CASES } from "../execution/testing/multi-epoch-cases.ts";
56
+ export type { KillHookDeclaration } from "../execution/testing/kill-hook.ts";
57
+ export { KILL_HOOK_CASES, KILL_HOOK_DECLARATIONS } from "../execution/testing/kill-hook.ts";
51
58
  export { MULTI_HAND_CASES } from "../execution/testing/multi-hand-cases.ts";
52
59
  export type { KillLedgerDeclaration } from "../execution/testing/kill-ledger.ts";
53
60
  export type { BatchCoordinator, BatchCoordinatorOptions } from "../execution/coordinator.ts";
@@ -23,8 +23,12 @@ export { TransportClosedError } from "../transport/transport.js";
23
23
  export { createExecutionLedger } from "../execution/ledger.js";
24
24
  export { LEDGER_CASES } from "../execution/testing/ledger-cases.js";
25
25
  export { KILL_LEDGER_CASES, KILL_LEDGER_DECLARATIONS } from "../execution/testing/kill-ledger.js";
26
+ export { EPOCH_CASES } from "../execution/testing/epoch-cases.js";
26
27
  export { FAULT_HAND_CASES } from "../execution/testing/fault-hand-cases.js";
27
28
  export { KILL_HAND_CASES, KILL_HAND_DECLARATIONS } from "../execution/testing/kill-hand.js";
29
+ export { KILL_EPOCH_CASES, KILL_EPOCH_DECLARATIONS } from "../execution/testing/kill-epoch.js";
30
+ export { MULTI_EPOCH_CASES } from "../execution/testing/multi-epoch-cases.js";
31
+ export { KILL_HOOK_CASES, KILL_HOOK_DECLARATIONS } from "../execution/testing/kill-hook.js";
28
32
  export { MULTI_HAND_CASES } from "../execution/testing/multi-hand-cases.js";
29
33
  export { BatchManifestConflictError, createBatchCoordinator } from "../execution/coordinator.js";
30
34
  export { interruptedReplayText } from "../execution/coordinator-plan.js";
@@ -4,7 +4,7 @@
4
4
  * Host adapters, carriers, persistence implementations and the Node harness stay outside.
5
5
  * Extend this closure when adding loop modules; never add a host implementation to it.
6
6
  */
7
- export declare const LOOP_CORE_MODULES: readonly ["agent.ts", "agent-loop.ts", "assistant-terminal-state.ts", "empty-assistant-recovery.ts", "internal-events.ts", "local-failure.ts", "response-timing.ts", "stream-fn.ts", "stream-keepalive.ts", "tool-arguments.ts", "tool-name-alias.ts", "types.ts", "durable/store.ts", "execution/tool-host.ts", "execution/tool-outcome-events.ts", "durable/store-admission.ts", "durable/wake-host.ts", "transport/transport.ts"];
7
+ export declare const LOOP_CORE_MODULES: readonly ["agent.ts", "agent-loop.ts", "assistant-terminal-state.ts", "empty-assistant-recovery.ts", "internal-events.ts", "local-failure.ts", "response-timing.ts", "stream-fn.ts", "stream-keepalive.ts", "tool-arguments.ts", "tool-name-alias.ts", "types.ts", "durable/store.ts", "execution/tool-host.ts", "execution/tool-outcome-events.ts", "execution/canonical-digest.ts", "execution/coordinator.ts", "execution/coordinator-codec.ts", "execution/coordinator-consent.ts", "execution/coordinator-plan.ts", "execution/coordinator-types.ts", "execution/ledger.ts", "execution/ledger-codec.ts", "execution/ledger-transition.ts", "execution/ledger-types.ts", "execution/prepared/executor.ts", "execution/prepared/executor-body.ts", "execution/prepared/executor-freeze.ts", "execution/prepared/executor-pipeline.ts", "execution/prepared/executor-types.ts", "execution/prepared/pipeline-prepared.ts", "execution/prepared/pipeline-prepared-batch.ts", "durable/store-admission.ts", "durable/wake-host.ts", "transport/transport.ts"];
8
8
  /**
9
9
  * Existing portable model/message utilities and schema types, not provider runtimes.
10
10
  * Exact specifiers deliberately exclude compat, OAuth, SDKs and host-specific subpaths.
@@ -20,6 +20,23 @@ export const LOOP_CORE_MODULES = [
20
20
  "durable/store.ts",
21
21
  "execution/tool-host.ts",
22
22
  "execution/tool-outcome-events.ts",
23
+ "execution/canonical-digest.ts",
24
+ "execution/coordinator.ts",
25
+ "execution/coordinator-codec.ts",
26
+ "execution/coordinator-consent.ts",
27
+ "execution/coordinator-plan.ts",
28
+ "execution/coordinator-types.ts",
29
+ "execution/ledger.ts",
30
+ "execution/ledger-codec.ts",
31
+ "execution/ledger-transition.ts",
32
+ "execution/ledger-types.ts",
33
+ "execution/prepared/executor.ts",
34
+ "execution/prepared/executor-body.ts",
35
+ "execution/prepared/executor-freeze.ts",
36
+ "execution/prepared/executor-pipeline.ts",
37
+ "execution/prepared/executor-types.ts",
38
+ "execution/prepared/pipeline-prepared.ts",
39
+ "execution/prepared/pipeline-prepared-batch.ts",
23
40
  "durable/store-admission.ts",
24
41
  "durable/wake-host.ts",
25
42
  "transport/transport.ts",
@@ -1,4 +1,6 @@
1
- import { KILL_HAND_DECLARATIONS } from "../execution/testing/kill-hand.js";
1
+ import { EPOCH_REGISTRY } from "../execution/testing/epoch-registry.js";
2
+ import { HAND_REGISTRY } from "../execution/testing/hand-registry.js";
3
+ import { KILL_HOOK_DECLARATIONS } from "../execution/testing/kill-hook.js";
2
4
  import { BATCH_REGISTRY } from "../execution/testing/batch-registry.js";
3
5
  import { LEDGER_REGISTRY } from "../execution/testing/ledger-registry.js";
4
6
  import { LIFECYCLE_REGISTRY } from "../execution/testing/lifecycle-registry.js";
@@ -33,24 +35,14 @@ const wakeCase = (id, impl, expected) => ({
33
35
  adapters: ["store", "wake"],
34
36
  expected,
35
37
  });
36
- const HAND_INTRO = "#5482";
37
- const handCase = (id, impl, expected) => ({
38
+ const KILL_HOOK_IMPL = "packages/agent/src/execution/testing/kill-hook.ts";
39
+ const HOOK_REGISTRY = KILL_HOOK_DECLARATIONS.map(({ id, expected }) => ({
38
40
  id,
39
- impl,
40
- intro: HAND_INTRO,
41
- adapters: ["store", "transport", "executor"],
41
+ impl: KILL_HOOK_IMPL,
42
+ intro: "#5726",
43
+ adapters: ["transport", "executor"],
42
44
  expected,
43
- });
44
- const KILL_HAND_IMPL = "packages/agent/src/execution/testing/kill-hand.ts";
45
- const MULTI_HAND_IMPL = "packages/agent/src/execution/testing/multi-hand-cases.ts";
46
- const FAULT_HAND_IMPL = "packages/agent/src/execution/testing/fault-hand-cases.ts";
47
- const HAND_REGISTRY = [
48
- ...KILL_HAND_DECLARATIONS.map(({ id, expected }) => handCase(id, KILL_HAND_IMPL, expected)),
49
- handCase("MULTI-HAND-01", MULTI_HAND_IMPL, "N scopes batch at once on one hand; each scope's calls start in lane order"),
50
- handCase("MULTI-KILL-01", MULTI_HAND_IMPL, "cross-machine: a hand killed with several scopes in flight; each ends hand_restarted, uncertain, never rerun"),
51
- ...["slow", "lossy", "laggy", "flap", "drop-reattach"].map((profile, index) => handCase(`FAULT-HAND-0${index + 1}`, FAULT_HAND_IMPL, `${profile} profile: every call settles with its unfaulted result, runs once, per-scope order kept`)),
52
- handCase("FAULT-HAND-MULTI-01", FAULT_HAND_IMPL, "hand unreachable past the resume window: dependent calls pause, then each scope resumes exactly once"),
53
- ];
45
+ }));
54
46
  const storeCase = (id, impl, expected) => ({
55
47
  id,
56
48
  impl,
@@ -103,5 +95,7 @@ export const CONFORMANCE_REGISTRY = [
103
95
  faultCase(4, "flap"),
104
96
  faultCase(5, "drop-reattach"),
105
97
  ...HAND_REGISTRY,
98
+ ...EPOCH_REGISTRY,
99
+ ...HOOK_REGISTRY,
106
100
  ];
107
101
  //# sourceMappingURL=registry.js.map
@@ -0,0 +1,102 @@
1
+ /**
2
+ * `ModelEgress`: one provider-pipeline layer that decides, per provider and per request, whether a model call
3
+ * is dialed directly (today's stream function, unchanged), with secrets released from sealed custody, or
4
+ * through a device the user owns. Only types and constants live here; implementations live with the
5
+ * provider pipeline, and the fused path passes today's stream function through untouched.
6
+ */
7
+ import type { StreamFn } from "../types.ts";
8
+ export type ProviderId = string;
9
+ export type DeviceId = string;
10
+ export type Epoch = number;
11
+ export type EgressRoute = "direct" | "sealed" | "device";
12
+ export type RouteReason = "fused" | "custody:sealed" | "custody:device" | "roster:unknown" | "custody:cwd-scoped" | "custody:unavailable" | "owner:revoked" | "definition:variant" | "address:private" | "address:self" | "address:unknown" | "capability:local-only" | "capability:ambient" | "capability:callback-stream" | "capability:callback-stream-undefined" | "api:no-fetch-injection" | "network:device-bound" | "provider:extension" | "provider:hand-local" | "provider:unknown" | "hook:stream" | "hook:stream-undefined" | "hook:unknown" | "hook:request-offline" | "redirect:cross-origin";
13
+ export type WaitCondition = {
14
+ readonly kind: "device-online";
15
+ readonly deviceId: DeviceId;
16
+ } | {
17
+ readonly kind: "custody-available";
18
+ } | {
19
+ readonly kind: "refresh-ack";
20
+ readonly providerId: ProviderId;
21
+ } | {
22
+ readonly kind: "roster-sync";
23
+ } | {
24
+ readonly kind: "hand-selected";
25
+ } | {
26
+ readonly kind: "hand-advertised";
27
+ readonly deviceId: DeviceId;
28
+ } | {
29
+ readonly kind: "config-head-change";
30
+ } | {
31
+ readonly kind: "live-digest-change";
32
+ readonly deviceId: DeviceId;
33
+ readonly providerId: ProviderId;
34
+ } | {
35
+ readonly kind: "storage-available";
36
+ } | {
37
+ readonly kind: "epoch-fresh";
38
+ } | {
39
+ readonly kind: "claim-renewed";
40
+ } | {
41
+ readonly kind: "user-choice";
42
+ readonly choiceId: string;
43
+ };
44
+ export interface EgressRouteDecision {
45
+ readonly route: EgressRoute;
46
+ readonly reason: RouteReason;
47
+ readonly deviceId?: DeviceId;
48
+ /** False: the call waits in the stream (never fails) until `waitFor` holds, showing `steer`. */
49
+ readonly servedNow: boolean;
50
+ readonly steer?: string;
51
+ readonly waitFor?: readonly WaitCondition[];
52
+ readonly requestHooksOn?: DeviceId;
53
+ readonly executorHooks?: "enabled" | "disabled";
54
+ readonly serveOwnDefinition?: true;
55
+ }
56
+ /** The durable admission fence; `generation` is the agent instance generation, and older generations are refused for good. */
57
+ export interface AdmissionFence {
58
+ readonly epoch: Epoch;
59
+ readonly admissionSeq: number;
60
+ readonly generation: number;
61
+ }
62
+ export interface StepRef {
63
+ readonly kind: "step";
64
+ readonly sessionId: string;
65
+ readonly stepId: string;
66
+ readonly attempt: number;
67
+ readonly fence: AdmissionFence;
68
+ }
69
+ export interface AuxRef {
70
+ readonly kind: "aux";
71
+ readonly sessionId: string;
72
+ readonly auxId: string;
73
+ readonly auxKey: string;
74
+ readonly streamKind: string;
75
+ readonly fence: AdmissionFence;
76
+ }
77
+ export type CallRef = StepRef | AuxRef;
78
+ export interface EgressWait {
79
+ readonly call: CallRef;
80
+ readonly reason: RouteReason | "device-offline" | "result-pending" | "refresh-pending" | "config-churn" | "epoch-stale" | "claim-expired";
81
+ readonly steer: string;
82
+ readonly waitFor: readonly WaitCondition[];
83
+ }
84
+ export interface EgressHostHooks {
85
+ currentStep(): StepRef;
86
+ admitAux(streamKind: string, auxKey: string): Promise<AuxRef>;
87
+ onWait(wait: EgressWait): Promise<void>;
88
+ onWaitEnd(callId: string): Promise<void>;
89
+ historyHasStep(stepId: string): Promise<boolean>;
90
+ }
91
+ /** Bound from a hosted session latching on a failed step commit to its rebuilt instance accepting work. */
92
+ export declare const HOSTED_REBUILD_DEADLINE_MS = 5000;
93
+ /** Maximum age of a registry epoch check accepted for a secret release, a step commit or a tool dispatch. */
94
+ export declare const EPOCH_FRESHNESS_MS = 5000;
95
+ /** Margin a new placement owner waits beyond `EPOCH_FRESHNESS_MS` before cutting over a moved session. */
96
+ export declare const MOVE_SKEW_MS = 2000;
97
+ export interface ModelEgress {
98
+ /** Pure and cheap: no I/O, safe to call from UI code. */
99
+ routeFor(providerId: ProviderId): EgressRouteDecision;
100
+ readonly stream: StreamFn;
101
+ }
102
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,7 @@
1
+ /** Bound from a hosted session latching on a failed step commit to its rebuilt instance accepting work. */
2
+ export const HOSTED_REBUILD_DEADLINE_MS = 5_000;
3
+ /** Maximum age of a registry epoch check accepted for a secret release, a step commit or a tool dispatch. */
4
+ export const EPOCH_FRESHNESS_MS = 5_000;
5
+ /** Margin a new placement owner waits beyond `EPOCH_FRESHNESS_MS` before cutting over a moved session. */
6
+ export const MOVE_SKEW_MS = 2_000;
7
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,10 @@
1
+ import type { StoreValue } from "../durable/store.ts";
2
+ /**
3
+ * The canonical JSON of a store value: object keys sorted by UTF-16 code unit, no whitespace. Every execution digest
4
+ * (a batch manifest, a call's request, a frozen call, a tool schema) hashes this form, so two sides that build the same
5
+ * value agree on its digest.
6
+ */
7
+ export declare function canonicalJson(value: StoreValue): string;
8
+ /** Lower-case hex SHA-256 of {@link canonicalJson}, through Web Crypto so the agent loop stays browser-safe. */
9
+ export declare function canonicalDigest(value: StoreValue): Promise<string>;
10
+ //# sourceMappingURL=canonical-digest.d.ts.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The canonical JSON of a store value: object keys sorted by UTF-16 code unit, no whitespace. Every execution digest
3
+ * (a batch manifest, a call's request, a frozen call, a tool schema) hashes this form, so two sides that build the same
4
+ * value agree on its digest.
5
+ */
6
+ export function canonicalJson(value) {
7
+ if (Array.isArray(value))
8
+ return `[${value.map(canonicalJson).join(",")}]`;
9
+ if (value !== null && typeof value === "object") {
10
+ const entries = Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
11
+ return `{${entries.map(([key, inner]) => `${JSON.stringify(key)}:${canonicalJson(inner)}`).join(",")}}`;
12
+ }
13
+ return JSON.stringify(value);
14
+ }
15
+ /** Lower-case hex SHA-256 of {@link canonicalJson}, through Web Crypto so the agent loop stays browser-safe. */
16
+ export async function canonicalDigest(value) {
17
+ const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonicalJson(value)));
18
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
19
+ }
20
+ //# sourceMappingURL=canonical-digest.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The hop count of a thread chain (brain/hand split, decision K8): session A's thread tool prompts session B, B's
3
+ * prompts A again, and so on. A→B→A is allowed. Each call carries the count of the hop it makes; a session started by
4
+ * a thread call is at that call's count, and its own thread calls carry one more. The only limit is a count the user
5
+ * sets; unset means unlimited. There is no cost limit, no hidden default and no refusal for coming back to an origin.
6
+ */
7
+ /** The refusal reason of a thread call past the user's count limit. */
8
+ export declare const CHAIN_COUNT_LIMIT = "chain_count_limit";
9
+ /** A user-started session is at count 0; its first thread call is hop 1. */
10
+ export declare const CHAIN_ORIGIN = 0;
11
+ export declare class ChainCountLimitError extends Error {
12
+ readonly reason = "chain_count_limit";
13
+ readonly count: number;
14
+ readonly limit: number;
15
+ constructor(count: number, limit: number);
16
+ }
17
+ /** The count a thread call sent from a session at `sessionCount` carries. */
18
+ export declare function nextChainCount(sessionCount: number): number;
19
+ /** Parses the count a thread call carries; absent means the call starts a chain (hop 1 from a user-started session). */
20
+ export declare function decodeChainCount(value: unknown): number;
21
+ /**
22
+ * Admits a thread call that makes its chain `count` hops long. `readLimit` is read at each admission, never cached
23
+ * (on the CLI: the user's `threads.chainCountLimit` setting); `undefined` admits every call at any length.
24
+ */
25
+ export declare function admitChainCall(count: number, readLimit: () => number | undefined): number;
26
+ //# sourceMappingURL=chain-count.d.ts.map
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The hop count of a thread chain (brain/hand split, decision K8): session A's thread tool prompts session B, B's
3
+ * prompts A again, and so on. A→B→A is allowed. Each call carries the count of the hop it makes; a session started by
4
+ * a thread call is at that call's count, and its own thread calls carry one more. The only limit is a count the user
5
+ * sets; unset means unlimited. There is no cost limit, no hidden default and no refusal for coming back to an origin.
6
+ */
7
+ /** The refusal reason of a thread call past the user's count limit. */
8
+ export const CHAIN_COUNT_LIMIT = "chain_count_limit";
9
+ /** A user-started session is at count 0; its first thread call is hop 1. */
10
+ export const CHAIN_ORIGIN = 0;
11
+ export class ChainCountLimitError extends Error {
12
+ constructor(count, limit) {
13
+ super(`This thread call would be hop ${count} of its chain; your thread chain count limit is ${limit}.`);
14
+ this.reason = CHAIN_COUNT_LIMIT;
15
+ this.name = "ChainCountLimitError";
16
+ this.count = count;
17
+ this.limit = limit;
18
+ }
19
+ }
20
+ const isCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
21
+ /** The count a thread call sent from a session at `sessionCount` carries. */
22
+ export function nextChainCount(sessionCount) {
23
+ if (!isCount(sessionCount))
24
+ throw new TypeError(`not a chain count: ${String(sessionCount)}`);
25
+ return sessionCount + 1;
26
+ }
27
+ /** Parses the count a thread call carries; absent means the call starts a chain (hop 1 from a user-started session). */
28
+ export function decodeChainCount(value) {
29
+ if (value === undefined)
30
+ return nextChainCount(CHAIN_ORIGIN);
31
+ if (!isCount(value) || value === CHAIN_ORIGIN)
32
+ throw new TypeError(`malformed chain count: ${JSON.stringify(value)}`);
33
+ return value;
34
+ }
35
+ /**
36
+ * Admits a thread call that makes its chain `count` hops long. `readLimit` is read at each admission, never cached
37
+ * (on the CLI: the user's `threads.chainCountLimit` setting); `undefined` admits every call at any length.
38
+ */
39
+ export function admitChainCall(count, readLimit) {
40
+ const limit = readLimit();
41
+ if (limit !== undefined && count > limit)
42
+ throw new ChainCountLimitError(count, limit);
43
+ return count;
44
+ }
45
+ //# sourceMappingURL=chain-count.js.map
@@ -1,7 +1,6 @@
1
1
  import type { BatchManifest, BatchPlan, CallOutcome, PrepareReply, SettleReply } from "./coordinator-types.ts";
2
2
  /**
3
- * Release dependencies exactly as today's scheduler assigns them (agent-loop.ts, executeToolCallsParallel): a
4
- * sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
3
+ * Release dependencies exactly as the agent loop has always ordered a batch: a sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
5
4
  * previous sequential call only.
6
5
  */
7
6
  export declare function batchDependencies(calls: readonly {
@@ -1,7 +1,7 @@
1
1
  import { TOOL_RESULT_PLACEHOLDER } from "@earendil-works/pi-ai";
2
+ import { canonicalDigest } from "./canonical-digest.js";
2
3
  /**
3
- * Release dependencies exactly as today's scheduler assigns them (agent-loop.ts, executeToolCallsParallel): a
4
- * sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
4
+ * Release dependencies exactly as the agent loop has always ordered a batch: a sequential call waits for the previous sequential call and every parallel call since; a parallel call waits for the
5
5
  * previous sequential call only.
6
6
  */
7
7
  export function batchDependencies(calls) {
@@ -22,19 +22,6 @@ export function batchDependencies(calls) {
22
22
  }
23
23
  return result;
24
24
  }
25
- function canonical(value) {
26
- if (Array.isArray(value))
27
- return `[${value.map(canonical).join(",")}]`;
28
- if (value !== null && typeof value === "object") {
29
- const entries = Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
30
- return `{${entries.map(([key, inner]) => `${JSON.stringify(key)}:${canonical(inner)}`).join(",")}}`;
31
- }
32
- return JSON.stringify(value);
33
- }
34
- async function digest(value) {
35
- const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical(value)));
36
- return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
37
- }
38
25
  export async function buildBatchManifest(issuer, plan) {
39
26
  const dependencies = batchDependencies(plan.calls);
40
27
  const calls = [];
@@ -45,11 +32,11 @@ export async function buildBatchManifest(issuer, plan) {
45
32
  sourceIndex,
46
33
  dependsOn: placement.dependsOn,
47
34
  wave: placement.wave,
48
- requestDigest: await digest({ name: call.name, args: call.args }),
35
+ requestDigest: await canonicalDigest({ name: call.name, args: call.args }),
49
36
  });
50
37
  }
51
38
  const { calls: _calls, ...header } = plan;
52
- return { ...header, issuer, calls, manifestDigest: await digest({ ...header, issuer, calls }) };
39
+ return { ...header, issuer, calls, manifestDigest: await canonicalDigest({ ...header, issuer, calls }) };
53
40
  }
54
41
  /**
55
42
  * A reply after which no later call is prepared and the decision is ABORT. A raw `settled` outcome other than a result