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
@@ -19,21 +19,11 @@
19
19
  import { createHash } from 'node:crypto';
20
20
  import { deriveTurnRecords } from '@maka/core/session';
21
21
  import { DEFAULT_TOOL_MODE } from '@maka/core/tool-mode';
22
- import { isTerminalRuntimeEvent } from '@maka/core/runtime-event';
23
22
  import { buildInvocationOpenedEvent, isSessionInlineInvocation, } from '@maka/core/runtime-invocation';
24
23
  import { backfillRuntimeEventsFromStoredMessages } from './runtime-event-backfill.js';
25
- import { projectRuntimeEventUserMessage } from './runtime-event-read-model.js';
26
- export async function materializeRuntimeEventTranscriptProjection(deps, sessionId, event, knownMessageIds) {
27
- const message = steeringMessageFromRuntimeEvent(event);
28
- if (!message)
29
- return false;
30
- const messageIds = knownMessageIds ?? new Set((await deps.readMessages(sessionId)).map((item) => item.id));
31
- if (messageIds.has(message.id))
32
- return false;
33
- await deps.appendMessage(sessionId, message);
34
- messageIds.add(message.id);
35
- return true;
36
- }
24
+ /** How much of a legacy transcript one conversion page holds. */
25
+ const TRANSCRIPT_CONVERSION_PAGE_MAX_MESSAGES = 256;
26
+ const TRANSCRIPT_CONVERSION_PAGE_MAX_BYTES = 4 * 1024 * 1024;
37
27
  export class RuntimeLedgerRepair {
38
28
  deps;
39
29
  queues = new Map();
@@ -41,72 +31,165 @@ export class RuntimeLedgerRepair {
41
31
  this.deps = deps;
42
32
  }
43
33
  /**
44
- * Give an imported transcript a runtime spine: one invocation per turn, opened
45
- * by its own opening fact and closed by its own terminal event.
34
+ * Give a transcript a runtime spine: one invocation per turn, opened by its
35
+ * own opening fact and closed by its own terminal event.
46
36
  *
47
- * The transcript is the only evidence there is, so a turn it cannot close is
48
- * refused rather than imported half-formed. Re-running is a no-op: a turn
49
- * whose invocation already exists is left exactly as it is.
37
+ * Every event id is derived from the run it belongs to and its position in
38
+ * that run, so importing the same transcript twice writes the same events and
39
+ * the store dedupes them. That is what makes an interrupted import resumable:
40
+ * a turn is skipped once its invocation has ended, and re-derived until then.
50
41
  */
51
42
  async materializeTranscriptLedger(header) {
52
43
  const sessionId = header.id;
53
- return this.withRepairQueue(sessionId, 'transcript-runs', async () => {
54
- const messages = await this.deps.readMessages(sessionId);
55
- const ledgerMessages = messages.filter((message) => message.type !== 'user' || message.steeringEventId === undefined);
56
- const openedTurnIds = new Set((await this.listInlineInvocations(sessionId)).map((invocation) => invocation.turnId));
57
- const messagesByTurn = groupMessagesByTurn(ledgerMessages);
58
- const turns = deriveTurnRecords(ledgerMessages).filter((turn) => (messagesByTurn.get(turn.turnId) ?? []).some((message) => message.type === 'user'));
59
- if (turns.length === 0)
60
- return;
61
- const firstOpenedAt = Math.max(0, header.createdAt - turns.length);
62
- for (const [index, turn] of turns.entries()) {
63
- if (openedTurnIds.has(turn.turnId))
44
+ return this.withRepairQueue(sessionId, async () => {
45
+ // A turn the ledger already owns is not converted again. Its own run is
46
+ // the authority even when it never ended — a crashed turn is settled by
47
+ // recovery on that run, and a second, transcript-derived invocation for
48
+ // the same turn would make the Session read as two. The one exception is
49
+ // this converter's own run: an interrupted import re-derives it, and the
50
+ // deterministic ids let the store dedupe what already landed.
51
+ const { ownedTurnIds, startedRunIds } = await this.readLedgerOwnership(sessionId);
52
+ for await (const scanned of this.readTurnsInPages(sessionId)) {
53
+ const turnMessages = scanned.messages;
54
+ // A turn whose only user row was steering is not a turn of its own: the
55
+ // steering was said into a Turn some durable Root already owns, so
56
+ // converting it would stand a second, synthetic run beside that one.
57
+ if (!turnMessages.some((message) => message.type === 'user'))
58
+ continue;
59
+ const [turn] = deriveTurnRecords(turnMessages);
60
+ if (!turn)
61
+ continue;
62
+ if (ownedTurnIds.has(turn.turnId))
64
63
  continue;
65
- const turnMessages = messagesByTurn.get(turn.turnId) ?? [];
66
64
  const runId = transcriptRunId(sessionId, turn.turnId);
67
- const openedAt = firstOpenedAt + index;
65
+ // Ordered by where the turn starts in the transcript rather than by its
66
+ // index among all turns: a paged conversion never holds that count, and
67
+ // both keep every imported opening ahead of the Session's own runs.
68
+ const openedAt = Math.max(0, header.createdAt - 1 - (scanned.highWater - scanned.firstSequence));
68
69
  const run = { sessionId, runId, turnId: turn.turnId, invocationId: runId };
69
- const events = [
70
- transcriptOpeningEvent({ header, run, openedAt, newId: this.deps.newId }),
70
+ // A build before the ids were derived converted under random ones, so
71
+ // an interrupted run of its can hold events this build cannot rederive.
72
+ // What it can read is which legacy row each of them came from, and that
73
+ // is the identity the conversion resumes on.
74
+ const started = startedRunIds.has(runId)
75
+ ? await this.deps.runtimeEventStore.readRuntimeEvents(sessionId, runId)
76
+ : [];
77
+ const converted = new Map();
78
+ for (const event of started) {
79
+ const rowId = event.refs?.storedMessageId;
80
+ if (rowId)
81
+ converted.set(rowId, (converted.get(rowId) ?? 0) + 1);
82
+ }
83
+ const hasOpening = started.some((event) => event.content?.kind === 'invocation_opened');
84
+ const derived = [
85
+ ...(hasOpening ? [] : [transcriptOpeningEvent({ header, run, openedAt })]),
71
86
  ...backfillRuntimeEventsFromStoredMessages({
72
87
  run,
73
88
  outcome: transcriptOutcome(turn, turnMessages, openedAt),
74
89
  messages: turnMessages,
75
- modelHistory: 'conversation_text',
76
- newId: this.deps.newId,
77
- now: this.deps.now,
90
+ // Another runtime's tool calls belong to its protocol, not to the
91
+ // provider this Session will talk to next, so a foreign transcript
92
+ // converts as the conversation it is. Maka's own history converts
93
+ // whole: its tool calls are the ones it would replay.
94
+ modelHistory: header.externalOrigin ? 'conversation_text' : 'full',
95
+ newId: transcriptEventIds(runId),
96
+ // The payload must be as repeatable as its id: SQLite dedupes
97
+ // complete events, including the backfill provenance timestamps.
98
+ now: () => openedAt,
78
99
  }).events,
79
100
  ];
80
- if (!events.some(isTerminalRuntimeEvent)) {
81
- throw new Error(`Imported transcript Run ${runId} has no terminal RuntimeEvent`);
82
- }
83
- for (const event of events) {
101
+ // The whole turn is derived either way, so the ids stay the ones a
102
+ // fresh conversion would mint; only the events whose row already has
103
+ // that many on the run are dropped. A row half-converted by a crash
104
+ // between two of its events keeps the rest.
105
+ const seen = new Map();
106
+ for (const event of derived) {
107
+ const rowId = event.refs?.storedMessageId;
108
+ if (rowId !== undefined) {
109
+ const index = seen.get(rowId) ?? 0;
110
+ seen.set(rowId, index + 1);
111
+ if (index < (converted.get(rowId) ?? 0))
112
+ continue;
113
+ }
84
114
  await this.deps.runtimeEventStore.appendRuntimeEvent(sessionId, runId, event);
85
115
  }
86
116
  }
117
+ // Appending gave every converted event an ordinal above the Session's
118
+ // existing runs, which is the wrong order whenever the transcript holds a
119
+ // turn older than a run already on the ledger. A released build could
120
+ // leave exactly that: it sent on an imported Session without converting
121
+ // first. `openedAt` above already says where each imported turn belongs;
122
+ // this is what makes the reader agree.
123
+ await this.deps.runtimeEventStore.resequenceSessionEventOrdinals(sessionId);
87
124
  });
88
125
  }
89
- async repairSteeringMessagesOnce(sessionId) {
90
- return this.withRepairQueue(sessionId, 'steering-transcript', async () => {
91
- const messages = await this.deps.readMessages(sessionId);
92
- const messageIds = new Set(messages.map((message) => message.id));
93
- const inlineRunIds = new Set((await this.listInlineInvocations(sessionId)).map((invocation) => invocation.runId));
94
- let repaired = 0;
95
- for (const event of await this.deps.runtimeEventStore.readSessionRuntimeEvents(sessionId)) {
96
- if (!inlineRunIds.has(event.runId))
126
+ /**
127
+ * The Session's legacy rows, one turn at a time, read a page at a time.
128
+ *
129
+ * A turn is only complete once a row of another turn follows it, so the rows
130
+ * of the page's last turn are carried into the next page rather than
131
+ * converted early. Peak memory is therefore one page plus one turn — the same
132
+ * bound the transcript reader keeps, and not the Session's whole history.
133
+ */
134
+ async *readTurnsInPages(sessionId) {
135
+ let carried;
136
+ let afterSequence;
137
+ while (true) {
138
+ const page = await this.deps.readMessagesAfter(sessionId, {
139
+ ...(afterSequence === undefined ? {} : { afterSequence }),
140
+ maxMessages: TRANSCRIPT_CONVERSION_PAGE_MAX_MESSAGES,
141
+ maxStoredBytes: TRANSCRIPT_CONVERSION_PAGE_MAX_BYTES,
142
+ });
143
+ const highWater = page.highWaterSequence;
144
+ if (highWater === null)
145
+ return;
146
+ const scanned = page.records.filter(({ message }) => message.type !== 'user' || message.steeringEventId === undefined);
147
+ const grouped = new Map();
148
+ if (carried)
149
+ grouped.set(turnIdOf(carried.messages[0]) ?? '', carried);
150
+ for (const { sequence, message } of scanned) {
151
+ const turnId = turnIdOf(message);
152
+ if (!turnId)
97
153
  continue;
98
- if (await materializeRuntimeEventTranscriptProjection(this.deps, sessionId, event, messageIds)) {
99
- repaired += 1;
100
- }
154
+ const bucket = grouped.get(turnId);
155
+ if (bucket)
156
+ bucket.messages.push(message);
157
+ else
158
+ grouped.set(turnId, { messages: [message], firstSequence: sequence });
101
159
  }
102
- return repaired;
103
- });
160
+ const turns = [...grouped.values()];
161
+ const lastSequence = page.records.at(-1)?.sequence;
162
+ // The last turn of a page may continue into the next one, so it is held
163
+ // back rather than converted from a prefix of its own rows. A page with
164
+ // nothing left to read ends the scan, and what was held back is whole.
165
+ carried = lastSequence === undefined ? undefined : turns.pop();
166
+ for (const turn of turns)
167
+ yield { ...turn, highWater };
168
+ if (lastSequence === undefined)
169
+ return;
170
+ afterSequence = lastSequence;
171
+ }
104
172
  }
105
- async listInlineInvocations(sessionId) {
106
- return (await this.deps.runtimeEventStore.listSessionInvocations(sessionId)).filter((invocation) => isSessionInlineInvocation(invocation.opening));
173
+ /**
174
+ * Which turns the ledger already owns and which runs it has started, as ids
175
+ * rather than records: the inventory is one row per invocation and the scan
176
+ * that follows outlives it, so nothing keeps the records themselves.
177
+ */
178
+ async readLedgerOwnership(sessionId) {
179
+ const ownedTurnIds = new Set();
180
+ const startedRunIds = new Set();
181
+ for (const invocation of await this.deps.runtimeEventStore.listSessionInvocations(sessionId)) {
182
+ if (!isSessionInlineInvocation(invocation.opening))
183
+ continue;
184
+ startedRunIds.add(invocation.runId);
185
+ if (invocation.terminalEvent ||
186
+ invocation.runId !== transcriptRunId(sessionId, invocation.turnId)) {
187
+ ownedTurnIds.add(invocation.turnId);
188
+ }
189
+ }
190
+ return { ownedTurnIds, startedRunIds };
107
191
  }
108
- async withRepairQueue(sessionId, runId, operation) {
109
- const key = `${sessionId}:${runId}`;
192
+ async withRepairQueue(key, operation) {
110
193
  const previous = this.queues.get(key) ?? Promise.resolve();
111
194
  const current = previous.then(operation, operation);
112
195
  const cleanup = current.then(() => undefined, () => undefined);
@@ -121,10 +204,26 @@ export class RuntimeLedgerRepair {
121
204
  }
122
205
  }
123
206
  }
207
+ /** Synthetic conversion runs belong to the importer, never execution recovery. */
208
+ export function isTranscriptLedgerInvocation(invocation) {
209
+ return invocation.runId === transcriptRunId(invocation.sessionId, invocation.turnId);
210
+ }
124
211
  function transcriptRunId(sessionId, turnId) {
125
212
  const digest = createHash('sha256').update(sessionId).update('\0').update(turnId).digest('hex');
126
213
  return `transcript-${digest.slice(0, 48)}`;
127
214
  }
215
+ /**
216
+ * Ids for one run's converted events, numbered in the order the converter
217
+ * emits them. The run id is already derived from the Session and turn, so the
218
+ * same transcript always produces the same ids and a re-run appends nothing.
219
+ */
220
+ function transcriptEventIds(runId) {
221
+ let seq = 0;
222
+ return () => {
223
+ seq += 1;
224
+ return `${runId}-e${seq}`;
225
+ };
226
+ }
128
227
  /**
129
228
  * The opening fact of an imported turn.
130
229
  *
@@ -154,7 +253,7 @@ function transcriptOpeningEvent(input) {
154
253
  source: { kind: 'fresh' },
155
254
  };
156
255
  return buildInvocationOpenedEvent({
157
- id: input.newId(),
256
+ id: `${input.run.runId}-opened`,
158
257
  run: input.run,
159
258
  openedAt: input.openedAt,
160
259
  opening,
@@ -189,26 +288,8 @@ function transcriptOutcomeStatus(status) {
189
288
  return 'completed';
190
289
  return 'cancelled';
191
290
  }
192
- function groupMessagesByTurn(messages) {
193
- const grouped = new Map();
194
- for (const message of messages) {
195
- const turnId = 'turnId' in message ? message.turnId : undefined;
196
- if (!turnId)
197
- continue;
198
- const bucket = grouped.get(turnId) ?? [];
199
- bucket.push(message);
200
- grouped.set(turnId, bucket);
201
- }
202
- return grouped;
203
- }
204
- function steeringMessageFromRuntimeEvent(event) {
205
- const messageId = event.refs?.providerEventId;
206
- if (event.role !== 'user' ||
207
- event.content?.kind !== 'text' ||
208
- event.content.steering !== true ||
209
- typeof messageId !== 'string' ||
210
- messageId.length === 0) {
291
+ function turnIdOf(message) {
292
+ if (!message)
211
293
  return undefined;
212
- }
213
- return projectRuntimeEventUserMessage(event, messageId);
294
+ return 'turnId' in message ? message.turnId : undefined;
214
295
  }
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import { deriveTurnRecords } from '@maka/core/session';
20
20
  import { isSessionInlineInvocation } from '@maka/core/runtime-invocation';
21
- import { classifyRuntimeEventTerminalFact, compareRuntimeReadModelMessages, isHardRuntimeEventReadModelDiagnostic, projectRuntimeEventsToStoredMessages, } from './runtime-event-read-model.js';
21
+ import { activePresentationRuntimeEvents, classifyRuntimeEventTerminalFact, isHardRuntimeEventReadModelDiagnostic, projectRuntimeEventsToStoredMessages, } from './runtime-event-read-model.js';
22
22
  import { buildRuntimeEventModelReplayPlan, } from './model-history.js';
23
23
  const CANONICAL_PERMISSION_READ_CONCURRENCY = 8;
24
24
  export class RuntimeReadModelError extends Error {
@@ -76,19 +76,12 @@ export class RuntimeReadModel {
76
76
  ]);
77
77
  }
78
78
  // No terminal event yet: the invocation is still open, or the process died
79
- // holding it. Either way the ledger is the whole truth about it, so the
80
- // in-flight projection cache supplies the rows a live turn has not
81
- // committed instead of a status field claiming otherwise.
79
+ // holding it. Either way its own events are the whole truth about it, read
80
+ // as a running turn reads — the arriving text presented as settled. No
81
+ // durable ordinals exist for them yet, so they keep ledger order.
82
82
  if (!invocation.terminalEvent) {
83
- diagnostics.push(readModelDiagnostic('incomplete_event', 'active run is using the in-flight projection cache', { runId: invocation.runId, turnId: invocation.turnId }));
84
83
  inFlightTurnIds.add(invocation.turnId);
85
- if (!this.deps.projectionCache) {
86
- throw new RuntimeReadModelError('RuntimeEvent ledger is incomplete for an active run', [
87
- readModelDiagnostic('incomplete_event', 'active run has no stable RuntimeEvent read projection', { runId: invocation.runId, turnId: invocation.turnId }),
88
- ]);
89
- }
90
- const overlayEvents = runEvents.flatMap(activeInteractionOverlayEvent);
91
- appendOrderedEvents(ordered, overlayEvents, runIndex);
84
+ appendOrderedEvents(ordered, activePresentationRuntimeEvents(runEvents), runIndex);
92
85
  continue;
93
86
  }
94
87
  const terminalFact = classifyRuntimeEventTerminalFact(invocation, runEvents);
@@ -135,30 +128,11 @@ export class RuntimeReadModel {
135
128
  if (projected.diagnostics.some(isHardRuntimeEventReadModelDiagnostic)) {
136
129
  throw new RuntimeReadModelError('RuntimeEvent read projection is incomplete', diagnostics);
137
130
  }
138
- const sessionId = input.invocations[0]?.sessionId;
139
- let cachedMessages;
140
- if (sessionId && this.deps.projectionCache) {
141
- try {
142
- cachedMessages = await this.deps.projectionCache.readMessages(sessionId);
143
- }
144
- catch (error) {
145
- const diagnostic = readModelDiagnostic('unsupported_event', 'SessionProjectionCache.readMessages failed', {
146
- error: errorMessage(error),
147
- });
148
- diagnostics.push(diagnostic);
149
- if (input.inFlightTurnIds && input.inFlightTurnIds.size > 0) {
150
- throw new RuntimeReadModelError('RuntimeEvent active projection cache read failed', diagnostics);
151
- }
152
- }
153
- }
154
- const messages = input.inFlightTurnIds && input.inFlightTurnIds.size > 0
155
- ? mergeInFlightProjectionCache(projected.messages, cachedMessages ?? [], input.inFlightTurnIds)
156
- : projected.messages;
157
- diagnostics.push(...this.compareProjectionCache(messages, cachedMessages, canonicalPermissionRead.outcomes));
131
+ const messages = projected.messages;
158
132
  return {
159
133
  source: 'runtime_events',
160
134
  messages,
161
- turns: deriveTurnRecords(messages),
135
+ turns: runningTurnRecords(deriveTurnRecords(messages), input.inFlightTurnIds),
162
136
  events: input.events,
163
137
  invocations: input.invocations,
164
138
  diagnostics,
@@ -195,66 +169,33 @@ export class RuntimeReadModel {
195
169
  await Promise.all(Array.from({ length: Math.min(CANONICAL_PERMISSION_READ_CONCURRENCY, requestIds.length) }, worker));
196
170
  return { outcomes, diagnostics };
197
171
  }
198
- compareProjectionCache(messages, cached, canonicalPermissionOutcomes) {
199
- if (!cached)
200
- return [];
201
- const canonicalRequestIds = new Set(canonicalPermissionOutcomes.keys());
202
- const excludesCanonicalPermission = (message) => message.type === 'permission_decision' && canonicalRequestIds.has(message.id);
203
- return compareRuntimeReadModelMessages(messages.filter((message) => !excludesCanonicalPermission(message)), cached.filter((message) => !excludesCanonicalPermission(message))).diagnostics;
204
- }
205
172
  }
206
173
  /**
207
- * The interaction facts an active run must keep even while its messages come
208
- * from the in-flight projection cache. Permission prompts were always carried
209
- * here; sandbox boundary requests and decisions belong for the same reason
210
- * (#1612): they are the only durable record that a prompt was raised and how
211
- * it settled, so dropping them makes a pending request invisible to anything
212
- * reading the view instead of the live backend.
174
+ * A turn whose invocation has not ended is running.
175
+ *
176
+ * The transcript has no row that says so, and it should not: "still running" is
177
+ * the absence of the terminal event, read off the invocation itself. Rows are
178
+ * what the turn produced, and a turn that has produced an answer but not ended
179
+ * would otherwise read as finished.
213
180
  */
214
- function activeInteractionOverlayEvent(event) {
215
- const permissionRequest = event.actions?.permissionRequest;
216
- const permissionAnswerAccepted = event.actions?.permissionAnswerAccepted;
217
- const permissionClosureAccepted = event.actions?.permissionClosureAccepted;
218
- const sandboxBoundaryRequest = event.actions?.stateDelta?.sandboxBoundaryRequest;
219
- const sandboxBoundaryDecision = event.actions?.stateDelta?.sandboxBoundaryDecision;
220
- if (!permissionRequest &&
221
- !permissionAnswerAccepted &&
222
- !permissionClosureAccepted &&
223
- sandboxBoundaryRequest === undefined &&
224
- sandboxBoundaryDecision === undefined) {
225
- return [];
226
- }
227
- const overlay = { ...event };
228
- delete overlay.content;
229
- delete overlay.status;
230
- const stateDelta = {
231
- ...(sandboxBoundaryRequest !== undefined ? { sandboxBoundaryRequest } : {}),
232
- ...(sandboxBoundaryDecision !== undefined ? { sandboxBoundaryDecision } : {}),
233
- };
234
- overlay.actions = {
235
- ...(permissionRequest ? { permissionRequest } : {}),
236
- ...(permissionAnswerAccepted ? { permissionAnswerAccepted } : {}),
237
- ...(permissionClosureAccepted ? { permissionClosureAccepted } : {}),
238
- ...(Object.keys(stateDelta).length > 0 ? { stateDelta } : {}),
239
- };
240
- return [overlay];
241
- }
242
- function mergeInFlightProjectionCache(runtimeMessages, cachedMessages, inFlightTurnIds) {
243
- const merged = runtimeMessages.map((message, index) => ({ message, index }));
244
- const seenIds = new Set(runtimeMessages.map((message) => message.id));
245
- for (const cached of cachedMessages) {
246
- const turnId = messageTurnId(cached);
247
- if (!turnId || !inFlightTurnIds.has(turnId) || seenIds.has(cached.id))
248
- continue;
249
- seenIds.add(cached.id);
250
- merged.push({ message: cached, index: merged.length });
181
+ function runningTurnRecords(turns, inFlightTurnIds) {
182
+ if (!inFlightTurnIds || inFlightTurnIds.size === 0)
183
+ return [...turns];
184
+ const running = new Set(inFlightTurnIds);
185
+ const marked = turns.map((turn) => {
186
+ if (!running.delete(turn.turnId))
187
+ return turn;
188
+ return { ...turn, status: 'running', statusSource: 'recorded' };
189
+ });
190
+ // An invocation that has opened but produced nothing yet still has a turn.
191
+ for (const turnId of running) {
192
+ marked.push({
193
+ turnId,
194
+ status: 'running',
195
+ statusSource: 'recorded',
196
+ });
251
197
  }
252
- return merged
253
- .sort((a, b) => a.message.ts - b.message.ts || a.index - b.index)
254
- .map((entry) => entry.message);
255
- }
256
- function messageTurnId(message) {
257
- return 'turnId' in message && typeof message.turnId === 'string' ? message.turnId : undefined;
198
+ return marked;
258
199
  }
259
200
  function readModelDiagnostic(code, message, detail) {
260
201
  return {
@@ -17,12 +17,13 @@
17
17
  * under the License.
18
18
  */
19
19
  import { isPartialRuntimeEvent, isTerminalRuntimeEvent, runtimeEventHasModelVisibleContent, } from '@maka/core/runtime-event';
20
- import { continuationStartEventMatchesClaim, invocationMatchesClaimTarget, } from '@maka/core/runtime-boundary';
20
+ import { buildImmutableRuntimePrefix, continuationStartEventMatchesClaim, invocationMatchesClaimTarget, } from '@maka/core/runtime-boundary';
21
21
  import { isDeepStrictEqual } from 'node:util';
22
22
  import { buildContinuationReplayPlan, } from './continuation-replay.js';
23
23
  import { PROVIDER_REPLAY_PROJECTION_VERSION, } from './model-history.js';
24
24
  import { resolveRuntimeRecovery } from './recovery-resolver.js';
25
25
  import { classifyRuntimeEventTerminalFact } from './runtime-event-read-model.js';
26
+ import { assertHandoffClaimSource, runtimeHandoffPause, } from '@maka/core/runtime-handoff';
26
27
  export class RuntimeContinuationRevalidationError extends Error {
27
28
  code;
28
29
  constructor(code, message) {
@@ -78,12 +79,49 @@ export const RUNTIME_RESUME_FAILPOINTS = [
78
79
  { id: 'P10', boundary: 'recovery decision commit', committedPrefix: 'after_terminal_event' },
79
80
  { id: 'P11', boundary: 'continuation run creation', committedPrefix: 'after_terminal_event' },
80
81
  ];
82
+ /** Keep logical ownership while independently checking the execution's current configuration. */
83
+ export function preserveHandoffOpening(continuation, computed, source) {
84
+ if (continuation.handoffRootRunId === undefined)
85
+ return computed;
86
+ if (source?.kind !== 'invocation_opened' ||
87
+ !continuation.claimId ||
88
+ !continuation.boundary ||
89
+ !isDeepStrictEqual(source.configuration, computed.configuration) ||
90
+ continuation.handoffRootRunId !==
91
+ (source.source.kind === 'handoff' ? source.source.rootRunId : continuation.sourceRunId)) {
92
+ throw new RuntimeContinuationRevalidationError('source_identity_changed', 'Handoff execution cannot preserve its source configuration and logical authority');
93
+ }
94
+ const { lineage: _computedLineage, ...opening } = computed;
95
+ return {
96
+ ...opening,
97
+ root: source.root,
98
+ ...(source.lineage ? { lineage: source.lineage } : {}),
99
+ source: {
100
+ kind: 'handoff',
101
+ rootRunId: continuation.handoffRootRunId,
102
+ sourceInvocationId: continuation.sourceInvocationId,
103
+ sourceRunId: continuation.sourceRunId,
104
+ sourceTurnId: continuation.sourceTurnId,
105
+ sourceRuntimeEventHighWater: continuation.sourceRuntimeEventHighWater,
106
+ claimId: continuation.claimId,
107
+ boundaryDigest: continuation.boundary.manifestDigest,
108
+ },
109
+ };
110
+ }
81
111
  export class RuntimeContinuationPlanner {
82
112
  deps;
83
113
  constructor(deps) {
84
114
  this.deps = deps;
85
115
  }
86
116
  async plan(input) {
117
+ return this.planBoundary(input);
118
+ }
119
+ /** A candidate is never execution authority and never escapes as a continuation. */
120
+ async previewHandoff(input, seal) {
121
+ const { continuation: _continuation, ...assessment } = await this.planBoundary({ ...input, purpose: 'handoff' }, seal);
122
+ return assessment;
123
+ }
124
+ async planBoundary(input, preview) {
87
125
  let sourceInvocation;
88
126
  try {
89
127
  sourceInvocation = await this.deps.readSourceInvocation(input.sessionId, input.sourceRunId);
@@ -101,8 +139,21 @@ export class RuntimeContinuationPlanner {
101
139
  }
102
140
  return parkedPlan('runtime_ledger_unreadable', 'RuntimeEvent ledger could not be read reliably');
103
141
  }
142
+ if (preview) {
143
+ const source = prefixes.at(-1);
144
+ if (!runtimeHandoffPause(preview) || source.events.some(isTerminalRuntimeEvent)) {
145
+ return parkedPlan('runtime_identity_mismatch', 'Handoff preview requires an unsealed live source');
146
+ }
147
+ prefixes[prefixes.length - 1] = buildImmutableRuntimePrefix(source.identity, [...source.events, preview].map((event, index) => ({ eventSeq: index + 1, event })));
148
+ }
104
149
  const sourcePrefix = prefixes.at(-1);
105
150
  const events = [...sourcePrefix.events];
151
+ const pause = events.at(-1) && runtimeHandoffPause(events.at(-1));
152
+ if ((input.purpose === 'handoff') !== Boolean(pause)) {
153
+ return parkedPlan('runtime_identity_mismatch', pause
154
+ ? 'This source is reserved for its sealed handoff successor'
155
+ : 'A physical handoff requires a durable pause seal');
156
+ }
106
157
  if (sourcePrefix.identity.sessionId !== input.sessionId ||
107
158
  sourcePrefix.identity.runId !== input.sourceRunId) {
108
159
  return parkedPlan('runtime_identity_mismatch', 'RuntimeEvent ledger does not belong to the requested source run');
@@ -157,10 +208,17 @@ export class RuntimeContinuationPlanner {
157
208
  // the same value at every mint site so the opening fact can be joined
158
209
  // either way while the two names are still being retired.
159
210
  continuationIdentity: (() => {
211
+ if (pause)
212
+ return {
213
+ invocationId: pause.successorInvocationId,
214
+ runId: pause.successorRunId,
215
+ turnId: sourcePrefix.identity.turnId,
216
+ };
160
217
  const invocationId = this.deps.newId();
161
218
  return { invocationId, runId: invocationId, turnId: this.deps.newId() };
162
219
  })(),
163
- continuationClaimId: this.deps.newId(),
220
+ continuationClaimId: pause?.claimId ?? this.deps.newId(),
221
+ ...(pause ? { handoffPause: pause } : {}),
164
222
  continuationReplayPlan: replay.plan,
165
223
  ...(input.expectedRuntimeEventHighWater !== undefined
166
224
  ? { expectedRuntimeEventHighWater: input.expectedRuntimeEventHighWater }
@@ -239,7 +297,7 @@ export class RuntimeContinuationPlanner {
239
297
  let depth = 1;
240
298
  while (true) {
241
299
  const opened = childInvocation.opening.source;
242
- const current = opened.kind === 'continuation' ? opened : undefined;
300
+ const current = opened.kind !== 'fresh' ? opened : undefined;
243
301
  const start = childPrefix.events[0]?.actions?.continuationStart;
244
302
  // A migrated opening keeps the lineage edge but names no claim, so only
245
303
  // an edge that names one can be authenticated against a durable claim.
@@ -337,6 +395,12 @@ export class RuntimeContinuationPlanner {
337
395
  !continuationStartEventMatchesClaim(edge.startEvent, state.claim, state.startKind)) {
338
396
  throw new RuntimeLineageError('runtime_lineage_claim_mismatch', `durable continuation claim does not authenticate ${edge.childRunId}`);
339
397
  }
398
+ try {
399
+ assertHandoffClaimSource(state.claim, segments[childIndex - 1]);
400
+ }
401
+ catch {
402
+ throw new RuntimeLineageError('runtime_lineage_claim_mismatch', `handoff source does not authenticate ${edge.childRunId}`);
403
+ }
340
404
  if (edge.providerProjectionVersion !== PROVIDER_REPLAY_PROJECTION_VERSION) {
341
405
  throw new RuntimeLineageError('runtime_lineage_replay_mismatch', `continuation provider replay version is unsupported for ${edge.childRunId}`);
342
406
  }
@@ -521,7 +585,13 @@ export function buildSafeBoundaryContinuationPlan(events, facts) {
521
585
  }
522
586
  if (facts.continuationIdentity.invocationId === source.invocationId ||
523
587
  facts.continuationIdentity.runId === source.runId ||
524
- facts.continuationIdentity.turnId === source.turnId) {
588
+ (facts.handoffPause
589
+ ? facts.continuationIdentity.turnId !== source.turnId ||
590
+ facts.continuationIdentity.runId !== facts.handoffPause.successorRunId ||
591
+ facts.continuationIdentity.invocationId !== facts.handoffPause.successorInvocationId ||
592
+ facts.continuationClaimId !== facts.handoffPause.claimId ||
593
+ !isDeepStrictEqual(events.at(-1)?.actions?.handoffPause, facts.handoffPause)
594
+ : facts.continuationIdentity.turnId === source.turnId)) {
525
595
  phaseOneDiagnostics.push({
526
596
  code: 'continuation_identity_reused',
527
597
  message: 'continuation must use fresh invocation, run, and turn identities',
@@ -677,6 +747,12 @@ export function buildSafeBoundaryContinuationPlan(events, facts) {
677
747
  ? { sourceRuntimeContext: legacyReplayPlan.replayRuntimeEvents }
678
748
  : {}),
679
749
  runtimeContext: [...modelRuntimeContext],
750
+ ...(facts.handoffPause
751
+ ? {
752
+ handoffRootRunId: facts.handoffPause.rootRunId,
753
+ handoffRemainingSteps: facts.handoffPause.remainingSteps,
754
+ }
755
+ : {}),
680
756
  ...(facts.continuationClaimId ? { claimId: facts.continuationClaimId } : {}),
681
757
  ...(compositeReplay
682
758
  ? {
@@ -92,6 +92,9 @@ export function mapSessionEventToRuntimeEvent(event, ctx, memory = createSession
92
92
  if (isHostProjectionSessionEvent(event)) {
93
93
  // These are Host/kernel projection facts, not backend events. The live
94
94
  // ingress drops them, so reaching this line bypassed that authority boundary.
95
+ // `context_compaction_started` is one of these: synthesized by the Runtime
96
+ // Host session projector for the renderer's live "compacting" row, never
97
+ // produced by a backend or the kernel.
95
98
  throw new Error(`${event.type} is not a backend event`);
96
99
  }
97
100
  if (isLegacyPermissionSessionEvent(event)) {
@@ -106,6 +109,7 @@ export function isLiveBackendSessionEvent(event) {
106
109
  function isHostProjectionSessionEvent(event) {
107
110
  return (event.type === 'queue_update' ||
108
111
  event.type === 'message_admission' ||
112
+ event.type === 'context_compaction_started' ||
109
113
  event.type === 'client_capability_request' ||
110
114
  event.type === 'client_capability_decision_ack');
111
115
  }
@@ -528,6 +532,7 @@ function mapBackendSessionEvent(event, ctx, memory) {
528
532
  ...(event.reason !== undefined ? { reason: event.reason } : {}),
529
533
  message: event.message,
530
534
  ...(event.details !== undefined ? { details: event.details } : {}),
535
+ ...(event.retry !== undefined ? { retry: event.retry } : {}),
531
536
  };
532
537
  memory.failureContent = content;
533
538
  return {