maka-agent 0.2.0-dev.22.20260905 → 0.2.0-dev.24.20260907

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 (194) hide show
  1. package/dist/acp/maka-acp-agent.js +2 -1
  2. package/dist/acp/session-configuration.js +143 -0
  3. package/dist/acp/session-registry.js +90 -4
  4. package/dist/cli-core.js +2 -0
  5. package/dist/pi-transcript.js +5 -12
  6. package/dist/pi-tui-runner.js +74 -4
  7. package/dist/runtime-host-cli-context.js +167 -78
  8. package/dist/runtime-host-cli-installation.js +8 -2
  9. package/dist/runtime-host-cli.js +31 -1
  10. package/dist/runtime-host-handoff-surface.js +81 -0
  11. package/dist/runtime-host-installed-update-bootstrap.js +13 -0
  12. package/dist/runtime-host-installed-update-coordinator.js +33 -0
  13. package/dist/runtime-host-lifecycle-transaction.js +9 -1
  14. package/dist/runtime-host-local-handoff.js +37 -4
  15. package/dist/runtime-host-local-managed-activation.js +84 -0
  16. package/dist/runtime-host-local-source-retirement.js +18 -2
  17. package/dist/runtime-host-managed-lifecycle-manager.js +1 -0
  18. package/dist/runtime-host-operator-retirement.js +50 -0
  19. package/dist/runtime-host-service-manager.js +3 -0
  20. package/dist/runtime-host-session-driver.js +4 -25
  21. package/dist/runtime-host-session-update.js +62 -0
  22. package/dist/runtime-host-tui-command.js +38 -73
  23. package/dist/runtime-host-tui-context.js +1 -0
  24. package/dist/runtime-host-tui-owner.js +226 -0
  25. package/dist/tui-copy-catalog.js +140 -3
  26. package/dist/tui-host-owner-copy.js +24 -0
  27. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  28. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  29. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  30. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  31. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  32. package/node_modules/@maka/core/dist/bot-events.js +18 -63
  33. package/node_modules/@maka/core/dist/canonical-runtime-event.js +3 -1
  34. package/node_modules/@maka/core/dist/model-call-attempt.js +0 -82
  35. package/node_modules/@maka/core/dist/model-call-usage-projection.js +0 -186
  36. package/node_modules/@maka/core/dist/model-failure.js +40 -0
  37. package/node_modules/@maka/core/dist/model-metadata.generated.js +4 -4
  38. package/node_modules/@maka/core/dist/model-metadata.js +3 -3
  39. package/node_modules/@maka/core/dist/model-web-search.js +5 -4
  40. package/node_modules/@maka/core/dist/provider-registry.js +45 -4
  41. package/node_modules/@maka/core/dist/record-schema.js +22 -2
  42. package/node_modules/@maka/core/dist/redaction.js +41 -58
  43. package/node_modules/@maka/core/dist/runtime-boundary.js +31 -11
  44. package/node_modules/@maka/core/dist/runtime-event.js +37 -6
  45. package/node_modules/@maka/core/dist/runtime-handoff.js +98 -0
  46. package/node_modules/@maka/core/dist/runtime-invocation.js +1 -1
  47. package/node_modules/@maka/core/dist/runtime-logical-execution.js +112 -0
  48. package/node_modules/@maka/core/dist/session-trace.js +5 -1
  49. package/node_modules/@maka/core/dist/session.js +54 -52
  50. package/node_modules/@maka/core/dist/slash-command-catalog.js +2 -0
  51. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +20 -0
  52. package/node_modules/@maka/core/dist/usage-ledger-merge.js +7 -9
  53. package/node_modules/@maka/core/dist/usage-record-schema.js +26 -35
  54. package/node_modules/@maka/core/dist/workhub-creation-intent.js +34 -20
  55. package/node_modules/@maka/core/package.json +4 -0
  56. package/node_modules/@maka/eval/harbor/egress-proxy/entrypoint.sh +2 -1
  57. package/node_modules/@maka/mcp/dist/index.js +131 -1
  58. package/node_modules/@maka/runtime/dist/agent-run.js +272 -105
  59. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +13 -5
  60. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +109 -34
  61. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +155 -134
  62. package/node_modules/@maka/runtime/dist/bots/base-adapter.js +17 -0
  63. package/node_modules/@maka/runtime/dist/bots/bot-test.js +38 -22
  64. package/node_modules/@maka/runtime/dist/bots/dingtalk-bridge.js +7 -5
  65. package/node_modules/@maka/runtime/dist/bots/discord-bridge.js +4 -4
  66. package/node_modules/@maka/runtime/dist/bots/feishu-bridge.js +4 -5
  67. package/node_modules/@maka/runtime/dist/bots/qq-bridge.js +6 -4
  68. package/node_modules/@maka/runtime/dist/bots/slack-bridge.js +3 -4
  69. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +4 -5
  70. package/node_modules/@maka/runtime/dist/bots/wechat-bridge.js +17 -19
  71. package/node_modules/@maka/runtime/dist/bots/wecom-bridge.js +5 -6
  72. package/node_modules/@maka/runtime/dist/bots/ws-bridge-base.js +2 -3
  73. package/node_modules/@maka/runtime/dist/context-budget.js +14 -9
  74. package/node_modules/@maka/runtime/dist/conversation-copy.js +5 -4
  75. package/node_modules/@maka/runtime/dist/goal-continuation.js +36 -4
  76. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +18 -9
  77. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +30 -22
  78. package/node_modules/@maka/runtime/dist/history-compaction.js +29 -4
  79. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +106 -0
  80. package/node_modules/@maka/runtime/dist/message-authority.js +9 -0
  81. package/node_modules/@maka/runtime/dist/model-adapter.js +19 -98
  82. package/node_modules/@maka/runtime/dist/model-factory.js +19 -81
  83. package/node_modules/@maka/runtime/dist/model-fetcher.js +7 -0
  84. package/node_modules/@maka/runtime/dist/model-runtime.js +85 -111
  85. package/node_modules/@maka/runtime/dist/native-web-search-tool.js +2 -1
  86. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +2 -2
  87. package/node_modules/@maka/runtime/dist/opencode-session-header.js +4 -2
  88. package/node_modules/@maka/runtime/dist/provider-error-classification.js +84 -123
  89. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +68 -108
  90. package/node_modules/@maka/runtime/dist/run-handoff-gate.js +97 -0
  91. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +82 -54
  92. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +117 -159
  93. package/node_modules/@maka/runtime/dist/runtime-kernel.js +150 -112
  94. package/node_modules/@maka/runtime/dist/runtime-ledger-repair.js +160 -79
  95. package/node_modules/@maka/runtime/dist/runtime-read-model.js +30 -89
  96. package/node_modules/@maka/runtime/dist/runtime-resume.js +80 -4
  97. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +5 -0
  98. package/node_modules/@maka/runtime/dist/session-manager.js +171 -288
  99. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +0 -27
  100. package/node_modules/@maka/runtime/dist/session-trace-projection.js +3 -30
  101. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +3 -4
  102. package/node_modules/@maka/runtime/dist/test-connection.js +16 -16
  103. package/node_modules/@maka/runtime/dist/tool-result-archive-encoding.js +38 -0
  104. package/node_modules/@maka/runtime/dist/tool-runtime.js +3 -61
  105. package/node_modules/@maka/runtime/package.json +1 -0
  106. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +35 -0
  107. package/node_modules/@maka/runtime-host/dist/candidate-entry.js +4 -1
  108. package/node_modules/@maka/runtime-host/dist/client/connect-or-spawn.js +9 -1
  109. package/node_modules/@maka/runtime-host/dist/client/connection.js +3 -0
  110. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +156 -0
  111. package/node_modules/@maka/runtime-host/dist/client/host-handoff.js +273 -0
  112. package/node_modules/@maka/runtime-host/dist/client/host-retirement.js +26 -5
  113. package/node_modules/@maka/runtime-host/dist/client/index.js +3 -1
  114. package/node_modules/@maka/runtime-host/dist/client/launcher.js +3 -0
  115. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +13 -0
  116. package/node_modules/@maka/runtime-host/dist/client/registered-host-termination.js +0 -59
  117. package/node_modules/@maka/runtime-host/dist/client/remote-compatibility-error.js +2 -0
  118. package/node_modules/@maka/runtime-host/dist/client/session-subscription.js +27 -5
  119. package/node_modules/@maka/runtime-host/dist/operator/index.js +2 -1
  120. package/node_modules/@maka/runtime-host/dist/operator/retirement-cancellation.js +20 -0
  121. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +28 -16
  122. package/node_modules/@maka/runtime-host/dist/protocol/external-session.js +4 -0
  123. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +29 -12
  124. package/node_modules/@maka/runtime-host/dist/protocol/index.js +37 -1
  125. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +2 -0
  126. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +28 -1
  127. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +40 -20
  128. package/node_modules/@maka/runtime-host/dist/protocol/session-transcript.js +0 -5
  129. package/node_modules/@maka/runtime-host/dist/protocol/session-turns.js +29 -58
  130. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +11 -1
  131. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +33 -0
  132. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +26 -1
  133. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +6 -1
  134. package/node_modules/@maka/runtime-host/dist/server/canonical-turn-snapshot.js +19 -4
  135. package/node_modules/@maka/runtime-host/dist/server/canonical-usage-reader.js +24 -11
  136. package/node_modules/@maka/runtime-host/dist/server/connection-session.js +7 -6
  137. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +7 -4
  138. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +168 -28
  139. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +5 -5
  140. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +3 -2
  141. package/node_modules/@maka/runtime-host/dist/server/external-session-coordinator.js +6 -3
  142. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +40 -1
  143. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +108 -23
  144. package/node_modules/@maka/runtime-host/dist/server/host-residency-registry.js +13 -7
  145. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-admission-registry.js +3 -1
  146. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-recovery.js +124 -62
  147. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +85 -8
  148. package/node_modules/@maka/runtime-host/dist/server/root-admission-owner.js +7 -0
  149. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +344 -71
  150. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +37 -2
  151. package/node_modules/@maka/runtime-host/dist/server/serial-outbound-writer.js +45 -3
  152. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +201 -12
  153. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +87 -25
  154. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +8 -55
  155. package/node_modules/@maka/runtime-host/dist/server/session-sidecar-purge.js +1 -16
  156. package/node_modules/@maka/runtime-host/dist/server/session-transcript-pager.js +0 -1
  157. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +460 -70
  158. package/node_modules/@maka/runtime-host/dist/server/shared-session-transcript.js +1 -1
  159. package/node_modules/@maka/runtime-host/dist/server/storage-maintenance.js +109 -0
  160. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +4 -11
  161. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +44 -15
  162. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +6 -2
  163. package/node_modules/@maka/storage/dist/agent-run-store.js +44 -0
  164. package/node_modules/@maka/storage/dist/artifact-store.js +21 -10
  165. package/node_modules/@maka/storage/dist/artifact-stores.js +1 -1
  166. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +0 -4
  167. package/node_modules/@maka/storage/dist/codex-session-adapter.js +0 -2
  168. package/node_modules/@maka/storage/dist/context-offload-snapshot.js +325 -0
  169. package/node_modules/@maka/storage/dist/conversation-operational-state.js +4 -0
  170. package/node_modules/@maka/storage/dist/execution-stores.js +11 -7
  171. package/node_modules/@maka/storage/dist/file-session-repository.js +1012 -0
  172. package/node_modules/@maka/storage/dist/model-call-ledger.js +199 -32
  173. package/node_modules/@maka/storage/dist/model-call-usage-sql.js +136 -0
  174. package/node_modules/@maka/storage/dist/opencode-session-adapter.js +0 -4
  175. package/node_modules/@maka/storage/dist/operational-state-backup.js +9 -5
  176. package/node_modules/@maka/storage/dist/operational-state-store-public.js +1 -1
  177. package/node_modules/@maka/storage/dist/operational-state-store.js +5 -3
  178. package/node_modules/@maka/storage/dist/runtime-event-persistence.js +1 -0
  179. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +308 -0
  180. package/node_modules/@maka/storage/dist/session-bundle-policy.js +24 -4
  181. package/node_modules/@maka/storage/dist/session-message-projection.js +15 -0
  182. package/node_modules/@maka/storage/dist/session-repository.js +767 -0
  183. package/node_modules/@maka/storage/dist/session-store.js +25 -99
  184. package/node_modules/@maka/storage/dist/sqlite-artifact-metadata.js +10 -3
  185. package/node_modules/@maka/storage/dist/sqlite-context-offload-store.js +24 -8
  186. package/node_modules/@maka/storage/dist/sqlite-core-execution-schema.js +17 -1
  187. package/node_modules/@maka/storage/dist/sqlite-runtime-schema.js +44 -1
  188. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +129 -25
  189. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +109 -892
  190. package/node_modules/@maka/storage/dist/sqlite-usage-schema.js +200 -20
  191. package/node_modules/@maka/storage/dist/tool-result-archive-evidence.js +111 -0
  192. package/node_modules/@maka/storage/dist/usage-stores.js +6 -2
  193. package/node_modules/@maka/storage/package.json +2 -0
  194. package/package.json +1 -1
@@ -18,6 +18,8 @@
18
18
  */
19
19
  import { createHash, randomUUID } from 'node:crypto';
20
20
  import { isDeepStrictEqual } from 'node:util';
21
+ import { readLogicalRuntimeExecution, readLogicalRuntimeExecutionForRun, } from '@maka/core/runtime-logical-execution';
22
+ import { runtimeHandoffPause } from '@maka/core/runtime-handoff';
21
23
  import { INLINE_REFERENCE_MAX_COUNT, messageContentDigest, messageContentsEqual, normalizeMessageContent, } from '@maka/core/events';
22
24
  import { isWorkHubCoordinationSessionId } from '@maka/core/session';
23
25
  import { resolveEffectiveOrchestration } from '@maka/core/orchestration';
@@ -58,6 +60,8 @@ export class RootTurnCoordinator {
58
60
  };
59
61
  #executions = new HostedExecutionRegistry();
60
62
  #admissions;
63
+ #handoffHold;
64
+ #cancelHandoff;
61
65
  #recoveryPlansBySession = new Map();
62
66
  stores;
63
67
  executionProjection;
@@ -117,6 +121,8 @@ export class RootTurnCoordinator {
117
121
  }
118
122
  }
119
123
  else {
124
+ if (plan.rootReplayAdmission === admission)
125
+ continue;
120
126
  if (admission.execution.kind !== 'safe_boundary_continuation') {
121
127
  throw new Error(`Startup recovery left Turn ${admission.turnId} non-terminal`);
122
128
  }
@@ -127,7 +133,11 @@ export class RootTurnCoordinator {
127
133
  if (!admission)
128
134
  continue;
129
135
  // Session recovery may have materialized this Run after the replay plan was prepared.
130
- if (await this.readRunIfPresent(sessionId, admission.runId))
136
+ const existingRun = await this.readRunIfPresent(sessionId, admission.runId);
137
+ const pendingHandoff = existingRun &&
138
+ (await readLogicalRuntimeExecution(this.stores.runtimeEventStore, admission, existingRun))
139
+ ?.pendingHandoff;
140
+ if (existingRun && !pendingHandoff)
131
141
  continue;
132
142
  const input = activationInputForAdmission(admission);
133
143
  const disposition = await this.sessionAdmission.run(sessionId, async (lease) => {
@@ -138,7 +148,7 @@ export class RootTurnCoordinator {
138
148
  return undefined;
139
149
  }
140
150
  }
141
- const continuation = admission.execution.kind === 'safe_boundary_continuation'
151
+ const continuation = admission.execution.kind === 'safe_boundary_continuation' && !pendingHandoff
142
152
  ? await this.reconstructAdmittedContinuation(admission)
143
153
  : undefined;
144
154
  if (continuation?.disposition === 'parked') {
@@ -169,6 +179,7 @@ export class RootTurnCoordinator {
169
179
  this.#recoveryPlansBySession.clear();
170
180
  }
171
181
  async close() {
182
+ this.#cancelHandoff?.();
172
183
  this.beginDrain();
173
184
  await this.#admissions.waitForSettledAdmissions();
174
185
  const errors = [];
@@ -221,7 +232,28 @@ export class RootTurnCoordinator {
221
232
  runId: active.runId,
222
233
  };
223
234
  }
224
- return this.#admissions.has(sessionId) ? { kind: 'reserved' } : { kind: 'idle' };
235
+ return this.#handoffHold || this.#admissions.has(sessionId)
236
+ ? { kind: 'reserved' }
237
+ : { kind: 'idle' };
238
+ }
239
+ /** Returns the newest Host-admitted continuation descended from one root execution. */
240
+ async readLatestRootTurnLineage(identity) {
241
+ const origin = await this.stores.agentRunStore.readRootTurnAdmission(identity.sessionId, identity.turnId);
242
+ if (!origin || origin.runId !== identity.runId) {
243
+ throw new RuntimeMessageAuthorityInvariantError(`Root execution ${identity.turnId}/${identity.runId} has no durable admission`);
244
+ }
245
+ let latest = origin;
246
+ while (true) {
247
+ const run = await this.readRunIfPresent(latest.sessionId, latest.runId);
248
+ const physical = run?.terminalEvent && runtimeHandoffPause(run.terminalEvent)
249
+ ? (await readLogicalRuntimeExecution(this.stores.runtimeEventStore, latest, run))?.tip
250
+ : run;
251
+ const continuation = await this.stores.agentRunStore.readRootTurnContinuationAdmission(identity.sessionId, latest.turnId, physical?.runId ?? latest.runId);
252
+ if (!continuation)
253
+ break;
254
+ latest = continuation;
255
+ }
256
+ return { sessionId: latest.sessionId, turnId: latest.turnId, runId: latest.runId };
225
257
  }
226
258
  startHostedExternalTransition(input, context) {
227
259
  return this.startInteractiveRootMessage({
@@ -234,12 +266,16 @@ export class RootTurnCoordinator {
234
266
  }, context);
235
267
  }
236
268
  reserveRootTurn(sessionId) {
269
+ if (this.#handoffHold)
270
+ return undefined;
237
271
  return this.#admissions.reserve(sessionId);
238
272
  }
239
273
  parkContinuationAdmission(admission) {
240
274
  this.#admissions.park(admission);
241
275
  }
242
276
  takeParkedContinuationReservation(admission) {
277
+ if (this.#handoffHold)
278
+ return undefined;
243
279
  return this.#admissions.takeParked(admission);
244
280
  }
245
281
  clearParkedContinuationAdmission(admission) {
@@ -257,6 +293,163 @@ export class RootTurnCoordinator {
257
293
  beginDrain() {
258
294
  this.#admissions.beginDrain();
259
295
  }
296
+ async prepareHandoff(hostEpoch, signal) {
297
+ if (this.#handoffHold || this.#admissions.isDraining || signal.aborted)
298
+ return undefined;
299
+ const hold = deferred();
300
+ this.#handoffHold = hold;
301
+ const held = new Map();
302
+ let sealed = false;
303
+ let detached = false;
304
+ const releaseHold = () => {
305
+ if (this.#handoffHold === hold) {
306
+ this.#handoffHold = undefined;
307
+ this.#cancelHandoff = undefined;
308
+ }
309
+ hold.resolve();
310
+ signal.removeEventListener('abort', cancel);
311
+ };
312
+ const cancel = () => {
313
+ if (detached)
314
+ return;
315
+ sealed = false;
316
+ for (const [active, { request, attachment }] of held) {
317
+ request.cancel();
318
+ attachment.arrived.resolve();
319
+ attachment.decision.resolve('resume');
320
+ if (active.handoff === attachment)
321
+ active.handoff = undefined;
322
+ }
323
+ releaseHold();
324
+ };
325
+ this.#cancelHandoff = cancel;
326
+ signal.addEventListener('abort', cancel, { once: true });
327
+ try {
328
+ await waitForHostedExecutionIdleOrAbort(this.#admissions.waitForSettledAdmissions(), signal);
329
+ // Natural completion can hand a queued follow-up to a fresh root while
330
+ // gates converge. Bound that convergence; never chase an endless queue.
331
+ for (let pass = 0; pass < 3; pass += 1) {
332
+ for (const [, active] of this.#executions.entries()) {
333
+ if (held.has(active))
334
+ continue;
335
+ await waitForHostedExecutionIdleOrAbort(active.startSettled.promise, signal);
336
+ if (this.#executions.get(active.sessionId) !== active)
337
+ continue;
338
+ const request = this.manager.requestRunHandoff(active.sessionId, active.continuation?.runId ?? active.runId, {
339
+ protocol: 'runtime_handoff_pause_v1',
340
+ hostEpoch,
341
+ handoffId: randomUUID(),
342
+ rootRunId: active.runId,
343
+ successorRunId: randomUUID(),
344
+ successorInvocationId: randomUUID(),
345
+ claimId: randomUUID(),
346
+ }, signal);
347
+ if (!request) {
348
+ cancel();
349
+ return undefined;
350
+ }
351
+ const attachment = {
352
+ decision: valueDeferred(),
353
+ arrived: deferred(),
354
+ };
355
+ active.handoff = attachment;
356
+ held.set(active, { request, attachment });
357
+ }
358
+ for (const [active, item] of held) {
359
+ if (await waitForAbortableValue(item.request.ready, signal))
360
+ continue;
361
+ const snapshot = await this.readCanonicalSnapshot(active.sessionId, active.turnId, active.runId);
362
+ if (!isTerminalSnapshot(snapshot)) {
363
+ cancel();
364
+ return undefined;
365
+ }
366
+ item.attachment.decision.resolve('resume');
367
+ if (active.handoff === item.attachment)
368
+ active.handoff = undefined;
369
+ await waitForHostedExecutionIdleOrAbort(active.done, signal);
370
+ held.delete(active);
371
+ }
372
+ if ([...this.#executions.entries()].every(([, active]) => held.has(active)))
373
+ break;
374
+ }
375
+ if (signal.aborted ||
376
+ [...this.#executions.entries()].some(([, active]) => !held.has(active))) {
377
+ cancel();
378
+ return undefined;
379
+ }
380
+ return {
381
+ executions: [...held.keys()].map(({ sessionId, turnId, runId }) => ({
382
+ sessionId,
383
+ turnId,
384
+ runId,
385
+ })),
386
+ seal: async () => {
387
+ if (signal.aborted || this.#handoffHold !== hold || detached)
388
+ return false;
389
+ if (sealed)
390
+ return true;
391
+ for (const [active, { request }] of held) {
392
+ if (this.#executions.get(active.sessionId) !== active || !request.commit()) {
393
+ cancel();
394
+ return false;
395
+ }
396
+ }
397
+ try {
398
+ const results = await Promise.all([...held.values()].map(({ request }) => request.sealed));
399
+ sealed = !signal.aborted && this.#handoffHold === hold && results.every(Boolean);
400
+ if (sealed) {
401
+ await Promise.all([...held].map(([active, { attachment }]) => Promise.race([
402
+ attachment.arrived.promise,
403
+ active.done.then(() => {
404
+ throw new Error('Sealed execution ended before its attachment handoff');
405
+ }),
406
+ ])));
407
+ }
408
+ }
409
+ catch (error) {
410
+ cancel();
411
+ throw error;
412
+ }
413
+ if (!sealed)
414
+ cancel();
415
+ return sealed;
416
+ },
417
+ residencies: async () => {
418
+ if (!sealed || signal.aborted || this.#handoffHold !== hold || detached)
419
+ return undefined;
420
+ const residencies = [];
421
+ for (const [active, { attachment }] of held) {
422
+ if (this.#executions.get(active.sessionId) !== active ||
423
+ active.handoff !== attachment ||
424
+ active.stopRequested)
425
+ return undefined;
426
+ const messages = await this.sessionAdmission.run(active.sessionId, (lease) => this.messages.handoffResidencies(active, lease));
427
+ if (!messages)
428
+ return undefined;
429
+ residencies.push(active.residency, ...messages);
430
+ }
431
+ return residencies;
432
+ },
433
+ detach: async () => {
434
+ if (!sealed || signal.aborted || this.#handoffHold !== hold || detached) {
435
+ throw new Error('Cannot detach a handoff without all durable seals');
436
+ }
437
+ detached = true;
438
+ for (const { attachment } of held.values())
439
+ attachment.decision.resolve('detach');
440
+ await Promise.all([...held.keys()].map((active) => active.done));
441
+ releaseHold();
442
+ },
443
+ cancel,
444
+ };
445
+ }
446
+ catch (error) {
447
+ cancel();
448
+ if (signal.aborted)
449
+ return undefined;
450
+ throw error;
451
+ }
452
+ }
260
453
  async runExclusiveSessionOperation(input, operation) {
261
454
  const { sessionId, abortSignal } = input;
262
455
  let reservation;
@@ -272,7 +465,7 @@ export class RootTurnCoordinator {
272
465
  }
273
466
  const active = this.#executions.get(sessionId);
274
467
  const pending = this.#admissions.get(sessionId);
275
- const whenIdle = active?.done ?? pending?.whenIdle.promise;
468
+ const whenIdle = active?.done ?? pending?.whenIdle.promise ?? this.#handoffHold?.promise;
276
469
  if (whenIdle) {
277
470
  await waitForHostedExecutionIdleOrAbort(whenIdle, abortSignal);
278
471
  }
@@ -321,6 +514,8 @@ export class RootTurnCoordinator {
321
514
  reason: 'Runtime Host execution authority is draining.',
322
515
  };
323
516
  }
517
+ if (this.#handoffHold)
518
+ return { kind: 'busy', whenIdle: this.#handoffHold.promise };
324
519
  const active = this.#executions.get(sessionId);
325
520
  if (active) {
326
521
  return {
@@ -513,7 +708,9 @@ export class RootTurnCoordinator {
513
708
  return this.#executions.subscribe(listener);
514
709
  }
515
710
  whenIdle(sessionId) {
516
- return (this.#executions.get(sessionId)?.done ?? this.#admissions.get(sessionId)?.whenIdle.promise);
711
+ return (this.#executions.get(sessionId)?.done ??
712
+ this.#admissions.get(sessionId)?.whenIdle.promise ??
713
+ this.#handoffHold?.promise);
517
714
  }
518
715
  stopRoot(identity, input = {}) {
519
716
  normalizeStopSessionSource(input.source, input.workHubActionId);
@@ -1291,6 +1488,12 @@ export class RootTurnCoordinator {
1291
1488
  sourceMessages: [],
1292
1489
  admittedAt: Date.now(),
1293
1490
  });
1491
+ if (admitted.kind === 'conflict') {
1492
+ return {
1493
+ kind: 'complete',
1494
+ outcome: operationConflict('This root execution already has a different continuation Turn'),
1495
+ };
1496
+ }
1294
1497
  if (admitted.admission.runId !== continuation.runId ||
1295
1498
  !isDeepStrictEqual(admitted.admission.execution, execution)) {
1296
1499
  throw new RuntimeMessageAuthorityInvariantError('Safe-boundary continuation admission changed identity');
@@ -1309,9 +1512,19 @@ export class RootTurnCoordinator {
1309
1512
  });
1310
1513
  }
1311
1514
  async planTurnResume(input) {
1312
- const plan = input.sourceRunId
1515
+ let sourceRunId = input.sourceRunId;
1516
+ if (sourceRunId) {
1517
+ const run = await this.readRunIfPresent(input.sessionId, sourceRunId);
1518
+ if (run?.terminalEvent && runtimeHandoffPause(run.terminalEvent)) {
1519
+ const logical = await readLogicalRuntimeExecutionForRun(this.stores.runtimeEventStore, run);
1520
+ // Queries may name the stable public root. The returned plan and the
1521
+ // subsequent start must still bind the exact physical source/high-water.
1522
+ sourceRunId = logical?.tip.runId ?? sourceRunId;
1523
+ }
1524
+ }
1525
+ const plan = sourceRunId
1313
1526
  ? await this.manager.planAuthoritativeSafeBoundaryContinuation(input.sessionId, {
1314
- sourceRunId: input.sourceRunId,
1527
+ sourceRunId,
1315
1528
  ...(input.expectedRuntimeEventHighWater !== undefined
1316
1529
  ? {
1317
1530
  expectedRuntimeEventHighWater: input.expectedRuntimeEventHighWater,
@@ -1370,9 +1583,9 @@ export class RootTurnCoordinator {
1370
1583
  }
1371
1584
  const fence = commitQueueFence();
1372
1585
  await this.messages.cancelMessages(input.sessionId, fence.retracted.map((message) => message.messageId));
1373
- await this.interactions.claimRunClosure(input, 'turn_stopped', admission);
1586
+ await this.interactions.claimRunClosure({ ...input, runId: active.continuation?.runId ?? active.runId }, 'turn_stopped', admission);
1374
1587
  const shouldDeliverStop = !active.stopRequested;
1375
- active.stopRequested = true;
1588
+ active.stopRequested = stopInput;
1376
1589
  return {
1377
1590
  active,
1378
1591
  deliverStop: () => shouldDeliverStop
@@ -1397,7 +1610,7 @@ export class RootTurnCoordinator {
1397
1610
  if (active?.turnId === input.turnId && active.runId === input.runId) {
1398
1611
  const fence = commitQueueFence();
1399
1612
  await this.messages.cancelMessages(input.sessionId, fence.retracted.map((message) => message.messageId));
1400
- active.stopRequested = true;
1613
+ active.stopRequested ??= { source: 'stop_button' };
1401
1614
  return { kind: 'await_terminal', active };
1402
1615
  }
1403
1616
  return { kind: 'complete', outcome: { ok: true, result: snapshot } };
@@ -1420,9 +1633,9 @@ export class RootTurnCoordinator {
1420
1633
  }
1421
1634
  const fence = commitQueueFence();
1422
1635
  await this.messages.cancelMessages(input.sessionId, fence.retracted.map((message) => message.messageId));
1423
- await this.interactions.claimRunClosure(input, 'turn_stopped', admissionLease);
1636
+ await this.interactions.claimRunClosure({ ...input, runId: active.continuation?.runId ?? active.runId }, 'turn_stopped', admissionLease);
1424
1637
  const shouldRequestStop = !active.stopRequested;
1425
- active.stopRequested = true;
1638
+ active.stopRequested ??= { source: 'stop_button' };
1426
1639
  return shouldRequestStop
1427
1640
  ? { kind: 'request_stop', active }
1428
1641
  : { kind: 'await_terminal', active };
@@ -1463,7 +1676,19 @@ export class RootTurnCoordinator {
1463
1676
  }
1464
1677
  if (active)
1465
1678
  return completedStart(sessionBusy('Session already has an active root Turn'));
1466
- throw new Error('Admitted non-terminal Turn has no active Runtime Host execution');
1679
+ const logical = await readLogicalRuntimeExecution(this.stores.runtimeEventStore, admission, existingRun);
1680
+ if (!logical?.pendingHandoff) {
1681
+ throw new Error('Admitted non-terminal Turn has no active Runtime Host execution');
1682
+ }
1683
+ const plan = await this.manager.planAuthoritativeSafeBoundaryContinuation(input.sessionId, {
1684
+ sourceRunId: logical.tip.runId,
1685
+ purpose: 'handoff',
1686
+ });
1687
+ if (!plan.continuation) {
1688
+ this.parkContinuationAdmission(admission);
1689
+ return completedStart(operationUnavailable(`Sealed handoff cannot resume: ${plan.rejectionReasons.join(', ')}`));
1690
+ }
1691
+ continuation = plan.continuation;
1467
1692
  }
1468
1693
  const active = this.#executions.get(input.sessionId);
1469
1694
  const currentReservation = this.#admissions.get(input.sessionId);
@@ -1496,6 +1721,9 @@ export class RootTurnCoordinator {
1496
1721
  try {
1497
1722
  this.messages.reserveRootTurn(messageIdentity);
1498
1723
  messageReserved = true;
1724
+ if (continuation?.handoffRootRunId !== undefined) {
1725
+ await this.messages.advanceHandoffRun(messageIdentity, continuation.runId, admissionLease);
1726
+ }
1499
1727
  await this.continuity.holdTerminalPublication(input.sessionId, input.turnId, runId, admissionLease);
1500
1728
  }
1501
1729
  catch (error) {
@@ -1526,7 +1754,7 @@ export class RootTurnCoordinator {
1526
1754
  startSettled,
1527
1755
  done: Promise.resolve(),
1528
1756
  residency,
1529
- stopRequested: false,
1757
+ stopRequested: undefined,
1530
1758
  messageTransitionCommitted: false,
1531
1759
  };
1532
1760
  if (replacing && this.#executions.get(input.sessionId) !== replacing) {
@@ -1592,6 +1820,7 @@ export class RootTurnCoordinator {
1592
1820
  }
1593
1821
  async drainTurn(input, active, startSettled) {
1594
1822
  let terminalTransitionStarted = false;
1823
+ let detached = false;
1595
1824
  try {
1596
1825
  const messageOrigin = hostedExecutionMessageOrigin(active.descriptor);
1597
1826
  const onRunStarted = async () => {
@@ -1599,46 +1828,80 @@ export class RootTurnCoordinator {
1599
1828
  await this.continuity.refreshCanonical(input.sessionId);
1600
1829
  startSettled.resolve();
1601
1830
  };
1602
- const stream = active.execution
1603
- ? active.execution.start({
1604
- runId: active.runId,
1605
- userMessageId: active.userMessageId,
1606
- onRunStarted: async () => {
1607
- await onRunStarted();
1608
- await active.execution?.onReady?.();
1609
- },
1831
+ let stream = active.continuation
1832
+ ? this.manager.resumeSafeBoundaryContinuation(active.continuation, {
1833
+ onRunStarted,
1834
+ stopBeforeDispatch: () => active.stopRequested,
1610
1835
  })
1611
- : active.descriptor.kind === 'context_compact'
1612
- ? this.manager.compactSession(input.sessionId, {
1613
- turnId: input.turnId,
1614
- hostedRoot: {
1615
- runId: active.runId,
1616
- onRunStarted,
1836
+ : active.execution
1837
+ ? active.execution.start({
1838
+ runId: active.runId,
1839
+ userMessageId: active.userMessageId,
1840
+ onRunStarted: async () => {
1841
+ await onRunStarted();
1842
+ await active.execution?.onReady?.();
1617
1843
  },
1618
1844
  })
1619
- : active.continuation
1620
- ? this.manager.resumeSafeBoundaryContinuation(active.continuation, {
1621
- onRunStarted,
1845
+ : active.descriptor.kind === 'context_compact'
1846
+ ? this.manager.compactSession(input.sessionId, {
1847
+ turnId: input.turnId,
1848
+ hostedRoot: {
1849
+ runId: active.runId,
1850
+ onRunStarted,
1851
+ },
1622
1852
  })
1623
- : this.startRootMessageTurn(input, active, normalizeMessageContent(requireRootMessageContent(input)), messageOrigin, onRunStarted);
1624
- for await (const event of stream) {
1625
- if (active.execution?.onEvent) {
1626
- try {
1627
- active.execution.onEvent(event);
1853
+ : active.continuation
1854
+ ? this.manager.resumeSafeBoundaryContinuation(active.continuation, {
1855
+ onRunStarted,
1856
+ })
1857
+ : this.startRootMessageTurn(input, active, normalizeMessageContent(requireRootMessageContent(input)), messageOrigin, onRunStarted);
1858
+ for (;;) {
1859
+ for await (const event of stream) {
1860
+ if (active.execution?.onEvent) {
1861
+ try {
1862
+ active.execution.onEvent(event);
1863
+ }
1864
+ catch {
1865
+ // Presentation observers do not participate in execution authority.
1866
+ }
1628
1867
  }
1629
- catch {
1630
- // Presentation observers do not participate in execution authority.
1868
+ if (isRuntimeSessionForwardedEvent(event)) {
1869
+ await this.continuity.acceptRuntimeEvent(input.sessionId, active.runId, event);
1870
+ }
1871
+ else if (isInteractionAnswerAck(event)) {
1872
+ await this.continuity.refreshCanonical(input.sessionId);
1873
+ }
1874
+ else if (event.type === 'user_question_request' || event.type === 'form_request') {
1875
+ this.continuity.enqueueCanonicalRefresh(input.sessionId);
1631
1876
  }
1632
1877
  }
1633
- if (isRuntimeSessionForwardedEvent(event)) {
1634
- await this.continuity.acceptRuntimeEvent(input.sessionId, active.runId, event);
1635
- }
1636
- else if (isInteractionAnswerAck(event)) {
1637
- await this.continuity.refreshCanonical(input.sessionId);
1638
- }
1639
- else if (event.type === 'user_question_request' || event.type === 'form_request') {
1640
- this.continuity.enqueueCanonicalRefresh(input.sessionId);
1878
+ const logical = await readLogicalRuntimeExecution(this.stores.runtimeEventStore, active);
1879
+ if (!logical?.pendingHandoff)
1880
+ break;
1881
+ const handoff = active.handoff;
1882
+ handoff?.arrived.resolve();
1883
+ if (handoff && (await handoff.decision.promise) === 'detach') {
1884
+ await this.sessionAdmission.run(input.sessionId, (lease) => this.messages.detachHandoffRoot(active, lease));
1885
+ detached = true;
1886
+ return;
1641
1887
  }
1888
+ await this.sessionAdmission.run(input.sessionId, async (lease) => {
1889
+ if (this.#executions.get(input.sessionId) !== active) {
1890
+ throw new RuntimeMessageAuthorityInvariantError('Sealed handoff lost its original root owner');
1891
+ }
1892
+ const plan = await this.manager.planAuthoritativeSafeBoundaryContinuation(input.sessionId, {
1893
+ sourceRunId: logical.tip.runId,
1894
+ purpose: 'handoff',
1895
+ });
1896
+ if (!plan.continuation)
1897
+ throw new Error(`Sealed handoff cannot resume: ${plan.rejectionReasons.join(', ')}`);
1898
+ await this.messages.advanceHandoffRun(active, plan.continuation.runId, lease);
1899
+ active.continuation = plan.continuation;
1900
+ });
1901
+ stream = this.manager.resumeSafeBoundaryContinuation(active.continuation, {
1902
+ onRunStarted,
1903
+ stopBeforeDispatch: () => active.stopRequested,
1904
+ });
1642
1905
  }
1643
1906
  const snapshot = await this.readCanonicalSnapshot(input.sessionId, input.turnId, active.runId);
1644
1907
  await this.assertCompletedExecutionIdentity(input, active);
@@ -1681,7 +1944,7 @@ export class RootTurnCoordinator {
1681
1944
  ((!active.stopRequested &&
1682
1945
  snapshot.status === 'failed' &&
1683
1946
  isContainableRunFailure(error)) ||
1684
- (active.stopRequested &&
1947
+ (Boolean(active.stopRequested) &&
1685
1948
  snapshot.status === 'cancelled' &&
1686
1949
  isStoppedInteractionAdmission(error)));
1687
1950
  }
@@ -1704,32 +1967,38 @@ export class RootTurnCoordinator {
1704
1967
  throw commandFailure;
1705
1968
  }
1706
1969
  finally {
1707
- this.observeExecutionCompletion(active, {
1708
- kind: 'authority_error',
1709
- execution: active,
1710
- reason: 'Runtime root Turn ended without a canonical completion.',
1711
- });
1712
- await active.observationSettled?.catch(() => this.requestHostDrain());
1713
- let releaseRootOwnership = active.messageTransitionCommitted;
1714
- if (!active.messageTransitionCommitted) {
1715
- try {
1716
- this.messages.abandonRootReservation({
1717
- sessionId: input.sessionId,
1718
- turnId: active.turnId,
1719
- runId: active.runId,
1720
- });
1721
- releaseRootOwnership = true;
1722
- }
1723
- catch {
1724
- this.requestHostDrain();
1725
- }
1726
- }
1727
- if (releaseRootOwnership) {
1970
+ if (detached) {
1728
1971
  this.#executions.release(active);
1729
1972
  active.residency.release();
1730
1973
  }
1731
- active.completion.resolve(active.observedCompletion);
1732
- this.#executions.publish(active);
1974
+ else {
1975
+ this.observeExecutionCompletion(active, {
1976
+ kind: 'authority_error',
1977
+ execution: active,
1978
+ reason: 'Runtime root Turn ended without a canonical completion.',
1979
+ });
1980
+ await active.observationSettled?.catch(() => this.requestHostDrain());
1981
+ let releaseRootOwnership = active.messageTransitionCommitted;
1982
+ if (!active.messageTransitionCommitted) {
1983
+ try {
1984
+ this.messages.abandonRootReservation({
1985
+ sessionId: input.sessionId,
1986
+ turnId: active.turnId,
1987
+ runId: active.runId,
1988
+ });
1989
+ releaseRootOwnership = true;
1990
+ }
1991
+ catch {
1992
+ this.requestHostDrain();
1993
+ }
1994
+ }
1995
+ if (releaseRootOwnership) {
1996
+ this.#executions.release(active);
1997
+ active.residency.release();
1998
+ }
1999
+ active.completion.resolve(active.observedCompletion);
2000
+ this.#executions.publish(active);
2001
+ }
1733
2002
  }
1734
2003
  }
1735
2004
  async materializeAdmittedMessageSources(active) {
@@ -1768,7 +2037,7 @@ export class RootTurnCoordinator {
1768
2037
  turnId: active.turnId,
1769
2038
  runId: active.runId,
1770
2039
  };
1771
- await this.interactions.assertTerminalFence(identity, lease);
2040
+ await this.interactions.assertTerminalFence({ ...identity, runId: active.continuation?.runId ?? active.runId }, lease);
1772
2041
  const batch = this.messages.beginTerminalTransition(identity);
1773
2042
  await this.continuity.publishTerminalProjection(sessionId, active.turnId, active.runId, lease);
1774
2043
  if (batch.sources.length === 0) {
@@ -1893,6 +2162,10 @@ export class RootTurnCoordinator {
1893
2162
  }
1894
2163
  }
1895
2164
  }
2165
+ async function waitForAbortableValue(value, signal) {
2166
+ await waitForHostedExecutionIdleOrAbort(value.then(() => undefined), signal);
2167
+ return value;
2168
+ }
1896
2169
  class HostedRootAdmissionGateError extends Error {
1897
2170
  cause;
1898
2171
  name = 'HostedRootAdmissionGateError';