@buildanagent/harness 0.0.0-stage → 0.1.0-alpha.29

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 (397) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +822 -2
  5. package/dist/ablation.d.ts +2 -0
  6. package/dist/ablation.js +3 -0
  7. package/dist/ablation.js.map +1 -0
  8. package/dist/completion/check.d.ts +64 -0
  9. package/dist/completion/check.js +152 -0
  10. package/dist/completion/check.js.map +1 -0
  11. package/dist/completion/checks.d.ts +45 -0
  12. package/dist/completion/checks.js +173 -0
  13. package/dist/completion/checks.js.map +1 -0
  14. package/dist/completion/flags.d.ts +25 -0
  15. package/dist/completion/flags.js +87 -0
  16. package/dist/completion/flags.js.map +1 -0
  17. package/dist/completion/index.d.ts +8 -0
  18. package/dist/completion/index.js +9 -0
  19. package/dist/completion/index.js.map +1 -0
  20. package/dist/completion/snapshot.d.ts +33 -0
  21. package/dist/completion/snapshot.js +83 -0
  22. package/dist/completion/snapshot.js.map +1 -0
  23. package/dist/context/cap.d.ts +32 -0
  24. package/dist/context/cap.js +50 -0
  25. package/dist/context/cap.js.map +1 -0
  26. package/dist/context/estimate.d.ts +18 -0
  27. package/dist/context/estimate.js +20 -0
  28. package/dist/context/estimate.js.map +1 -0
  29. package/dist/context/file-spill.d.ts +15 -0
  30. package/dist/context/file-spill.js +40 -0
  31. package/dist/context/file-spill.js.map +1 -0
  32. package/dist/context/index.d.ts +10 -0
  33. package/dist/context/index.js +10 -0
  34. package/dist/context/index.js.map +1 -0
  35. package/dist/context/mask.d.ts +27 -0
  36. package/dist/context/mask.js +71 -0
  37. package/dist/context/mask.js.map +1 -0
  38. package/dist/context/mid-turn.d.ts +40 -0
  39. package/dist/context/mid-turn.js +82 -0
  40. package/dist/context/mid-turn.js.map +1 -0
  41. package/dist/context/policy.d.ts +9 -0
  42. package/dist/context/policy.js +140 -0
  43. package/dist/context/policy.js.map +1 -0
  44. package/dist/context/spill-ledger.d.ts +25 -0
  45. package/dist/context/spill-ledger.js +54 -0
  46. package/dist/context/spill-ledger.js.map +1 -0
  47. package/dist/context/spill.d.ts +10 -0
  48. package/dist/context/spill.js +18 -0
  49. package/dist/context/spill.js.map +1 -0
  50. package/dist/context/summarize.d.ts +53 -0
  51. package/dist/context/summarize.js +204 -0
  52. package/dist/context/summarize.js.map +1 -0
  53. package/dist/context/summary-template.d.ts +29 -0
  54. package/dist/context/summary-template.js +69 -0
  55. package/dist/context/summary-template.js.map +1 -0
  56. package/dist/context/types.d.ts +150 -0
  57. package/dist/context/types.js +2 -0
  58. package/dist/context/types.js.map +1 -0
  59. package/dist/context/write-cap.d.ts +19 -0
  60. package/dist/context/write-cap.js +41 -0
  61. package/dist/context/write-cap.js.map +1 -0
  62. package/dist/create-harness.d.ts +7 -0
  63. package/dist/create-harness.js +21 -0
  64. package/dist/create-harness.js.map +1 -0
  65. package/dist/credentials/addresses.d.ts +14 -0
  66. package/dist/credentials/addresses.js +144 -0
  67. package/dist/credentials/addresses.js.map +1 -0
  68. package/dist/credentials/allowlist.d.ts +54 -0
  69. package/dist/credentials/allowlist.js +134 -0
  70. package/dist/credentials/allowlist.js.map +1 -0
  71. package/dist/credentials/egress-policy.d.ts +69 -0
  72. package/dist/credentials/egress-policy.js +170 -0
  73. package/dist/credentials/egress-policy.js.map +1 -0
  74. package/dist/credentials/egress-proxy.d.ts +82 -0
  75. package/dist/credentials/egress-proxy.js +650 -0
  76. package/dist/credentials/egress-proxy.js.map +1 -0
  77. package/dist/credentials/git-route.d.ts +68 -0
  78. package/dist/credentials/git-route.js +288 -0
  79. package/dist/credentials/git-route.js.map +1 -0
  80. package/dist/credentials/index.d.ts +13 -0
  81. package/dist/credentials/index.js +14 -0
  82. package/dist/credentials/index.js.map +1 -0
  83. package/dist/credentials/scrub.d.ts +23 -0
  84. package/dist/credentials/scrub.js +115 -0
  85. package/dist/credentials/scrub.js.map +1 -0
  86. package/dist/errors.d.ts +60 -0
  87. package/dist/errors.js +67 -0
  88. package/dist/errors.js.map +1 -0
  89. package/dist/extensions/compose.d.ts +27 -0
  90. package/dist/extensions/compose.js +83 -0
  91. package/dist/extensions/compose.js.map +1 -0
  92. package/dist/extensions/context-files-node.d.ts +28 -0
  93. package/dist/extensions/context-files-node.js +74 -0
  94. package/dist/extensions/context-files-node.js.map +1 -0
  95. package/dist/extensions/context-files.d.ts +68 -0
  96. package/dist/extensions/context-files.js +214 -0
  97. package/dist/extensions/context-files.js.map +1 -0
  98. package/dist/extensions/digest.d.ts +6 -0
  99. package/dist/extensions/digest.js +68 -0
  100. package/dist/extensions/digest.js.map +1 -0
  101. package/dist/extensions/index.d.ts +10 -0
  102. package/dist/extensions/index.js +10 -0
  103. package/dist/extensions/index.js.map +1 -0
  104. package/dist/extensions/load.d.ts +42 -0
  105. package/dist/extensions/load.js +211 -0
  106. package/dist/extensions/load.js.map +1 -0
  107. package/dist/extensions/lock.d.ts +8 -0
  108. package/dist/extensions/lock.js +95 -0
  109. package/dist/extensions/lock.js.map +1 -0
  110. package/dist/extensions/node.d.ts +10 -0
  111. package/dist/extensions/node.js +11 -0
  112. package/dist/extensions/node.js.map +1 -0
  113. package/dist/extensions/project-dirs.d.ts +24 -0
  114. package/dist/extensions/project-dirs.js +97 -0
  115. package/dist/extensions/project-dirs.js.map +1 -0
  116. package/dist/extensions/skills-node.d.ts +34 -0
  117. package/dist/extensions/skills-node.js +123 -0
  118. package/dist/extensions/skills-node.js.map +1 -0
  119. package/dist/extensions/skills.d.ts +51 -0
  120. package/dist/extensions/skills.js +175 -0
  121. package/dist/extensions/skills.js.map +1 -0
  122. package/dist/extensions/trust-file.d.ts +3 -0
  123. package/dist/extensions/trust-file.js +62 -0
  124. package/dist/extensions/trust-file.js.map +1 -0
  125. package/dist/extensions/trust-store-node.d.ts +10 -0
  126. package/dist/extensions/trust-store-node.js +33 -0
  127. package/dist/extensions/trust-store-node.js.map +1 -0
  128. package/dist/extensions/types.d.ts +42 -0
  129. package/dist/extensions/types.js +2 -0
  130. package/dist/extensions/types.js.map +1 -0
  131. package/dist/harness.d.ts +156 -0
  132. package/dist/harness.js +2 -0
  133. package/dist/harness.js.map +1 -0
  134. package/dist/index.d.ts +4 -0
  135. package/dist/index.js +5 -0
  136. package/dist/index.js.map +1 -0
  137. package/dist/mcp/connection.d.ts +22 -0
  138. package/dist/mcp/connection.js +267 -0
  139. package/dist/mcp/connection.js.map +1 -0
  140. package/dist/mcp/content.d.ts +27 -0
  141. package/dist/mcp/content.js +177 -0
  142. package/dist/mcp/content.js.map +1 -0
  143. package/dist/mcp/errors.d.ts +19 -0
  144. package/dist/mcp/errors.js +21 -0
  145. package/dist/mcp/errors.js.map +1 -0
  146. package/dist/mcp/index.d.ts +10 -0
  147. package/dist/mcp/index.js +10 -0
  148. package/dist/mcp/index.js.map +1 -0
  149. package/dist/mcp/manager.d.ts +7 -0
  150. package/dist/mcp/manager.js +173 -0
  151. package/dist/mcp/manager.js.map +1 -0
  152. package/dist/mcp/record.d.ts +7 -0
  153. package/dist/mcp/record.js +20 -0
  154. package/dist/mcp/record.js.map +1 -0
  155. package/dist/mcp/stdio.d.ts +39 -0
  156. package/dist/mcp/stdio.js +382 -0
  157. package/dist/mcp/stdio.js.map +1 -0
  158. package/dist/mcp/types.d.ts +172 -0
  159. package/dist/mcp/types.js +2 -0
  160. package/dist/mcp/types.js.map +1 -0
  161. package/dist/memory/index.d.ts +2 -0
  162. package/dist/memory/index.js +3 -0
  163. package/dist/memory/index.js.map +1 -0
  164. package/dist/permissions/default-rules.d.ts +7 -0
  165. package/dist/permissions/default-rules.js +42 -0
  166. package/dist/permissions/default-rules.js.map +1 -0
  167. package/dist/permissions/errors.d.ts +11 -0
  168. package/dist/permissions/errors.js +14 -0
  169. package/dist/permissions/errors.js.map +1 -0
  170. package/dist/permissions/index.d.ts +9 -0
  171. package/dist/permissions/index.js +9 -0
  172. package/dist/permissions/index.js.map +1 -0
  173. package/dist/permissions/match.d.ts +33 -0
  174. package/dist/permissions/match.js +287 -0
  175. package/dist/permissions/match.js.map +1 -0
  176. package/dist/permissions/pipeline.d.ts +9 -0
  177. package/dist/permissions/pipeline.js +235 -0
  178. package/dist/permissions/pipeline.js.map +1 -0
  179. package/dist/permissions/rules.d.ts +22 -0
  180. package/dist/permissions/rules.js +74 -0
  181. package/dist/permissions/rules.js.map +1 -0
  182. package/dist/permissions/shadow.d.ts +5 -0
  183. package/dist/permissions/shadow.js +22 -0
  184. package/dist/permissions/shadow.js.map +1 -0
  185. package/dist/permissions/types.d.ts +104 -0
  186. package/dist/permissions/types.js +2 -0
  187. package/dist/permissions/types.js.map +1 -0
  188. package/dist/sandbox/base.d.ts +45 -0
  189. package/dist/sandbox/base.js +74 -0
  190. package/dist/sandbox/base.js.map +1 -0
  191. package/dist/sandbox/docker/index.d.ts +41 -0
  192. package/dist/sandbox/docker/index.js +497 -0
  193. package/dist/sandbox/docker/index.js.map +1 -0
  194. package/dist/sandbox/errors.d.ts +44 -0
  195. package/dist/sandbox/errors.js +57 -0
  196. package/dist/sandbox/errors.js.map +1 -0
  197. package/dist/sandbox/host-files.d.ts +65 -0
  198. package/dist/sandbox/host-files.js +258 -0
  199. package/dist/sandbox/host-files.js.map +1 -0
  200. package/dist/sandbox/index.d.ts +10 -0
  201. package/dist/sandbox/index.js +10 -0
  202. package/dist/sandbox/index.js.map +1 -0
  203. package/dist/sandbox/none.d.ts +17 -0
  204. package/dist/sandbox/none.js +108 -0
  205. package/dist/sandbox/none.js.map +1 -0
  206. package/dist/sandbox/policy.d.ts +49 -0
  207. package/dist/sandbox/policy.js +149 -0
  208. package/dist/sandbox/policy.js.map +1 -0
  209. package/dist/sandbox/process.d.ts +61 -0
  210. package/dist/sandbox/process.js +253 -0
  211. package/dist/sandbox/process.js.map +1 -0
  212. package/dist/sandbox/spawn-env.d.ts +20 -0
  213. package/dist/sandbox/spawn-env.js +128 -0
  214. package/dist/sandbox/spawn-env.js.map +1 -0
  215. package/dist/sandbox/srt/index.d.ts +38 -0
  216. package/dist/sandbox/srt/index.js +283 -0
  217. package/dist/sandbox/srt/index.js.map +1 -0
  218. package/dist/sandbox/srt/settings.d.ts +60 -0
  219. package/dist/sandbox/srt/settings.js +84 -0
  220. package/dist/sandbox/srt/settings.js.map +1 -0
  221. package/dist/sandbox/types.d.ts +125 -0
  222. package/dist/sandbox/types.js +6 -0
  223. package/dist/sandbox/types.js.map +1 -0
  224. package/dist/server/answers.d.ts +16 -0
  225. package/dist/server/answers.js +43 -0
  226. package/dist/server/answers.js.map +1 -0
  227. package/dist/server/connection.d.ts +99 -0
  228. package/dist/server/connection.js +309 -0
  229. package/dist/server/connection.js.map +1 -0
  230. package/dist/server/dispatcher.d.ts +86 -0
  231. package/dist/server/dispatcher.js +800 -0
  232. package/dist/server/dispatcher.js.map +1 -0
  233. package/dist/server/index.d.ts +13 -0
  234. package/dist/server/index.js +12 -0
  235. package/dist/server/index.js.map +1 -0
  236. package/dist/server/local-transport.d.ts +44 -0
  237. package/dist/server/local-transport.js +103 -0
  238. package/dist/server/local-transport.js.map +1 -0
  239. package/dist/server/outbox.d.ts +31 -0
  240. package/dist/server/outbox.js +130 -0
  241. package/dist/server/outbox.js.map +1 -0
  242. package/dist/server/params.d.ts +25 -0
  243. package/dist/server/params.js +112 -0
  244. package/dist/server/params.js.map +1 -0
  245. package/dist/server/protocol.schema.json +2448 -0
  246. package/dist/server/rpc-session.d.ts +43 -0
  247. package/dist/server/rpc-session.js +167 -0
  248. package/dist/server/rpc-session.js.map +1 -0
  249. package/dist/server/stdio-streams.d.ts +67 -0
  250. package/dist/server/stdio-streams.js +218 -0
  251. package/dist/server/stdio-streams.js.map +1 -0
  252. package/dist/server/stdio.d.ts +59 -0
  253. package/dist/server/stdio.js +189 -0
  254. package/dist/server/stdio.js.map +1 -0
  255. package/dist/server/websocket.d.ts +106 -0
  256. package/dist/server/websocket.js +327 -0
  257. package/dist/server/websocket.js.map +1 -0
  258. package/dist/session/approvals.d.ts +81 -0
  259. package/dist/session/approvals.js +217 -0
  260. package/dist/session/approvals.js.map +1 -0
  261. package/dist/session/code-call-log.d.ts +42 -0
  262. package/dist/session/code-call-log.js +63 -0
  263. package/dist/session/code-call-log.js.map +1 -0
  264. package/dist/session/code-call-result.d.ts +19 -0
  265. package/dist/session/code-call-result.js +95 -0
  266. package/dist/session/code-call-result.js.map +1 -0
  267. package/dist/session/code-call.d.ts +49 -0
  268. package/dist/session/code-call.js +345 -0
  269. package/dist/session/code-call.js.map +1 -0
  270. package/dist/session/effect-scope.d.ts +11 -0
  271. package/dist/session/effect-scope.js +10 -0
  272. package/dist/session/effect-scope.js.map +1 -0
  273. package/dist/session/errors.d.ts +19 -0
  274. package/dist/session/errors.js +27 -0
  275. package/dist/session/errors.js.map +1 -0
  276. package/dist/session/file-index.d.ts +8 -0
  277. package/dist/session/file-index.js +70 -0
  278. package/dist/session/file-index.js.map +1 -0
  279. package/dist/session/file-key-store.d.ts +16 -0
  280. package/dist/session/file-key-store.js +169 -0
  281. package/dist/session/file-key-store.js.map +1 -0
  282. package/dist/session/file-lock.d.ts +52 -0
  283. package/dist/session/file-lock.js +324 -0
  284. package/dist/session/file-lock.js.map +1 -0
  285. package/dist/session/index.d.ts +22 -0
  286. package/dist/session/index.js +20 -0
  287. package/dist/session/index.js.map +1 -0
  288. package/dist/session/jsonl-store.d.ts +37 -0
  289. package/dist/session/jsonl-store.js +386 -0
  290. package/dist/session/jsonl-store.js.map +1 -0
  291. package/dist/session/jsonl.d.ts +9 -0
  292. package/dist/session/jsonl.js +10 -0
  293. package/dist/session/jsonl.js.map +1 -0
  294. package/dist/session/lock.d.ts +19 -0
  295. package/dist/session/lock.js +2 -0
  296. package/dist/session/lock.js.map +1 -0
  297. package/dist/session/memory-store.d.ts +12 -0
  298. package/dist/session/memory-store.js +60 -0
  299. package/dist/session/memory-store.js.map +1 -0
  300. package/dist/session/migrate.d.ts +41 -0
  301. package/dist/session/migrate.js +86 -0
  302. package/dist/session/migrate.js.map +1 -0
  303. package/dist/session/pointer.d.ts +15 -0
  304. package/dist/session/pointer.js +22 -0
  305. package/dist/session/pointer.js.map +1 -0
  306. package/dist/session/rebuild.d.ts +53 -0
  307. package/dist/session/rebuild.js +230 -0
  308. package/dist/session/rebuild.js.map +1 -0
  309. package/dist/session/resume.d.ts +26 -0
  310. package/dist/session/resume.js +128 -0
  311. package/dist/session/resume.js.map +1 -0
  312. package/dist/session/retention.d.ts +97 -0
  313. package/dist/session/retention.js +702 -0
  314. package/dist/session/retention.js.map +1 -0
  315. package/dist/session/runner.d.ts +156 -0
  316. package/dist/session/runner.js +656 -0
  317. package/dist/session/runner.js.map +1 -0
  318. package/dist/session/scheduler.d.ts +47 -0
  319. package/dist/session/scheduler.js +85 -0
  320. package/dist/session/scheduler.js.map +1 -0
  321. package/dist/session/secret-key-store.d.ts +47 -0
  322. package/dist/session/secret-key-store.js +79 -0
  323. package/dist/session/secret-key-store.js.map +1 -0
  324. package/dist/session/session.d.ts +106 -0
  325. package/dist/session/session.js +353 -0
  326. package/dist/session/session.js.map +1 -0
  327. package/dist/session/sticky.d.ts +48 -0
  328. package/dist/session/sticky.js +232 -0
  329. package/dist/session/sticky.js.map +1 -0
  330. package/dist/session/store.d.ts +108 -0
  331. package/dist/session/store.js +163 -0
  332. package/dist/session/store.js.map +1 -0
  333. package/dist/telemetry/index.d.ts +2 -0
  334. package/dist/telemetry/index.js +3 -0
  335. package/dist/telemetry/index.js.map +1 -0
  336. package/dist/testing/fake-sandbox.d.ts +52 -0
  337. package/dist/testing/fake-sandbox.js +370 -0
  338. package/dist/testing/fake-sandbox.js.map +1 -0
  339. package/dist/testing/index.d.ts +10 -0
  340. package/dist/testing/index.js +11 -0
  341. package/dist/testing/index.js.map +1 -0
  342. package/dist/testing/key-store-conformance.d.ts +22 -0
  343. package/dist/testing/key-store-conformance.js +97 -0
  344. package/dist/testing/key-store-conformance.js.map +1 -0
  345. package/dist/testing/run-cases.d.ts +21 -0
  346. package/dist/testing/run-cases.js +20 -0
  347. package/dist/testing/run-cases.js.map +1 -0
  348. package/dist/testing/sandbox-conformance.d.ts +64 -0
  349. package/dist/testing/sandbox-conformance.js +468 -0
  350. package/dist/testing/sandbox-conformance.js.map +1 -0
  351. package/dist/testing/scheduler-conformance.d.ts +32 -0
  352. package/dist/testing/scheduler-conformance.js +72 -0
  353. package/dist/testing/scheduler-conformance.js.map +1 -0
  354. package/dist/testing/store-conformance.d.ts +21 -0
  355. package/dist/testing/store-conformance.js +320 -0
  356. package/dist/testing/store-conformance.js.map +1 -0
  357. package/dist/tools/builtins/bash.d.ts +9 -0
  358. package/dist/tools/builtins/bash.js +75 -0
  359. package/dist/tools/builtins/bash.js.map +1 -0
  360. package/dist/tools/builtins/builtins.d.ts +38 -0
  361. package/dist/tools/builtins/builtins.js +48 -0
  362. package/dist/tools/builtins/builtins.js.map +1 -0
  363. package/dist/tools/builtins/descriptions.d.ts +69 -0
  364. package/dist/tools/builtins/descriptions.js +94 -0
  365. package/dist/tools/builtins/descriptions.js.map +1 -0
  366. package/dist/tools/builtins/fetch.d.ts +12 -0
  367. package/dist/tools/builtins/fetch.js +157 -0
  368. package/dist/tools/builtins/fetch.js.map +1 -0
  369. package/dist/tools/builtins/files.d.ts +27 -0
  370. package/dist/tools/builtins/files.js +274 -0
  371. package/dist/tools/builtins/files.js.map +1 -0
  372. package/dist/tools/builtins/paths.d.ts +30 -0
  373. package/dist/tools/builtins/paths.js +62 -0
  374. package/dist/tools/builtins/paths.js.map +1 -0
  375. package/dist/tools/builtins/results.d.ts +15 -0
  376. package/dist/tools/builtins/results.js +31 -0
  377. package/dist/tools/builtins/results.js.map +1 -0
  378. package/dist/tools/builtins/search.d.ts +18 -0
  379. package/dist/tools/builtins/search.js +217 -0
  380. package/dist/tools/builtins/search.js.map +1 -0
  381. package/dist/tools/errors.d.ts +13 -0
  382. package/dist/tools/errors.js +17 -0
  383. package/dist/tools/errors.js.map +1 -0
  384. package/dist/tools/index.d.ts +12 -0
  385. package/dist/tools/index.js +11 -0
  386. package/dist/tools/index.js.map +1 -0
  387. package/dist/tools/registry.d.ts +3 -0
  388. package/dist/tools/registry.js +234 -0
  389. package/dist/tools/registry.js.map +1 -0
  390. package/dist/tools/tool-search.d.ts +30 -0
  391. package/dist/tools/tool-search.js +118 -0
  392. package/dist/tools/tool-search.js.map +1 -0
  393. package/dist/tools/types.d.ts +106 -0
  394. package/dist/tools/types.js +2 -0
  395. package/dist/tools/types.js.map +1 -0
  396. package/llms.txt +469 -0
  397. package/package.json +118 -3
@@ -0,0 +1,41 @@
1
+ import type { SessionLock } from "./lock.js";
2
+ import type { SessionIndex } from "./pointer.js";
3
+ import type { SessionKey, SessionStore } from "./store.js";
4
+ /** One step of format change: it maps each entry of a file at format `from` to an entry at format `to`. */
5
+ export interface Migration {
6
+ readonly from: number;
7
+ readonly to: number;
8
+ /** Returns the entry in the new format, header included: its `formatVersion` must be `to`. */
9
+ migrate(entry: unknown): unknown;
10
+ }
11
+ /** The options of `migrateSession()`. */
12
+ export interface MigrateOptions {
13
+ readonly store: SessionStore;
14
+ readonly index: SessionIndex;
15
+ readonly key: SessionKey;
16
+ /** The session's writer lock, taken for the whole migration so no writer or second migration interleaves with it. */
17
+ readonly lock: SessionLock;
18
+ /** The steps this harness knows, from any format to the next. A session is taken through them in order. */
19
+ readonly migrations: readonly Migration[];
20
+ /** Makes the id in the new file's name. Defaults to a random UUID; a test passes a fixed one. */
21
+ readonly newId?: () => string;
22
+ }
23
+ /** What `migrateSession()` did. */
24
+ export type MigrationResult = {
25
+ readonly migrated: false;
26
+ readonly version: number;
27
+ } | {
28
+ readonly migrated: true;
29
+ readonly from: number;
30
+ readonly to: number;
31
+ readonly file: string;
32
+ readonly entries: number;
33
+ };
34
+ /**
35
+ * Migrates the session's current file to the current format. A session already in the current format is left alone. A session from a
36
+ * newer format is refused, because only a newer harness can read it. Otherwise the entries go through each step, the
37
+ * new file is written in one append (which checks every entry against the current format), read back and compared, and
38
+ * only then does the pointer move. A file whose header names a parent file is refused, because its parent would stay in the old format. Forks that name
39
+ * this file as their parent can't be found, because a store has no index of dependents, so they are not checked.
40
+ */
41
+ export declare function migrateSession(options: MigrateOptions): Promise<MigrationResult>;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * `migrateSession()`: moves a session's log to the current format by writing a new file, checking it and then moving the
3
+ * pointer. The old file is never changed, so a crash at any step leaves the session readable where it was.
4
+ */
5
+ import { FORMAT_VERSION, parseEntry } from "@buildanagent/protocol";
6
+ import { HarnessError } from "../errors.js";
7
+ import { DERIVED } from "./session.js";
8
+ async function rawEntries(store, key) {
9
+ if (store.loadRaw === undefined) {
10
+ throw new HarnessError("unsupported_format", "this store can't read a log as it was written, so it can't migrate one");
11
+ }
12
+ const found = [];
13
+ for await (const entry of store.loadRaw(key))
14
+ found.push(entry);
15
+ return found;
16
+ }
17
+ /** The format version in a log's header, which a migration refuses to guess when it is missing. */
18
+ function versionOf(entries) {
19
+ const header = entries[0];
20
+ if (header?.type !== "session_header" || typeof header.formatVersion !== "number") {
21
+ throw new HarnessError("unsupported_format", "the log does not start with a session header that names its format");
22
+ }
23
+ return header.formatVersion;
24
+ }
25
+ function stepsFrom(version, migrations) {
26
+ const steps = [];
27
+ for (let at = version; at < FORMAT_VERSION;) {
28
+ const step = migrations.find((migration) => migration.from === at);
29
+ if (step === undefined || step.to <= at) {
30
+ throw new HarnessError("unsupported_format", `no migration takes format ${at} towards ${FORMAT_VERSION}`);
31
+ }
32
+ steps.push(step);
33
+ at = step.to;
34
+ }
35
+ return steps;
36
+ }
37
+ /**
38
+ * Migrates the session's current file to the current format. A session already in the current format is left alone. A session from a
39
+ * newer format is refused, because only a newer harness can read it. Otherwise the entries go through each step, the
40
+ * new file is written in one append (which checks every entry against the current format), read back and compared, and
41
+ * only then does the pointer move. A file whose header names a parent file is refused, because its parent would stay in the old format. Forks that name
42
+ * this file as their parent can't be found, because a store has no index of dependents, so they are not checked.
43
+ */
44
+ export async function migrateSession(options) {
45
+ const handle = await options.lock.acquire(options.key);
46
+ if (handle === "would_block") {
47
+ throw new HarnessError("session_locked", `another writer holds the session ${JSON.stringify(options.key.sessionId)}`);
48
+ }
49
+ try {
50
+ return await migrateLocked(options);
51
+ }
52
+ finally {
53
+ await handle.release();
54
+ }
55
+ }
56
+ async function migrateLocked(options) {
57
+ const { store, index, key } = options;
58
+ const file = (await index.get(key)) ?? key.sessionId;
59
+ const raw = await rawEntries(store, { userId: key.userId, sessionId: file });
60
+ const version = versionOf(raw);
61
+ if (version === FORMAT_VERSION)
62
+ return { migrated: false, version };
63
+ if (version > FORMAT_VERSION) {
64
+ throw new HarnessError("unsupported_format", `the log is format ${version}, newer than this harness reads (${FORMAT_VERSION})`);
65
+ }
66
+ const first = raw[0];
67
+ // A spawned child has a parent link but no shared path, so nothing of the parent stays in the old format.
68
+ if (first.parent !== undefined && first.spawn === undefined) {
69
+ throw new HarnessError("unsupported_format", "this file continues a parent file, which would stay in the old format and make the session unreadable, so migrate the parent's session first and fork again");
70
+ }
71
+ const steps = stepsFrom(version, options.migrations);
72
+ const moved = raw.map((entry) => steps.reduce((value, step) => step.migrate(value), entry));
73
+ const parsed = moved.map((entry) => parseEntry(entry));
74
+ const newFile = `${DERIVED}m${(options.newId ?? (() => globalThis.crypto.randomUUID()))()}`;
75
+ const target = { userId: key.userId, sessionId: newFile };
76
+ await store.append(target, parsed.map(({ seq: _seq, ...entry }) => entry), { expectedLastId: null });
77
+ const written = [];
78
+ for await (const entry of store.load(target))
79
+ written.push(entry.id);
80
+ if (written.join() !== parsed.map((entry) => entry.id).join()) {
81
+ throw new HarnessError("session_corrupt", "the migrated file does not match what was written, so the pointer was not moved");
82
+ }
83
+ await index.set(key, newFile);
84
+ return { migrated: true, from: version, to: FORMAT_VERSION, file: newFile, entries: parsed.length };
85
+ }
86
+ //# sourceMappingURL=migrate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate.js","sourceRoot":"","sources":["../../src/session/migrate.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C5D,EAAE,cAAc,EAAE,IAAI,EAAE,CACzB,CAAC;IACF,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC;QAAE,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACrE,IAAI,OAAO,CAAC,IAAI,EAAE,KAAK,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QAC9D,MAAM,IAAI,YAAY,CACpB,iBAAiB,EACjB,iFAAiF,CAClF,CAAC;IACJ,CAAC;IACD,MAAM,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IAC9B,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC;AACtG,CAAC","sourcesContent":["/**\n * `migrateSession()`: moves a session's log to the current format by writing a new file, checking it and then moving the\n * pointer. The old file is never changed, so a crash at any step leaves the session readable where it was.\n */\nimport { FORMAT_VERSION, parseEntry } from \"@buildanagent/protocol\";\nimport { HarnessError } from \"../errors.js\";\nimport type { SessionLock } from \"./lock.js\";\nimport type { SessionIndex } from \"./pointer.js\";\nimport { DERIVED } from \"./session.js\";\nimport type { EntryInput, SessionKey, SessionStore } from \"./store.js\";\n\n/** One step of format change: it maps each entry of a file at format `from` to an entry at format `to`. */\nexport interface Migration {\n readonly from: number;\n readonly to: number;\n /** Returns the entry in the new format, header included: its `formatVersion` must be `to`. */\n migrate(entry: unknown): unknown;\n}\n\n/** The options of `migrateSession()`. */\nexport interface MigrateOptions {\n readonly store: SessionStore;\n readonly index: SessionIndex;\n readonly key: SessionKey;\n /** The session's writer lock, taken for the whole migration so no writer or second migration interleaves with it. */\n readonly lock: SessionLock;\n /** The steps this harness knows, from any format to the next. A session is taken through them in order. */\n readonly migrations: readonly Migration[];\n /** Makes the id in the new file's name. Defaults to a random UUID; a test passes a fixed one. */\n readonly newId?: () => string;\n}\n\n/** What `migrateSession()` did. */\nexport type MigrationResult =\n | { readonly migrated: false; readonly version: number }\n | {\n readonly migrated: true;\n readonly from: number;\n readonly to: number;\n readonly file: string;\n readonly entries: number;\n };\n\nasync function rawEntries(store: SessionStore, key: SessionKey): Promise<unknown[]> {\n if (store.loadRaw === undefined) {\n throw new HarnessError(\n \"unsupported_format\",\n \"this store can't read a log as it was written, so it can't migrate one\",\n );\n }\n const found: unknown[] = [];\n for await (const entry of store.loadRaw(key)) found.push(entry);\n return found;\n}\n\n/** The format version in a log's header, which a migration refuses to guess when it is missing. */\nfunction versionOf(entries: readonly unknown[]): number {\n const header = entries[0] as { type?: unknown; formatVersion?: unknown } | undefined;\n if (header?.type !== \"session_header\" || typeof header.formatVersion !== \"number\") {\n throw new HarnessError(\"unsupported_format\", \"the log does not start with a session header that names its format\");\n }\n return header.formatVersion;\n}\n\nfunction stepsFrom(version: number, migrations: readonly Migration[]): Migration[] {\n const steps: Migration[] = [];\n for (let at = version; at < FORMAT_VERSION; ) {\n const step = migrations.find((migration) => migration.from === at);\n if (step === undefined || step.to <= at) {\n throw new HarnessError(\"unsupported_format\", `no migration takes format ${at} towards ${FORMAT_VERSION}`);\n }\n steps.push(step);\n at = step.to;\n }\n return steps;\n}\n\n/**\n * Migrates the session's current file to the current format. A session already in the current format is left alone. A session from a\n * newer format is refused, because only a newer harness can read it. Otherwise the entries go through each step, the\n * new file is written in one append (which checks every entry against the current format), read back and compared, and\n * only then does the pointer move. A file whose header names a parent file is refused, because its parent would stay in the old format. Forks that name\n * this file as their parent can't be found, because a store has no index of dependents, so they are not checked.\n */\nexport async function migrateSession(options: MigrateOptions): Promise<MigrationResult> {\n const handle = await options.lock.acquire(options.key);\n if (handle === \"would_block\") {\n throw new HarnessError(\n \"session_locked\",\n `another writer holds the session ${JSON.stringify(options.key.sessionId)}`,\n );\n }\n try {\n return await migrateLocked(options);\n } finally {\n await handle.release();\n }\n}\n\nasync function migrateLocked(options: MigrateOptions): Promise<MigrationResult> {\n const { store, index, key } = options;\n const file = (await index.get(key)) ?? key.sessionId;\n const raw = await rawEntries(store, { userId: key.userId, sessionId: file });\n const version = versionOf(raw);\n if (version === FORMAT_VERSION) return { migrated: false, version };\n if (version > FORMAT_VERSION) {\n throw new HarnessError(\n \"unsupported_format\",\n `the log is format ${version}, newer than this harness reads (${FORMAT_VERSION})`,\n );\n }\n const first = raw[0] as { parent?: unknown; spawn?: unknown };\n // A spawned child has a parent link but no shared path, so nothing of the parent stays in the old format.\n if (first.parent !== undefined && first.spawn === undefined) {\n throw new HarnessError(\n \"unsupported_format\",\n \"this file continues a parent file, which would stay in the old format and make the session unreadable, so migrate the parent's session first and fork again\",\n );\n }\n const steps = stepsFrom(version, options.migrations);\n const moved = raw.map((entry) => steps.reduce((value, step) => step.migrate(value), entry));\n const parsed = moved.map((entry) => parseEntry(entry));\n const newFile = `${DERIVED}m${(options.newId ?? (() => globalThis.crypto.randomUUID()))()}`;\n const target = { userId: key.userId, sessionId: newFile };\n await store.append(\n target,\n parsed.map(({ seq: _seq, ...entry }) => entry as EntryInput),\n { expectedLastId: null },\n );\n const written: string[] = [];\n for await (const entry of store.load(target)) written.push(entry.id);\n if (written.join() !== parsed.map((entry) => entry.id).join()) {\n throw new HarnessError(\n \"session_corrupt\",\n \"the migrated file does not match what was written, so the pointer was not moved\",\n );\n }\n await index.set(key, newFile);\n return { migrated: true, from: version, to: FORMAT_VERSION, file: newFile, entries: parsed.length };\n}\n"]}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The session pointer: which file holds a session's log now. A session's key stays the same while the file under it
3
+ * changes, because a revert or a migration writes a new file and moves the pointer, and no file is ever rewritten. The
4
+ * pointer is the only mutable state in the log. A session with no pointer is in the file named by its session id.
5
+ */
6
+ import { type SessionKey } from "./store.js";
7
+ /** Where each session's current file is. Replacing a pointer must be atomic, so a crash leaves the old one or the new. */
8
+ export interface SessionIndex {
9
+ /** The id of the session's current file, or `undefined` when it has no pointer. */
10
+ get(key: SessionKey): Promise<string | undefined>;
11
+ /** Points the session at another file. */
12
+ set(key: SessionKey, file: string): Promise<void>;
13
+ }
14
+ /** A pointer index in memory, for tests and for a process that keeps its sessions in `memoryStore()`. */
15
+ export declare function memoryIndex(): SessionIndex;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The session pointer: which file holds a session's log now. A session's key stays the same while the file under it
3
+ * changes, because a revert or a migration writes a new file and moves the pointer, and no file is ever rewritten. The
4
+ * pointer is the only mutable state in the log. A session with no pointer is in the file named by its session id.
5
+ */
6
+ import { checkKey } from "./store.js";
7
+ const slot = (key) => JSON.stringify([key.userId, key.sessionId]);
8
+ /** A pointer index in memory, for tests and for a process that keeps its sessions in `memoryStore()`. */
9
+ export function memoryIndex() {
10
+ const pointers = new Map();
11
+ return {
12
+ async get(key) {
13
+ checkKey(key);
14
+ return pointers.get(slot(key));
15
+ },
16
+ async set(key, file) {
17
+ checkKey(key);
18
+ pointers.set(slot(key), file);
19
+ },
20
+ };
21
+ }
22
+ //# sourceMappingURL=pointer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pointer.js","sourceRoot":"","sources":["../../src/session/pointer.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,QAAQ,EAAmB,MAAM,YAAY,CAAC;AAUvD,MAAM,IAAI,GAAG,CAAC,GAAe,EAAU,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;AAEtF,yGAAyG;AACzG,MAAM,UAAU,WAAW;IACzB,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC3C,OAAO;QACL,KAAK,CAAC,GAAG,CAAC,GAAG;YACX,QAAQ,CAAC,GAAG,CAAC,CAAC;YACd,OAAO,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QACjC,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI;YACjB,QAAQ,CAAC,GAAG,CAAC,CAAC;YACd,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,CAAC,CAAC;QAChC,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The session pointer: which file holds a session's log now. A session's key stays the same while the file under it\n * changes, because a revert or a migration writes a new file and moves the pointer, and no file is ever rewritten. The\n * pointer is the only mutable state in the log. A session with no pointer is in the file named by its session id.\n */\nimport { checkKey, type SessionKey } from \"./store.js\";\n\n/** Where each session's current file is. Replacing a pointer must be atomic, so a crash leaves the old one or the new. */\nexport interface SessionIndex {\n /** The id of the session's current file, or `undefined` when it has no pointer. */\n get(key: SessionKey): Promise<string | undefined>;\n /** Points the session at another file. */\n set(key: SessionKey, file: string): Promise<void>;\n}\n\nconst slot = (key: SessionKey): string => JSON.stringify([key.userId, key.sessionId]);\n\n/** A pointer index in memory, for tests and for a process that keeps its sessions in `memoryStore()`. */\nexport function memoryIndex(): SessionIndex {\n const pointers = new Map<string, string>();\n return {\n async get(key) {\n checkKey(key);\n return pointers.get(slot(key));\n },\n async set(key, file) {\n checkKey(key);\n pointers.set(slot(key), file);\n },\n };\n}\n"]}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Rebuilds the SDK's `Context` from a session's entries, so the log is the only state: any process can read the log
3
+ * and go on with `continueRun()`. A message is the `message_block` entries that share a `messageId`, in `index` order;
4
+ * an assistant message is closed by its `message_end` and takes its usage and cost from the `usage` entry right after
5
+ * it. A `usage` entry anywhere else belongs to a call whose message was superseded, and builds no message. A code
6
+ * call is the host's, not the model's, so its entries build no message either.
7
+ */
8
+ import type { Message } from "@buildanagent/gateway";
9
+ import type { SessionEntry } from "@buildanagent/protocol";
10
+ import type { Context, SignedPendingRequest } from "@buildanagent/sdk";
11
+ /** A request that waits for a person, with the input its call would run with once approved. */
12
+ export interface PendingApproval {
13
+ readonly request: SignedPendingRequest;
14
+ readonly input: unknown;
15
+ }
16
+ /**
17
+ * The requests on `path` that still wait: the latest request for each call of the last assistant message, while the call
18
+ * has no result. A resolution does not end a wait, because the run that applies it may refuse it or never finish: only
19
+ * the call's result does. A resume that started and died before the result is a crash, which `crashedResumes()` names,
20
+ * and its requests do not wait.
21
+ */
22
+ export declare function pendingApprovals(path: readonly SessionEntry[]): PendingApproval[];
23
+ /**
24
+ * The ids of the requests whose resume started and died: the log ends in a `continue` turn that has no end, after
25
+ * allows were written for it. An approved call may have run, so it is settled as a crash and not asked again, even
26
+ * when the run died before it reached that call.
27
+ */
28
+ export declare function crashedResumes(path: readonly SessionEntry[]): Set<string>;
29
+ /** The user message that stands for the summarised span, so the model reads the summary where the span was. */
30
+ export declare function summaryMessage(summary: string): Message;
31
+ /**
32
+ * The entries a context is built from, and whether a compaction applies. The latest `compaction` on the path replaces
33
+ * everything before its `firstKeptEntryId`. The kept tail loses its signed reasoning, because a block that follows the
34
+ * edited span would carry a signature the summary made stale; blocks written after the compaction are untouched.
35
+ */
36
+ export declare function entriesAfterCompaction(path: readonly SessionEntry[]): {
37
+ readonly entries: readonly SessionEntry[];
38
+ readonly summary: string | undefined;
39
+ /** The ids of messages that lost a signed reasoning block. */
40
+ readonly stripped: ReadonlySet<string>;
41
+ };
42
+ /**
43
+ * The context a path of entries stands for, with the id of the entry each message starts at (`null` for a summary).
44
+ * `path` is a session's `path()`: the root to a HEAD, without `checkout` entries. The system prompt is the latest
45
+ * `turn_start`'s, byte for byte, so a harness whose prompt changed later still rebuilds the conversation the model
46
+ * saw. The latest compaction applies: its summary stands first, then the kept tail and what followed it.
47
+ */
48
+ export declare function contextWithStarts(path: readonly SessionEntry[]): {
49
+ readonly context: Context;
50
+ readonly starts: readonly (string | null)[];
51
+ };
52
+ /** The context a path of entries stands for. See `contextWithStarts()`. */
53
+ export declare function contextOf(path: readonly SessionEntry[]): Context;
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Rebuilds the SDK's `Context` from a session's entries, so the log is the only state: any process can read the log
3
+ * and go on with `continueRun()`. A message is the `message_block` entries that share a `messageId`, in `index` order;
4
+ * an assistant message is closed by its `message_end` and takes its usage and cost from the `usage` entry right after
5
+ * it. A `usage` entry anywhere else belongs to a call whose message was superseded, and builds no message. A code
6
+ * call is the host's, not the model's, so its entries build no message either.
7
+ */
8
+ import { HarnessError } from "../errors.js";
9
+ const ordered = (blocks) => [...blocks].sort((a, b) => a.index - b.index).map((entry) => entry.block);
10
+ /** Builds messages from entries one at a time, keeping a message open until the entry that ends it arrives. */
11
+ class MessageBuilder {
12
+ messages = [];
13
+ /** The id of the first entry of each message, in step with `messages`. */
14
+ starts = [];
15
+ #open;
16
+ #dropEmpty;
17
+ #ended;
18
+ constructor(dropEmpty = new Set()) {
19
+ this.#dropEmpty = dropEmpty;
20
+ }
21
+ /** Closes the user message being built, if there is one. */
22
+ #closeUser() {
23
+ if (this.#open?.role !== "user")
24
+ return;
25
+ this.messages.push({ role: "user", content: ordered(this.#open.blocks) });
26
+ this.starts.push(this.#open.firstId);
27
+ this.#open = undefined;
28
+ }
29
+ block(entry) {
30
+ this.#settleEnded(undefined);
31
+ if (this.#open === undefined || this.#open.id !== entry.messageId || this.#open.role !== entry.role) {
32
+ this.#closeUser();
33
+ this.#open = { role: entry.role, id: entry.messageId, blocks: [], firstId: entry.id };
34
+ }
35
+ this.#open.blocks.push(entry);
36
+ }
37
+ /** An assistant message with no usage entry after it still counts, with unknown cost. */
38
+ #settleEnded(usage) {
39
+ const end = this.#ended;
40
+ const open = this.#open;
41
+ if (end === undefined || open === undefined)
42
+ return;
43
+ this.#ended = undefined;
44
+ this.#open = undefined;
45
+ // A message whose signed reasoning was left out and that has nothing else would be an empty assistant turn.
46
+ if (open.blocks.length === 0 && this.#dropEmpty.has(open.id))
47
+ return;
48
+ const message = {
49
+ role: "assistant",
50
+ content: ordered(open.blocks),
51
+ model: end.model,
52
+ stopReason: end.stopReason,
53
+ ...(end.error === undefined ? {} : { error: end.error }),
54
+ usage: usage?.usage ?? EMPTY_USAGE,
55
+ ...(usage?.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: usage.lastAttemptUsage }),
56
+ cost: usage?.cost ?? EMPTY_COST,
57
+ };
58
+ this.messages.push(message);
59
+ this.starts.push(open.firstId);
60
+ }
61
+ end(entry) {
62
+ this.#settleEnded(undefined);
63
+ if (this.#open?.role !== "assistant" || this.#open.id !== entry.messageId) {
64
+ // A message with no blocks has no open message to close.
65
+ this.#closeUser();
66
+ this.#open = { role: "assistant", id: entry.messageId, blocks: [], firstId: entry.id };
67
+ }
68
+ this.#ended = entry;
69
+ }
70
+ usage(entry) {
71
+ if (entry.source === "model_call" && this.#ended !== undefined)
72
+ this.#settleEnded(entry);
73
+ }
74
+ toolResult(entry) {
75
+ this.#settleEnded(undefined);
76
+ this.#closeUser();
77
+ this.messages.push({ role: "tool", callId: entry.callId, content: entry.content, isError: entry.isError });
78
+ this.starts.push(entry.id);
79
+ }
80
+ finish() {
81
+ this.#settleEnded(undefined);
82
+ this.#closeUser();
83
+ return this.messages;
84
+ }
85
+ }
86
+ // A message with no usage entry, which a crash between the two writes leaves, has no usage anyone knows.
87
+ const EMPTY_USAGE = {
88
+ uncachedInput: 0,
89
+ cacheRead: 0,
90
+ cacheWrite: { "5m": 0, "1h": 0 },
91
+ output: 0,
92
+ reasoning: 0,
93
+ raw: null,
94
+ };
95
+ const EMPTY_COST = { total: null, basis: "unknown", currency: "USD" };
96
+ /**
97
+ * The requests on `path` that still wait: the latest request for each call of the last assistant message, while the call
98
+ * has no result. A resolution does not end a wait, because the run that applies it may refuse it or never finish: only
99
+ * the call's result does. A resume that started and died before the result is a crash, which `crashedResumes()` names,
100
+ * and its requests do not wait.
101
+ */
102
+ export function pendingApprovals(path) {
103
+ const answered = new Set();
104
+ const latest = new Map();
105
+ let lastMessage;
106
+ let lastCalls = new Set();
107
+ for (const entry of path) {
108
+ if (entry.type === "tool_result")
109
+ answered.add(entry.callId);
110
+ if (entry.type === "approval_requested")
111
+ latest.set(entry.request.callId, { request: entry.request, input: entry.input });
112
+ if (entry.type === "message_block" && entry.role === "assistant") {
113
+ if (entry.messageId !== lastMessage)
114
+ lastCalls = new Set();
115
+ lastMessage = entry.messageId;
116
+ if (entry.block.type === "tool_call")
117
+ lastCalls.add(entry.block.callId);
118
+ }
119
+ }
120
+ const crashed = crashedResumes(path);
121
+ return [...latest.values()].filter((entry) => lastCalls.has(entry.request.callId) && !answered.has(entry.request.callId) && !crashed.has(entry.request.id));
122
+ }
123
+ /**
124
+ * The ids of the requests whose resume started and died: the log ends in a `continue` turn that has no end, after
125
+ * allows were written for it. An approved call may have run, so it is settled as a crash and not asked again, even
126
+ * when the run died before it reached that call.
127
+ */
128
+ export function crashedResumes(path) {
129
+ const start = path.findLastIndex((entry) => entry.type === "turn_start");
130
+ const turn = path[start];
131
+ if (turn?.type !== "turn_start" || turn.mode !== "continue")
132
+ return new Set();
133
+ if (path.slice(start).some((entry) => entry.type === "turn_end"))
134
+ return new Set();
135
+ // Only the allows this run was given: a deny or an answer runs nothing, and an earlier run's answers are its own.
136
+ const since = path.slice(0, start).findLastIndex((entry) => entry.type === "turn_end");
137
+ return new Set(path.slice(since + 1, start).flatMap((entry) => {
138
+ const answer = entry.type === "approval_resolved" && entry.quorum === undefined ? entry.resolution : undefined;
139
+ return answer !== undefined && "decision" in answer && answer.decision === "allow" ? [answer.requestId] : [];
140
+ }));
141
+ }
142
+ const isSignedReasoning = (entry) => entry.type === "message_block" && entry.block.type === "reasoning" && entry.block.signature !== undefined;
143
+ /** The user message that stands for the summarised span, so the model reads the summary where the span was. */
144
+ export function summaryMessage(summary) {
145
+ return {
146
+ role: "user",
147
+ content: [
148
+ { type: "text", text: `The earlier part of this conversation was summarized to save space:\n\n${summary}` },
149
+ ],
150
+ };
151
+ }
152
+ /**
153
+ * The entries a context is built from, and whether a compaction applies. The latest `compaction` on the path replaces
154
+ * everything before its `firstKeptEntryId`. The kept tail loses its signed reasoning, because a block that follows the
155
+ * edited span would carry a signature the summary made stale; blocks written after the compaction are untouched.
156
+ */
157
+ export function entriesAfterCompaction(path) {
158
+ const at = path.findLastIndex((entry) => entry.type === "compaction");
159
+ const compaction = path[at];
160
+ if (compaction?.type !== "compaction")
161
+ return { entries: path, summary: undefined, stripped: new Set() };
162
+ const kept = path.findIndex((entry) => entry.id === compaction.firstKeptEntryId);
163
+ if (kept < 0) {
164
+ throw new HarnessError("entry_not_found", `the compaction ${compaction.id} keeps from entry ${compaction.firstKeptEntryId}, which is not on this path`);
165
+ }
166
+ // The messages that lose a block here are the only ones an empty result may drop.
167
+ const stripped = new Set();
168
+ const entries = path.slice(kept).filter((entry, i) => {
169
+ const drop = kept + i < at && isSignedReasoning(entry);
170
+ if (drop && entry.type === "message_block")
171
+ stripped.add(entry.messageId);
172
+ return !drop;
173
+ });
174
+ return { entries: entries.filter((entry) => entry.type !== "compaction"), summary: compaction.summary, stripped };
175
+ }
176
+ /**
177
+ * The context a path of entries stands for, with the id of the entry each message starts at (`null` for a summary).
178
+ * `path` is a session's `path()`: the root to a HEAD, without `checkout` entries. The system prompt is the latest
179
+ * `turn_start`'s, byte for byte, so a harness whose prompt changed later still rebuilds the conversation the model
180
+ * saw. The latest compaction applies: its summary stands first, then the kept tail and what followed it.
181
+ */
182
+ export function contextWithStarts(path) {
183
+ const { entries, summary, stripped } = entriesAfterCompaction(path);
184
+ const builder = new MessageBuilder(stripped);
185
+ let system = "";
186
+ for (const entry of path)
187
+ if (entry.type === "turn_start")
188
+ system = entry.system;
189
+ // A code call's result answers no call the model made, so the model never reads it.
190
+ const codeCalls = new Set(path.flatMap((entry) => (entry.type === "code_call" ? [entry.callId] : [])));
191
+ for (const entry of entries) {
192
+ if (entry.type === "tool_result" && codeCalls.has(entry.callId))
193
+ continue;
194
+ switch (entry.type) {
195
+ case "message_block":
196
+ builder.block(entry);
197
+ break;
198
+ case "message_end":
199
+ builder.end(entry);
200
+ break;
201
+ case "usage":
202
+ builder.usage(entry);
203
+ break;
204
+ case "tool_result":
205
+ builder.toolResult(entry);
206
+ break;
207
+ default:
208
+ }
209
+ }
210
+ const built = builder.finish();
211
+ const messages = summary === undefined ? built : [summaryMessage(summary), ...built];
212
+ const starts = summary === undefined ? builder.starts : [null, ...builder.starts];
213
+ const waiting = pendingApprovals(path);
214
+ if (waiting.length === 0)
215
+ return { context: { system, messages }, starts };
216
+ return {
217
+ context: {
218
+ system,
219
+ messages,
220
+ pending: waiting.map((entry) => entry.request),
221
+ pendingInputs: Object.fromEntries(waiting.map((entry) => [entry.request.id, entry.input])),
222
+ },
223
+ starts,
224
+ };
225
+ }
226
+ /** The context a path of entries stands for. See `contextWithStarts()`. */
227
+ export function contextOf(path) {
228
+ return contextWithStarts(path).context;
229
+ }
230
+ //# sourceMappingURL=rebuild.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rebuild.js","sourceRoot":"","sources":["../../src/session/rebuild.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAK5C,MAAM,OAAO,GAAG,CAAC,MAAwB,EAAkB,EAAE,CAC3D,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAE5E,+GAA+G;AAC/G,MAAM,cAAc;IACT,QAAQ,GAAc,EAAE,CAAC;IAClC,0EAA0E;IACjE,MAAM,GAAa,EAAE,CAAC;IAC/B,KAAK,CAAsB;IAClB,UAAU,CAAsB;IACzC,MAAM,CAA6D;IAEnE,YAAY,SAAS,GAAwB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G,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;SAC3F;QACD,MAAM;KACP,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,SAAS,CAAC,IAA6B;IACrD,OAAO,iBAAiB,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC;AACzC,CAAC","sourcesContent":["/**\n * Rebuilds the SDK's `Context` from a session's entries, so the log is the only state: any process can read the log\n * and go on with `continueRun()`. A message is the `message_block` entries that share a `messageId`, in `index` order;\n * an assistant message is closed by its `message_end` and takes its usage and cost from the `usage` entry right after\n * it. A `usage` entry anywhere else belongs to a call whose message was superseded, and builds no message. A code\n * call is the host's, not the model's, so its entries build no message either.\n */\n\nimport type { AssistantMessage, ContentBlock, Message } from \"@buildanagent/gateway\";\nimport type { SessionEntry } from \"@buildanagent/protocol\";\nimport type { Context, SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { HarnessError } from \"../errors.js\";\n\ntype Block = Extract<SessionEntry, { type: \"message_block\" }>;\ntype Pending = { role: \"user\" | \"assistant\"; id: string; blocks: Block[]; firstId: string };\n\nconst ordered = (blocks: readonly Block[]): ContentBlock[] =>\n [...blocks].sort((a, b) => a.index - b.index).map((entry) => entry.block);\n\n/** Builds messages from entries one at a time, keeping a message open until the entry that ends it arrives. */\nclass MessageBuilder {\n readonly messages: Message[] = [];\n /** The id of the first entry of each message, in step with `messages`. */\n readonly starts: string[] = [];\n #open: Pending | undefined;\n readonly #dropEmpty: ReadonlySet<string>;\n #ended: Extract<SessionEntry, { type: \"message_end\" }> | undefined;\n\n constructor(dropEmpty: ReadonlySet<string> = new Set()) {\n this.#dropEmpty = dropEmpty;\n }\n\n /** Closes the user message being built, if there is one. */\n #closeUser(): void {\n if (this.#open?.role !== \"user\") return;\n this.messages.push({ role: \"user\", content: ordered(this.#open.blocks) });\n this.starts.push(this.#open.firstId);\n this.#open = undefined;\n }\n\n block(entry: Block): void {\n this.#settleEnded(undefined);\n if (this.#open === undefined || this.#open.id !== entry.messageId || this.#open.role !== entry.role) {\n this.#closeUser();\n this.#open = { role: entry.role, id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#open.blocks.push(entry);\n }\n\n /** An assistant message with no usage entry after it still counts, with unknown cost. */\n #settleEnded(usage: Extract<SessionEntry, { type: \"usage\" }> | undefined): void {\n const end = this.#ended;\n const open = this.#open;\n if (end === undefined || open === undefined) return;\n this.#ended = undefined;\n this.#open = undefined;\n // A message whose signed reasoning was left out and that has nothing else would be an empty assistant turn.\n if (open.blocks.length === 0 && this.#dropEmpty.has(open.id)) return;\n const message: AssistantMessage = {\n role: \"assistant\",\n content: ordered(open.blocks),\n model: end.model,\n stopReason: end.stopReason,\n ...(end.error === undefined ? {} : { error: end.error }),\n usage: usage?.usage ?? EMPTY_USAGE,\n ...(usage?.lastAttemptUsage === undefined ? {} : { lastAttemptUsage: usage.lastAttemptUsage }),\n cost: usage?.cost ?? EMPTY_COST,\n };\n this.messages.push(message);\n this.starts.push(open.firstId);\n }\n\n end(entry: Extract<SessionEntry, { type: \"message_end\" }>): void {\n this.#settleEnded(undefined);\n if (this.#open?.role !== \"assistant\" || this.#open.id !== entry.messageId) {\n // A message with no blocks has no open message to close.\n this.#closeUser();\n this.#open = { role: \"assistant\", id: entry.messageId, blocks: [], firstId: entry.id };\n }\n this.#ended = entry;\n }\n\n usage(entry: Extract<SessionEntry, { type: \"usage\" }>): void {\n if (entry.source === \"model_call\" && this.#ended !== undefined) this.#settleEnded(entry);\n }\n\n toolResult(entry: Extract<SessionEntry, { type: \"tool_result\" }>): void {\n this.#settleEnded(undefined);\n this.#closeUser();\n this.messages.push({ role: \"tool\", callId: entry.callId, content: entry.content, isError: entry.isError });\n this.starts.push(entry.id);\n }\n\n finish(): Message[] {\n this.#settleEnded(undefined);\n this.#closeUser();\n return this.messages;\n }\n}\n\n// A message with no usage entry, which a crash between the two writes leaves, has no usage anyone knows.\nconst EMPTY_USAGE: AssistantMessage[\"usage\"] = {\n uncachedInput: 0,\n cacheRead: 0,\n cacheWrite: { \"5m\": 0, \"1h\": 0 },\n output: 0,\n reasoning: 0,\n raw: null,\n};\nconst EMPTY_COST: AssistantMessage[\"cost\"] = { total: null, basis: \"unknown\", currency: \"USD\" };\n\n/** A request that waits for a person, with the input its call would run with once approved. */\nexport interface PendingApproval {\n readonly request: SignedPendingRequest;\n readonly input: unknown;\n}\n\n/**\n * The requests on `path` that still wait: the latest request for each call of the last assistant message, while the call\n * has no result. A resolution does not end a wait, because the run that applies it may refuse it or never finish: only\n * the call's result does. A resume that started and died before the result is a crash, which `crashedResumes()` names,\n * and its requests do not wait.\n */\nexport function pendingApprovals(path: readonly SessionEntry[]): PendingApproval[] {\n const answered = new Set<string>();\n const latest = new Map<string, PendingApproval>();\n let lastMessage: string | undefined;\n let lastCalls = new Set<string>();\n for (const entry of path) {\n if (entry.type === \"tool_result\") answered.add(entry.callId);\n if (entry.type === \"approval_requested\")\n latest.set(entry.request.callId, { request: entry.request, input: entry.input });\n if (entry.type === \"message_block\" && entry.role === \"assistant\") {\n if (entry.messageId !== lastMessage) lastCalls = new Set();\n lastMessage = entry.messageId;\n if (entry.block.type === \"tool_call\") lastCalls.add(entry.block.callId);\n }\n }\n const crashed = crashedResumes(path);\n return [...latest.values()].filter(\n (entry) =>\n lastCalls.has(entry.request.callId) && !answered.has(entry.request.callId) && !crashed.has(entry.request.id),\n );\n}\n\n/**\n * The ids of the requests whose resume started and died: the log ends in a `continue` turn that has no end, after\n * allows were written for it. An approved call may have run, so it is settled as a crash and not asked again, even\n * when the run died before it reached that call.\n */\nexport function crashedResumes(path: readonly SessionEntry[]): Set<string> {\n const start = path.findLastIndex((entry) => entry.type === \"turn_start\");\n const turn = path[start];\n if (turn?.type !== \"turn_start\" || turn.mode !== \"continue\") return new Set();\n if (path.slice(start).some((entry) => entry.type === \"turn_end\")) return new Set();\n // Only the allows this run was given: a deny or an answer runs nothing, and an earlier run's answers are its own.\n const since = path.slice(0, start).findLastIndex((entry) => entry.type === \"turn_end\");\n return new Set(\n path.slice(since + 1, start).flatMap((entry) => {\n const answer = entry.type === \"approval_resolved\" && entry.quorum === undefined ? entry.resolution : undefined;\n return answer !== undefined && \"decision\" in answer && answer.decision === \"allow\" ? [answer.requestId] : [];\n }),\n );\n}\n\nconst isSignedReasoning = (entry: SessionEntry): boolean =>\n entry.type === \"message_block\" && entry.block.type === \"reasoning\" && entry.block.signature !== undefined;\n\n/** The user message that stands for the summarised span, so the model reads the summary where the span was. */\nexport function summaryMessage(summary: string): Message {\n return {\n role: \"user\",\n content: [\n { type: \"text\", text: `The earlier part of this conversation was summarized to save space:\\n\\n${summary}` },\n ],\n };\n}\n\n/**\n * The entries a context is built from, and whether a compaction applies. The latest `compaction` on the path replaces\n * everything before its `firstKeptEntryId`. The kept tail loses its signed reasoning, because a block that follows the\n * edited span would carry a signature the summary made stale; blocks written after the compaction are untouched.\n */\nexport function entriesAfterCompaction(path: readonly SessionEntry[]): {\n readonly entries: readonly SessionEntry[];\n readonly summary: string | undefined;\n /** The ids of messages that lost a signed reasoning block. */\n readonly stripped: ReadonlySet<string>;\n} {\n const at = path.findLastIndex((entry) => entry.type === \"compaction\");\n const compaction = path[at];\n if (compaction?.type !== \"compaction\") return { entries: path, summary: undefined, stripped: new Set() };\n const kept = path.findIndex((entry) => entry.id === compaction.firstKeptEntryId);\n if (kept < 0) {\n throw new HarnessError(\n \"entry_not_found\",\n `the compaction ${compaction.id} keeps from entry ${compaction.firstKeptEntryId}, which is not on this path`,\n );\n }\n // The messages that lose a block here are the only ones an empty result may drop.\n const stripped = new Set<string>();\n const entries = path.slice(kept).filter((entry, i) => {\n const drop = kept + i < at && isSignedReasoning(entry);\n if (drop && entry.type === \"message_block\") stripped.add(entry.messageId);\n return !drop;\n });\n return { entries: entries.filter((entry) => entry.type !== \"compaction\"), summary: compaction.summary, stripped };\n}\n\n/**\n * The context a path of entries stands for, with the id of the entry each message starts at (`null` for a summary).\n * `path` is a session's `path()`: the root to a HEAD, without `checkout` entries. The system prompt is the latest\n * `turn_start`'s, byte for byte, so a harness whose prompt changed later still rebuilds the conversation the model\n * saw. The latest compaction applies: its summary stands first, then the kept tail and what followed it.\n */\nexport function contextWithStarts(path: readonly SessionEntry[]): {\n readonly context: Context;\n readonly starts: readonly (string | null)[];\n} {\n const { entries, summary, stripped } = entriesAfterCompaction(path);\n const builder = new MessageBuilder(stripped);\n let system = \"\";\n for (const entry of path) if (entry.type === \"turn_start\") system = entry.system;\n // A code call's result answers no call the model made, so the model never reads it.\n const codeCalls = new Set(path.flatMap((entry) => (entry.type === \"code_call\" ? [entry.callId] : [])));\n for (const entry of entries) {\n if (entry.type === \"tool_result\" && codeCalls.has(entry.callId)) continue;\n switch (entry.type) {\n case \"message_block\":\n builder.block(entry);\n break;\n case \"message_end\":\n builder.end(entry);\n break;\n case \"usage\":\n builder.usage(entry);\n break;\n case \"tool_result\":\n builder.toolResult(entry);\n break;\n default:\n }\n }\n const built = builder.finish();\n const messages = summary === undefined ? built : [summaryMessage(summary), ...built];\n const starts = summary === undefined ? builder.starts : [null, ...builder.starts];\n const waiting = pendingApprovals(path);\n if (waiting.length === 0) return { context: { system, messages }, starts };\n return {\n context: {\n system,\n messages,\n pending: waiting.map((entry) => entry.request),\n pendingInputs: Object.fromEntries(waiting.map((entry) => [entry.request.id, entry.input])),\n },\n starts,\n };\n}\n\n/** The context a path of entries stands for. See `contextWithStarts()`. */\nexport function contextOf(path: readonly SessionEntry[]): Context {\n return contextWithStarts(path).context;\n}\n"]}
@@ -0,0 +1,26 @@
1
+ import type { SessionEntry, ToolResultEntry } from "@buildanagent/protocol";
2
+ import type { Harness } from "../harness.js";
3
+ type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
4
+ type Body = DistributiveOmit<SessionEntry, "id" | "parentId" | "timestamp" | "origin" | "seq">;
5
+ /** Writes one entry with the origin it names, after the entries before it. */
6
+ export type WriteEntry = (origin: "harness" | "model" | "tool", body: Body) => Promise<unknown>;
7
+ /**
8
+ * The result of a call whose own result never reached the log. A call to a write, or to a tool the registry no longer
9
+ * has, may have taken effect, so its outcome is `unknown`; a read-only call changed nothing, so it gets a plain error.
10
+ */
11
+ export declare function interruptedResult<H>(harness: Harness<H>, name: string): Pick<ToolResultEntry, "content" | "isError" | "details" | "trust">;
12
+ /**
13
+ * The calls the path's assistant blocks make that no `tool_result` answers, in the order the model made them. A turn
14
+ * that ended waiting for an approval or an answer leaves its calls open on purpose, so they are left out unless
15
+ * `includePaused` is set.
16
+ */
17
+ export declare function unansweredCalls(path: readonly SessionEntry[], includePaused?: boolean): {
18
+ callId: string;
19
+ name: string;
20
+ }[];
21
+ /**
22
+ * Settles what a crash left open and returns whether it wrote anything. `closeTurns` is false when HEAD was moved by
23
+ * a checkout, because a turn that has no end on the branch left behind was not interrupted.
24
+ */
25
+ export declare function settleOpenCalls<H>(path: readonly SessionEntry[], harness: Harness<H>, write: WriteEntry, closeTurns: boolean): Promise<boolean>;
26
+ export {};