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
@@ -21,6 +21,7 @@ import { mkdirSync } from 'node:fs';
21
21
  import { createRequire } from 'node:module';
22
22
  import { dirname } from 'node:path';
23
23
  import { isDeepStrictEqual } from 'node:util';
24
+ import { assertHandoffClaimSource } from '@maka/core/runtime-handoff';
24
25
  import { buildWorkspaceBaselineAuthorityEvents, buildWorkspaceSuccessorAuthorityEvent, scanWorkspaceBaselineAuthority, WORKSPACE_AUTHORITY_SESSION_ID, WORKSPACE_VERSION_AUTHORITY_CAPABILITY_V1, } from '@maka/core/workspace-version-authority';
25
26
  import { decodeRuntimeEvent, decodeRuntimeInvocationOpened, isPartialRuntimeEvent, isTerminalRuntimeEvent, runtimeEventInvocationOpening, } from '@maka/core/runtime-event';
26
27
  import { RunSealedError, RUNTIME_CONTINUATION_AUTHORITY_V1, TOOL_RECOVERY_BUNDLE_CAPABILITY_V1, } from '@maka/core/runtime-event-store';
@@ -34,19 +35,8 @@ import { registerWorkspaceBaselineAuthorityWriterInternal, } from './workspace-v
34
35
  import { assertEvidenceReadBudget, measureEvidenceRows, } from './bounded-evidence.js';
35
36
  import { immutableSteeringMessageId, isRuntimeStorageSafeId } from './runtime-event-invariants.js';
36
37
  import { assertNoReservedWorkspaceAuthorityAppend } from './runtime-event-authority.js';
38
+ import { RuntimeTranscriptQuery, TERMINAL_RUNTIME_EVENT_SQL, } from './runtime-transcript-query.js';
37
39
  export { SQLITE_RUNTIME_SCHEMA_VERSION } from './sqlite-runtime-schema.js';
38
- /**
39
- * `isTerminalRuntimeEvent` asked in SQL.
40
- *
41
- * The TypeScript predicate stays the authority; this only lets a query find the
42
- * terminal event without decoding every row it passes over. Both have to say the
43
- * same thing, so the SQL half is written once here instead of at each query.
44
- */
45
- const TERMINAL_RUNTIME_EVENT_SQL = `(
46
- json_extract(payload_json, '$.actions.endInvocation') = 1
47
- OR json_extract(payload_json, '$.status')
48
- IN ('completed', 'failed', 'aborted', 'cancelled')
49
- )`;
50
40
  const RUNTIME_EVENT_SCAN_BATCH_SIZE = 128;
51
41
  const RUNTIME_PARTIAL_SEGMENT_TARGET_BYTES = 64 * 1024;
52
42
  function assertRuntimeEventScanBudget(budget) {
@@ -287,6 +277,33 @@ export class SqliteRuntimeStore {
287
277
  async readRuntimeEvents(sessionId, runId) {
288
278
  return this.readRuntimeEventsSync(sessionId, runId);
289
279
  }
280
+ transcriptQuery() {
281
+ return new RuntimeTranscriptQuery(this.db, (sessionId, invocationId) => {
282
+ // By invocation rather than by run: both shelves key their opening on it,
283
+ // so a page's records cost the page instead of the Session's Turns.
284
+ const opening = this.readInvocationOpeningsSync(sessionId, {
285
+ direction: 'asc',
286
+ invocationId,
287
+ }).at(0);
288
+ if (!opening)
289
+ throw new Error(`Transcript invocation ${invocationId} is missing`);
290
+ return this.completeInvocationRecordSync(opening);
291
+ });
292
+ }
293
+ async readTranscriptHighWater(sessionId) {
294
+ assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
295
+ return this.readTransaction(() => this.transcriptQuery().highWater(sessionId));
296
+ }
297
+ async readTranscriptInvocations(sessionId, request) {
298
+ assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
299
+ assertInvocationSearchLimit(request.limit);
300
+ return this.readTransaction(() => this.transcriptQuery().invocations(sessionId, request));
301
+ }
302
+ async readTranscriptLandmarks(sessionId, throughOrdinal, limit) {
303
+ assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
304
+ assertInvocationSearchLimit(limit);
305
+ return this.readTransaction(() => this.transcriptQuery().landmarks(sessionId, throughOrdinal, limit));
306
+ }
290
307
  /**
291
308
  * Enumerate a Session's invocations: the opening fact names each one, and its
292
309
  * highest-sequence event says whether it ended.
@@ -400,6 +417,8 @@ export class SqliteRuntimeStore {
400
417
  1 AS from_events
401
418
  FROM runtime_events
402
419
  WHERE session_id = :sessionId AND event_kind = 'invocation_opened'
420
+ ${options.runId === undefined ? '' : 'AND run_id = :runId'}
421
+ ${options.invocationId === undefined ? '' : 'AND invocation_id = :invocationId'}
403
422
  UNION ALL
404
423
  SELECT
405
424
  NULL,
@@ -411,15 +430,15 @@ export class SqliteRuntimeStore {
411
430
  0
412
431
  FROM runtime_legacy_invocation_openings AS legacy
413
432
  WHERE legacy.session_id = :sessionId
433
+ ${options.runId === undefined ? '' : 'AND legacy.run_id = :runId'}
434
+ ${options.invocationId === undefined ? '' : 'AND legacy.invocation_id = :invocationId'}
414
435
  AND NOT EXISTS (
415
436
  SELECT 1 FROM runtime_events
416
437
  WHERE runtime_events.invocation_id = legacy.invocation_id
417
438
  AND runtime_events.event_kind = 'invocation_opened'
418
439
  )
419
440
  )
420
- WHERE (:invocationId IS NULL OR invocation_id = :invocationId)
421
- AND (:runId IS NULL OR run_id = :runId)
422
- AND (
441
+ WHERE (
423
442
  :beforeOpenedAt IS NULL
424
443
  OR opened_at < :beforeOpenedAt
425
444
  OR (opened_at = :beforeOpenedAt AND invocation_id < :beforeInvocationId)
@@ -429,8 +448,8 @@ export class SqliteRuntimeStore {
429
448
  `)
430
449
  .all({
431
450
  sessionId,
432
- invocationId: options.invocationId ?? null,
433
- runId: options.runId ?? null,
451
+ ...(options.invocationId === undefined ? {} : { invocationId: options.invocationId }),
452
+ ...(options.runId === undefined ? {} : { runId: options.runId }),
434
453
  beforeOpenedAt: options.before?.openedAt ?? null,
435
454
  beforeInvocationId: options.before?.invocationId ?? null,
436
455
  limit: options.limit ?? -1,
@@ -801,12 +820,12 @@ export class SqliteRuntimeStore {
801
820
  const conflict = this.readContinuationClaimRow(`claim_id = ?
802
821
  OR target_invocation_id = ?
803
822
  OR target_run_id = ?
804
- OR (target_session_id = ? AND target_turn_id = ?)
823
+ OR (? = 0 AND target_session_id = ? AND target_turn_id = ?)
805
824
  OR (
806
825
  source_session_id = ?
807
826
  AND source_run_id = ?
808
827
  AND source_event_high_water = ?
809
- )`, claim.claimId, claim.target.invocationId, claim.target.runId, claim.target.sessionId, claim.target.turnId, source.identity.sessionId, source.identity.runId, source.position.lastEventSeq);
828
+ )`, claim.claimId, claim.target.invocationId, claim.target.runId, claim.targetOpening.source.kind === 'handoff' ? 1 : 0, claim.target.sessionId, claim.target.turnId, source.identity.sessionId, source.identity.runId, source.position.lastEventSeq);
810
829
  if (conflict) {
811
830
  return { kind: 'conflict', claim: decodeContinuationClaimRow(conflict) };
812
831
  }
@@ -844,12 +863,12 @@ export class SqliteRuntimeStore {
844
863
  this.readContinuationClaimRow(`claim_id = ?
845
864
  OR target_invocation_id = ?
846
865
  OR target_run_id = ?
847
- OR (target_session_id = ? AND target_turn_id = ?)
866
+ OR (? = 0 AND target_session_id = ? AND target_turn_id = ?)
848
867
  OR (
849
868
  source_session_id = ?
850
869
  AND source_run_id = ?
851
870
  AND source_event_high_water = ?
852
- )`, claim.claimId, claim.target.invocationId, claim.target.runId, claim.target.sessionId, claim.target.turnId, source.identity.sessionId, source.identity.runId, source.position.lastEventSeq);
871
+ )`, claim.claimId, claim.target.invocationId, claim.target.runId, claim.targetOpening.source.kind === 'handoff' ? 1 : 0, claim.target.sessionId, claim.target.turnId, source.identity.sessionId, source.identity.runId, source.position.lastEventSeq);
853
872
  if (!raced)
854
873
  throw error;
855
874
  const racedClaim = decodeContinuationClaimRow(raced);
@@ -1015,6 +1034,57 @@ export class SqliteRuntimeStore {
1015
1034
  return { ordinal: row.ordinal, event };
1016
1035
  });
1017
1036
  }
1037
+ async resequenceSessionEventOrdinals(sessionId) {
1038
+ assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
1039
+ this.transaction(() => {
1040
+ // Lifted above the range first: the second statement renumbers into the
1041
+ // space these rows occupy, and (session_id, ordinal) is a primary key.
1042
+ // Shifting up rather than below zero keeps every intermediate value
1043
+ // inside the table's own `ordinal > 0`, and lands them past the 1..N the
1044
+ // renumber assigns, since the count cannot exceed the maximum.
1045
+ const { shift } = this.db
1046
+ .prepare(`
1047
+ SELECT COALESCE(MAX(ordinal), 0) AS shift
1048
+ FROM runtime_session_event_ordinals
1049
+ WHERE session_id = ?
1050
+ `)
1051
+ .get(sessionId);
1052
+ this.db
1053
+ .prepare(`
1054
+ UPDATE runtime_session_event_ordinals
1055
+ SET ordinal = ordinal + :shift
1056
+ WHERE session_id = :sessionId
1057
+ `)
1058
+ .run({ sessionId, shift });
1059
+ this.db
1060
+ .prepare(`
1061
+ WITH opening AS (
1062
+ SELECT invocation_id, CAST(json_extract(payload_json, '$.ts') AS INTEGER) AS opened_at
1063
+ FROM runtime_events
1064
+ WHERE session_id = :sessionId AND event_kind = 'invocation_opened'
1065
+ ),
1066
+ ordered AS MATERIALIZED (
1067
+ SELECT
1068
+ o.event_id AS event_id,
1069
+ ROW_NUMBER() OVER (
1070
+ ORDER BY COALESCE(opening.opened_at, e.committed_at), e.invocation_id, o.ordinal
1071
+ ) AS ordinal
1072
+ FROM runtime_session_event_ordinals o
1073
+ JOIN runtime_events e ON e.event_id = o.event_id
1074
+ LEFT JOIN opening ON opening.invocation_id = e.invocation_id
1075
+ WHERE o.session_id = :sessionId
1076
+ )
1077
+ UPDATE runtime_session_event_ordinals
1078
+ SET ordinal = (
1079
+ SELECT ordered.ordinal
1080
+ FROM ordered
1081
+ WHERE ordered.event_id = runtime_session_event_ordinals.event_id
1082
+ )
1083
+ WHERE session_id = :sessionId
1084
+ `)
1085
+ .run({ sessionId });
1086
+ });
1087
+ }
1018
1088
  async #commitWorkspaceBaseline(input, rootId) {
1019
1089
  const events = buildWorkspaceBaselineAuthorityEvents(input);
1020
1090
  return this.transaction(() => {
@@ -1290,8 +1360,7 @@ export class SqliteRuntimeStore {
1290
1360
  });
1291
1361
  }
1292
1362
  registerWorkspaceBaselineAuthorityWriter() {
1293
- const readWorkspaceHead = this.readWorkspaceHead.bind(this);
1294
- registerWorkspaceBaselineAuthorityWriterInternal(this, (input, rootId) => this.#commitWorkspaceBaseline(input, rootId), (input, rootId) => this.#commitWorkspaceSuccessor(input, rootId), (input, rootId) => this.#commitManagedMutationTerminal(input, rootId), (rootId) => this.#bindWorkspaceStorageRoot(rootId), readWorkspaceHead, (workspaceInstanceId) => this.#readActiveManagedMutation(workspaceInstanceId));
1363
+ registerWorkspaceBaselineAuthorityWriterInternal(this, (input, rootId) => this.#commitWorkspaceBaseline(input, rootId), (input, rootId) => this.#commitWorkspaceSuccessor(input, rootId), (input, rootId) => this.#commitManagedMutationTerminal(input, rootId), (rootId) => this.#bindWorkspaceStorageRoot(rootId), (workspaceInstanceId) => this.#readActiveManagedMutation(workspaceInstanceId));
1295
1364
  }
1296
1365
  async #readActiveManagedMutation(workspaceInstanceId) {
1297
1366
  return this.readTransaction(() => {
@@ -2428,6 +2497,7 @@ export class SqliteRuntimeStore {
2428
2497
  target.invocationId,
2429
2498
  target.sessionId,
2430
2499
  target.runId,
2500
+ claim.targetOpening.source.kind === 'handoff' ? 1 : 0,
2431
2501
  target.sessionId,
2432
2502
  target.turnId,
2433
2503
  ];
@@ -2437,7 +2507,7 @@ export class SqliteRuntimeStore {
2437
2507
  FROM runtime_events
2438
2508
  WHERE invocation_id = ?
2439
2509
  OR (session_id = ? AND run_id = ?)
2440
- OR (session_id = ? AND turn_id = ?)
2510
+ OR (? = 0 AND session_id = ? AND turn_id = ?)
2441
2511
  LIMIT 1
2442
2512
  `)
2443
2513
  .get(...values);
@@ -2449,7 +2519,7 @@ export class SqliteRuntimeStore {
2449
2519
  FROM runtime_partial_snapshots
2450
2520
  WHERE invocation_id = ?
2451
2521
  OR (session_id = ? AND run_id = ?)
2452
- OR (session_id = ? AND turn_id = ?)
2522
+ OR (? = 0 AND session_id = ? AND turn_id = ?)
2453
2523
  LIMIT 1
2454
2524
  `)
2455
2525
  .get(...values) !== undefined);
@@ -2474,6 +2544,7 @@ export class SqliteRuntimeStore {
2474
2544
  }
2475
2545
  assertContinuationBoundaryMatchesLedger(claim) {
2476
2546
  const lastIndex = claim.boundary.segments.length - 1;
2547
+ let previousPrefix;
2477
2548
  for (const [index, segment] of claim.boundary.segments.entries()) {
2478
2549
  let prefix;
2479
2550
  try {
@@ -2501,13 +2572,34 @@ export class SqliteRuntimeStore {
2501
2572
  ? 'Continuation source boundary changed'
2502
2573
  : `Continuation ancestor boundary changed for ${segment.identity.runId}`);
2503
2574
  }
2575
+ const opening = prefix.events[0]?.content;
2576
+ const repeatsTurn = previousPrefix?.identity.turnId === prefix.identity.turnId;
2577
+ if (repeatsTurn ||
2578
+ (opening?.kind === 'invocation_opened' && opening.source.kind === 'handoff')) {
2579
+ if (!previousPrefix ||
2580
+ opening?.kind !== 'invocation_opened' ||
2581
+ opening.source.kind !== 'handoff') {
2582
+ throw new Error('Same-turn boundary requires an authenticated handoff edge');
2583
+ }
2584
+ const row = this.readContinuationClaimRow('claim_id = ?', opening.source.claimId);
2585
+ const state = row && this.decodeContinuationClaimStateRow(row);
2586
+ if (!state ||
2587
+ state.startEventId !== prefix.events[0]?.id ||
2588
+ !isDeepStrictEqual(state.claim.boundary.segments, claim.boundary.segments.slice(0, index)) ||
2589
+ !continuationStartEventMatchesClaim(prefix.events[0], state.claim, state.startKind)) {
2590
+ throw new Error('Same-turn boundary handoff claim does not authenticate its lineage');
2591
+ }
2592
+ assertHandoffClaimSource(state.claim, previousPrefix);
2593
+ }
2504
2594
  if (index === lastIndex) {
2595
+ assertHandoffClaimSource(claim, prefix);
2505
2596
  const terminalEvents = prefix.events.filter(isTerminalRuntimeEvent);
2506
2597
  const terminal = terminalEvents[0];
2507
2598
  if (terminalEvents.length !== 1 || !terminal || prefix.events.at(-1)?.id !== terminal.id) {
2508
2599
  throw new Error('Continuation source boundary must end with exactly one terminal RuntimeEvent');
2509
2600
  }
2510
2601
  }
2602
+ previousPrefix = prefix;
2511
2603
  }
2512
2604
  }
2513
2605
  assertToolLedgerTransition(candidateEvents, expectedTransition) {
@@ -2639,16 +2731,27 @@ export class SqliteRuntimeStore {
2639
2731
  }
2640
2732
  }
2641
2733
  assertContinuationAuthorityAllowsEvent(event, authorizedPendingClaimId, exactRetry = false) {
2642
- for (const row of this.readContinuationClaimRows()) {
2734
+ const rows = this.readContinuationClaimRows();
2735
+ const ownClaim = rows.find((row) => row.target_session_id === event.sessionId &&
2736
+ row.target_invocation_id === event.invocationId &&
2737
+ row.target_run_id === event.runId &&
2738
+ row.target_turn_id === event.turnId);
2739
+ const ownHandoff = ownClaim && decodeContinuationClaimRow(ownClaim);
2740
+ for (const row of rows) {
2643
2741
  const claim = decodeContinuationClaimRow(row);
2644
2742
  const source = claim.boundary.segments.find((segment) => segment.identity.sessionId === event.sessionId && segment.identity.runId === event.runId);
2645
2743
  if (source && !exactRetry) {
2646
2744
  throw new Error(`RuntimeEvent source boundary is sealed by continuation claim ${claim.claimId}`);
2647
2745
  }
2746
+ if (source && exactRetry)
2747
+ continue;
2648
2748
  const target = claim.target;
2649
2749
  const collidesWithTarget = event.invocationId === target.invocationId ||
2650
2750
  (event.sessionId === target.sessionId && event.runId === target.runId) ||
2651
- (event.sessionId === target.sessionId && event.turnId === target.turnId);
2751
+ (event.sessionId === target.sessionId &&
2752
+ event.turnId === target.turnId &&
2753
+ !(ownHandoff?.targetOpening.source.kind === 'handoff' &&
2754
+ ownHandoff.boundary.segments.some((segment) => segment.identity.runId === target.runId)));
2652
2755
  if (!collidesWithTarget)
2653
2756
  continue;
2654
2757
  if (event.sessionId !== target.sessionId ||