maka-agent 0.2.0-dev.30.20260912 → 0.2.0-dev.32.20260914

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 (245) hide show
  1. package/THIRD_PARTY_NOTICES.txt +392 -0
  2. package/dist/acp/maka-acp-agent.js +8 -2
  3. package/dist/acp/prompt-content.js +225 -0
  4. package/dist/acp/session-event-mapper.js +103 -0
  5. package/dist/acp/session-registry.js +654 -17
  6. package/dist/acp/stdio-server.js +10 -1
  7. package/dist/cli-core.js +1 -1
  8. package/dist/pi-transcript-tools.js +3 -2
  9. package/dist/pi-transcript.js +15 -6
  10. package/dist/runtime-host-session-channel.js +63 -9
  11. package/native/runtime-host-windows-task-launcher/prebuilds/win32-x64/maka-runtime-host-task-launcher.exe +0 -0
  12. package/node_modules/@maka/core/dist/agent-graph-schedule.js +15 -4
  13. package/node_modules/@maka/core/dist/artifacts.js +6 -0
  14. package/node_modules/@maka/core/dist/attachments.js +7 -2
  15. package/node_modules/@maka/core/dist/durable-tool-result-projection.js +3 -1
  16. package/node_modules/@maka/core/dist/events.js +21 -0
  17. package/node_modules/@maka/core/dist/executor-id.js +22 -0
  18. package/node_modules/@maka/core/dist/external-session.js +18 -0
  19. package/node_modules/@maka/core/dist/goal.js +44 -2
  20. package/node_modules/@maka/core/dist/model-call-usage-projection.js +0 -13
  21. package/node_modules/@maka/core/dist/permission.js +0 -1
  22. package/node_modules/@maka/core/dist/runtime-boundary.js +73 -29
  23. package/node_modules/@maka/core/dist/runtime-event.js +25 -6
  24. package/node_modules/@maka/core/dist/runtime-handoff.js +10 -2
  25. package/node_modules/@maka/core/dist/runtime-logical-execution.js +39 -14
  26. package/node_modules/@maka/core/dist/session-send-projection.js +6 -3
  27. package/node_modules/@maka/core/dist/session.js +8 -2
  28. package/node_modules/@maka/core/dist/shell-run-result.js +1 -0
  29. package/node_modules/@maka/core/dist/shell-run.js +4 -0
  30. package/node_modules/@maka/core/dist/tool-result-archive-evidence.js +3 -1
  31. package/node_modules/@maka/core/dist/tool-result-record-schema.js +2 -1
  32. package/node_modules/@maka/core/dist/unified-diff.js +33 -26
  33. package/node_modules/@maka/core/dist/work-board.js +94 -1
  34. package/node_modules/@maka/core/package.json +1 -0
  35. package/node_modules/@maka/eval/dist/fleet-simulation.js +270 -0
  36. package/node_modules/@maka/eval/dist/fleet-store.js +243 -0
  37. package/node_modules/@maka/eval/dist/fleet-worker.js +125 -0
  38. package/node_modules/@maka/eval/dist/fleet.js +329 -0
  39. package/node_modules/@maka/eval/dist/index.js +3 -0
  40. package/node_modules/@maka/runtime/dist/agent-run.js +2 -17
  41. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +55 -180
  42. package/node_modules/@maka/runtime/dist/ai-sdk-message-projection.js +43 -26
  43. package/node_modules/@maka/runtime/dist/ai-sdk-turn.js +271 -382
  44. package/node_modules/@maka/runtime/dist/background-task-health-tool.js +104 -0
  45. package/node_modules/@maka/runtime/dist/bash-model-output.js +7 -1
  46. package/node_modules/@maka/runtime/dist/bash-tail-buffer.js +13 -52
  47. package/node_modules/@maka/runtime/dist/builtin-tools.js +59 -111
  48. package/node_modules/@maka/runtime/dist/child-fd-input.js +3 -2
  49. package/node_modules/@maka/runtime/dist/context-budget-policy.js +1 -11
  50. package/node_modules/@maka/runtime/dist/context-budget.js +12 -1
  51. package/node_modules/@maka/runtime/dist/conversation-copy.js +104 -9
  52. package/node_modules/@maka/runtime/dist/filesystem-executor.js +10 -6
  53. package/node_modules/@maka/runtime/dist/filesystem-worker/client.js +77 -19
  54. package/node_modules/@maka/runtime/dist/filesystem-worker/launch-spec.js +66 -55
  55. package/node_modules/@maka/runtime/dist/filesystem-worker/operations.js +34 -97
  56. package/node_modules/@maka/runtime/dist/filesystem-worker/protocol.js +25 -10
  57. package/node_modules/@maka/runtime/dist/filesystem-worker/worker-entry.js +2 -0
  58. package/node_modules/@maka/runtime/dist/glob-search.js +74 -0
  59. package/node_modules/@maka/runtime/dist/goal-continuation.js +78 -8
  60. package/node_modules/@maka/runtime/dist/goal-state.js +7 -0
  61. package/node_modules/@maka/runtime/dist/grep-search.js +155 -0
  62. package/node_modules/@maka/runtime/dist/history-compaction.js +3 -1
  63. package/node_modules/@maka/runtime/dist/ledger-tool-result-archive-reader.js +84 -94
  64. package/node_modules/@maka/runtime/dist/local-web-fetch.js +1 -1
  65. package/node_modules/@maka/runtime/dist/model-adapter.js +62 -53
  66. package/node_modules/@maka/runtime/dist/model-history.js +26 -8
  67. package/node_modules/@maka/runtime/dist/pipe-tail-collector.js +6 -9
  68. package/node_modules/@maka/runtime/dist/plugin-executor-backend.js +311 -0
  69. package/node_modules/@maka/runtime/dist/plugin-executor-service.js +344 -0
  70. package/node_modules/@maka/runtime/dist/provider-error-classification.js +7 -1
  71. package/node_modules/@maka/runtime/dist/provider-request-telemetry.js +35 -8
  72. package/node_modules/@maka/runtime/dist/read-page.js +231 -0
  73. package/node_modules/@maka/runtime/dist/request-projection.js +2 -15
  74. package/node_modules/@maka/runtime/dist/ripgrep-executable.js +62 -0
  75. package/node_modules/@maka/runtime/dist/ripgrep-guidance.js +81 -0
  76. package/node_modules/@maka/runtime/dist/runtime-event-backfill.js +7 -1
  77. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +188 -20
  78. package/node_modules/@maka/runtime/dist/runtime-invocation-route.js +49 -0
  79. package/node_modules/@maka/runtime/dist/runtime-kernel.js +72 -150
  80. package/node_modules/@maka/runtime/dist/runtime-read-model.js +2 -3
  81. package/node_modules/@maka/runtime/dist/sandbox/linux-profile-path.js +7 -1
  82. package/node_modules/@maka/runtime/dist/sandbox/linux-sandbox.js +20 -5
  83. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +3 -0
  84. package/node_modules/@maka/runtime/dist/session-manager.js +106 -64
  85. package/node_modules/@maka/runtime/dist/session-recap.js +9 -5
  86. package/node_modules/@maka/runtime/dist/shell-exec.js +7 -25
  87. package/node_modules/@maka/runtime/dist/shell-run-manager.js +10 -4
  88. package/node_modules/@maka/runtime/dist/shell-run-tool-result.js +2 -1
  89. package/node_modules/@maka/runtime/dist/shell-tools.js +6 -12
  90. package/node_modules/@maka/runtime/dist/stream-graph-schedule-reconcile.js +1 -0
  91. package/node_modules/@maka/runtime/dist/stream-graph-supervisor-tools.js +26 -4
  92. package/node_modules/@maka/runtime/dist/subagent-tools.js +7 -0
  93. package/node_modules/@maka/runtime/dist/tool-availability.js +0 -1
  94. package/node_modules/@maka/runtime/dist/tool-output.js +1 -1
  95. package/node_modules/@maka/runtime/dist/tool-result-archive-capability.js +24 -36
  96. package/node_modules/@maka/runtime/dist/tool-result-archive-resource.js +32 -527
  97. package/node_modules/@maka/runtime/dist/tool-result-archive-transition.js +17 -119
  98. package/node_modules/@maka/runtime/dist/tool-result-archive.js +7 -25
  99. package/node_modules/@maka/runtime/dist/tool-runtime.js +52 -471
  100. package/node_modules/@maka/runtime/dist/workers/filesystem-worker.js +6933 -3681
  101. package/node_modules/@maka/runtime/dist/workspace-executor.js +20 -24
  102. package/node_modules/@maka/runtime/package.json +5 -0
  103. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +7 -2
  104. package/node_modules/@maka/runtime-host/dist/client/host-handoff-copy.js +185 -191
  105. package/node_modules/@maka/runtime-host/dist/client/reconnecting-connection.js +3 -0
  106. package/node_modules/@maka/runtime-host/dist/client/session-catalog-summary.js +1 -0
  107. package/node_modules/@maka/runtime-host/dist/protocol/external-session.js +24 -3
  108. package/node_modules/@maka/runtime-host/dist/protocol/index.js +8 -1
  109. package/node_modules/@maka/runtime-host/dist/protocol/message.js +2 -2
  110. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  111. package/node_modules/@maka/runtime-host/dist/protocol/plugin-platform.js +42 -5
  112. package/node_modules/@maka/runtime-host/dist/protocol/session-catalog.js +31 -3
  113. package/node_modules/@maka/runtime-host/dist/protocol/session-continuity.js +8 -2
  114. package/node_modules/@maka/runtime-host/dist/protocol/turn.js +10 -2
  115. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +38 -0
  116. package/node_modules/@maka/runtime-host/dist/server/child-agent-composition.js +1 -0
  117. package/node_modules/@maka/runtime-host/dist/server/execution-artifacts.js +3 -30
  118. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +56 -8
  119. package/node_modules/@maka/runtime-host/dist/server/external-session-coordinator.js +14 -1
  120. package/node_modules/@maka/runtime-host/dist/server/goal-coordinator.js +81 -7
  121. package/node_modules/@maka/runtime-host/dist/server/host-session-availability.js +10 -2
  122. package/node_modules/@maka/runtime-host/dist/server/hosted-execution-tool-profile.js +13 -13
  123. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +65 -0
  124. package/node_modules/@maka/runtime-host/dist/server/plugin-platform-coordinator.js +6 -0
  125. package/node_modules/@maka/runtime-host/dist/server/plugin-platform.js +6 -0
  126. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +1 -0
  127. package/node_modules/@maka/runtime-host/dist/server/session-catalog-coordinator.js +56 -16
  128. package/node_modules/@maka/runtime-host/dist/server/session-continuity-coordinator.js +9 -5
  129. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +4 -0
  130. package/node_modules/@maka/runtime-host/dist/server/session-transcript-reader.js +88 -72
  131. package/node_modules/@maka/runtime-host/dist/server/web-fetch-tool.js +37 -1
  132. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +21 -4
  133. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +145 -1
  134. package/node_modules/@maka/storage/dist/agent-run-store.js +5 -2
  135. package/node_modules/@maka/storage/dist/claude-code-session-adapter.js +450 -234
  136. package/node_modules/@maka/storage/dist/claude-code-transcript-lineage.js +106 -77
  137. package/node_modules/@maka/storage/dist/execution-stores.js +2 -1
  138. package/node_modules/@maka/storage/dist/legacy-run-header.js +2 -2
  139. package/node_modules/@maka/storage/dist/model-call-usage-sql.js +1 -1
  140. package/node_modules/@maka/storage/dist/runtime-transcript-query.js +27 -14
  141. package/node_modules/@maka/storage/dist/session-store.js +12 -2
  142. package/node_modules/@maka/storage/dist/sqlite-long-term-memory-store.js +86 -12
  143. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +69 -3
  144. package/node_modules/@maka/storage/dist/work-board-store.js +40 -1
  145. package/node_modules/balanced-match/LICENSE.md +23 -0
  146. package/node_modules/balanced-match/README.md +57 -0
  147. package/node_modules/balanced-match/dist/commonjs/index.js +59 -0
  148. package/node_modules/balanced-match/dist/commonjs/package.json +3 -0
  149. package/node_modules/balanced-match/dist/esm/index.js +54 -0
  150. package/node_modules/balanced-match/dist/esm/package.json +3 -0
  151. package/node_modules/balanced-match/package.json +68 -0
  152. package/node_modules/brace-expansion/LICENSE +23 -0
  153. package/node_modules/brace-expansion/README.md +105 -0
  154. package/node_modules/brace-expansion/dist/commonjs/index.js +289 -0
  155. package/node_modules/brace-expansion/dist/commonjs/package.json +3 -0
  156. package/node_modules/brace-expansion/dist/esm/index.js +285 -0
  157. package/node_modules/brace-expansion/dist/esm/package.json +3 -0
  158. package/node_modules/brace-expansion/package.json +64 -0
  159. package/node_modules/glob/LICENSE.md +63 -0
  160. package/node_modules/glob/README.md +1203 -0
  161. package/node_modules/glob/dist/commonjs/glob.js +248 -0
  162. package/node_modules/glob/dist/commonjs/has-magic.js +27 -0
  163. package/node_modules/glob/dist/commonjs/ignore.js +119 -0
  164. package/node_modules/glob/dist/commonjs/index.js +68 -0
  165. package/node_modules/glob/dist/commonjs/index.min.js +4 -0
  166. package/node_modules/glob/dist/commonjs/package.json +3 -0
  167. package/node_modules/glob/dist/commonjs/pattern.js +223 -0
  168. package/node_modules/glob/dist/commonjs/processor.js +301 -0
  169. package/node_modules/glob/dist/commonjs/walker.js +387 -0
  170. package/node_modules/glob/dist/esm/glob.js +244 -0
  171. package/node_modules/glob/dist/esm/has-magic.js +23 -0
  172. package/node_modules/glob/dist/esm/ignore.js +115 -0
  173. package/node_modules/glob/dist/esm/index.js +55 -0
  174. package/node_modules/glob/dist/esm/index.min.js +4 -0
  175. package/node_modules/glob/dist/esm/package.json +3 -0
  176. package/node_modules/glob/dist/esm/pattern.js +219 -0
  177. package/node_modules/glob/dist/esm/processor.js +294 -0
  178. package/node_modules/glob/dist/esm/walker.js +381 -0
  179. package/node_modules/glob/package.json +98 -0
  180. package/node_modules/minimatch/LICENSE.md +55 -0
  181. package/node_modules/minimatch/README.md +528 -0
  182. package/node_modules/minimatch/dist/commonjs/assert-valid-pattern.js +14 -0
  183. package/node_modules/minimatch/dist/commonjs/ast.js +845 -0
  184. package/node_modules/minimatch/dist/commonjs/brace-expressions.js +150 -0
  185. package/node_modules/minimatch/dist/commonjs/escape.js +30 -0
  186. package/node_modules/minimatch/dist/commonjs/index.js +1127 -0
  187. package/node_modules/minimatch/dist/commonjs/package.json +3 -0
  188. package/node_modules/minimatch/dist/commonjs/unescape.js +38 -0
  189. package/node_modules/minimatch/dist/esm/assert-valid-pattern.js +10 -0
  190. package/node_modules/minimatch/dist/esm/ast.js +841 -0
  191. package/node_modules/minimatch/dist/esm/brace-expressions.js +146 -0
  192. package/node_modules/minimatch/dist/esm/escape.js +26 -0
  193. package/node_modules/minimatch/dist/esm/index.js +1114 -0
  194. package/node_modules/minimatch/dist/esm/package.json +3 -0
  195. package/node_modules/minimatch/dist/esm/unescape.js +34 -0
  196. package/node_modules/minimatch/package.json +73 -0
  197. package/node_modules/minipass/LICENSE.md +55 -0
  198. package/node_modules/minipass/README.md +825 -0
  199. package/node_modules/minipass/dist/commonjs/index.js +1038 -0
  200. package/node_modules/minipass/dist/commonjs/package.json +3 -0
  201. package/node_modules/minipass/dist/esm/index.js +1020 -0
  202. package/node_modules/minipass/dist/esm/package.json +3 -0
  203. package/node_modules/minipass/package.json +77 -0
  204. package/node_modules/path-scurry/LICENSE.md +55 -0
  205. package/node_modules/path-scurry/README.md +636 -0
  206. package/node_modules/path-scurry/dist/commonjs/index.js +2018 -0
  207. package/node_modules/path-scurry/dist/commonjs/package.json +3 -0
  208. package/node_modules/path-scurry/dist/esm/index.js +1983 -0
  209. package/node_modules/path-scurry/dist/esm/package.json +3 -0
  210. package/node_modules/path-scurry/node_modules/lru-cache/LICENSE.md +55 -0
  211. package/node_modules/path-scurry/node_modules/lru-cache/README.md +469 -0
  212. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/browser/diagnostics-channel.js +7 -0
  213. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/browser/index.js +1726 -0
  214. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/browser/index.min.js +2 -0
  215. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/browser/perf.js +10 -0
  216. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/diagnostics-channel-cjs.d.cts.map +1 -0
  217. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/diagnostics-channel.js +7 -0
  218. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/index.js +1726 -0
  219. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/index.min.js +2 -0
  220. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/node/diagnostics-channel.js +9 -0
  221. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/node/index.js +1726 -0
  222. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/node/index.min.js +2 -0
  223. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/node/perf.js +10 -0
  224. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/package.json +3 -0
  225. package/node_modules/path-scurry/node_modules/lru-cache/dist/commonjs/perf.js +10 -0
  226. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/browser/diagnostics-channel.js +4 -0
  227. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/browser/index.js +1722 -0
  228. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/browser/index.min.js +2 -0
  229. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/browser/perf.js +7 -0
  230. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/diagnostics-channel-esm.d.mts.map +1 -0
  231. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/diagnostics-channel.js +19 -0
  232. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/index.js +1722 -0
  233. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/index.min.js +2 -0
  234. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/node/diagnostics-channel.js +6 -0
  235. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/node/index.js +1722 -0
  236. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/node/index.min.js +2 -0
  237. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/node/perf.js +7 -0
  238. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/package.json +3 -0
  239. package/node_modules/path-scurry/node_modules/lru-cache/dist/esm/perf.js +7 -0
  240. package/node_modules/path-scurry/node_modules/lru-cache/package.json +154 -0
  241. package/node_modules/path-scurry/package.json +72 -0
  242. package/package.json +1 -1
  243. package/node_modules/@maka/runtime/dist/active-tool-result-prune.js +0 -248
  244. package/node_modules/@maka/runtime/dist/active-tool-result-working-set.js +0 -218
  245. package/node_modules/@maka/runtime/dist/archive-read-tool.js +0 -115
@@ -20,6 +20,102 @@ function stringField(record, key) {
20
20
  const value = record[key];
21
21
  return typeof value === 'string' && value.length > 0 ? value : undefined;
22
22
  }
23
+ /**
24
+ * Incremental lineage index used by large transcript imports.
25
+ *
26
+ * It retains only graph identity, never complete transcript records. Once the
27
+ * first pass is complete, independent filters can replay the fixed source
28
+ * snapshot while applying the same de-duplication and rewind selection as
29
+ * {@link resolveTranscriptLineage}.
30
+ */
31
+ export class TranscriptLineageIndexer {
32
+ #nodes = new Map();
33
+ #duplicates = 0;
34
+ #compactBoundaries = 0;
35
+ accept(record) {
36
+ const uuid = stringField(record, 'uuid');
37
+ if (uuid !== undefined && this.#nodes.has(uuid)) {
38
+ this.#duplicates += 1;
39
+ return;
40
+ }
41
+ if (record.subtype === 'compact_boundary')
42
+ this.#compactBoundaries += 1;
43
+ if (uuid === undefined)
44
+ return;
45
+ const parentUuid = transcriptParentUuid(record);
46
+ this.#nodes.set(uuid, {
47
+ uuid,
48
+ ...(parentUuid !== undefined ? { parentUuid } : {}),
49
+ isPrompt: isPromptRecord(record),
50
+ isSidechain: record.isSidechain === true,
51
+ });
52
+ }
53
+ finish() {
54
+ const main = [...this.#nodes.values()].filter((node) => !node.isSidechain);
55
+ const present = new Set(main.map((node) => node.uuid));
56
+ const childrenOf = new Map();
57
+ const promptsOf = new Map();
58
+ for (const node of main) {
59
+ const key = node.parentUuid !== undefined && present.has(node.parentUuid) ? node.parentUuid : ROOT_KEY;
60
+ const children = childrenOf.get(key);
61
+ if (children)
62
+ children.push(node.uuid);
63
+ else
64
+ childrenOf.set(key, [node.uuid]);
65
+ if (node.isPrompt) {
66
+ const prompts = promptsOf.get(key);
67
+ if (prompts)
68
+ prompts.push(node.uuid);
69
+ else
70
+ promptsOf.set(key, [node.uuid]);
71
+ }
72
+ }
73
+ const withdrawn = [];
74
+ for (const prompts of promptsOf.values()) {
75
+ if (prompts.length > 1)
76
+ withdrawn.push(...prompts.slice(0, -1));
77
+ }
78
+ const dropped = new Set();
79
+ const stack = [...withdrawn];
80
+ while (stack.length > 0) {
81
+ const uuid = stack.pop();
82
+ if (dropped.has(uuid))
83
+ continue;
84
+ dropped.add(uuid);
85
+ for (const child of childrenOf.get(uuid) ?? [])
86
+ stack.push(child);
87
+ }
88
+ return new FinishedTranscriptLineageIndex(dropped, withdrawn.length, this.#duplicates, this.#compactBoundaries);
89
+ }
90
+ }
91
+ class FinishedTranscriptLineageIndex {
92
+ withdrawnPrompts;
93
+ duplicates;
94
+ compactBoundaries;
95
+ #dropped;
96
+ abandoned;
97
+ constructor(dropped, withdrawnPrompts, duplicates, compactBoundaries) {
98
+ this.withdrawnPrompts = withdrawnPrompts;
99
+ this.duplicates = duplicates;
100
+ this.compactBoundaries = compactBoundaries;
101
+ this.#dropped = dropped;
102
+ this.abandoned = this.#dropped.size;
103
+ }
104
+ createFilter() {
105
+ const seen = new Set();
106
+ return {
107
+ keep: (record) => {
108
+ const uuid = stringField(record, 'uuid');
109
+ if (uuid === undefined)
110
+ return true;
111
+ if (seen.has(uuid))
112
+ return false;
113
+ seen.add(uuid);
114
+ return !this.#dropped.has(uuid);
115
+ },
116
+ };
117
+ }
118
+ }
23
119
  /**
24
120
  * The parent a record hangs from: `parentUuid`, and nothing else.
25
121
  *
@@ -52,86 +148,19 @@ export function isPromptRecord(record) {
52
148
  block !== null &&
53
149
  block.type === 'tool_result');
54
150
  }
55
- /**
56
- * Drop repeats of a `uuid` already seen, keeping the first.
57
- *
58
- * A record written twice replays whatever identity it carries — a prompt, a
59
- * turn boundary, a tool call. Measured: 3 repeats across 1130 local
60
- * transcripts. Rare enough to be invisible in testing, permanent once it is
61
- * persisted as canonical history.
62
- */
63
- function deduplicate(records) {
64
- const seen = new Set();
65
- const kept = [];
66
- let duplicates = 0;
67
- for (const record of records) {
68
- const uuid = stringField(record, 'uuid');
69
- if (uuid !== undefined) {
70
- if (seen.has(uuid)) {
71
- duplicates += 1;
72
- continue;
73
- }
74
- seen.add(uuid);
75
- }
76
- kept.push(record);
77
- }
78
- return { kept, duplicates };
79
- }
80
151
  const ROOT_KEY = ' root';
81
152
  export function resolveTranscriptLineage(rawRecords) {
82
- const { kept: records, duplicates } = deduplicate(rawRecords);
83
- const compactBoundaries = records.filter((r) => r.subtype === 'compact_boundary').length;
84
- const main = records.filter((r) => r.isSidechain !== true && stringField(r, 'uuid') !== undefined);
85
- if (main.length === 0) {
86
- return { records, abandoned: 0, withdrawnPrompts: 0, duplicates, compactBoundaries };
87
- }
88
- const present = new Set(main.map((r) => stringField(r, 'uuid')));
89
- const childrenOf = new Map();
90
- for (const record of main) {
91
- const parent = transcriptParentUuid(record);
92
- // A parent outside this file is no parent: the record roots its own
93
- // segment rather than being orphaned into nothing.
94
- const key = parent !== undefined && present.has(parent) ? parent : ROOT_KEY;
95
- const siblings = childrenOf.get(key);
96
- if (siblings)
97
- siblings.push(record);
98
- else
99
- childrenOf.set(key, [record]);
100
- }
101
- // Among sibling prompts the last written is the one that was asked; the
102
- // earlier ones were withdrawn by the edit that replaced them.
103
- const withdrawn = [];
104
- for (const [, siblings] of childrenOf) {
105
- const prompts = siblings.filter(isPromptRecord);
106
- if (prompts.length < 2)
107
- continue;
108
- withdrawn.push(...prompts.slice(0, -1));
109
- }
110
- if (withdrawn.length === 0) {
111
- return { records, abandoned: 0, withdrawnPrompts: 0, duplicates, compactBoundaries };
112
- }
113
- // A withdrawn prompt takes its subtree: the answer to a question that was
114
- // never asked is not conversation either.
115
- const dropped = new Set();
116
- const stack = [...withdrawn];
117
- while (stack.length > 0) {
118
- const record = stack.pop();
119
- const uuid = stringField(record, 'uuid');
120
- if (dropped.has(uuid))
121
- continue;
122
- dropped.add(uuid);
123
- for (const child of childrenOf.get(uuid) ?? [])
124
- stack.push(child);
125
- }
126
- const resolved = records.filter((record) => {
127
- const uuid = stringField(record, 'uuid');
128
- return uuid === undefined || !dropped.has(uuid);
129
- });
153
+ const indexer = new TranscriptLineageIndexer();
154
+ for (const record of rawRecords)
155
+ indexer.accept(record);
156
+ const index = indexer.finish();
157
+ const filter = index.createFilter();
158
+ const resolved = rawRecords.filter((record) => filter.keep(record));
130
159
  return {
131
160
  records: resolved,
132
- abandoned: dropped.size,
133
- withdrawnPrompts: withdrawn.length,
134
- duplicates,
135
- compactBoundaries,
161
+ abandoned: index.abandoned,
162
+ withdrawnPrompts: index.withdrawnPrompts,
163
+ duplicates: index.duplicates,
164
+ compactBoundaries: index.compactBoundaries,
136
165
  };
137
166
  }
@@ -229,6 +229,7 @@ async function createExecutionStoresForWrite(lease, kind, extension) {
229
229
  readRuntimeEventsBounded: (sessionId, runId, budget) => run(() => runtimeEventStore.readRuntimeEventsBounded(sessionId, runId, budget)),
230
230
  readImmutableRuntimeEvents: (sessionId, runId) => run(() => runtimeEventStore.readImmutableRuntimeEvents(sessionId, runId)),
231
231
  readImmutableRuntimePrefix: (input) => run(() => runtimeEventStore.readImmutableRuntimePrefix(input)),
232
+ readImmutableRuntimePrefixProof: (input, budget) => run(() => runtimeEventStore.readImmutableRuntimePrefixProof(input, budget)),
232
233
  listSessionInvocations: (sessionId) => run(() => runtimeEventStore.listSessionInvocations(sessionId)),
233
234
  readRunInvocation: (sessionId, runId) => run(() => runtimeEventStore.readRunInvocation(sessionId, runId)),
234
235
  listSessionInvocationsBounded: (sessionId, limit) => run(() => runtimeEventStore.listSessionInvocationsBounded(sessionId, limit)),
@@ -238,7 +239,7 @@ async function createExecutionStoresForWrite(lease, kind, extension) {
238
239
  readSessionRuntimeEventEntries: (sessionId) => run(() => runtimeEventStore.readSessionRuntimeEventEntries(sessionId)),
239
240
  resequenceSessionEventOrdinals: (sessionId) => run(() => runtimeEventStore.resequenceSessionEventOrdinals(sessionId)),
240
241
  readTranscriptHighWater: (sessionId) => run(() => runtimeEventStore.readTranscriptHighWater(sessionId)),
241
- readTranscriptInvocations: (sessionId, request) => run(() => runtimeEventStore.readTranscriptInvocations(sessionId, request)),
242
+ readTranscriptInvocations: (sessionId, request, project) => run(() => runtimeEventStore.readTranscriptInvocations(sessionId, request, project)),
242
243
  readTranscriptLandmarks: (sessionId, throughOrdinal, limit) => run(() => runtimeEventStore.readTranscriptLandmarks(sessionId, throughOrdinal, limit)),
243
244
  claimContinuation: (input) => run(() => runtimeEventStore.claimContinuation(input)),
244
245
  readContinuationClaimByBoundary: (boundaryDigest) => run(() => runtimeEventStore.readContinuationClaimByBoundary(boundaryDigest)),
@@ -232,7 +232,7 @@ export function invocationOpeningFromLegacyRunHeader(header) {
232
232
  };
233
233
  }
234
234
  function invocationRouteFromLegacyRunHeader(header) {
235
- if (header.llmConnectionId === undefined) {
235
+ if (header.llmConnectionId === undefined || header.backendKind === 'plugin-executor') {
236
236
  return {
237
237
  provenance: 'unknown',
238
238
  backendKind: header.backendKind,
@@ -320,7 +320,7 @@ function isLegacyContinuationSource(value) {
320
320
  }
321
321
  /** `'fake'` stays accepted: runs written by builds that shipped FakeBackend must keep decoding (#3211). */
322
322
  function isPersistedBackendKind(value) {
323
- return value === 'ai-sdk' || value === 'fake';
323
+ return value === 'ai-sdk' || value === 'plugin-executor' || value === 'fake';
324
324
  }
325
325
  function isSha256Digest(value) {
326
326
  return typeof value === 'string' && /^sha256:[0-9a-f]{64}$/.test(value);
@@ -34,7 +34,7 @@ export const CACHE_READ_TOKENS = `
34
34
  * when the price was simply never resolved.
35
35
  */
36
36
  export const PRICED_COST = `CASE WHEN cost_basis = 'priced' THEN COALESCE(cost_usd, 0) ELSE 0 END`;
37
- /** Mirrors `usageStatusForAttempt`: only a provider failure is an error. */
37
+ /** Only a provider failure is an error. */
38
38
  const ERROR_ROW = `status = 'failed'`;
39
39
  export const TOKEN_SUMS = `
40
40
  SUM(COALESCE(input_tokens, 0)) AS input,
@@ -107,9 +107,12 @@ export class RuntimeTranscriptQuery {
107
107
  });
108
108
  return row?.last ?? null;
109
109
  }
110
- invocations(sessionId, request) {
110
+ invocations(sessionId, request, project) {
111
111
  assertOrdinal(request.throughOrdinal);
112
112
  assertOrdinal(request.position);
113
+ assertReadLimit(request.maxEvents, 'event count');
114
+ assertReadLimit(request.maxBytes, 'byte');
115
+ assertReadLimit(request.maxRecordBytes, 'record byte');
113
116
  if (request.direction !== 'older' && request.direction !== 'newer') {
114
117
  throw new Error('Invalid transcript direction');
115
118
  }
@@ -130,12 +133,11 @@ export class RuntimeTranscriptQuery {
130
133
  throughOrdinal: request.throughOrdinal,
131
134
  limit: request.limit,
132
135
  }).sort((a, b) => a.first - b.first);
133
- return rows.map((row) => ({
136
+ return rows.map((row) => project({
134
137
  invocation: this.invocation(sessionId, row.invocation_id),
135
138
  firstOrdinal: row.first,
136
139
  lastOrdinal: row.last,
137
- events: this.events(row.invocation_id, request),
138
- }));
140
+ }, this.events(row.invocation_id, request)));
139
141
  }
140
142
  landmarks(sessionId, throughOrdinal, limit) {
141
143
  assertOrdinal(throughOrdinal);
@@ -258,29 +260,35 @@ export class RuntimeTranscriptQuery {
258
260
  limit: bounds.limit,
259
261
  });
260
262
  }
261
- events(invocationId, limits) {
262
- // Walked row by row: the limits cap what one Turn may pull into memory, so
263
- // a check after `.all()` has already paid the cost it was meant to refuse.
263
+ *events(invocationId, limits) {
264
+ // Walked row by row so cumulative limits apply to raw IO without retaining
265
+ // the Turn. SQLite withholds an oversized payload before it crosses into JS.
264
266
  const cursor = this.db
265
267
  .prepare(`
266
- SELECT o.ordinal, e.event_id, e.session_id, e.invocation_id, e.run_id, e.turn_id, e.payload_json
268
+ SELECT o.ordinal, e.event_id, e.session_id, e.invocation_id, e.run_id, e.turn_id,
269
+ length(CAST(e.payload_json AS BLOB)) AS stored_bytes,
270
+ CASE WHEN length(CAST(e.payload_json AS BLOB)) <= ? THEN e.payload_json END AS payload_json
267
271
  FROM runtime_events e JOIN runtime_session_event_ordinals o ON o.event_id = e.event_id
268
272
  WHERE e.invocation_id = ? ORDER BY e.event_seq
269
273
  `)
270
- .iterate(invocationId);
271
- const events = [];
274
+ .iterate(limits.maxRecordBytes, invocationId);
275
+ let count = 0;
272
276
  let bytes = 0;
273
277
  for (const row of cursor) {
274
- if (events.length === limits.maxEvents) {
278
+ if (count === limits.maxEvents) {
275
279
  throw new RuntimeTranscriptOversizedTurnError(`Turn ${invocationId} holds more RuntimeEvents than a transcript page may read`);
276
280
  }
277
- bytes += Buffer.byteLength(row.payload_json);
281
+ const payload = row.payload_json;
282
+ if (payload === null) {
283
+ throw new RuntimeTranscriptOversizedTurnError(`Turn ${invocationId} holds a RuntimeEvent larger than a transcript page may read`);
284
+ }
285
+ bytes += row.stored_bytes;
278
286
  if (bytes > limits.maxBytes) {
279
287
  throw new RuntimeTranscriptOversizedTurnError(`Turn ${invocationId} holds more RuntimeEvent bytes than a transcript page may read`);
280
288
  }
281
- events.push({ ordinal: row.ordinal, event: decodeStoredEvent(row) });
289
+ count += 1;
290
+ yield { ordinal: row.ordinal, event: decodeStoredEvent({ ...row, payload_json: payload }) };
282
291
  }
283
- return events;
284
292
  }
285
293
  event(id) {
286
294
  const row = this.db
@@ -306,3 +314,8 @@ function assertOrdinal(value) {
306
314
  if (!Number.isSafeInteger(value) || value < 0)
307
315
  throw new Error('Invalid transcript event ordinal');
308
316
  }
317
+ function assertReadLimit(value, name) {
318
+ if (!Number.isSafeInteger(value) || value < 1) {
319
+ throw new RangeError(`Invalid transcript ${name} limit`);
320
+ }
321
+ }
@@ -22,6 +22,7 @@ import { createSqliteSessionMetadataStore, SessionMetadataVersionConflictError,
22
22
  import { isDiscardableConversationCopy } from './session-conversation-copy.js';
23
23
  import { acquireOperationalStateDatabase, OPERATIONAL_STATE_DATABASE_NAME, } from './operational-state-store.js';
24
24
  import { DEFAULT_SESSION_NAME, normalizeUserSessionName } from '@maka/core/session-name';
25
+ import { isExecutorId } from '@maka/core/executor-id';
25
26
  import { decodeCanonicalMessage, deriveTurnRecords, isSessionBlockedReason, isSessionConversationCopy, isSubagentSessionParent, isSubagentSessionRuntime, isSubagentSessionSpawn, isSessionStatus, isWorkHubCoordinationSessionId, subagentSessionRuntimeSummary, WORKHUB_COORDINATION_SESSION_ID, WORKHUB_COORDINATION_SESSION_ROLE, } from '@maka/core/session';
26
27
  import { isCollaborationMode } from '@maka/core/collaboration';
27
28
  import { isOrchestrationMode } from '@maka/core/orchestration';
@@ -609,7 +610,8 @@ function buildSessionHeader(workspaceRoot, input, sessionId = randomUUID(), conv
609
610
  ...(input.revisionIndex !== undefined ? { revisionIndex: input.revisionIndex } : {}),
610
611
  ...(input.revisionState ? { revisionState: input.revisionState } : {}),
611
612
  hasUnread: false,
612
- backend: 'ai-sdk',
613
+ backend: input.executorId ? 'plugin-executor' : 'ai-sdk',
614
+ ...(input.executorId ? { executorId: input.executorId } : {}),
613
615
  ...(input.llmConnectionId === undefined ? {} : { llmConnectionId: input.llmConnectionId }),
614
616
  llmConnectionSlug: input.llmConnectionSlug,
615
617
  // A subagent Session's route is chosen by the spawn that created it and is
@@ -669,6 +671,7 @@ export function normalizeSessionHeader(header, sessionId = header.id) {
669
671
  (header.lastReadMessageId === undefined || typeof header.lastReadMessageId === 'string') &&
670
672
  typeof header.hasUnread === 'boolean' &&
671
673
  isPersistedBackendKind(header.backend) &&
674
+ isValidExecutorSelection(header) &&
672
675
  (header.llmConnectionId === undefined ||
673
676
  (typeof header.llmConnectionId === 'string' && header.llmConnectionId.length > 0)) &&
674
677
  typeof header.llmConnectionSlug === 'string' &&
@@ -805,7 +808,13 @@ function isValidSubagentSessionLineage(header) {
805
808
  * FakeBackend fail `normalizeSessionHeader` and read back as malformed (#3211).
806
809
  */
807
810
  function isPersistedBackendKind(value) {
808
- return value === 'ai-sdk' || value === 'fake';
811
+ return value === 'ai-sdk' || value === 'plugin-executor' || value === 'fake';
812
+ }
813
+ function isValidExecutorSelection(header) {
814
+ if (header.backend === 'plugin-executor') {
815
+ return isExecutorId(header.executorId);
816
+ }
817
+ return header.executorId === undefined;
809
818
  }
810
819
  function isFiniteNumber(value) {
811
820
  return typeof value === 'number' && Number.isFinite(value);
@@ -871,6 +880,7 @@ function toSummary(header) {
871
880
  ...(header.revisionIndex !== undefined ? { revisionIndex: header.revisionIndex } : {}),
872
881
  ...(header.revisionState ? { revisionState: header.revisionState } : {}),
873
882
  backend: header.backend,
883
+ ...(header.executorId ? { executorId: header.executorId } : {}),
874
884
  ...(header.llmConnectionId === undefined ? {} : { llmConnectionId: header.llmConnectionId }),
875
885
  llmConnectionSlug: header.llmConnectionSlug,
876
886
  connectionLocked: header.connectionLocked,
@@ -555,14 +555,12 @@ export class SqliteMemoryItemStore {
555
555
  });
556
556
  return this.#readSnapshot(() => {
557
557
  const rows = this.#database.prepare(query.sql).all(...query.parameters);
558
- return rows.map((row) => {
558
+ const itemIds = rows.map((row) => {
559
559
  if (typeof row.item_id !== 'string')
560
560
  throw new Error('Invalid Memory Item search result');
561
- const record = this.#readItemRecord(row.item_id);
562
- if (!record)
563
- throw new Error(`Memory Item ${row.item_id} disappeared during read`);
564
- return record;
561
+ return row.item_id;
565
562
  });
563
+ return this.#readItemRecords(itemIds);
566
564
  });
567
565
  }
568
566
  async readOperation(operationId) {
@@ -685,13 +683,55 @@ export class SqliteMemoryItemStore {
685
683
  FROM memory_item_sources WHERE item_id = ? ORDER BY event_id ASC
686
684
  LIMIT ${MAX_SOURCES_PER_ITEM + 1}`)
687
685
  .all(itemId);
688
- assertChildCardinality('keys', keys.length, MAX_KEYS_PER_ITEM);
689
- assertChildCardinality('sources', sources.length, MAX_SOURCES_PER_ITEM);
690
- return {
691
- item: decodeItem(row),
692
- keys: keys.map(decodeKey),
693
- sources: sources.map(decodeSource),
694
- };
686
+ return decodeItemRecord(row, keys, sources);
687
+ }
688
+ #readItemRecords(itemIds) {
689
+ if (itemIds.length === 0)
690
+ return [];
691
+ if (itemIds.length === 1) {
692
+ const record = this.#readItemRecord(itemIds[0]);
693
+ if (!record)
694
+ throw new Error(`Memory Item ${itemIds[0]} disappeared during read`);
695
+ return [record];
696
+ }
697
+ const rows = this.#database
698
+ .prepare(`SELECT * FROM memory_items WHERE item_id IN (${placeholders(itemIds.length)})`)
699
+ .all(...itemIds);
700
+ const items = new Map(rows.map((row) => [row.item_id, row]));
701
+ const keys = this.#readItemChildren('keys', itemIds, ([, key_text, normalized_key, key_type, key_origin]) => ({
702
+ key_text,
703
+ normalized_key,
704
+ key_type,
705
+ key_origin,
706
+ }));
707
+ const sources = this.#readItemChildren('sources', itemIds, ([, session_id, run_id, turn_id, event_id]) => ({ session_id, run_id, turn_id, event_id }));
708
+ // IN queries need not return search order; preserve the ranked ID sequence.
709
+ return itemIds.map((itemId) => {
710
+ const row = items.get(itemId);
711
+ if (!row)
712
+ throw new Error(`Memory Item ${itemId} disappeared during read`);
713
+ return decodeItemRecord(row, keys.get(itemId) ?? [], sources.get(itemId) ?? []);
714
+ });
715
+ }
716
+ #readItemChildren(child, itemIds, toRow) {
717
+ const statement = this.#database.prepare(buildMemoryChildBatchQuery(child, itemIds.length));
718
+ // Native array results avoid SQLite's per-column object property construction
719
+ // for as many as 25,700 sources. Column validation still happens in search order.
720
+ statement.setReturnArrays(true);
721
+ const rows = statement.all(...itemIds);
722
+ const grouped = new Map();
723
+ let previousItemId;
724
+ let children;
725
+ for (const row of rows) {
726
+ const itemId = row[0];
727
+ if (!children || itemId !== previousItemId) {
728
+ children = [];
729
+ grouped.set(itemId, children);
730
+ previousItemId = itemId;
731
+ }
732
+ children.push(toRow(row));
733
+ }
734
+ return grouped;
695
735
  }
696
736
  #requireItemRecord(itemId) {
697
737
  const record = this.#readItemRecord(itemId);
@@ -796,6 +836,31 @@ export function buildSqliteMemoryKeySearchQuery(input) {
796
836
  parameters,
797
837
  };
798
838
  }
839
+ function buildMemoryChildBatchQuery(child, itemCount) {
840
+ const table = child === 'keys' ? 'memory_item_keys' : 'memory_item_sources';
841
+ const orderColumn = child === 'keys' ? 'normalized_key' : 'event_id';
842
+ const columns = child === 'keys'
843
+ ? 'c.key_text, c.normalized_key, c.key_type, c.key_origin'
844
+ : 'c.session_id, c.run_id, c.turn_id, c.event_id';
845
+ const maximum = child === 'keys' ? MAX_KEYS_PER_ITEM : MAX_SOURCES_PER_ITEM;
846
+ // Each composite primary key supplies at most maximum + 1 children per Item,
847
+ // including the overflow sentinel used by cardinality validation. A missing
848
+ // sentinel falls back to the last child, keeping corrupt child sets bounded.
849
+ // Fix Items as the outer loop so both indexes supply order without a temp sort.
850
+ return `
851
+ SELECT i.item_id, ${columns}
852
+ FROM memory_items i
853
+ CROSS JOIN ${table} c
854
+ ON c.item_id = i.item_id
855
+ AND c.${orderColumn} <= COALESCE(
856
+ (SELECT ${orderColumn} FROM ${table}
857
+ WHERE item_id = i.item_id ORDER BY ${orderColumn} ASC LIMIT 1 OFFSET ${maximum}),
858
+ (SELECT ${orderColumn} FROM ${table}
859
+ WHERE item_id = i.item_id ORDER BY ${orderColumn} DESC LIMIT 1)
860
+ )
861
+ WHERE i.item_id IN (${placeholders(itemCount)})
862
+ ORDER BY i.item_id ASC, c.${orderColumn} ASC`;
863
+ }
799
864
  function normalizeMutations(mutations) {
800
865
  if (!Array.isArray(mutations) || mutations.length === 0) {
801
866
  throw new Error('Memory operation requires at least one mutation');
@@ -1108,6 +1173,15 @@ function mutationResult(mutationIndex, mutationType, item, outcome) {
1108
1173
  outcome,
1109
1174
  };
1110
1175
  }
1176
+ function decodeItemRecord(row, keys, sources) {
1177
+ assertChildCardinality('keys', keys.length, MAX_KEYS_PER_ITEM);
1178
+ assertChildCardinality('sources', sources.length, MAX_SOURCES_PER_ITEM);
1179
+ return {
1180
+ item: decodeItem(row),
1181
+ keys: keys.map(decodeKey),
1182
+ sources: sources.map(decodeSource),
1183
+ };
1184
+ }
1111
1185
  function decodeItem(row) {
1112
1186
  const kind = requiredString(row.kind, 'kind');
1113
1187
  const statementType = requiredString(row.statement_type, 'statement_type');
@@ -28,7 +28,7 @@ import { RunSealedError, RUNTIME_CONTINUATION_AUTHORITY_V1, TOOL_RECOVERY_BUNDLE
28
28
  import { canonicalToolArgsHash, stableJsonStringify } from '@maka/core/tool-args-identity';
29
29
  import { encodeCanonicalRuntimeEvent } from '@maka/core/canonical-runtime-event';
30
30
  import { scanToolLedger, ToolLedgerCorruptionError, ToolLedgerRejectionError, validateGenericToolLedgerAppend, validateToolLedgerEventLane, validateToolLedgerTransition, } from '@maka/core/tool-ledger-scanner';
31
- import { buildImmutableRuntimePrefix, continuationStartEventMatchesClaim, decodeContinuationClaim, } from '@maka/core/runtime-boundary';
31
+ import { buildImmutableRuntimePrefix, buildImmutableRuntimePrefixProof, continuationStartEventMatchesClaim, decodeContinuationClaim, } from '@maka/core/runtime-boundary';
32
32
  import { assertToolRecoveryEventBundle, interpretScannedToolRecovery, } from '@maka/core/tool-recovery-bundle';
33
33
  import { configureSqliteRuntimeDatabase, migrateSqliteRuntimeDatabase, readUserVersion, RUNTIME_RECOVERY_AUTHORITY_CAPABILITY, RUNTIME_RECOVERY_AUTHORITY_CAPABILITY_VERSION, RUNTIME_CONTINUATION_AUTHORITY_CAPABILITY, RUNTIME_CONTINUATION_AUTHORITY_CAPABILITY_VERSION, RUNTIME_WORKSPACE_VERSION_AUTHORITY_CAPABILITY, RUNTIME_WORKSPACE_VERSION_AUTHORITY_CAPABILITY_VERSION, runtimeEventKind, SQLITE_RUNTIME_SCHEMA_VERSION, } from './sqlite-runtime-schema.js';
34
34
  import { registerWorkspaceBaselineAuthorityWriterInternal, } from './workspace-version-authority-internal.js';
@@ -46,6 +46,13 @@ function assertRuntimeEventScanBudget(budget) {
46
46
  }
47
47
  }
48
48
  }
49
+ function assertImmutableRuntimePrefixProofReadBudget(budget) {
50
+ for (const [name, value] of Object.entries(budget)) {
51
+ if (!Number.isSafeInteger(value) || value < 1) {
52
+ throw new Error(`Invalid immutable RuntimeEvent prefix proof ${name}`);
53
+ }
54
+ }
55
+ }
49
56
  function requireRuntimeEventScanCount(value) {
50
57
  if (!Number.isSafeInteger(value) || value < 0) {
51
58
  throw new Error('Invalid RuntimeEvent scan measurement');
@@ -294,10 +301,10 @@ export class SqliteRuntimeStore {
294
301
  assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
295
302
  return this.readTransaction(() => this.transcriptQuery().highWater(sessionId));
296
303
  }
297
- async readTranscriptInvocations(sessionId, request) {
304
+ async readTranscriptInvocations(sessionId, request, project) {
298
305
  assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
299
306
  assertInvocationSearchLimit(request.limit);
300
- return this.readTransaction(() => this.transcriptQuery().invocations(sessionId, request));
307
+ return this.readTransaction(() => this.transcriptQuery().invocations(sessionId, request, project));
301
308
  }
302
309
  async readTranscriptLandmarks(sessionId, throughOrdinal, limit) {
303
310
  assertRuntimeStorageSafeId(sessionId, 'Invalid session id');
@@ -798,6 +805,65 @@ export class SqliteRuntimeStore {
798
805
  turnId: first.turnId,
799
806
  }, decoded);
800
807
  }
808
+ async readImmutableRuntimePrefixProof(input, budget) {
809
+ assertImmutableRuntimePrefixProofReadBudget(budget);
810
+ if (input.upToEventSeq !== undefined &&
811
+ (!Number.isSafeInteger(input.upToEventSeq) || input.upToEventSeq <= 0)) {
812
+ throw new Error('Invalid immutable RuntimeEvent prefix high-water');
813
+ }
814
+ const highWater = input.upToEventSeq ?? null;
815
+ const cursor = this.db
816
+ .prepare(`
817
+ SELECT event_id, session_id, invocation_id, run_id, turn_id, event_seq,
818
+ length(CAST(payload_json AS BLOB)) AS stored_bytes,
819
+ CASE WHEN length(CAST(payload_json AS BLOB)) <= ? THEN payload_json END AS payload_json
820
+ FROM runtime_events
821
+ WHERE session_id = ? AND run_id = ?
822
+ AND (? IS NULL OR event_seq <= ?)
823
+ ORDER BY event_seq ASC
824
+ `)
825
+ .iterate(budget.maxRecordBytes, input.sessionId, input.runId, highWater, highWater)[Symbol.iterator]();
826
+ const firstRow = cursor.next();
827
+ if (firstRow.done)
828
+ throw new Error('immutable RuntimeEvent prefix is empty');
829
+ let count = 0;
830
+ let bytes = 0;
831
+ let lastEventSeq = 0;
832
+ const decode = function* () {
833
+ let step = firstRow;
834
+ while (!step.done) {
835
+ const row = step.value;
836
+ count += 1;
837
+ if (count > budget.maxEvents) {
838
+ throw new Error('Immutable RuntimeEvent prefix proof exceeds its event limit');
839
+ }
840
+ const payloadJson = row.payload_json;
841
+ if (payloadJson === null) {
842
+ throw new Error('Immutable RuntimeEvent prefix proof exceeds its record byte limit');
843
+ }
844
+ bytes += requireRuntimeEventScanCount(row.stored_bytes);
845
+ if (bytes > budget.maxBytes) {
846
+ throw new Error('Immutable RuntimeEvent prefix proof exceeds its byte limit');
847
+ }
848
+ lastEventSeq = requireRuntimeEventScanCount(row.event_seq);
849
+ yield {
850
+ eventSeq: lastEventSeq,
851
+ event: decodeRuntimeEventStorageRow({ ...row, payload_json: payloadJson }),
852
+ };
853
+ step = cursor.next();
854
+ }
855
+ };
856
+ const proof = buildImmutableRuntimePrefixProof({
857
+ sessionId: firstRow.value.session_id,
858
+ invocationId: firstRow.value.invocation_id,
859
+ runId: firstRow.value.run_id,
860
+ turnId: firstRow.value.turn_id,
861
+ }, decode());
862
+ if (input.upToEventSeq !== undefined && lastEventSeq !== input.upToEventSeq) {
863
+ throw new Error(`immutable RuntimeEvent prefix high-water ${input.upToEventSeq} is unavailable`);
864
+ }
865
+ return proof;
866
+ }
801
867
  async claimContinuation(input) {
802
868
  const claim = decodeContinuationClaim(input.claim);
803
869
  if (claim.target.sessionId === WORKSPACE_AUTHORITY_SESSION_ID ||