maka-agent 0.2.0-dev.23.20260906 → 0.2.0-dev.25.20260908

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 (215) hide show
  1. package/README.md +38 -19
  2. package/README.zh-CN.md +34 -19
  3. package/dist/acp/maka-acp-agent.js +2 -1
  4. package/dist/acp/session-configuration.js +143 -0
  5. package/dist/acp/session-registry.js +90 -4
  6. package/dist/cli-core.js +2 -0
  7. package/dist/pi-transcript-tools.js +6 -0
  8. package/dist/pi-transcript.js +5 -12
  9. package/dist/pi-tui-layout.js +56 -10
  10. package/dist/pi-tui-pickers.js +102 -1
  11. package/dist/pi-tui-runner.js +230 -46
  12. package/dist/pi-tui-todo.js +221 -0
  13. package/dist/pi-tui-transcript-viewer.js +134 -7
  14. package/dist/runtime-host-cli-context.js +224 -78
  15. package/dist/runtime-host-cli-installation.js +8 -2
  16. package/dist/runtime-host-cli.js +31 -1
  17. package/dist/runtime-host-handoff-surface.js +106 -0
  18. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  19. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  20. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  21. package/dist/runtime-host-local-handoff.js +48 -5
  22. package/dist/runtime-host-local-managed-activation.js +84 -0
  23. package/dist/runtime-host-local-source-retirement.js +18 -2
  24. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  25. package/dist/runtime-host-operator-retirement.js +50 -0
  26. package/dist/runtime-host-service-manager.js +3 -3
  27. package/dist/runtime-host-session-channel.js +13 -0
  28. package/dist/runtime-host-session-driver.js +46 -26
  29. package/dist/runtime-host-session-update.js +62 -0
  30. package/dist/runtime-host-tui-command.js +38 -73
  31. package/dist/runtime-host-tui-context.js +1 -0
  32. package/dist/runtime-host-tui-owner.js +226 -0
  33. package/dist/tui-copy-catalog.js +219 -6
  34. package/dist/tui-host-owner-copy.js +24 -0
  35. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  36. package/node_modules/@maka/core/dist/agent-run.js +1 -0
  37. package/node_modules/@maka/core/dist/attachments.js +3 -0
  38. package/node_modules/@maka/core/dist/canonical-json.js +27 -0
  39. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  40. package/node_modules/@maka/core/dist/capabilities.js +35 -0
  41. package/node_modules/@maka/core/dist/computer-use.js +0 -1
  42. package/node_modules/@maka/core/dist/display-redaction.js +18 -0
  43. package/node_modules/@maka/core/dist/llm-connections.js +13 -0
  44. package/node_modules/@maka/core/dist/model-call-attempt.js +2 -0
  45. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  46. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  47. package/node_modules/@maka/core/dist/model-metadata.js +7 -3
  48. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  49. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  50. package/node_modules/@maka/core/dist/record-schema.js +9 -2
  51. package/node_modules/@maka/core/dist/redaction.js +35 -0
  52. package/node_modules/@maka/core/dist/run-composition.js +77 -2
  53. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  54. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  55. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  56. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  57. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  58. package/node_modules/@maka/core/dist/session.js +84 -56
  59. package/node_modules/@maka/core/dist/slash-command-catalog.js +3 -0
  60. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  61. package/node_modules/@maka/core/dist/tool-result-record-schema.js +2 -1
  62. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  63. package/node_modules/@maka/core/package.json +5 -0
  64. package/node_modules/@maka/eval/dist/experiment-directory.js +4 -13
  65. package/node_modules/@maka/mcp/dist/index.js +131 -1
  66. package/node_modules/@maka/runtime/dist/agent-run-inspect.js +0 -13
  67. package/node_modules/@maka/runtime/dist/agent-run.js +351 -105
  68. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +29 -13
  69. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  70. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +184 -183
  71. package/node_modules/@maka/runtime/dist/archive-read-tool.js +2 -2
  72. package/node_modules/@maka/runtime/dist/context-budget-helpers.js +0 -16
  73. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  74. package/node_modules/@maka/runtime/dist/conversation-copy.js +158 -15
  75. package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +3 -3
  76. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  77. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  78. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  79. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  80. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +174 -0
  81. package/node_modules/@maka/runtime/dist/mcp-tools.js +7 -2
  82. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  83. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  84. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  85. package/node_modules/@maka/runtime/dist/model-fetcher.js +49 -2
  86. package/node_modules/@maka/runtime/dist/model-history.js +0 -112
  87. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  88. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  89. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  90. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  91. package/node_modules/@maka/runtime/dist/plugin-runtime.js +20 -10
  92. package/node_modules/@maka/runtime/dist/plugin-tool-service.js +205 -0
  93. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  94. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +76 -109
  95. package/node_modules/@maka/runtime/dist/request-shape.js +23 -0
  96. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  97. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +83 -55
  98. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +121 -159
  99. package/node_modules/@maka/runtime/dist/runtime-kernel.js +157 -112
  100. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  101. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  102. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  103. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  104. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  105. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  106. package/node_modules/@maka/runtime/dist/stream-graph-coordinator.js +21 -0
  107. package/node_modules/@maka/runtime/dist/stream-graph-supervisor-tools.js +0 -5
  108. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  109. package/node_modules/@maka/runtime/dist/test-connection.js +16 -17
  110. package/node_modules/@maka/runtime/dist/tool-activation-identity.js +41 -0
  111. package/node_modules/@maka/runtime/dist/tool-availability.js +11 -1
  112. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  113. package/node_modules/@maka/runtime/dist/tool-result-archive-resource.js +63 -1
  114. package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +42 -12
  115. package/node_modules/@maka/runtime/dist/tool-result-archive.js +27 -4
  116. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  117. package/node_modules/@maka/runtime/package.json +2 -0
  118. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  119. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  120. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  121. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +179 -0
  122. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +275 -0
  123. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  124. package/node_modules/@maka/runtime-host/dist/client/index.js +2 -0
  125. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  126. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  127. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +46 -5
  128. package/node_modules/@maka/runtime-host/dist/control/endpoint.js +1 -3
  129. package/node_modules/@maka/runtime-host/dist/node-error.js +22 -0
  130. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  131. package/node_modules/@maka/runtime-host/dist/operator/managed-deployment.js +1 -3
  132. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  133. package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +0 -1
  134. package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +1 -1
  135. package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +1 -3
  136. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +21 -12
  137. package/node_modules/@maka/runtime-host/dist/protocol/index.js +29 -1
  138. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  139. package/node_modules/@maka/runtime-host/dist/protocol/plan.js +1 -0
  140. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +27 -5
  141. package/node_modules/@maka/runtime-host/dist/protocol/project-catalog.js +2 -2
  142. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  143. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  144. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  145. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  146. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +31 -2
  147. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  148. package/node_modules/@maka/runtime-host/dist/server/agent-graph-coordinator.js +0 -3
  149. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  150. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  151. package/node_modules/@maka/runtime-host/dist/server/execution-artifacts.js +32 -32
  152. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +144 -33
  153. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  154. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +45 -16
  155. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  156. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +96 -17
  157. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  158. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  159. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  160. package/node_modules/@maka/runtime-host/dist/server/interactive-run-composer.js +47 -22
  161. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +76 -6
  162. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +6 -0
  163. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +6 -0
  164. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +325 -73
  165. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  166. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  167. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +50 -7
  168. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  169. package/node_modules/@maka/runtime-host/dist/server/session-retirement-coordinator.js +5 -2
  170. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +12 -55
  171. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  172. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  173. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  174. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  175. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  176. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +20 -2
  177. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +13 -4
  178. package/node_modules/@maka/runtime-host/dist/server/workhub-message-attachments.js +46 -0
  179. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  180. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  181. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -5
  182. package/node_modules/@maka/storage/dist/codex-session-adapter.js +284 -198
  183. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  184. package/node_modules/@maka/storage/dist/execution-stores.js +9 -7
  185. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  186. package/node_modules/@maka/storage/dist/git-exec.js +61 -0
  187. package/node_modules/@maka/storage/dist/git-worktree-child-executor.js +8 -35
  188. package/node_modules/@maka/storage/dist/goal-authority.js +2 -2
  189. package/node_modules/@maka/storage/dist/interaction-store.js +2 -2
  190. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  191. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  192. package/node_modules/@maka/storage/dist/project-catalog.js +2 -23
  193. package/node_modules/@maka/storage/dist/runtime-event-invariants.js +2 -2
  194. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  195. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +8 -3
  196. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  197. package/node_modules/@maka/storage/dist/scheduled-task-store.js +249 -283
  198. package/node_modules/@maka/storage/dist/session-bundle-manifest.js +5 -17
  199. package/node_modules/@maka/storage/dist/session-bundle-policy.js +26 -5
  200. package/node_modules/@maka/storage/dist/session-copy-cleanup.js +2 -1
  201. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  202. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  203. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  204. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  205. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  206. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +7 -1
  207. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  208. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +130 -27
  209. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  210. package/node_modules/@maka/storage/dist/storage-id.js +28 -0
  211. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +138 -0
  212. package/node_modules/@maka/storage/dist/workspace-identity.js +2 -15
  213. package/node_modules/@maka/storage/dist/workspace-version-authority-internal.js +1 -8
  214. package/node_modules/@maka/storage/package.json +2 -0
  215. package/package.json +1 -1
@@ -17,25 +17,31 @@
17
17
  * under the License.
18
18
  */
19
19
  import { RUN_COMPOSITION_RECORDED_EVENT_TYPE } from '@maka/core/agent-run';
20
- import { decodeRunCompositionSnapshot } from '@maka/core/run-composition';
20
+ import { isRuntimeHandoffPause } from '@maka/core/runtime-handoff';
21
+ import { RunHandoffGate } from './run-handoff-gate.js';
22
+ import { preserveHandoffOpening } from './runtime-resume.js';
23
+ import { createRequestCompositionSnapshot, decodeRequestCompositionSnapshot, decodeRunCompositionSnapshot, } from '@maka/core/run-composition';
21
24
  import { DurableStoreWriteError, RunSealedError } from '@maka/core/runtime-event-store';
22
25
  import { buildInvocationOpenedEvent, buildSyntheticTerminalRuntimeEvent, isSessionInlineInvocation, } from '@maka/core/runtime-invocation';
23
26
  import { MODEL_PROJECTION_TRANSITION_EVENT_TYPE, } from '@maka/core/model-projection-transition';
24
27
  import { isTerminalRuntimeEvent } from '@maka/core/runtime-event';
25
28
  import { ToolLedgerCorruptionError, ToolLedgerRejectionError, } from '@maka/core/tool-ledger-scanner';
29
+ import { stableHash } from './request-shape.js';
26
30
  import { Buffer } from 'node:buffer';
27
31
  import { isDeepStrictEqual } from 'node:util';
28
32
  import { redactSecrets } from '@maka/core/redaction';
33
+ import { truncateUtf8 } from '@maka/core/diagnostic-log';
34
+ import { MODEL_FAILURE_MESSAGE_MAX_BYTES } from '@maka/core/model-failure';
29
35
  import { MODEL_CALL_ATTEMPT_EVENT_TYPE, } from '@maka/core/model-call-attempt';
30
36
  import { resolveEffectiveOrchestration, } from '@maka/core/orchestration';
31
- import { messageContentsEqual } from '@maka/core/events';
32
37
  import { buildPriorRuntimeContext as buildPriorRuntimeContextProjection, } from './prior-run-context.js';
33
38
  import { buildStatusPatch, normalizeStopSessionSource, statusFromEvent, turnStatusFromEvent, } from './session-projection-helpers.js';
39
+ import { admittedPromptEventId } from './message-authority.js';
34
40
  import { commitOrCreateTerminalRunFact } from './terminal-run-commit.js';
35
41
  import { createRuntimeContinuationStartAdmissionProof, } from './runtime-continuation-admission.js';
36
42
  import { DEFAULT_TOOL_MODE, isToolMode } from '@maka/core/tool-mode';
37
- import { materializeRuntimeEventTranscriptProjection } from './runtime-ledger-repair.js';
38
43
  import { cloneAndFreezeRuntimeSnapshot } from './runtime-snapshot.js';
44
+ import { projectRuntimeEventUserMessage } from './runtime-event-read-model.js';
39
45
  export class ContinuationStartCommitError extends Error {
40
46
  storeCause;
41
47
  name = 'ContinuationStartCommitError';
@@ -65,6 +71,7 @@ export class AgentRun {
65
71
  runStoreAvailable = true;
66
72
  runtimeEventStoreAvailable = true;
67
73
  runtimeEventStoreFailure;
74
+ lastAssistantPreview;
68
75
  runtimePartialStreamKey;
69
76
  runtimePartialBuffer = [];
70
77
  runtimePartialBufferBytes = 0;
@@ -72,6 +79,10 @@ export class AgentRun {
72
79
  traceWriteError;
73
80
  runComposition;
74
81
  runCompositionWrite;
82
+ runCompositionCommitted = false;
83
+ requestComposition;
84
+ requestCompositionIndex;
85
+ requestCompositionIndexRead;
75
86
  failureClass;
76
87
  failureMessage;
77
88
  lastTs = 0;
@@ -79,11 +90,16 @@ export class AgentRun {
79
90
  finalStatus;
80
91
  turnFailed = false;
81
92
  finalized = false;
93
+ handoffGate = new RunHandoffGate();
94
+ handoffRequest;
95
+ handoffPaused = false;
82
96
  terminalRunFactCommitted = false;
83
97
  continuationActive = false;
84
98
  providerStateIdentity;
85
99
  invocationOpening;
86
100
  invocationOpeningCommitted = false;
101
+ /** Set once `begin()` owes this run's prompt, cleared once the ledger has it. */
102
+ initialRuntimeEventPending = false;
87
103
  terminalClaim;
88
104
  constructor(input) {
89
105
  const acceptedInput = {
@@ -92,6 +108,9 @@ export class AgentRun {
92
108
  ...(input.effectiveOrchestration
93
109
  ? { effectiveOrchestration: cloneAndFreezeRuntimeSnapshot(input.effectiveOrchestration) }
94
110
  : {}),
111
+ ...(input.handoffSourceComposition
112
+ ? { handoffSourceComposition: decodeRunCompositionSnapshot(input.handoffSourceComposition) }
113
+ : {}),
95
114
  };
96
115
  this.input = acceptedInput;
97
116
  if (acceptedInput.runStore && !acceptedInput.runtimeEventStore) {
@@ -140,12 +159,121 @@ export class AgentRun {
140
159
  return false;
141
160
  this.terminalClaim = { owner: 'stop' };
142
161
  this.stopped = true;
162
+ this.handoffGate.close();
143
163
  this.abortSource = abortSource;
144
164
  return true;
145
165
  }
146
166
  isStopped() {
147
167
  return this.stopped;
148
168
  }
169
+ requestHandoff(pause, signal) {
170
+ if (this.handoffRequest ||
171
+ this.finalized ||
172
+ this.terminalClaim ||
173
+ this.input.runtimeEventStore?.durability !== 'canonical' ||
174
+ !this.toolBoundaryProtocol ||
175
+ Object.hasOwn(pause, 'remainingSteps') ||
176
+ !isRuntimeHandoffPause({ ...pause, remainingSteps: null }) ||
177
+ !this.invocationOpening ||
178
+ pause.rootRunId !==
179
+ (this.invocationOpening.source.kind === 'handoff'
180
+ ? this.invocationOpening.source.rootRunId
181
+ : this.runId)) {
182
+ throw new Error('Run cannot reserve a cooperative handoff');
183
+ }
184
+ let settle;
185
+ let fail;
186
+ const sealed = new Promise((resolve, reject) => {
187
+ settle = resolve;
188
+ fail = reject;
189
+ });
190
+ void sealed.catch(() => { });
191
+ const pending = {
192
+ pause: cloneAndFreezeRuntimeSnapshot(pause),
193
+ preview: undefined,
194
+ committed: false,
195
+ settle: (value) => {
196
+ signal.removeEventListener('abort', onAbort);
197
+ settle(value);
198
+ },
199
+ fail: (error) => {
200
+ signal.removeEventListener('abort', onAbort);
201
+ fail(error);
202
+ },
203
+ };
204
+ this.handoffRequest = pending;
205
+ const gate = this.handoffGate.request(signal);
206
+ const cancel = () => {
207
+ if (pending.committed || this.handoffRequest !== pending)
208
+ return;
209
+ gate.cancel();
210
+ this.handoffRequest = undefined;
211
+ pending.settle(false);
212
+ };
213
+ const onAbort = () => cancel();
214
+ signal.addEventListener('abort', onAbort, { once: true });
215
+ if (signal.aborted)
216
+ cancel();
217
+ void gate.ready.then((ready) => {
218
+ if (!ready)
219
+ cancel();
220
+ });
221
+ return {
222
+ ready: gate.ready,
223
+ sealed,
224
+ cancel,
225
+ preview: () => {
226
+ if (this.handoffRequest !== pending ||
227
+ this.stopped ||
228
+ pending.committed ||
229
+ !pending.preview) {
230
+ throw new Error('Handoff preview requires the currently held Runtime boundary');
231
+ }
232
+ this.assertRunCompositionCommitted();
233
+ return pending.preview;
234
+ },
235
+ commit: () => {
236
+ this.assertRunCompositionCommitted();
237
+ if (this.handoffRequest !== pending || !gate.commit())
238
+ return false;
239
+ pending.committed = true;
240
+ return true;
241
+ },
242
+ };
243
+ }
244
+ async reachHandoffBoundary(signal, remainingSteps) {
245
+ if (remainingSteps !== null && (!Number.isSafeInteger(remainingSteps) || remainingSteps <= 0)) {
246
+ throw new Error('Invalid handoff step budget');
247
+ }
248
+ const pending = this.handoffRequest;
249
+ if (pending) {
250
+ pending.preview = cloneAndFreezeRuntimeSnapshot({
251
+ id: this.input.newId(),
252
+ sessionId: this.sessionId,
253
+ runId: this.runId,
254
+ invocationId: this.invocationId,
255
+ turnId: this.turnId,
256
+ ts: this.input.now(),
257
+ partial: false,
258
+ role: 'system',
259
+ author: 'host',
260
+ modelVisibility: 'hidden',
261
+ actions: { endInvocation: true, handoffPause: { ...pending.pause, remainingSteps } },
262
+ });
263
+ }
264
+ const decision = await this.handoffGate.reachBoundary(signal);
265
+ if (decision === 'pause') {
266
+ this.handoffPaused = true;
267
+ }
268
+ return decision;
269
+ }
270
+ hasCommittedHandoff() {
271
+ return (this.handoffPaused &&
272
+ this.handoffRequest?.committed === true &&
273
+ !this.stopped &&
274
+ !this.failureClass &&
275
+ !this.terminalClaim);
276
+ }
149
277
  headerSnapshot() {
150
278
  return this.header;
151
279
  }
@@ -251,6 +379,15 @@ export class AgentRun {
251
379
  return Promise.reject(new Error('AgentRun store is not configured'));
252
380
  }
253
381
  const normalized = decodeRunCompositionSnapshot(snapshot);
382
+ const expected = this.input.handoffSourceComposition;
383
+ if (expected &&
384
+ (normalized.baseSystemPromptHash !== expected.baseSystemPromptHash ||
385
+ normalized.toolCatalogHash !== expected.toolCatalogHash ||
386
+ normalized.toolAvailabilityHash !== expected.toolAvailabilityHash ||
387
+ normalized.baseProviderOptionsHash !== expected.baseProviderOptionsHash ||
388
+ normalized.contextWindow !== expected.contextWindow)) {
389
+ return Promise.reject(new Error('Handoff Run Composition execution semantics changed'));
390
+ }
254
391
  if (this.runComposition && !isDeepStrictEqual(this.runComposition, normalized)) {
255
392
  return Promise.reject(new Error('AgentRun Run Composition changed after resolution'));
256
393
  }
@@ -266,7 +403,12 @@ export class AgentRun {
266
403
  turnId: this.turnId,
267
404
  ts: this.input.now(),
268
405
  data: { runComposition: normalized },
269
- }, { durable: this.requiresDurablePersistence() });
406
+ }, {
407
+ durable: this.requiresDurablePersistence() ||
408
+ this.input.runtimeEventStore?.durability === 'canonical',
409
+ });
410
+ }).then(() => {
411
+ this.runCompositionCommitted = true;
270
412
  });
271
413
  this.runCompositionWrite = write;
272
414
  return write.catch((error) => {
@@ -275,6 +417,77 @@ export class AgentRun {
275
417
  throw error;
276
418
  });
277
419
  }
420
+ assertRunCompositionCommitted() {
421
+ if (!this.runCompositionCommitted) {
422
+ throw new Error('Cooperative handoff requires a durably committed Run Composition');
423
+ }
424
+ }
425
+ /**
426
+ * Durably binds one logical model step to its effective request surface.
427
+ * Unchanged steps reuse the latest snapshot; a changed surface appends a full
428
+ * replacement before provider dispatch, matching DSH request/header epochs.
429
+ */
430
+ async recordRequestComposition(input) {
431
+ if (!this.input.runStore) {
432
+ throw new Error('AgentRun store is not configured');
433
+ }
434
+ await this.loadRequestCompositionIndex();
435
+ const snapshot = createRequestCompositionSnapshot(input, this.requestCompositionIndex?.size ? 'change' : 'initial');
436
+ const surfaceHash = requestCompositionSurfaceHash(snapshot);
437
+ const existing = this.requestCompositionIndex?.get(surfaceHash);
438
+ if (existing) {
439
+ if (!sameRequestCompositionSurface(existing, snapshot)) {
440
+ throw new Error(`Request Composition surface hash collision: ${surfaceHash}`);
441
+ }
442
+ this.requestComposition = existing;
443
+ return existing.compositionId;
444
+ }
445
+ await this.enqueueRequiredRunStoreWrite('append request composition', async () => {
446
+ await this.input.runStore?.appendEvent(this.sessionId, this.runId, {
447
+ type: 'request_composition_resolved',
448
+ id: snapshot.compositionId,
449
+ runId: this.runId,
450
+ sessionId: this.sessionId,
451
+ turnId: this.turnId,
452
+ ts: this.input.now(),
453
+ data: { snapshot },
454
+ }, { durable: true });
455
+ });
456
+ this.requestComposition = snapshot;
457
+ this.requestCompositionIndex?.set(surfaceHash, snapshot);
458
+ return snapshot.compositionId;
459
+ }
460
+ async loadRequestCompositionIndex() {
461
+ if (this.requestCompositionIndex)
462
+ return;
463
+ if (this.requestCompositionIndexRead)
464
+ return await this.requestCompositionIndexRead;
465
+ const read = (async () => {
466
+ const index = new Map();
467
+ const events = await this.input.runStore?.readEvents(this.sessionId, this.runId);
468
+ for (const event of events ?? []) {
469
+ if (event.type !== 'request_composition_resolved')
470
+ continue;
471
+ const snapshot = decodeRequestCompositionSnapshot(event.data?.snapshot);
472
+ const surfaceHash = requestCompositionSurfaceHash(snapshot);
473
+ const existing = index.get(surfaceHash);
474
+ if (existing && !sameRequestCompositionSurface(existing, snapshot)) {
475
+ throw new Error(`Request Composition surface hash collision: ${surfaceHash}`);
476
+ }
477
+ index.set(surfaceHash, existing ?? snapshot);
478
+ this.requestComposition = snapshot;
479
+ }
480
+ this.requestCompositionIndex = index;
481
+ })();
482
+ this.requestCompositionIndexRead = read;
483
+ try {
484
+ await read;
485
+ }
486
+ finally {
487
+ if (this.requestCompositionIndexRead === read)
488
+ this.requestCompositionIndexRead = undefined;
489
+ }
490
+ }
278
491
  /**
279
492
  * Canonical accounting record for one physical provider request (#1679).
280
493
  *
@@ -406,8 +619,10 @@ export class AgentRun {
406
619
  requireTerminalWrite: options.requireTerminalWrite ?? Boolean(this.input.runtimeEventStore),
407
620
  });
408
621
  await this.recordSessionEvent(sessionEvent, options);
622
+ await this.commitMessageProjection(this.lastAssistantPreview);
409
623
  return;
410
624
  }
625
+ this.rememberAssistantPreview(runtimeEvent);
411
626
  if (this.requiresDurablePersistence() && isInteractionResumeAck(sessionEvent)) {
412
627
  // A hosted continuation may resume execution only after its identity-only
413
628
  // settlement fact is durable. Session status advances next, and the queue
@@ -435,48 +650,54 @@ export class AgentRun {
435
650
  // stays fail-open (a trace gap, not a correctness gap).
436
651
  const steering = runtimeEvent.content?.kind === 'text' && runtimeEvent.content.steering === true;
437
652
  await this.recordRuntimeEvents([runtimeEvent], steering ? { requireDurableWrite: true } : {});
438
- await materializeRuntimeEventTranscriptProjection(this.input.store, this.sessionId, runtimeEvent);
653
+ if (steering) {
654
+ await this.commitMessageProjection(projectRuntimeEventUserMessage(runtimeEvent, runtimeEvent.id));
655
+ }
439
656
  }
440
657
  }
658
+ /**
659
+ * A user message is fail-CLOSED: it also takes the Session's connection lock,
660
+ * and no other path re-derives that latch now that the transcript is not a
661
+ * second authority. An assistant preview is fail-open — losing it costs a
662
+ * stale sidebar entry, never the turn.
663
+ */
664
+ async commitMessageProjection(message) {
665
+ const commit = this.input.hooks.commitMessageProjection;
666
+ if (!commit || !message)
667
+ return;
668
+ const committed = commit.call(this.input.hooks, this.sessionId, message);
669
+ if (message.type === 'user')
670
+ return committed;
671
+ await committed.catch(() => { });
672
+ }
673
+ /**
674
+ * The assistant text the Session list shows once the Turn ends.
675
+ *
676
+ * Kept as the run goes so the catalog costs one write per Turn rather than
677
+ * one per streamed step, and read only after the terminal fact is durable —
678
+ * a Turn that never spoke leaves the previous preview standing.
679
+ */
680
+ rememberAssistantPreview(event) {
681
+ if (event.role !== 'model' || event.content?.kind !== 'text')
682
+ return;
683
+ if (!event.content.text?.trim())
684
+ return;
685
+ this.lastAssistantPreview = {
686
+ type: 'assistant',
687
+ id: event.id,
688
+ turnId: event.turnId,
689
+ ts: event.ts,
690
+ text: event.content.text,
691
+ modelId: this.header.model,
692
+ };
693
+ }
441
694
  async begin() {
695
+ // Owed from here, not from after the opening: `openInvocation` can leave the
696
+ // invocation open and still throw, and `finalize` reopens what it can.
697
+ this.initialRuntimeEventPending = true;
442
698
  await this.openInvocation();
443
- let initialRuntimeEventId;
444
- const userMessageTs = this.input.now();
445
- if (this.input.userMessageId === null) {
446
- initialRuntimeEventId = this.input.newId();
447
- }
448
- else {
449
- const userMessageId = this.input.userMessageId ?? this.input.newId();
450
- initialRuntimeEventId = userMessageId;
451
- const userMsg = cloneAndFreezeRuntimeSnapshot({
452
- type: 'user',
453
- id: userMessageId,
454
- turnId: this.turnId,
455
- ts: userMessageTs,
456
- text: this.input.userInput.text,
457
- ...(this.input.userInput.displayText !== undefined
458
- ? { displayText: this.input.userInput.displayText }
459
- : {}),
460
- ...(this.input.userInput.attachments
461
- ? { attachments: this.input.userInput.attachments }
462
- : {}),
463
- ...(this.input.userInput.directoryReferences
464
- ? { directoryReferences: this.input.userInput.directoryReferences }
465
- : {}),
466
- ...(this.input.userInput.quotes ? { quotes: this.input.userInput.quotes } : {}),
467
- ...(this.input.userInput.inlineReferences
468
- ? { inlineReferences: this.input.userInput.inlineReferences }
469
- : {}),
470
- ...(this.input.userInput.origin ? { origin: this.input.userInput.origin } : {}),
471
- });
472
- await appendUserMessageOnce(this.input.store, this.sessionId, userMsg);
473
- }
474
- await this.input.hooks.appendTurnState(this.sessionId, this.turnId, 'running', this.lineage);
475
- this.lastTs = userMessageTs;
476
- const initialRuntimeEvent = cloneAndFreezeRuntimeSnapshot(this.buildInitialRuntimeEvent(initialRuntimeEventId, this.lastTs));
477
- await this.recordRuntimeEvents([initialRuntimeEvent], {
478
- requireDurableWrite: this.requiresDurablePersistence(),
479
- });
699
+ this.lastTs = this.input.now();
700
+ const initialRuntimeEvent = await this.recordInitialRuntimeEvent(this.lastTs);
480
701
  this.active = await this.input.hooks.reserveRun(this.sessionId, this.header, this);
481
702
  await this.input.hooks.updateStatus(this.sessionId, 'running', undefined, this.lastTs);
482
703
  const priorRuntimeContext = await this.buildPriorRuntimeContext();
@@ -507,13 +728,23 @@ export class AgentRun {
507
728
  initialRuntimeEvent,
508
729
  };
509
730
  }
731
+ /** Say what this run was asked to do. */
732
+ async recordInitialRuntimeEvent(ts) {
733
+ const event = cloneAndFreezeRuntimeSnapshot(this.buildInitialRuntimeEvent(admittedPromptEventId(this.runId, this.input.userMessageId), ts));
734
+ await this.recordRuntimeEvents([event], {
735
+ requireDurableWrite: this.requiresDurablePersistence(),
736
+ });
737
+ // Owed until the catalog carries it too, not just until the ledger does:
738
+ // the projection is where the connection lock latches, and re-recording the
739
+ // event is free because its id is derived and the store dedupes it.
740
+ await this.commitMessageProjection(projectRuntimeEventUserMessage(event, event.id));
741
+ this.initialRuntimeEventPending = false;
742
+ return event;
743
+ }
510
744
  async beginOperation() {
511
745
  await this.openInvocation();
512
746
  const startedAt = this.input.now();
513
747
  this.lastTs = startedAt;
514
- await this.input.hooks.appendTurnState(this.sessionId, this.turnId, 'running', this.lineage, {
515
- ts: startedAt,
516
- });
517
748
  this.active = await this.input.hooks.reserveRun(this.sessionId, this.header, this);
518
749
  await this.input.hooks.updateStatus(this.sessionId, 'running', undefined, startedAt);
519
750
  const priorRuntimeContext = await this.buildPriorRuntimeContext();
@@ -545,9 +776,6 @@ export class AgentRun {
545
776
  throw new ContinuationStartCommitError(error);
546
777
  }
547
778
  await this.input.continuationFailpoint?.('after_continuation_start_committed');
548
- await this.input.hooks.appendTurnState(this.sessionId, this.turnId, 'running', this.lineage, {
549
- ts: startedAt,
550
- });
551
779
  this.active = await this.input.hooks.reserveRun(this.sessionId, this.header, this);
552
780
  await this.input.hooks.updateStatus(this.sessionId, 'running', undefined, startedAt);
553
781
  return {
@@ -603,10 +831,29 @@ export class AgentRun {
603
831
  : {}),
604
832
  };
605
833
  }
606
- async recordStoredSessionEvent(ev) {
607
- if (ev.type === 'token_usage') {
608
- await this.input.store.appendMessage(this.sessionId, { ...ev });
609
- }
834
+ /**
835
+ * Record something the runtime needs to tell the reader about this turn.
836
+ *
837
+ * It is a fact of the invocation, so it goes where the invocation's facts go.
838
+ * Never model-visible: the note describes what happened to the conversation,
839
+ * it is not part of it.
840
+ */
841
+ async recordSystemNote(kind, data) {
842
+ await this.recordRuntimeEvents([
843
+ {
844
+ id: this.input.newId(),
845
+ invocationId: this.invocationId,
846
+ runId: this.runId,
847
+ sessionId: this.sessionId,
848
+ turnId: this.turnId,
849
+ ts: this.input.now(),
850
+ partial: false,
851
+ role: 'system',
852
+ author: 'system',
853
+ modelVisibility: 'hidden',
854
+ content: { kind: 'system_note', note: kind, ...(data !== undefined ? { data } : {}) },
855
+ },
856
+ ]);
610
857
  }
611
858
  async recordSessionEvent(ev, options = {}) {
612
859
  this.lastTs = ev.ts;
@@ -631,9 +878,9 @@ export class AgentRun {
631
878
  this.markRunFailed(turnStatus.errorClass, `turn ended with stopReason=${ev.type === 'complete' ? ev.stopReason : 'unknown'}`);
632
879
  }
633
880
  }
634
- if (transition && !this.stopped) {
881
+ if (transition && !this.stopped && ev.type !== 'error') {
635
882
  const updateSessionStatus = async () => {
636
- if (terminalSessionEvent || ev.type === 'error') {
883
+ if (terminalSessionEvent) {
637
884
  await this.input.hooks
638
885
  .updateStatus(this.sessionId, transition.status, transition.blockedReason, ev.ts)
639
886
  .catch((error) => this.enqueueTraceWriteFailure(error, 'terminal session projection'));
@@ -643,21 +890,6 @@ export class AgentRun {
643
890
  };
644
891
  await updateSessionStatus();
645
892
  }
646
- if (turnStatus && !this.stopped) {
647
- const appendTurnState = this.input.hooks.appendTurnState(this.sessionId, this.turnId, turnStatus.status, this.lineage, {
648
- ts: ev.ts,
649
- errorClass: turnStatus.errorClass,
650
- ...(turnStatus.status === 'aborted' && this.abortSource
651
- ? { abortSource: this.abortSource }
652
- : {}),
653
- });
654
- if (terminalSessionEvent || ev.type === 'error') {
655
- await appendTurnState.catch((error) => this.enqueueTraceWriteFailure(error, 'terminal session projection'));
656
- }
657
- else {
658
- await appendTurnState;
659
- }
660
- }
661
893
  if (ev.type === 'error') {
662
894
  if (this.stopped) {
663
895
  this.finalStatus = { status: 'aborted' };
@@ -665,12 +897,6 @@ export class AgentRun {
665
897
  else {
666
898
  this.turnFailed = true;
667
899
  this.finalStatus = transition ?? { status: 'blocked', blockedReason: 'unknown' };
668
- await this.input.hooks
669
- .appendTurnState(this.sessionId, this.turnId, 'failed', this.lineage, {
670
- ts: ev.ts,
671
- errorClass: ev.reason ?? ev.code ?? 'unknown',
672
- })
673
- .catch((error) => this.enqueueTraceWriteFailure(error, 'terminal session projection'));
674
900
  this.markRunFailed(ev.reason ?? ev.code ?? 'unknown', ev.message);
675
901
  }
676
902
  }
@@ -766,17 +992,40 @@ export class AgentRun {
766
992
  return;
767
993
  }
768
994
  this.finalStatus = { status: 'blocked', blockedReason: 'unknown' };
769
- await this.input.hooks
770
- .appendTurnState(this.sessionId, this.turnId, 'failed', this.lineage, {
771
- errorClass: error instanceof Error ? error.name : 'unknown',
772
- })
773
- .catch(() => { });
774
- this.markRunFailed(error instanceof Error ? error.name : 'unknown', errorMessage(error));
995
+ this.markRunFailed(error instanceof Error ? error.name : 'unknown', error instanceof Error ? error.message : String(error));
775
996
  }
776
997
  async finalize() {
777
998
  if (this.finalized)
778
999
  return;
779
1000
  this.finalized = true;
1001
+ this.handoffGate.close();
1002
+ const handoff = this.handoffRequest;
1003
+ if (this.handoffPaused &&
1004
+ handoff?.committed &&
1005
+ !this.stopped &&
1006
+ !this.failureClass &&
1007
+ !this.terminalClaim) {
1008
+ try {
1009
+ await this.flushRuntimePartialBuffer(true);
1010
+ // Stop may have claimed the logical outcome during the flush. Reserving
1011
+ // the pause below is synchronous up to its first write, so only one wins.
1012
+ if (!this.stopped && !this.failureClass && !this.terminalClaim) {
1013
+ this.assertRunCompositionCommitted();
1014
+ await this.recordRuntimeEvents([handoff.preview], { requireTerminalWrite: true });
1015
+ this.terminalRunFactCommitted = true;
1016
+ if (this.active)
1017
+ await this.input.hooks.unregisterRun(this.active, this);
1018
+ await this.traceQueue;
1019
+ handoff.settle(true);
1020
+ return;
1021
+ }
1022
+ }
1023
+ catch (error) {
1024
+ handoff.fail(error);
1025
+ throw error;
1026
+ }
1027
+ }
1028
+ handoff?.settle(false);
780
1029
  // A run cannot end without having begun. Finalizing one that never reached
781
1030
  // its start would otherwise leave a terminal event on an invocation the
782
1031
  // inventory cannot see, because nothing opened it. A continuation is the
@@ -784,6 +1033,13 @@ export class AgentRun {
784
1033
  // and a continuation that never committed one has no invocation to end.
785
1034
  if (!this.input.commitContinuationStart)
786
1035
  await this.openInvocation().catch(() => { });
1036
+ // A run also cannot end without saying what it was asked to do. `begin()`
1037
+ // can fail between opening the invocation and recording its prompt, and
1038
+ // the terminal event below seals the run against every later append —
1039
+ // including the one crash recovery would use to repair the same shape.
1040
+ if (this.initialRuntimeEventPending) {
1041
+ await this.recordInitialRuntimeEvent(this.lastTs || this.input.now()).catch(() => { });
1042
+ }
787
1043
  await this.flushRuntimePartialBuffer(true);
788
1044
  const lastTs = this.lastTs || this.input.now();
789
1045
  if (this.stopped)
@@ -809,17 +1065,6 @@ export class AgentRun {
809
1065
  catch {
810
1066
  // The user-visible turn already completed; preserve existing behavior.
811
1067
  }
812
- if (this.sawCompletion) {
813
- await this.input.store
814
- .appendMessage(this.sessionId, {
815
- type: 'system_note',
816
- id: this.input.newId(),
817
- turnId: this.turnId,
818
- ts: lastTs,
819
- kind: 'session_resume',
820
- })
821
- .catch(() => { });
822
- }
823
1068
  await this.finishRun(this.finalStatus, lastTs);
824
1069
  }
825
1070
  async openInvocation(continuation) {
@@ -864,7 +1109,7 @@ export class AgentRun {
864
1109
  ...(this.input.userInput.agentName ? { agentName: this.input.userInput.agentName } : {}),
865
1110
  ...(continuation ? { parentRunId: continuation.sourceRunId } : {}),
866
1111
  };
867
- return {
1112
+ const opening = {
868
1113
  kind: 'invocation_opened',
869
1114
  protocol: 'invocation_opened_v1',
870
1115
  route: this.header.llmConnectionId === undefined
@@ -912,6 +1157,9 @@ export class AgentRun {
912
1157
  : { kind: 'fresh' },
913
1158
  ...(Object.keys(lineage).length > 0 ? { lineage } : {}),
914
1159
  };
1160
+ return continuation
1161
+ ? preserveHandoffOpening(continuation, opening, this.input.handoffSourceOpening)
1162
+ : opening;
915
1163
  }
916
1164
  invocationRootAuthority() {
917
1165
  const origin = this.input.userInput.origin;
@@ -976,12 +1224,13 @@ export class AgentRun {
976
1224
  /**
977
1225
  * Remember why this run is going to fail.
978
1226
  *
1227
+ * Preserve diagnostic text without trace redaction, within the byte budget.
979
1228
  * Nothing is written here: the terminal RuntimeEvent carries the failure, and
980
1229
  * it is committed once, at the end, by `commitTerminalRun`.
981
1230
  */
982
1231
  markRunFailed(failureClass, message) {
983
1232
  this.failureClass = failureClass;
984
- this.failureMessage = redactTraceString(message);
1233
+ this.failureMessage = truncateUtf8(message, MODEL_FAILURE_MESSAGE_MAX_BYTES, '…');
985
1234
  }
986
1235
  /**
987
1236
  * End the run by committing its terminal RuntimeEvent, and nothing else.
@@ -1394,17 +1643,14 @@ function redactTraceString(value) {
1394
1643
  function errorMessage(error) {
1395
1644
  return redactTraceString(error instanceof Error ? error.message : String(error));
1396
1645
  }
1397
- async function appendUserMessageOnce(store, sessionId, message) {
1398
- const existing = (await store.readMessages(sessionId)).find((candidate) => candidate.id === message.id);
1399
- if (!existing) {
1400
- await store.appendMessage(sessionId, message);
1401
- return;
1402
- }
1403
- if (existing.type !== 'user' ||
1404
- existing.turnId !== message.turnId ||
1405
- !messageContentsEqual(existing, message)) {
1406
- throw new Error(`Durable UserMessage identity ${message.id} has conflicting content`);
1407
- }
1646
+ function sameRequestCompositionSurface(current, candidate) {
1647
+ const { schemaVersion: _schemaVersion, compositionId: _compositionId, step: _step, reason: _reason, ...currentSurface } = current;
1648
+ const { schemaVersion: _candidateSchemaVersion, compositionId: _candidateCompositionId, step: _candidateStep, reason: _candidateReason, ...candidateSurface } = candidate;
1649
+ return isDeepStrictEqual(currentSurface, candidateSurface);
1650
+ }
1651
+ function requestCompositionSurfaceHash(snapshot) {
1652
+ const { schemaVersion: _schemaVersion, compositionId: _compositionId, step: _step, reason: _reason, ...surface } = snapshot;
1653
+ return stableHash(surface);
1408
1654
  }
1409
1655
  function isInteractionResumeAck(event) {
1410
1656
  return (event.type === 'sandbox_boundary_decision_ack' ||