dal-code 1.0.57 → 1.0.59

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 (275) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/bundle/chunks/{anthropic-messages-ASQGS6BL.js → anthropic-messages-HVFHIIGX.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-ZSCUJBSU.js → azure-openai-responses-RMWKIGFW.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-6SPX3U36.js → chunk-4BOWD7PQ.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-F577XLVZ.js → chunk-4PBY6OYS.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-S7K3JBWA.js → chunk-BBNE2TWS.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-6PQZ4KMC.js → chunk-C5ELI234.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-GPI2GHBH.js → chunk-F52JQCLE.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-MAJODFX6.js → chunk-GZJEAFRS.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-2E7RGBKM.js → chunk-IKSSB5ZJ.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-34D4KVPX.js → chunk-IONGABQF.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-JPCWLZUZ.js → chunk-J6H2LYOZ.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-TNSXMGQB.js → chunk-KQRRELCF.js} +1 -1
  15. package/dist/bundle/chunks/chunk-KT7CXVDN.js +17 -0
  16. package/dist/bundle/chunks/{chunk-YTDTROS5.js → chunk-MPLE6M5C.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-O3XFDBJ3.js → chunk-PMFHJN7I.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-MZ7O6YLD.js → chunk-QU2VEHMW.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-KP7CMLOT.js → chunk-TPOKZ2EU.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-PD6QS7YD.js → chunk-VDPDHGGJ.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-LZTZWS3N.js → chunk-WLQ33LIH.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-FSX34SAZ.js → chunk-X63WCLSX.js} +6 -6
  23. package/dist/bundle/chunks/{chunk-IRSW3MVW.js → chunk-XQF5XDEM.js} +2 -2
  24. package/dist/bundle/chunks/{chunk-XIJS4F22.js → chunk-YOQ3KBG5.js} +1 -1
  25. package/dist/bundle/chunks/{cli-IDAZVEZ2.js → cli-BFWJUYZ5.js} +1 -1
  26. package/dist/bundle/chunks/{cli-NP7QEFQE.js → cli-NQ7B7BGV.js} +1 -1
  27. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-WLKVTF6I.js → cloudflare-workers-ai-system-one-RXFI2EBV.js} +1 -1
  28. package/dist/bundle/chunks/{execute-VXSJSHXH.js → execute-NJRE4WBO.js} +1 -1
  29. package/dist/bundle/chunks/{google-generative-ai-3HIBMVL4.js → google-generative-ai-5F5544G4.js} +1 -1
  30. package/dist/bundle/chunks/{google-vertex-7PIUZFM3.js → google-vertex-4PSVELDG.js} +1 -1
  31. package/dist/bundle/chunks/{llama-cpp-classify-5OLOZHKT.js → llama-cpp-classify-IPNT4VOW.js} +1 -1
  32. package/dist/bundle/chunks/{mcp-GHYUCPI4.js → mcp-F3BQ6MQW.js} +1 -1
  33. package/dist/bundle/chunks/{mistral-conversations-6Y33SI3U.js → mistral-conversations-RSYLYGE4.js} +1 -1
  34. package/dist/bundle/chunks/{office-2JSKOL7V.js → office-UBOUFRAU.js} +1 -1
  35. package/dist/bundle/chunks/{openai-codex-responses-BYGMMTPH.js → openai-codex-responses-OKPZLYIS.js} +1 -1
  36. package/dist/bundle/chunks/{openai-completions-UWYQMOLR.js → openai-completions-BFCQZRZ2.js} +1 -1
  37. package/dist/bundle/chunks/{openai-decisions-I5J7OD62.js → openai-decisions-RJ4MH5XI.js} +1 -1
  38. package/dist/bundle/chunks/{openai-responses-LWVKQGLT.js → openai-responses-PT5MXG3Q.js} +1 -1
  39. package/dist/bundle/chunks/{openrouter-images-BDUFN6XX.js → openrouter-images-ICCH2YHW.js} +1 -1
  40. package/dist/bundle/chunks/{pi-messages-64FHWMQR.js → pi-messages-Z2XWHIYT.js} +1 -1
  41. package/dist/bundle/chunks/{review-OQEOVDLP.js → review-WTYIVWYR.js} +1 -1
  42. package/dist/bundle/chunks/{router-3UQE4LBN.js → router-V3EIAYOF.js} +1 -1
  43. package/dist/bundle/chunks/{runtime-E7KOB62K.js → runtime-FNCZJKOC.js} +1 -1
  44. package/dist/bundle/chunks/{sdk-5V64WBOZ.js → sdk-32L63XRF.js} +1 -1
  45. package/dist/bundle/chunks/sync-Z5USQ7AN.js +21 -0
  46. package/dist/bundle/chunks/{typesafe-system-one-7QFJ5JNW.js → typesafe-system-one-6UYWINOZ.js} +1 -1
  47. package/dist/bundle/chunks/{usage-MG7QDPG2.js → usage-JODQIC2H.js} +1 -1
  48. package/dist/bundle/chunks/{virtual-modules-73ZLFCNE.js → virtual-modules-ERCLFZEY.js} +1 -1
  49. package/dist/bundle/cli-runtime.js +1 -1
  50. package/dist/bundle/index.js +1 -1
  51. package/dist/bundle/rpc-entry.js +1 -1
  52. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  53. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  54. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  55. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  56. package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
  57. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  58. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  59. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  60. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  61. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  62. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  63. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  64. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  65. package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
  66. package/dist/node_modules/@dalcode/dal-learn/src/engine.js +3 -3
  67. package/dist/node_modules/@dalcode/dal-learn/src/index.js +11 -11
  68. package/dist/node_modules/@dalcode/dal-learn/src/lessons.js +4 -4
  69. package/dist/node_modules/@dalcode/dal-learn/src/project-map.js +2 -2
  70. package/dist/node_modules/@dalcode/dal-learn/src/signals.js +6 -6
  71. package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -4
  72. package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -6
  73. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  74. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
  75. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  76. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
  77. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  78. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  79. package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
  80. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  81. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  82. package/dist/node_modules/@dalcode/dal-router/package.json +6 -6
  83. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  84. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  85. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  86. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  87. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  88. package/dist/node_modules/@dalcode/dal-sync/package.json +4 -4
  89. package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -4
  90. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  91. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  92. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  93. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  94. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  95. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  96. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  97. package/dist/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
  98. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  99. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  100. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  101. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  102. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  103. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  104. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  105. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  106. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  107. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  108. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -1
  109. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -1
  110. package/dist/node_modules/@earendil-works/pi-ai/package.json +3 -3
  111. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  112. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  113. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  114. package/dist/node_modules/@earendil-works/pi-schema/package.json +1 -1
  115. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  116. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  117. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  118. package/examples/extensions/gondolin/package-lock.json +2 -2
  119. package/examples/extensions/gondolin/package.json +1 -1
  120. package/examples/extensions/with-deps/package-lock.json +2 -2
  121. package/examples/extensions/with-deps/package.json +1 -1
  122. package/npm-shrinkwrap.json +2 -2
  123. package/package.json +1 -1
  124. package/dist/bun/register-bedrock.js +0 -1
  125. package/dist/bundle/chunks/chunk-JPBJUBY4.js +0 -17
  126. package/dist/bundle/chunks/sync-INSWGFSB.js +0 -21
  127. package/dist/cli/experimental/auth.js +0 -1
  128. package/dist/cli/experimental/cli.js +0 -1
  129. package/dist/cli/experimental/command-options.js +0 -1
  130. package/dist/cli/experimental/command.js +0 -1
  131. package/dist/cli/experimental/commands/client.js +0 -1
  132. package/dist/cli/experimental/commands/pi.js +0 -1
  133. package/dist/cli/experimental/commands/server.js +0 -1
  134. package/dist/cli/experimental/transport-address.js +0 -1
  135. package/dist/client/index.js +0 -1
  136. package/dist/client/remote-session.js +0 -1
  137. package/dist/client/transcript.js +0 -1
  138. package/dist/core/provider-attribution.js +0 -1
  139. package/dist/modes/interactive/components/daxnuts.js +0 -1
  140. package/dist/modes/interactive/theme/theme-json.js +0 -12
  141. package/dist/modes/interactive/theme/theme-schema.json +0 -356
  142. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js +0 -1
  143. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js +0 -37
  144. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js +0 -104
  145. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/utils.js +0 -16
  146. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/config.js +0 -1
  147. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/context.js +0 -1
  148. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js +0 -10
  149. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/events.js +0 -1
  150. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/assistant.js +0 -1
  151. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/effect-gate.js +0 -1
  152. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/tools.js +0 -1
  153. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/hooks.js +0 -1
  154. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.js +0 -17
  155. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bash.js +0 -1
  156. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bounded.js +0 -1
  157. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/chord.js +0 -1
  158. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/context.js +0 -1
  159. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/harness.js +0 -1
  160. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/hooks.js +0 -1
  161. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/index.js +0 -1
  162. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/jsonl.js +0 -4
  163. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/collapse.js +0 -3
  164. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/entries.js +0 -1
  165. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/frames.js +0 -1
  166. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/generation.js +0 -1
  167. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/job.js +0 -1
  168. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/plugin.js +0 -1
  169. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/post-tools.js +0 -1
  170. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/task-api.js +0 -1
  171. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/tool.js +0 -3
  172. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/membrane.js +0 -1
  173. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/memory.js +0 -1
  174. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/scheduler.js +0 -1
  175. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/session.js +0 -1
  176. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/system.js +0 -8
  177. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/types.js +0 -1
  178. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/view.js +0 -1
  179. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/prompt-templates.js +0 -5
  180. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js +0 -1
  181. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/result.js +0 -1
  182. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/boundary.js +0 -1
  183. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/checkpoint.js +0 -1
  184. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/deferred.js +0 -1
  185. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/generation.js +0 -1
  186. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/reconcile.js +0 -1
  187. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/recovery.js +0 -1
  188. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/response.js +0 -1
  189. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/retry.js +0 -1
  190. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/structural.js +0 -1
  191. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/terminal.js +0 -1
  192. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tool-placement.js +0 -1
  193. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tools.js +0 -1
  194. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive.js +0 -1
  195. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/harness.js +0 -1
  196. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/index.js +0 -1
  197. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/lane.js +0 -1
  198. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/progress.js +0 -1
  199. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/reducer.js +0 -1
  200. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/restore.js +0 -1
  201. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/transcript.js +0 -1
  202. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/types.js +0 -1
  203. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/commit.js +0 -1
  204. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.js +0 -1
  205. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork-policy.js +0 -1
  206. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork.js +0 -1
  207. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/in-memory-storage-state.js +0 -1
  208. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/index.js +0 -1
  209. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js +0 -1
  210. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.js +0 -1
  211. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/fork.js +0 -1
  212. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/index.js +0 -1
  213. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/io.js +0 -3
  214. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/legacy-v3.js +0 -1
  215. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/repo.js +0 -1
  216. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/storage.js +0 -8
  217. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/types.js +0 -1
  218. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-repo.js +0 -1
  219. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-storage.js +0 -5
  220. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl.js +0 -1
  221. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-repo.js +0 -1
  222. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-storage.js +0 -1
  223. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory.js +0 -1
  224. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/mutation-line.js +0 -1
  225. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/repo-utils.js +0 -1
  226. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.js +0 -1
  227. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/state.js +0 -1
  228. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/datasets.js +0 -1
  229. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/session-repo.js +0 -1
  230. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/storage.js +0 -1
  231. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/session-repo.js +0 -1
  232. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/storage.js +0 -1
  233. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance.js +0 -1
  234. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/gating-storage.js +0 -1
  235. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/index.js +0 -1
  236. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/instrumented-storage.js +0 -1
  237. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/storage-decorator.js +0 -1
  238. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/types.js +0 -0
  239. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.js +0 -1
  240. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/values.js +0 -1
  241. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/skills.js +0 -10
  242. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/system-prompt.js +0 -2
  243. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/telemetry.js +0 -1
  244. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/bash.js +0 -12
  245. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit-diff.js +0 -16
  246. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js +0 -1
  247. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/file-mutation-queue.js +0 -1
  248. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/image.js +0 -1
  249. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.js +0 -1
  250. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/path-utils.js +0 -1
  251. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/read.js +0 -14
  252. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.js +0 -0
  253. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js +0 -1
  254. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/types.js +0 -1
  255. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/adaptive-publisher.js +0 -1
  256. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/output-capture.js +0 -5
  257. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/shell-output.js +0 -1
  258. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/truncate.js +0 -5
  259. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/usage.js +0 -1
  260. package/dist/node_modules/@earendil-works/pi-agent-core/dist/node.js +0 -1
  261. package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/index.js +0 -0
  262. package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.js +0 -1
  263. package/dist/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.js +0 -1
  264. package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/oauth-page.js +0 -74
  265. package/dist/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +0 -1
  266. package/dist/node_modules/@earendil-works/pi-ai/dist/images-models.js +0 -1
  267. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.js +0 -1
  268. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.models.js +0 -1
  269. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter-images.js +0 -1
  270. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.js +0 -1
  271. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/deferred-tools.js +0 -1
  272. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js +0 -1
  273. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/typebox-helpers.js +0 -1
  274. package/dist/server/create-harness.js +0 -1
  275. package/dist/utils/clipboard-native.js +0 -1
@@ -1 +0,0 @@
1
- var d=Object.defineProperty;var r=(e,t)=>d(e,"name",{value:t,configurable:!0});function c(e){return{kind:"entry",entry:e}}r(c,"insertEntry");function y(e){return{kind:"usage",row:e}}r(y,"insertUsage");function p(e,t,a){switch(e.kind){case"entry":return{kind:"entry",...e.entry,seq:t,timestamp:a};case"usage":return{kind:"usage",...e.row,seq:t};case"value":return e.op==="set"?{kind:"value",op:"set",seq:t,namespace:e.namespace,key:e.key,value:e.value}:{kind:"value",op:"delete",seq:t,namespace:e.namespace,key:e.key};case"list":return e.op==="append"?{kind:"list",op:"append",seq:t,namespace:e.namespace,key:e.key,value:e.value}:{kind:"list",op:"delete",seq:t,namespace:e.namespace,key:e.key}}}r(p,"commitWrite");function k(e,t,a){return{...e,seq:t,timestamp:a}}r(k,"materializeCommittedEntry");function m(e,t,a){const s=e.map((o,i)=>p(o,t+i,a));return{writes:s,result:{firstSeq:t,seqs:s.map(o=>o.seq),timestamp:a}}}r(m,"prepareStorageCommit");function l(e,t,a){let s=t-1;const o=new Set,i=new Set;for(const n of e){if(n.seq<=s)throw new Error(`Non-monotonic storage sequence: ${n.seq}`);if(s=n.seq,!(n.kind!=="entry"&&n.kind!=="usage")){if(a.hasEntryOrUsageId(n.id)||o.has(n.id))throw new Error(`Duplicate entry or usage id: ${n.id}`);if(n.kind==="entry"&&n.parentId!==null&&!a.hasEntryId(n.parentId)&&!i.has(n.parentId))throw new Error(`Missing parent entry: ${n.parentId}`);o.add(n.id),n.kind==="entry"&&i.add(n.id)}}}r(l,"validateCommittedWrites");export{p as commitWrite,c as insertEntry,y as insertUsage,k as materializeCommittedEntry,m as prepareStorageCommit,l as validateCommittedWrites};
@@ -1 +0,0 @@
1
- var m=Object.defineProperty;var n=(e,o)=>m(e,"name",{value:o,configurable:!0});import{createBranchSummaryMessage as u,createCompactionSummaryMessage as f}from"../messages.js";function p(e){let o,r=-1;for(let t=e.length-1;t>=0;t--){const s=e[t];if(s?.type==="compaction"){o=s,r=t;break}}return o===void 0?[...e]:[o,...e.slice(r+1)]}n(p,"buildContextEntries");function i(e){return e.role!=="assistant"||e.stopReason!=="error"&&e.stopReason!=="aborted"&&e.stopReason!=="deferred"}n(i,"isContextMessage");function d(e){switch(e.type){case"message":return i(e.message)?[e.message]:[];case"compaction":return[f(e.summary,e.tokensBefore,e.timestamp),...e.retainedTail.filter(i)];case"branch_summary":return e.summary?[u(e.summary,e.fromId,e.timestamp)]:[];case"custom":return[]}}n(d,"sessionEntryToContextMessages");async function g(e,o,r){o??={};const t=p(e),s=[];for(const a of t){if(a.type!=="custom"){s.push(...d(a));continue}const c=o.entryProjectors?.[a.customType];c!==void 0&&s.push(...await c(a,r)??[])}return s}n(g,"buildSessionContext");export{p as buildContextEntries,g as buildSessionContext,d as sessionEntryToContextMessages};
@@ -1 +0,0 @@
1
- var u=Object.defineProperty;var i=(e,n)=>u(e,"name",{value:n,configurable:!0});function d(e,n){if(n.tip===void 0)throw new Error(`Unknown source branch: ${e.branch}`);const t=e.entryId??n.tip;let a=t===null,s=null,r=n.tip;for(;r!==null;){const c=n.getParent(r);if(c===void 0)throw new Error(`Corrupt source branch: missing parent ${r}`);r===t?(a=!0,s=e.position==="before"?c:r,e.position!=="before"&&n.selectEntry(r)):a&&n.selectEntry(r),r=c}if(!a)throw new Error(`Fork entry ${t} is not on source branch ${JSON.stringify(e.branch)}`);return{scope:"branch",branch:e.branch,destinationTip:s}}i(d,"selectBranchFork");function p(e,n,t){switch(e.namespace){case"pi.session.name":return e;case"pi.entry.label":return t(e.key)?e:void 0;case"pi.branch.tip":return n.scope==="tree"?e:e.key===n.branch?{...e,value:n.destinationTip}:void 0;case"pi.lane.config":return n.scope==="tree"||e.key===n.branch?e:void 0;case"pi.lane.state":return n.scope==="tree"||e.key===n.branch?{...e,value:{currentOperationId:null,lastOperationId:null,inbox:[]}}:void 0;case"pi.result":return}if(!(e.namespace.startsWith("pi.op.")||e.namespace.startsWith("pi.pending."))){if(e.namespace==="pi"||e.namespace.startsWith("pi."))throw new Error(`Unknown reserved fork namespace: ${e.namespace}`);return n.scope==="tree"?e:void 0}}i(p,"projectForkCurrentStateWrite");export{p as projectForkCurrentStateWrite,d as selectBranchFork};
@@ -1 +0,0 @@
1
- var k=Object.defineProperty;var o=(e,r)=>k(e,"name",{value:r,configurable:!0});import{projectForkCurrentStateWrite as y,selectBranchFork as S}from"./fork-policy.js";import{branchTip as w,laneConfig as u,laneState as p,value as g}from"./values.js";function v(e,r){return e.filter(s=>s.address.namespace===r.namespace)}o(v,"storedValuesInNamespace");function h(e,r){return e.find(s=>s.address.namespace===r.namespace&&s.address.key===r.key)}o(h,"findStoredValue");function N(e,r){const s=new Map(e.entries.map(c=>[c.id,c])),t=v(e.scalarValues,w(""));V(e,s,t,r);const{entryIds:d,plan:a}=b(s,t,r),n=new Map;for(const c of d)n.set(c,s.get(c));const i=[];let f=Math.max(0,...[...n.values()].map(c=>c.seq))+1;for(const c of e.scalarValues){const l=y({kind:"value",op:"set",seq:c.seq,namespace:c.address.namespace,key:c.address.key,value:c.value},a,m=>d.has(m));l!==void 0&&i.push({address:g(l.namespace,l.key),value:l.value,seq:f++})}return{entries:n,scalarValues:i,nextSeq:f}}o(N,"createForkSnapshot");function b(e,r,s){const t=new Set;if(s.scope==="tree"){for(const n of e.keys())t.add(n);return{entryIds:t,plan:{scope:"tree"}}}const d=r.find(n=>n.address.key===s.branch),a=S(s,{tip:d?.value,getParent:o(n=>e.get(n)?.parentId,"getParent"),selectEntry:o(n=>t.add(n),"selectEntry")});return{entryIds:t,plan:a}}o(b,"selectForkContents");function V(e,r,s,t){const d=new Set(s.map(a=>a.address.key));for(const a of e.scalarValues)if((a.address.namespace===u("").namespace||a.address.namespace===p("").namespace)&&!d.has(a.address.key))throw new Error(`Source session branch ${JSON.stringify(a.address.key)} is missing branch.tip`);for(const a of s){const n=h(e.scalarValues,u(a.address.key)),i=h(e.scalarValues,p(a.address.key));if(n===void 0!=(i===void 0))throw new Error(`Source session branch ${JSON.stringify(a.address.key)} has incomplete lane state`);if(t.scope==="branch"&&a.address.key===t.branch&&n===void 0)throw new Error(`Source branch ${JSON.stringify(t.branch)} is not a configured AgentLane`);if((e.entriesComplete!==!1||t.scope==="tree")&&a.value!==null&&!r.has(a.value))throw new Error(`Source session branch ${JSON.stringify(a.address.key)} has an unknown tip`)}}o(V,"validateForkSourceSnapshot");export{N as createForkSnapshot};
@@ -1 +0,0 @@
1
- var h=Object.defineProperty;var o=(d,e)=>h(d,"name",{value:e,configurable:!0});import{addUsage as f,emptyUsage as m}from"../utils/usage.js";import{prepareStorageCommit as g,validateCommittedWrites as S}from"./commit.js";import{projectForkCurrentStateWrite as u,selectBranchFork as k}from"./fork-policy.js";import{branchTip as y,laneConfig as v,laneState as V,list as q,resolveListReadOptions as I,value as b}from"./values.js";function l(d,e){return`${d}\0${e}`}o(l,"physicalKey");function x(d,e){const t=Array.from(d,r=>r.codePointAt(0)),s=Array.from(e,r=>r.codePointAt(0)),n=Math.min(t.length,s.length);for(let r=0;r<n;r++){const a=t[r]-s[r];if(a!==0)return a}return t.length-s.length}o(x,"compareKeys");class p{static{o(this,"InMemoryStorageState")}entries;entriesBySeq;scalarValues;listValues;usage;stats;nextSeq;constructor(){this.entries=new Map,this.entriesBySeq=[],this.scalarValues=new Map,this.listValues=new Map,this.usage=new Map,this.stats={messageCount:0,usage:m()},this.nextSeq=1}prepareCommit(e,t){const s=g(e,this.nextSeq,t);return this.validateCommitted(s.writes),s}validateCommitted(e){S(e,this.nextSeq,{hasEntryOrUsageId:o(t=>this.entries.has(t)||this.usage.has(t),"hasEntryOrUsageId"),hasEntryId:o(t=>this.entries.has(t),"hasEntryId")})}applyValidated(e){for(const t of e){switch(t.kind){case"entry":{const{kind:s,...n}=t;this.entries.set(n.id,n),this.entriesBySeq.push(n),n.type==="message"&&(this.stats={...this.stats,messageCount:this.stats.messageCount+1});break}case"usage":{const{kind:s,...n}=t;this.usage.set(n.id,n),this.stats={...this.stats,usage:f(this.stats.usage,n.usage)};break}case"value":t.op==="delete"?this.scalarValues.delete(l(t.namespace,t.key)):this.applyValueSetOrListAppend(t);break;case"list":t.op==="delete"?this.listValues.delete(l(t.namespace,t.key)):this.applyValueSetOrListAppend(t);break}this.nextSeq=t.seq+1}return this.stats}createFork(e){const t=this.selectForkPlan(e),s=o(a=>t.scope==="tree"?!0:t.entryIds.has(a),"isEntryCopied"),n=new p;let r=0;for(const a of this.entriesBySeq)s(a.id)&&(n.entries.set(a.id,a),n.entriesBySeq.push(a),a.type==="message"&&r++);n.stats={...n.stats,messageCount:r};for(const a of this.scalarValues.values()){const i=u({kind:"value",op:"set",seq:a.seq,namespace:a.address.namespace,key:a.address.key,value:a.value},t,s);i!==void 0&&n.applyValueSetOrListAppend(i)}for(const a of this.listValues.values())for(const i of a.elements){const c=u({kind:"list",op:"append",seq:i.seq,namespace:a.address.namespace,key:a.address.key,value:i.value},t,s);c!==void 0&&n.applyValueSetOrListAppend(c)}return n.nextSeq=this.nextSeq,n}selectForkPlan(e){if(e.scope==="tree")return{scope:"tree"};const t=new Set,s=k(e,{tip:this.getValue(y(e.branch))?.value,getParent:o(n=>this.entries.get(n)?.parentId,"getParent"),selectEntry:o(n=>t.add(n),"selectEntry")});if(this.getValue(v(e.branch))===void 0||this.getValue(V(e.branch))===void 0)throw new Error(`Source branch ${JSON.stringify(e.branch)} is not a configured AgentLane`);return{...s,entryIds:t}}applyValueSetOrListAppend(e){const t=l(e.namespace,e.key);if(e.kind==="value"){this.scalarValues.set(t,{address:b(e.namespace,e.key),value:e.value,seq:e.seq});return}const s={seq:e.seq,value:e.value},n=this.listValues.get(t);n===void 0?this.listValues.set(t,{address:q(e.namespace,e.key),elements:[s]}):n.elements.push(s)}advanceNextSeq(e){if(!Number.isSafeInteger(e)||e<1)throw new Error(`Invalid storage sequence high-water mark: ${e}`);this.nextSeq=Math.max(this.nextSeq,e)}getEntries(e){const t=new Map;for(const s of e){const n=this.entries.get(s);n!==void 0&&t.set(s,n)}return t}getValue(e){return this.scalarValues.get(l(e.namespace,e.key))}scanValues(e){return[...this.scalarValues.values()].filter(t=>t.address.namespace===e.namespace&&t.address.key.startsWith(e.key)).sort((t,s)=>x(t.address.key,s.address.key))}readList(e,t){const s=I(t),r=(this.listValues.get(l(e.namespace,e.key))?.elements??[]).filter(i=>s.cursor===void 0?!0:s.order==="asc"?i.seq>s.cursor.seq:i.seq<s.cursor.seq);return(s.order==="asc"?r:[...r].reverse()).slice(0,s.limit)}scanBranch(e){const t=this.entries.get(e.start);if(t===void 0)throw new Error(`Unknown branch start: ${e.start}`);const s=[];let n=t;for(;n!==void 0&&(s.push(n),n.parentId!==null);)if(n=this.entries.get(n.parentId),n===void 0)throw new Error("Corrupt branch: missing parent");e.order==="oldestFirst"&&s.reverse();const r=[];for(const i of s)if(r.push(i),i.id===e.stopAtId||i.type===e.stopAtType)break;const a=r.filter(i=>e.type===void 0||i.type===e.type).filter(i=>e.customType===void 0||i.customType===e.customType).filter(i=>e.cursor===void 0||(e.order==="oldestFirst"?i.seq>e.cursor.seq:i.seq<e.cursor.seq));return e.limit===void 0?a:a.slice(0,Math.max(0,e.limit))}scanBranchStructure(e){return this.scanBranch(e).map(t=>({id:t.id,parentId:t.parentId,seq:t.seq,timestamp:t.timestamp,type:t.type,...t.customType===void 0?{}:{customType:t.customType}}))}scanEntries(e){const t=e.limit===void 0?Number.POSITIVE_INFINITY:Math.max(0,Math.trunc(e.limit)),s=[],n=e.order==="desc";let r=n?this.entriesBySeq.length-1:0;for(;r>=0&&r<this.entriesBySeq.length&&s.length<t;){const a=this.entriesBySeq[r];(e.type===void 0||a.type===e.type)&&(e.customType===void 0||a.customType===e.customType)&&(e.fromSeq===void 0||a.seq>=e.fromSeq)&&(e.toSeq===void 0||a.seq<=e.toSeq)&&s.push(a),r+=n?-1:1}return s}scanUsage(e){const t=[...this.usage.values()].filter(s=>e.fromSeq===void 0||s.seq>=e.fromSeq).filter(s=>e.toSeq===void 0||s.seq<=e.toSeq).sort((s,n)=>e.order==="desc"?n.seq-s.seq:s.seq-n.seq);return e.limit===void 0?t:t.slice(0,Math.max(0,e.limit))}getStats(){return this.stats}getNextSeq(){return this.nextSeq}}export{p as InMemoryStorageState};
@@ -1 +0,0 @@
1
- import{commitWrite as e,insertEntry as t,insertUsage as s,prepareStorageCommit as n,validateCommittedWrites as i}from"./commit.js";import{createForkSnapshot as m}from"./fork.js";import{projectForkCurrentStateWrite as p}from"./fork-policy.js";import{JSONL_STORAGE_VERSION as E,JsonlSessionRepo as f}from"./jsonl/index.js";import{MemorySessionRepo as g}from"./memory.js";import{SessionBranchExistsError as k,SessionInvalidBranchError as R,SessionInvariantError as h,SessionPendingAssistantMessageError as l,SessionUnknownTargetError as v,StorageBackedSession as B}from"./session.js";export*from"./types.js";export*from"./values.js";export{E as JSONL_STORAGE_VERSION,f as JsonlSessionRepo,g as MemorySessionRepo,k as SessionBranchExistsError,R as SessionInvalidBranchError,h as SessionInvariantError,l as SessionPendingAssistantMessageError,v as SessionUnknownTargetError,B as StorageBackedSession,e as commitWrite,m as createForkSnapshot,t as insertEntry,s as insertUsage,n as prepareStorageCommit,p as projectForkCurrentStateWrite,i as validateCommittedWrites};
@@ -1 +0,0 @@
1
- var f=Object.defineProperty;var t=(e,r)=>f(e,"name",{value:r,configurable:!0});import{err as s,ok as i}from"../../types.js";import{JSONL_FORMAT_VERSION as p}from"./types.js";function o(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}t(o,"isRecord");function n(e,r){return Number.isSafeInteger(e)&&e>=r}t(n,"isSafeIntegerAtLeast");function S(e){return o(e)&&e.type==="session"&&e.version===3&&typeof e.id=="string"&&typeof e.cwd=="string"&&typeof e.timestamp=="string"&&Number.isFinite(Date.parse(e.timestamp))&&(e.parentSession===void 0||typeof e.parentSession=="string")}t(S,"isLegacyV3SessionHeader");function a(e){return o(e)&&e.kind==="header"&&e.v===p&&typeof e.id=="string"&&typeof e.cwd=="string"&&n(e.storageVersion,1)&&n(e.createdAt,0)&&(e.nextSeq===void 0||n(e.nextSeq,1))&&(e.parentSessionId===void 0||typeof e.parentSessionId=="string")&&(e.legacyParentSessionPath===void 0||typeof e.legacyParentSessionPath=="string")}t(a,"isJsonlStorageHeader");function m(e){let r;try{r=JSON.parse(e)}catch(d){return s(new Error("Invalid JSONL session header: not valid JSON",{cause:d}))}return a(r)?i({format:"v4",header:r}):S(r)?i({format:"v3-legacy",header:r}):s(new Error("Unsupported JSONL session header"))}t(m,"parseJsonlSessionHeader");export{a as isJsonlStorageHeader,S as isLegacyV3SessionHeader,m as parseJsonlSessionHeader};
@@ -1 +0,0 @@
1
- var t=Object.defineProperty;var o=(r,e)=>t(r,"name",{value:e,configurable:!0});import{SessionError as d}from"../types.js";class a extends Error{static{o(this,"JsonlDecodeError")}kind;constructor(e,n,i){super(n,i===void 0?void 0:{cause:i}),this.name="JsonlDecodeError",this.kind=e}}function l(r,e){if(!r.ok)throw new d(r.error.code==="not_found"?"not_found":"storage",`${e}: ${r.error.message}`,r.error);return r.value}o(l,"fileResult");function c(r,e,n){return new d("invalid_entry",`Invalid JSONL v4 session ${r}: line ${e} ${n.message}`,n)}o(c,"invalidFile");export{a as JsonlDecodeError,l as fileResult,c as invalidFile};
@@ -1 +0,0 @@
1
- var k=Object.defineProperty;var i=(t,e)=>k(t,"name",{value:e,configurable:!0});import{projectForkCurrentStateWrite as h,selectBranchFork as g}from"../fork-policy.js";import{fileValue as f,parseJsonlTransaction as m,publishJsonl as q,readJsonlHeader as v}from"./io.js";import{JSONL_STORAGE_VERSION as w}from"./types.js";function l(t,e){return`${t}\0${e}`}i(l,"physicalKey");async function y(t,e,a){const r=await v(t,e.path,a);if(r.format!=="v4")throw new Error(`Invalid JSONL storage ${e.path}: expected format 4 header`);const n=r.header;if(n.id!==e.id||n.cwd!==e.cwd)throw new Error(`Session identity does not match header: ${e.id}`);if(n.storageVersion!==w)throw new Error(`Session ${e.id} uses unsupported storage version ${n.storageVersion}`);return n}i(y,"readJsonlForkHeader");function L(t,e){if(e===void 0||t.length===0)return!1;const a=t[0],r=t.at(-1);if(a.seq>=e)return!0;if(r.seq>=e)throw new Error(`JSONL transaction crosses fork sequence boundary ${e}`);return!1}i(L,"reachesForkBoundary");async function*p(t,e,a,r){for(;;){const n=f(await t.readLine(r),`Failed to read JSONL fork source ${e}`);if(n===void 0||!n.terminated)break;const s=m(n.text);if(L(s,a))break;yield s}}i(p,"readJsonlForkTransactions");class b{static{i(this,"JsonlForkIndex")}currentScalarSeqs=new Map;branchTips=new Map;firstSurvivingListSeqs=new Map;entryParents=new Map;copiedEntryIds=new Set;laneConfigs=new Set;laneStates=new Set;applyEntry(e,a){this.entryParents.set(e,a)}applyWrites(e){for(const a of e)switch(a.kind){case"entry":this.applyEntry(a.id,a.parentId);break;case"value":{const r=l(a.namespace,a.key);a.op==="delete"?this.currentScalarSeqs.delete(r):this.currentScalarSeqs.set(r,a.seq),this.applyLaneValue(a);break}case"list":{const r=l(a.namespace,a.key);a.op==="delete"?this.firstSurvivingListSeqs.delete(r):this.firstSurvivingListSeqs.has(r)||this.firstSurvivingListSeqs.set(r,a.seq);break}case"usage":break}}applyLaneValue(e){const a=e.op==="set";switch(e.namespace){case"pi.branch.tip":a?this.branchTips.set(e.key,e.value):this.branchTips.delete(e.key);break;case"pi.lane.config":a?this.laneConfigs.add(e.key):this.laneConfigs.delete(e.key);break;case"pi.lane.state":a?this.laneStates.add(e.key):this.laneStates.delete(e.key);break}}getBranchTip(e){return this.branchTips.get(e)}hasCompleteLane(e){return this.laneConfigs.has(e)&&this.laneStates.has(e)}getCurrentScalarSeq(e,a){return this.currentScalarSeqs.get(l(e,a))}isSurvivingListElement(e,a,r){const n=this.firstSurvivingListSeqs.get(l(e,a));return n!==void 0&&r>=n}getParent(e){return this.entryParents.get(e)}selectEntry(e){this.copiedEntryIds.add(e)}isEntrySelected(e){return this.copiedEntryIds.has(e)}}function E(t,e){if(e.scope==="tree")return{scope:"tree"};const a=g(e,{tip:t.getBranchTip(e.branch),getParent:i(r=>t.getParent(r),"getParent"),selectEntry:i(r=>t.selectEntry(r),"selectEntry")});if(!t.hasCompleteLane(e.branch))throw new Error(`Source branch ${JSON.stringify(e.branch)} is not a configured AgentLane`);return a}i(E,"selectJsonlFork");function J(t,e,a,r){switch(t.kind){case"entry":return r(t.id)?t:void 0;case"value":return t.op!=="set"||e.getCurrentScalarSeq(t.namespace,t.key)!==t.seq?void 0:h(t,a,r);case"list":return t.op!=="append"||!e.isSurvivingListElement(t.namespace,t.key,t.seq)?void 0:h(t,a,r);case"usage":return}}i(J,"projectJsonlForkWrite");async function F(t,e,a){const r=new b;if(t.kind==="legacy-v3"){for(const s of t.normalized.entryStructures())r.applyEntry(s.id,s.parentId);return r.applyWrites(t.normalized.values),{index:r,nextSeq:t.normalized.nextSeq}}const n=f(await e.openTextLineReader(t.metadata.path,a),`Failed to open JSONL fork source ${t.metadata.path}`);try{const s=await y(n,t.metadata,a),d=t.kind==="open"?t.nextSeq:void 0;let o=0;for await(const c of p(n,t.metadata.path,d,a))r.applyWrites(c),c.length!==0&&(o=c.at(-1).seq);return{index:r,nextSeq:t.kind==="open"?t.nextSeq:Math.max(s.nextSeq??1,o+1)}}finally{await n.close(a)}}i(F,"indexForkInput");async function*I(t,e,a,r,n){if(t.kind==="legacy-v3"){yield*t.normalized.writes(n,r);return}const s=f(await e.openTextLineReader(t.metadata.path,n),`Failed to open JSONL fork source ${t.metadata.path}`);try{await y(s,t.metadata,n);for await(const d of p(s,t.metadata.path,a,n))yield*d}finally{await s.close(n)}}i(I,"streamForkWrites");async function N(t,e){const{index:a,nextSeq:r}=await F(t.input,t.fileSystem,e);let n=t.fork;t.input.kind==="legacy-v3"&&n.scope==="branch"&&n.entryId!==void 0&&(n={...n,entryId:t.input.normalized.translateForkEntryId(n.entryId)});const s=E(a,n),d=i(o=>s.scope==="tree"?!0:a.isEntrySelected(o),"isEntryCopied");await q(t.fileSystem,t.destinationPath,{...t.destinationHeader,nextSeq:r},e,async o=>{const c=I(t.input,t.fileSystem,r,d,e);for await(const S of c){const u=J(S,a,s,d);u!==void 0&&await o([u])}})}i(N,"runJsonlFork");export{N as runJsonlFork};
@@ -1 +0,0 @@
1
- export*from"./repo.js";export*from"./storage.js";export*from"./types.js";
@@ -1,3 +0,0 @@
1
- var p=Object.defineProperty;var i=(r,e)=>p(r,"name",{value:e,configurable:!0});import{parseJsonlSessionHeader as w}from"./codec.js";function s(r,e){if(!r.ok)throw new Error(`${e}: ${r.error.message}`,{cause:r.error});return r.value}i(s,"fileValue");async function N(r,e,t){const o=s(await r.readLine(t),`Failed to read JSONL storage ${e}`);if(o===void 0||!o.terminated||o.text==="")throw new Error(`Invalid JSONL storage ${e}: missing header`);const n=w(o.text);if(!n.ok)throw new Error(`Invalid JSONL storage ${e}: invalid header`,{cause:n.error});return n.value}i(N,"readJsonlHeader");function f(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}i(f,"isRecord");function c(r,e,t){if(!Number.isSafeInteger(r)||r<t)throw new Error(`Invalid JSONL ${e}`)}i(c,"requireSafeInteger");function l(r){if(!f(r))throw new Error("Invalid JSONL transaction write");switch(c(r.seq,"write seq",1),r.kind){case"entry":return c(r.timestamp,"entry timestamp",0),r;case"usage":return r;case"value":if(r.op==="set"||r.op==="delete")return r;throw new Error(`Invalid JSONL value operation: ${String(r.op)}`);case"list":if(r.op==="append"||r.op==="delete")return r;throw new Error(`Invalid JSONL list operation: ${String(r.op)}`);default:throw new Error(`Invalid JSONL write kind: ${String(r.kind)}`)}}i(l,"parseCommittedWrite");function O(r){let e;try{e=JSON.parse(r)}catch(t){throw new Error("Invalid JSONL transaction: not valid JSON",{cause:t})}return(Array.isArray(e)?e:[e]).map(l)}i(O,"parseJsonlTransaction");function J(r){return JSON.stringify(r.length===1?r[0]:r)}i(J,"serializeJsonlTransaction");async function S(r,e,t,o){const n=`${e}.tmp`;try{s(await r.writeFile(n,"",t),`Failed to stage JSONL storage ${e}`),await o(async a=>{s(await r.appendFile(n,a,t),`Failed to append JSONL storage ${e}`)}),s(await r.renameFile(n,e,t),`Failed to publish JSONL storage ${e}`)}catch(a){throw await r.remove(n,{force:!0},t),a}}i(S,"publishFileAtomically");async function m(r,e,t,o,n){await S(r,e,o,async a=>{await a(`${JSON.stringify(t)}
2
- `),await n(d=>a(`${J(d)}
3
- `))})}i(m,"publishJsonl");export{s as fileValue,O as parseJsonlTransaction,S as publishFileAtomically,m as publishJsonl,N as readJsonlHeader,J as serializeJsonlTransaction};
@@ -1 +0,0 @@
1
- var S=Object.defineProperty;var c=(e,t)=>S(e,"name",{value:t,configurable:!0});import{uuidv7 as k}from"@earendil-works/pi-ai/utils/uuid";import{createBranchSummaryMessage as b,createCompactionSummaryMessage as E}from"../../messages.js";import{addUsage as T,emptyUsage as q}from"../../utils/usage.js";import{branchTip as x,entryLabel as M,laneConfig as N,laneState as V,sessionName as $,setValue as p}from"../values.js";import{parseJsonlSessionHeader as O}from"./codec.js";import{fileValue as f,readJsonlHeader as h}from"./io.js";import{JSONL_FORMAT_VERSION as R,JSONL_STORAGE_VERSION as C}from"./types.js";async function H(e,t,a){const s=await e.readTextLines(t,{maxLines:1},a);if(!s.ok||s.value[0]===void 0)return;const n=O(s.value[0]);return n.ok?n.value.header.id:void 0}c(H,"resolveLegacyV3ParentSessionId");async function J(e,t,a){const s={id:t.id,createdAt:Date.parse(t.timestamp),storageVersion:C,cwd:t.cwd};if(t.parentSession!==void 0){const n=await H(e,t.parentSession,a);n!==void 0?s.parentSessionId=n:s.legacyParentSessionPath=t.parentSession}return s}c(J,"metadataFromLegacyV3Header");async function U(e,t,a){return{v:R,kind:"header",...await J(e,t,a)}}c(U,"normalizeLegacyV3Header");function y(e){let t;try{t=JSON.parse(e)}catch(s){throw new Error("Invalid legacy v3 JSONL record: not valid JSON",{cause:s})}const a=t?.type;if(a!=="message"&&a!=="custom"&&a!=="custom_message"&&a!=="branch_summary"&&a!=="compaction"&&a!=="model_change"&&a!=="thinking_level_change"&&a!=="active_tools_change"&&a!=="session_info"&&a!=="label")throw new Error(`Unsupported legacy v3 record type: ${String(a)}`);return t}c(y,"parseLegacyV3Entry");function v(e){return{role:"custom",customType:e.customType,content:e.content,details:e.details,display:e.display,timestamp:Date.parse(e.timestamp)}}c(v,"importedCustomMessage");function m(e){return e.type!=="model_change"&&e.type!=="thinking_level_change"&&e.type!=="active_tools_change"&&e.type!=="session_info"&&e.type!=="label"}c(m,"isRetainedEntry");function I(e){return t=>{if(t===null)return null;const a=e.get(t)?.mappedId;if(a===void 0)throw new Error(`Missing legacy v3 entry reference: ${t}`);return a}}c(I,"createLegacyIdResolver");function w(e,t){return t==="root"?null:e(t)}c(w,"resolveBranchSummaryFromId");function B(e,t){switch(e.type){case"message":return e.message;case"custom_message":return v(e);case"branch_summary":return e.summary?b(e.summary,w(t,e.fromId),e.timestamp):void 0;case"compaction":return E(e.summary,e.tokensBefore,e.timestamp);case"custom":case"model_change":case"thinking_level_change":case"active_tools_change":case"session_info":case"label":return}}c(B,"projectContextMessage");function*_(e,t){let a=e.parentId;for(;a!==null;){const s=t.get(a);if(yield s,a===e.firstKeptEntryId)return;a=s.parentId}throw new Error(`Legacy v3 compaction ${e.id} firstKeptEntryId is not on its parent branch: ${e.firstKeptEntryId}`)}c(_,"retainedTailStructure");function F(e,t,a,s){const n={kind:"entry",id:t.mappedId,parentId:s(t.parentId),seq:t.seq,timestamp:Date.parse(e.timestamp)};return e.type==="message"?{...n,type:"message",message:e.message}:e.type==="custom_message"?{...n,type:"message",message:v(e)}:e.type==="branch_summary"?{...n,type:"branch_summary",fromId:w(s,e.fromId),summary:e.summary,details:e.details,usage:e.usage,fromHook:e.fromHook??!1}:e.type==="compaction"?{...n,type:"compaction",summary:e.summary,retainedTail:a,tokensBefore:e.tokensBefore,details:e.details,usage:e.usage,fromHook:e.fromHook??!1}:{...n,type:"custom",customType:e.customType,data:e.data}}c(F,"normalizeRetainedEntry");function P(e,t){const a=new Set(["model_change","thinking_level_change","active_tools_change"]);let s,n,r,i=t;for(;i!==null&&a.size!==0;){const o=e.get(i);if(a.delete(o.type))switch(o.type){case"model_change":s={provider:o.provider,modelId:o.modelId};break;case"thinking_level_change":n=o.thinkingLevel;break;case"active_tools_change":r=[...o.activeToolNames];break}i=o.parentId}if(!(s===void 0||n===void 0))return{model:s,thinkingLevel:n,activeToolNames:r??[]}}c(P,"selectedConfiguration");function z(e,t,a,s){const n=e.parentId===null?null:s.get(e.parentId)?.mappedId;if(n===void 0)throw new Error(`Legacy v3 entry ${e.id} has a missing or forward parent at line ${t}: ${e.parentId}`);const r={id:e.id,parentId:e.parentId,mappedId:n};if(!m(e))switch(e.type){case"label":return{...r,type:e.type,targetId:e.targetId,label:e.label};case"model_change":return{...r,type:e.type,provider:e.provider,modelId:e.modelId};case"thinking_level_change":return{...r,type:e.type,thinkingLevel:e.thinkingLevel};case"active_tools_change":return{...r,type:e.type,activeToolNames:e.activeToolNames};case"session_info":return{...r,type:e.type}}if(e.id===null)throw new Error("Legacy v3 entry reference has no retained ancestor: null");const i={...r,mappedId:k(Date.parse(e.timestamp)),seq:a};switch(e.type){case"branch_summary":return{...i,type:e.type,fromId:e.fromId};case"compaction":return{...i,type:e.type,firstKeptEntryId:e.firstKeptEntryId};default:return{...i,type:e.type}}}c(z,"indexLegacyV3Entry");function D(e){switch(e.type){case"message":return e.message.role==="assistant"||e.message.role==="toolResult"?e.message.usage:void 0;case"compaction":case"branch_summary":return e.usage;default:return}}c(D,"legacyEntryUsage");async function K(e,t){const a=new Map;let s=1,n=q(),r,i=null;for(;;){const o=f(await e.readLine(t),"Failed to read legacy v3 source");if(o===void 0||!o.terminated)break;const l=a.size+2,d=y(o.text);if(a.has(d.id))throw new Error(`Duplicate legacy v3 entry id: ${d.id}`);const u=z(d,l,s,a);a.set(d.id,u),m(u)&&s++,i=d.id,d.type==="session_info"&&(r=d.name);const g=D(d);g!==void 0&&(n=T(n,g))}return{entries:a,nextSeq:s,importedUsage:n,name:r,finalId:i}}c(K,"readLegacyV3Inventory");function A(e){const{entries:t,name:a,finalId:s}=e,n=I(t);let r=e.nextSeq;const i=[];a&&i.push({...p($,a),seq:r++});const o=new Map;for(const d of t.values()){if(d.type!=="label")continue;const u=n(d.targetId);u!==null&&(d.label?o.set(u,d.label):o.delete(u))}for(const[d,u]of o)i.push({...p(M(d),u),seq:r++});i.push({...p(x("main"),n(s)),seq:r++});const l=P(t,s);return l!==void 0&&(i.push({...p(N("main"),l),seq:r++}),i.push({...p(V("main"),{currentOperationId:null,lastOperationId:null,inbox:[]}),seq:r++})),i}c(A,"normalizeLegacyV3Values");class L{static{c(this,"LegacyV3Source")}header;importedUsage;nextSeq;values;fileSystem;path;entries;resolveLegacyId;constructor(t,a,s,n,r,i,o){this.fileSystem=t,this.path=a,this.header=s,this.entries=n,this.resolveLegacyId=I(n),this.importedUsage=r,this.values=i,this.nextSeq=o}static async read(t,a,s){const n=f(await t.openTextLineReader(a,s),`Failed to open legacy v3 source ${a}`);try{const r=await h(n,a,s);if(r.format!=="v3-legacy")throw new Error(`Invalid legacy v3 JSONL storage ${a}: expected format 3 header`);const i=await K(n,s),o=A(i);return new L(t,a,await U(t,r.header,s),i.entries,i.importedUsage,o,i.nextSeq+o.length)}finally{await n.close(s)}}*entryStructures(){for(const t of this.entries.values())m(t)&&(yield{id:t.mappedId,parentId:this.resolveLegacyId(t.parentId),seq:t.seq})}translateForkEntryId(t){const a=this.entries.get(t);if(a===void 0)throw new Error(`Legacy v3 fork entry does not exist: ${t}`);if(!m(a))throw new Error(`Legacy v3 fork entry is not a retained entry: ${t}`);return a.mappedId}collectRequiredTailMessageIds(t){const a=new Set;for(const s of this.entries.values())if(!(s.type!=="compaction"||!(t===void 0||t(s.mappedId))))for(const r of _(s,this.entries))m(r)&&r.type!=="custom"&&a.add(r.id);return a}async*writes(t,a){const s=this.collectRequiredTailMessageIds(a),n=new Map;for await(const{entry:r,indexed:i}of this.readCapturedEntries(t)){if(s.has(r.id)){const l=B(r,this.resolveLegacyId);l!==void 0&&n.set(r.id,l)}if(!m(i)||!m(r)||a!==void 0&&!a(i.mappedId))continue;const o=[];if(i.type==="compaction"){for(const l of _(i,this.entries)){const d=n.get(l.id);d!==void 0&&o.push(d)}o.reverse()}yield F(r,i,o,this.resolveLegacyId)}yield*this.values}async*readCapturedEntries(t){const a=f(await this.fileSystem.openTextLineReader(this.path,t),`Failed to reopen legacy v3 source ${this.path}`);try{const s=await h(a,this.path,t);if(s.format!=="v3-legacy"||s.header.id!==this.header.id||s.header.cwd!==this.header.cwd)throw new Error("Legacy v3 source header changed");for(const n of this.entries.values()){const r=f(await a.readLine(t),"Failed to reread legacy v3 source");if(r===void 0||!r.terminated)throw new Error("Legacy v3 source ended before captured entries");const i=y(r.text);if(i.id!==n.id||i.type!==n.type)throw new Error("Legacy v3 source changed");yield{entry:i,indexed:n}}}finally{await a.close(t)}}}export{L as LegacyV3Source,J as metadataFromLegacyV3Header,U as normalizeLegacyV3Header};
@@ -1 +0,0 @@
1
- var F=Object.defineProperty;var c=(d,e)=>F(d,"name",{value:e,configurable:!0});import{uuidv7 as u}from"@earendil-works/pi-ai/utils/uuid";import{StorageBackedSession as k}from"../session.js";import{parseJsonlSessionHeader as $}from"./codec.js";import{runJsonlFork as I}from"./fork.js";import{fileValue as a}from"./io.js";import{LegacyV3Source as P,metadataFromLegacyV3Header as E}from"./legacy-v3.js";import{JsonlStorage as S}from"./storage.js";import{JSONL_FORMAT_VERSION as g,JSONL_STORAGE_VERSION as p}from"./types.js";function y(d,e,s){return{id:d.id,createdAt:d.createdAt,storageVersion:d.storageVersion,cwd:d.cwd,path:e,modifiedAt:s,...d.parentSessionId===void 0?{}:{parentSessionId:d.parentSessionId},...d.legacyParentSessionPath===void 0?{}:{legacyParentSessionPath:d.legacyParentSessionPath}}}c(y,"metadataFromHeader");function O(d){return`--${d.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}c(O,"sessionDirectoryName");function D(d,e){return`${new Date(d).toISOString().replace(/[:.]/g,"-")}_${encodeURIComponent(e)}.jsonl`}c(D,"sessionFileName");class K{static{c(this,"JsonlSessionRepo")}fileSystem;sessionsRootInput;now;openSessions=new Map;pendingCreates=new Set;closed=!1;closePromise;constructor(e){this.fileSystem=e.fileSystem,this.sessionsRootInput=e.sessionsRoot,this.now=e.now??Date.now}async create(e,s){this.assertOpen();const i=this.now(),{cwd:t,id:o}=await this.resolveCreateDestination(e.cwd,e.id,i,s),r=this.sessionKey(t,o);if(this.openSessions.has(r)||this.pendingCreates.has(r))throw new Error(`Session already exists: ${o}`);this.pendingCreates.add(r);let n,l;try{n=await this.resolveNewSessionPath(t,i,o,s);const h={v:g,kind:"header",id:o,storageVersion:p,createdAt:i,cwd:t,...e.parentSessionId===void 0?{}:{parentSessionId:e.parentSessionId}};l=await S.create({fileSystem:this.fileSystem,path:n,now:this.now},h,[],s);const f=a(await this.fileSystem.fileInfo(n,s),`Failed to read session ${n}`);return this.publishOpenSession(y(h,n,f.mtimeMs),l,r)}catch(h){throw await l?.close(s).catch(()=>{}),n!==void 0&&await this.fileSystem.remove(n,{force:!0},s),h}finally{this.pendingCreates.delete(r)}}async open(e,s){this.assertOpen();const i=this.sessionKey(e.cwd,e.id);if(this.openSessions.has(i))throw new Error(`Session is already open: ${e.id}`);let t;try{return t=await this.loadStorage(e,s),this.publishOpenSession(e,t,i)}catch(o){throw await t?.close(s),o}}async list(e,s){e??={},this.assertOpen();const i=e.cwd===void 0?void 0:a(await this.fileSystem.absolutePath(e.cwd,s),`Failed to resolve session cwd ${e.cwd}`),t=await this.root(s);if(!a(await this.fileSystem.exists(t,s),`Failed to check sessions root ${t}`))return[];const o=i===void 0?await this.sessionDirectories(t,s):[await this.sessionDirectory(i,s)],r=[];for(const n of o)r.push(...await this.listDirectory(n,i,s));return r.sort((n,l)=>l.createdAt-n.createdAt||n.id.localeCompare(l.id)||n.cwd.localeCompare(l.cwd))}async delete(e,s){this.assertOpen();const i=this.sessionKey(e.cwd,e.id);if(this.openSessions.has(i))throw new Error(`Session is open: ${e.id}`);if(!a(await this.fileSystem.exists(e.path,s),`Failed to check session ${e.path}`))throw new Error(`Session file does not exist: ${e.path}`);a(await this.fileSystem.remove(e.path,void 0,s),`Failed to delete session ${e.path}`)}async fork(e,s,i){this.assertOpen();const t=this.now(),o=e.cwd,r=s.id??u(t),n=this.sessionKey(o,r);if(this.openSessions.has(n)||this.pendingCreates.has(n))throw new Error(`Session already exists: ${r}`);this.pendingCreates.add(n);const l=this.openSessions.get(this.sessionKey(e.cwd,e.id));let h,f;try{const w=await this.resolveForkInput(e,l,i);h=await this.resolveNewSessionPath(o,t,r,i);const m={v:g,kind:"header",id:r,storageVersion:p,createdAt:t,cwd:o,parentSessionId:e.id};await I({input:w,fileSystem:this.fileSystem,destinationPath:h,destinationHeader:m,fork:s},i),f=await S.open({fileSystem:this.fileSystem,path:h,now:this.now},i);const v=a(await this.fileSystem.fileInfo(h,i),`Failed to read session ${h}`);return this.publishOpenSession(y(m,h,v.mtimeMs),f,n)}catch(w){throw await f?.close(i).catch(()=>{}),h!==void 0&&await this.fileSystem.remove(h,{force:!0},i),w}finally{this.pendingCreates.delete(n)}}close(e){return this.closePromise!==void 0?this.closePromise:(this.closed=!0,this.closePromise=Promise.resolve(),this.closePromise)}async resolveCreateDestination(e,s,i,t){const o=s??u(i);return{cwd:a(await this.fileSystem.absolutePath(e,t),`Failed to resolve session cwd ${e}`),id:o}}async listDirectory(e,s,i){if(!a(await this.fileSystem.exists(e,i),`Failed to check sessions directory ${e}`))return[];const t=a(await this.fileSystem.listDir(e,i),`Failed to list sessions directory ${e}`).filter(r=>r.kind!=="directory"&&r.name.endsWith(".jsonl")),o=[];for(const r of t){const n=await this.readSessionMetadata(r,i);n!==void 0&&(s===void 0||n.cwd===s)&&o.push(n)}return o}async readSessionMetadata(e,s){const i=a(await this.fileSystem.readTextLines(e.path,{maxLines:1},s),`Failed to read session header ${e.path}`);if(i[0]===void 0)return;const t=$(i[0]);if(t.ok)return t.value.format==="v3-legacy"?{...await E(this.fileSystem,t.value.header,s),path:e.path,modifiedAt:e.mtimeMs}:y(t.value.header,e.path,e.mtimeMs)}async sessionDirectories(e,s){return a(await this.fileSystem.listDir(e,s),`Failed to list sessions root ${e}`).filter(i=>i.kind==="directory").map(i=>i.path)}async sessionDirectory(e,s){return a(await this.fileSystem.joinPath([await this.root(s),O(e)],s),`Failed to resolve sessions directory for ${e}`)}async resolveNewSessionPath(e,s,i,t){const o=await this.sessionDirectory(e,t);return await this.assertSessionIdAvailable(o,i,t),a(await this.fileSystem.createDir(o,void 0,t),`Failed to create sessions directory ${o}`),a(await this.fileSystem.joinPath([o,D(s,i)],t),`Failed to resolve path for session ${i}`)}async assertSessionIdAvailable(e,s,i){if(!a(await this.fileSystem.exists(e,i),`Failed to check sessions directory ${e}`))return;const t=`_${encodeURIComponent(s)}.jsonl`;if(a(await this.fileSystem.listDir(e,i),`Failed to list sessions directory ${e}`).some(r=>r.kind!=="directory"&&r.name.endsWith(t)))throw new Error(`Session already exists: ${s}`)}async resolveForkInput(e,s,i){if(s!==void 0){if(s.isLegacyV3())throw new Error("Cannot fork an open legacy v3 JSONL session; commit a non-empty transaction to upgrade it to format 4 first");const t=await s.captureForkNextSeq(i);return{kind:"open",metadata:e,nextSeq:t}}if(await this.isLegacyV3ForkSource(e,i)){const t=await P.read(this.fileSystem,e.path,i);if(t.header.id!==e.id||t.header.cwd!==e.cwd)throw new Error(`Session identity does not match header: ${e.id}`);return{kind:"legacy-v3",normalized:t}}return{kind:"closed",metadata:e}}async isLegacyV3ForkSource(e,s){const i=a(await this.fileSystem.readTextLines(e.path,{maxLines:1},s),`Failed to read session header ${e.path}`);if(i[0]===void 0)return!1;const t=$(i[0]);return t.ok&&t.value.format==="v3-legacy"}publishOpenSession(e,s,i){if(this.openSessions.has(i))throw new Error(`Session is already open: ${e.id}`);const t=new k(e,s,{onClose:c(()=>{this.openSessions.get(i)===s&&this.openSessions.delete(i)},"onClose")});return this.openSessions.set(i,s),t}sessionKey(e,s){return`${e}\0${s}`}async loadStorage(e,s){if(!a(await this.fileSystem.exists(e.path,s),`Failed to check session ${e.path}`))throw new Error(`Session file does not exist: ${e.path}`);const i=await S.open({fileSystem:this.fileSystem,path:e.path,now:this.now},s);try{if(i.header.id!==e.id||i.header.cwd!==e.cwd)throw new Error(`Session identity does not match header: ${e.id}`);if(i.header.storageVersion!==p)throw new Error(`Session ${e.id} uses unsupported storage version ${i.header.storageVersion}`);return i}catch(t){throw await i.close(s),t}}root(e){return this.fileSystem.absolutePath(this.sessionsRootInput,e).then(s=>a(s,`Failed to resolve sessions root ${this.sessionsRootInput}`))}assertOpen(){if(this.closed)throw new Error("JsonlSessionRepo is closed")}}export{K as JsonlSessionRepo};
@@ -1,8 +0,0 @@
1
- var p=Object.defineProperty;var m=(c,e)=>p(c,"name",{value:e,configurable:!0});import{uuidv7 as S}from"@earendil-works/pi-ai/utils/uuid";import{insertUsage as w}from"../commit.js";import{InMemoryStorageState as f}from"../in-memory-storage-state.js";import{fileValue as d,parseJsonlTransaction as y,publishFileAtomically as V,publishJsonl as g,readJsonlHeader as v,serializeJsonlTransaction as E}from"./io.js";import{LegacyV3Source as P}from"./legacy-v3.js";import{JSONL_STORAGE_VERSION as k}from"./types.js";function x(c){if(c.endsWith(`
2
- `))return{lines:c.slice(0,-1).split(`
3
- `),torn:!1};const e=c.lastIndexOf(`
4
- `);return e===-1?{lines:[],torn:!0}:{lines:c.slice(0,e).split(`
5
- `),torn:!0}}m(x,"splitCompleteLines");class l{static{m(this,"JsonlStorage")}fileSystem;path;now;header;backing;storageState=new f;commitQueue=Promise.resolve();state="open";closePromise;constructor(e,t,s){this.fileSystem=e.fileSystem,this.path=e.path,this.now=e.now??Date.now,this.header=t,this.backing=s}static async create(e,t,s,a){const r=new l(e,t,{kind:"v4"}),n=r.storageState.prepareCommit(s,r.now());return await g(e.fileSystem,e.path,t,a,async o=>{n.writes.length!==0&&await o(n.writes)}),r.storageState.applyValidated(n.writes),r}static async open(e,t){const s=d(await e.fileSystem.openTextLineReader(e.path,t),`Failed to read JSONL storage ${e.path}`),a=await v(s,e.path,t).finally(()=>s.close(t));return a.format==="v3-legacy"?l.openLegacyV3(e,t):l.openV4(e,a.header,t)}static async openV4(e,t,s){const a=d(await e.fileSystem.readTextFile(e.path,s),`Failed to read JSONL storage ${e.path}`),{lines:r,torn:n}=x(a);if(t.storageVersion!==k)throw new Error(`Session ${t.id} uses unsupported storage version ${t.storageVersion}`);const o=new l(e,t,{kind:"v4"});for(let i=1;i<r.length;i++){const h=r[i];try{o.replayCommitted(y(h))}catch(u){throw new Error(`Invalid JSONL storage ${e.path}: line ${i+1}`,{cause:u})}}return t.nextSeq!==void 0&&o.storageState.advanceNextSeq(t.nextSeq),n&&await V(e.fileSystem,e.path,s,i=>i(`${r.join(`
6
- `)}
7
- `)),o}static async openLegacyV3(e,t){const s=await P.read(e.fileSystem,e.path,t),a=new l(e,{...s.header,nextSeq:s.nextSeq},{kind:"v3",source:s});for await(const r of s.writes(t))a.replayCommitted([r]);return a}replayCommitted(e){this.storageState.validateCommitted(e),this.storageState.applyValidated(e)}async commit(e,t){if(this.state!=="open")throw new Error("JsonlStorage is closed");const s=this.commitQueue.then(()=>this.applyCommit(e,t));return this.commitQueue=s.then(()=>{},()=>{}),s}async applyCommit(e,t){if(this.backing.kind==="v3"&&e.length!==0)return this.upgradeLegacyV3ToV4(this.backing.source,e,t);const s=this.storageState.prepareCommit(e,this.now());s.writes.length!==0&&d(await this.fileSystem.appendFile(this.path,`${E(s.writes)}
8
- `,t),`Failed to append JSONL storage ${this.path}`);const a=this.storageState.applyValidated(s.writes);return{...s.result,stats:this.withImportedUsage(a)}}async upgradeLegacyV3ToV4(e,t,s){const a=this.now(),r=this.storageState.prepareCommit([w({id:S(a),usage:e.importedUsage,adjustment:!0,details:{source:"v3-import"}}),...t],a),n=r.result.firstSeq+r.writes.length,o={...this.header,nextSeq:n};await g(this.fileSystem,this.path,o,s,async h=>{for await(const u of e.writes(s))await h([u]);await h(r.writes)});const i=this.storageState.applyValidated(r.writes);return this.backing={kind:"v4"},{...r.result,firstSeq:r.result.firstSeq+1,seqs:r.result.seqs.slice(1),stats:i}}getEntries(e,t){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.storageState.getEntries(e))}getValue(e,t){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.storageState.getValue(e))}scanValues(e,t){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.storageState.scanValues(e))}async readList(e,t,s){if(this.state!=="open")throw new Error("JsonlStorage is closed");return this.storageState.readList(e,t)}async scanBranch(e,t){if(this.state!=="open")throw new Error("JsonlStorage is closed");return this.storageState.scanBranch(e)}async scanBranchStructure(e,t){if(this.state!=="open")throw new Error("JsonlStorage is closed");return this.storageState.scanBranchStructure(e)}scanEntries(e,t){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.storageState.scanEntries(e))}scanUsage(e,t){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.storageState.scanUsage(e))}getStats(e){return this.state!=="open"?Promise.reject(new Error("JsonlStorage is closed")):Promise.resolve(this.withImportedUsage(this.storageState.getStats()))}withImportedUsage(e){return this.backing.kind==="v4"?e:{...e,usage:this.backing.source.importedUsage}}isLegacyV3(){return this.backing.kind==="v3"}captureForkNextSeq(e){if(this.state!=="open")return Promise.reject(new Error("JsonlStorage is closed"));const t=this.commitQueue.then(()=>this.storageState.getNextSeq());return this.commitQueue=t.then(()=>{},()=>{}),t}close(e){return this.closePromise!==void 0?this.closePromise:(this.state="closing",this.closePromise=this.commitQueue.then(()=>{this.state="closed"}),this.closePromise)}}export{l as JsonlStorage};
@@ -1 +0,0 @@
1
- const O=4,S=1;export{O as JSONL_FORMAT_VERSION,S as JSONL_STORAGE_VERSION};
@@ -1 +0,0 @@
1
- var g=Object.defineProperty;var d=(c,s)=>g(c,"name",{value:s,configurable:!0});import{SessionError as w,toError as y}from"../types.js";import{JsonlSessionStorage as f,loadJsonlSessionMetadata as F}from"./jsonl-storage.js";import{createSessionId as u,createTimestamp as S,getEntriesToFork as m,getFileSystemResultOrThrow as o,toSession as l}from"./repo-utils.js";function D(c){return`--${c.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}d(D,"encodeCwd");class v{static{d(this,"JsonlSessionRepo")}fs;sessionsRootInput;sessionsRoot;constructor(s){this.fs=s.fs,this.sessionsRootInput=s.sessionsRoot}async getSessionsRoot(){return this.sessionsRoot||(this.sessionsRoot=o(await this.fs.absolutePath(this.sessionsRootInput),`Failed to resolve sessions root ${this.sessionsRootInput}`)),this.sessionsRoot}async getSessionDir(s){return o(await this.fs.joinPath([await this.getSessionsRoot(),D(s)]),`Failed to resolve session directory for ${s}`)}async createSessionFilePath(s,t,e){return o(await this.fs.joinPath([await this.getSessionDir(s),`${e.replace(/[:.]/g,"-")}_${t}.jsonl`]),`Failed to resolve session file path for ${t}`)}async create(s){const t=s.id??u(),e=S(),i=await this.getSessionDir(s.cwd);o(await this.fs.createDir(i,{recursive:!0}),`Failed to create session directory ${i}`);const a=await this.createSessionFilePath(s.cwd,t,e),r=await f.create(this.fs,a,{cwd:s.cwd,sessionId:t,parentSessionPath:s.parentSessionPath,metadata:s.metadata});return l(r)}async open(s){if(!o(await this.fs.exists(s.path),`Failed to check session ${s.path}`))throw new w("not_found",`Session not found: ${s.path}`);const t=await f.open(this.fs,s.path);return l(t)}async list(s={}){const t=s.cwd?[await this.getSessionDir(s.cwd)]:await this.listSessionDirs(),e=[];for(const i of t){if(!o(await this.fs.exists(i),`Failed to check session directory ${i}`))continue;const a=o(await this.fs.listDir(i),`Failed to list sessions in ${i}`).filter(r=>r.kind!=="directory"&&r.name.endsWith(".jsonl"));for(const r of a)try{e.push(await F(this.fs,r.path))}catch(h){const n=y(h);if(!(n instanceof w)||n.code!=="invalid_session")throw n}}return e.sort((i,a)=>new Date(a.createdAt).getTime()-new Date(i.createdAt).getTime()),e}async delete(s){o(await this.fs.remove(s.path,{force:!0}),`Failed to delete session ${s.path}`)}async fork(s,t){const e=await this.open(s),i=await m(e.getStorage(),t),a=t.id??u(),r=S(),h=await this.getSessionDir(t.cwd);o(await this.fs.createDir(h,{recursive:!0}),`Failed to create session directory ${h}`);const n=await f.create(this.fs,await this.createSessionFilePath(t.cwd,a,r),{cwd:t.cwd,sessionId:a,parentSessionPath:t.parentSessionPath??s.path,metadata:t.metadata??s.metadata});for(const p of i)await n.appendEntry(p);return l(n)}async listSessionDirs(){const s=await this.getSessionsRoot();return o(await this.fs.exists(s),`Failed to check sessions root ${s}`)?o(await this.fs.listDir(s),`Failed to list sessions root ${s}`).filter(e=>e.kind==="directory").map(e=>e.path):[]}}export{v as JsonlSessionRepo};
@@ -1,5 +0,0 @@
1
- var v=Object.defineProperty;var o=(i,t)=>v(i,"name",{value:t,configurable:!0});import{uuidv7 as h}from"@earendil-works/pi-ai";import{SessionError as p,toError as m}from"../types.js";import{getFileSystemResultOrThrow as f}from"./repo-utils.js";function g(i,t){if(t.type!=="label")return;const s=t.label?.trim();s?i.set(t.targetId,s):i.delete(t.targetId)}o(g,"updateLabelCache");function L(i){const t=new Map;for(const s of i)g(t,s);return t}o(L,"buildLabelsById");function w(i){for(let t=0;t<100;t++){const s=h().slice(-8);if(!i.has(s))return s}return h()}o(w,"generateEntryId");function c(i,t,s){return new p("invalid_session",`Invalid JSONL session file ${i}: ${t}`,s)}o(c,"invalidSession");function u(i,t,s,e){return new p("invalid_entry",`Invalid JSONL session file ${i}: line ${t} ${s}`,e)}o(u,"invalidEntry");function I(i,t){let s;try{s=JSON.parse(i)}catch(n){throw c(t,"first line is not a valid session header",m(n))}if(typeof s!="object"||s===null)throw c(t,"first line is not a valid session header");const e=s;if(e.type!=="session")throw c(t,"first line is not a valid session header");if(e.version!==3)throw c(t,"unsupported session version");if(typeof e.id!="string"||!e.id)throw c(t,"session header is missing id");if(typeof e.timestamp!="string"||!e.timestamp)throw c(t,"session header is missing timestamp");if(typeof e.cwd!="string"||!e.cwd)throw c(t,"session header is missing cwd");if(e.parentSession!==void 0&&typeof e.parentSession!="string")throw c(t,"session header parentSession must be a string");if(e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null||Array.isArray(e.metadata)))throw c(t,"session header metadata must be an object");return{type:"session",version:3,id:e.id,timestamp:e.timestamp,cwd:e.cwd,parentSession:e.parentSession,metadata:e.metadata}}o(I,"parseHeaderLine");function E(i,t,s){let e;try{e=JSON.parse(i)}catch(d){throw u(t,s,"is not valid JSON",m(d))}if(typeof e!="object"||e===null)throw u(t,s,"is not a valid session entry");const n=e;if(typeof n.type!="string")throw u(t,s,"is missing entry type");if(typeof n.id!="string"||!n.id)throw u(t,s,"is missing entry id");if(n.parentId!==null&&typeof n.parentId!="string")throw u(t,s,"has invalid parentId");if(typeof n.timestamp!="string"||!n.timestamp)throw u(t,s,"is missing timestamp");if(n.type==="leaf"&&n.targetId!==null&&typeof n.targetId!="string")throw u(t,s,"has invalid targetId");return n}o(E,"parseEntryLine");function b(i){return i.type==="leaf"?i.targetId:i.id}o(b,"leafIdAfterEntry");function S(i,t){return{id:i.id,createdAt:i.timestamp,cwd:i.cwd,path:t,parentSessionPath:i.parentSession,metadata:i.metadata}}o(S,"headerToSessionMetadata");async function k(i,t){const e=f(await i.readTextLines(t,{maxLines:1}),`Failed to read session header ${t}`)[0];if(e?.trim())return S(I(e,t),t);throw c(t,"missing session header")}o(k,"loadJsonlSessionMetadata");async function $(i,t){const e=f(await i.readTextFile(t),`Failed to read session ${t}`).split(`
2
- `).filter(r=>r.trim());if(e.length===0)throw c(t,"missing session header");const n=I(e[0],t),d=[];let a=null;for(let r=1;r<e.length;r++){const y=E(e[r],t,r+1);d.push(y),a=b(y)}return{header:n,entries:d,leafId:a}}o($,"loadJsonlStorage");class l{static{o(this,"JsonlSessionStorage")}fs;filePath;metadata;entries;byId;labelsById;currentLeafId;constructor(t,s,e,n,d){this.fs=t,this.filePath=s,this.metadata=S(e,this.filePath),this.entries=n,this.byId=new Map(n.map(a=>[a.id,a])),this.labelsById=L(n),this.currentLeafId=d}static async open(t,s){const e=await $(t,s);return new l(t,s,e.header,e.entries,e.leafId)}static async create(t,s,e){const n={type:"session",version:3,id:e.sessionId,timestamp:new Date().toISOString(),cwd:e.cwd,parentSession:e.parentSessionPath,metadata:e.metadata};return f(await t.writeFile(s,`${JSON.stringify(n)}
3
- `),`Failed to create session ${s}`),new l(t,s,n,[],null)}async getMetadata(){return this.metadata}async getLeafId(){if(this.currentLeafId!==null&&!this.byId.has(this.currentLeafId))throw new p("invalid_session",`Entry ${this.currentLeafId} not found`);return this.currentLeafId}async setLeafId(t){if(t!==null&&!this.byId.has(t))throw new p("not_found",`Entry ${t} not found`);const s={type:"leaf",id:w(this.byId),parentId:this.currentLeafId,timestamp:new Date().toISOString(),targetId:t};f(await this.fs.appendFile(this.filePath,`${JSON.stringify(s)}
4
- `),`Failed to append session leaf ${s.id}`),this.entries.push(s),this.byId.set(s.id,s),this.currentLeafId=t}async createEntryId(){return w(this.byId)}async appendEntry(t){f(await this.fs.appendFile(this.filePath,`${JSON.stringify(t)}
5
- `),`Failed to append session entry ${t.id}`),this.entries.push(t),this.byId.set(t.id,t),g(this.labelsById,t),this.currentLeafId=b(t)}async getEntry(t){return this.byId.get(t)}async findEntries(t){return this.entries.filter(s=>s.type===t)}async getLabel(t){return this.labelsById.get(t)}async getSessionName(){const t=await this.findEntries("session_info");return t[t.length-1]?.name?.trim()||void 0}async getSessionStats(){let t=0,s=0,e=0,n=0,d=0;for(const a of this.entries){a.type==="message"&&(t+=1);const r=a.type==="message"?a.message.role==="assistant"?a.message.usage:void 0:a.type==="compaction"||a.type==="branch_summary"?a.usage:void 0;!r||typeof r.input!="number"||typeof r.output!="number"||typeof r.cacheRead!="number"||typeof r.cacheWrite!="number"||typeof r.cost?.total!="number"||(s+=r.cacheRead,e+=r.input+r.cacheWrite,n+=r.input+r.output+r.cacheRead+r.cacheWrite,d+=r.cost.total)}return{messageCount:t,cachedTokens:s,uncachedTokens:e,totalTokens:n,costTotal:d}}async getPathToRootOrCompaction(t){if(t===null)return[];const s=[];let e=null,n=this.byId.get(t);if(!n)throw new p("not_found",`Entry ${t} not found`);for(;n&&(s.unshift(n),!(e!==null&&n.id===e));){if(n.type==="compaction"){if(n.retainedTail)break;e=n.firstKeptEntryId??null}if(!n.parentId)break;const d=this.byId.get(n.parentId);if(!d)throw new p("invalid_session",`Entry ${n.parentId} not found`);n=d}return s}async getEntries(t){const s=t?.afterEntrySeq??0,e=t?.limit===void 0?void 0:s+t.limit;return this.entries.slice(s,e)}}export{l as JsonlSessionStorage,k as loadJsonlSessionMetadata};
@@ -1 +0,0 @@
1
- import{JsonlSessionRepo as s}from"./jsonl/repo.js";export{s as JsonlSessionRepo};
@@ -1 +0,0 @@
1
- var g=Object.defineProperty;var a=(n,s)=>g(n,"name",{value:s,configurable:!0});import{SessionError as u}from"../types.js";import{InMemorySessionStorage as c}from"./memory-storage.js";import{createSessionId as d,createTimestamp as m,getEntriesToFork as S,toSession as p}from"./repo-utils.js";class M{static{a(this,"InMemorySessionRepo")}sessions=new Map;async create(s={}){const e={id:s.id??d(),createdAt:m()},o=new c({metadata:e}),t=p(o);return this.sessions.set(e.id,t),t}async open(s){const e=this.sessions.get(s.id);if(!e)throw new u("not_found",`Session not found: ${s.id}`);return e}async list(){return Promise.all([...this.sessions.values()].map(s=>s.getMetadata()))}async delete(s){this.sessions.delete(s.id)}async fork(s,e){const o=await this.open(s),t=await S(o.getStorage(),e),i={id:e.id??d(),createdAt:m()},f=new c({metadata:i,entries:t}),r=p(f);return this.sessions.set(i.id,r),r}}export{M as InMemorySessionRepo};
@@ -1 +0,0 @@
1
- var y=Object.defineProperty;var d=(i,t)=>y(i,"name",{value:t,configurable:!0});import{uuidv7 as u}from"@earendil-works/pi-ai";import{SessionError as l}from"../types.js";function f(i,t){if(t.type!=="label")return;const e=t.label?.trim();e?i.set(t.targetId,e):i.delete(t.targetId)}d(f,"updateLabelCache");function I(i){const t=new Map;for(const e of i)f(t,e);return t}d(I,"buildLabelsById");function c(i){for(let t=0;t<100;t++){const e=u().slice(-8);if(!i.has(e))return e}return u()}d(c,"generateEntryId");function h(i){return i.type==="leaf"?i.targetId:i.id}d(h,"leafIdAfterEntry");class g{static{d(this,"InMemorySessionStorage")}metadata;entries;byId;labelsById;leafId;constructor(t){this.entries=t?.entries?[...t.entries]:[],this.byId=new Map(this.entries.map(e=>[e.id,e])),this.labelsById=I(this.entries),this.leafId=null;for(const e of this.entries)this.leafId=h(e);if(this.leafId!==null&&!this.byId.has(this.leafId))throw new l("invalid_session",`Entry ${this.leafId} not found`);this.metadata=t?.metadata??{id:u(),createdAt:new Date().toISOString()}}async getMetadata(){return this.metadata}async getLeafId(){if(this.leafId!==null&&!this.byId.has(this.leafId))throw new l("invalid_session",`Entry ${this.leafId} not found`);return this.leafId}async setLeafId(t){if(t!==null&&!this.byId.has(t))throw new l("not_found",`Entry ${t} not found`);const e={type:"leaf",id:c(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId:t};this.entries.push(e),this.byId.set(e.id,e),this.leafId=t}async createEntryId(){return c(this.byId)}async appendEntry(t){this.entries.push(t),this.byId.set(t.id,t),f(this.labelsById,t),this.leafId=h(t)}async getEntry(t){return this.byId.get(t)}async findEntries(t){return this.entries.filter(e=>e.type===t)}async getLabel(t){return this.labelsById.get(t)}async getSessionName(){const t=await this.findEntries("session_info");return t[t.length-1]?.name?.trim()||void 0}async getSessionStats(){let t=0,e=0,a=0,n=0,o=0;for(const r of this.entries){r.type==="message"&&(t+=1);const s=r.type==="message"?r.message.role==="assistant"?r.message.usage:void 0:r.type==="compaction"||r.type==="branch_summary"?r.usage:void 0;!s||typeof s.input!="number"||typeof s.output!="number"||typeof s.cacheRead!="number"||typeof s.cacheWrite!="number"||typeof s.cost?.total!="number"||(e+=s.cacheRead,a+=s.input+s.cacheWrite,n+=s.input+s.output+s.cacheRead+s.cacheWrite,o+=s.cost.total)}return{messageCount:t,cachedTokens:e,uncachedTokens:a,totalTokens:n,costTotal:o}}async getPathToRootOrCompaction(t){if(t===null)return[];const e=[];let a=null,n=this.byId.get(t);if(!n)throw new l("not_found",`Entry ${t} not found`);for(;n&&(e.unshift(n),!(a!==null&&n.id===a));){if(n.type==="compaction"){if(n.retainedTail)break;a=n.firstKeptEntryId??null}if(!n.parentId)break;const o=this.byId.get(n.parentId);if(!o)throw new l("invalid_session",`Entry ${n.parentId} not found`);n=o}return e}async getEntries(t){const e=t?.afterEntrySeq??0,a=t?.limit===void 0?void 0:e+t.limit;return this.entries.slice(e,a)}}export{g as InMemorySessionStorage};
@@ -1 +0,0 @@
1
- var w=Object.defineProperty;var o=(h,e)=>w(h,"name",{value:e,configurable:!0});import{uuidv7 as u}from"@earendil-works/pi-ai/utils/uuid";import{InMemoryStorageState as f}from"./in-memory-storage-state.js";import{StorageBackedSession as l}from"./session.js";class c{static{o(this,"MemoryStorage")}now;storageState=new f;commitQueue=Promise.resolve();state="open";closePromise;constructor(e={}){this.now=e.now??Date.now}async commit(e,t){if(this.state!=="open")throw new Error("MemoryStorage is closed");const s=this.commitQueue.then(()=>{const i=this.storageState.prepareCommit(e,this.now()),a=this.storageState.applyValidated(i.writes);return{...i.result,stats:a}});return this.commitQueue=s.then(()=>{},()=>{}),s}getEntries(e,t){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.getEntries(e))}getValue(e,t){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.getValue(e))}scanValues(e,t){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.scanValues(e))}async readList(e,t,s){if(this.state!=="open")throw new Error("MemoryStorage is closed");return this.storageState.readList(e,t)}async scanBranch(e,t){if(this.state!=="open")throw new Error("MemoryStorage is closed");return this.storageState.scanBranch(e)}async scanBranchStructure(e,t){if(this.state!=="open")throw new Error("MemoryStorage is closed");return this.storageState.scanBranchStructure(e)}scanEntries(e,t){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.scanEntries(e))}scanUsage(e,t){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.scanUsage(e))}getStats(e){return this.state!=="open"?Promise.reject(new Error("MemoryStorage is closed")):Promise.resolve(this.storageState.getStats())}fork(e){if(this.state!=="open")return Promise.reject(new Error("MemoryStorage is closed"));const t=this.commitQueue.then(()=>{const s=new c({now:this.now});return s.storageState=this.storageState.createFork(e),s});return this.commitQueue=t.then(()=>{},()=>{}),t}close(e){return this.closePromise!==void 0?this.closePromise:(this.state="closing",this.closePromise=this.commitQueue.then(()=>{this.state="closed"}),this.closePromise)}}const p=1;class S{static{o(this,"MemorySessionFacade")}metadata;idGenerator;session;onClose;admitted=new Set;closedError=new Error("Session is closed");state="open";closePromise;constructor(e,t){this.session=e,this.metadata=e.metadata,this.idGenerator=e.idGenerator,this.onClose=t}async beginMutation(e){let t;const s=new Promise(r=>{t=r});this.admitted.add(s);let i;try{i=await this.admit(()=>this.session.beginMutation(e))}catch(r){throw this.admitted.delete(s),t(),r}if(this.state!=="open")throw await i.end(e),this.admitted.delete(s),t(),this.closedError;let a=!1;return{commit:o((r,n)=>i.commit(r,n),"commit"),end:o(async r=>{try{await i.end(r)}finally{a||(a=!0,this.admitted.delete(s),t())}},"end"),getEntries:o((r,n)=>i.getEntries(r,n),"getEntries"),getStats:o(r=>i.getStats(r),"getStats"),getValue:o((r,n)=>i.getValue(r,n),"getValue"),scanValues:o((r,n)=>i.scanValues(r,n),"scanValues"),readList:o((r,n,d)=>i.readList(r,n,d),"readList"),scanBranch:o((r,n)=>i.scanBranch(r,n),"scanBranch")}}mutate(e,t){return this.admit(()=>this.session.mutate((s,i)=>{if(this.state!=="open")throw this.closedError;return e(s,i)},t))}getEntries(e,t){return this.admit(()=>this.session.getEntries(e,t))}getEntry(e,t){return this.admit(()=>this.session.getEntry(e,t))}getValue(e,t){return this.admit(()=>this.session.getValue(e,t))}scanValues(e,t){return this.admit(()=>this.session.scanValues(e,t))}readList(e,t,s){return this.admit(()=>this.session.readList(e,t,s))}scanBranch(e,t){return this.admit(()=>this.session.scanBranch(e,t))}getStats(e){return this.admit(()=>this.session.getStats(e))}getName(e){return this.admit(()=>this.session.getName(e))}getLabel(e,t){return this.admit(()=>this.session.getLabel(e,t))}findEntries(e,t){return this.admit(()=>this.session.findEntries(e,t))}findEntry(e,t){return this.admit(()=>this.session.findEntry(e,t))}async branch(e,t){const s=await this.admit(()=>this.session.branch(e,t));return s===void 0?void 0:this.wrapBranch(s)}async createBranch(e,t,s){return this.wrapBranch(await this.admit(()=>this.session.createBranch(e,t,s)))}setValue(e,t,s){return this.admit(()=>this.session.setValue(e,t,s))}deleteValue(e,t){return this.admit(()=>this.session.deleteValue(e,t))}appendList(e,t,s){return this.admit(()=>this.session.appendList(e,t,s))}deleteList(e,t){return this.admit(()=>this.session.deleteList(e,t))}setName(e,t){return this.admit(()=>this.session.setName(e,t))}setLabel(e,t,s){return this.admit(()=>this.session.setLabel(e,t,s))}close(e){return this.closePromise!==void 0?this.closePromise:(this.state="closing",this.closePromise=Promise.allSettled([...this.admitted]).then(()=>{this.state="closed",this.onClose()}),this.closePromise)}wrapBranch(e){return{name:e.name,getTipId:o(t=>this.admit(()=>e.getTipId(t)),"getTipId"),findEntries:o((t,s)=>this.admit(()=>e.findEntries(t,s)),"findEntries"),findEntry:o((t,s)=>this.admit(()=>e.findEntry(t,s)),"findEntry"),appendMessage:o((t,s)=>this.admit(()=>e.appendMessage(t,s)),"appendMessage"),appendCustomEntry:o((t,s,i)=>this.admit(()=>e.appendCustomEntry(t,s,i)),"appendCustomEntry")}}admit(e){if(this.state!=="open")return Promise.reject(this.closedError);let t;try{t=e()}catch(s){t=Promise.reject(s)}return this.admitted.add(t),t.then(()=>this.admitted.delete(t),()=>this.admitted.delete(t)),t}}class V{static{o(this,"MemorySessionRepo")}now;sessions=new Map;pendingIds=new Set;closed=!1;closePromise;constructor(e={}){this.now=e.now??Date.now}async create(e,t){this.assertOpen();const s=this.now(),i=e.id??u(s);this.reserveId(i);const a={id:i,createdAt:s,storageVersion:p,...e.parentSessionId===void 0?{}:{parentSessionId:e.parentSessionId}},r=new c({now:this.now}),n=new l(a,r);try{const d={metadata:a,storage:r,session:n,open:!0};return this.sessions.set(i,d),this.openRecord(d)}catch(d){throw await n.close(t),d}finally{this.pendingIds.delete(i)}}open(e,t){this.assertOpen();const s=this.sessions.get(e.id);return s===void 0?Promise.reject(new Error(`Unknown session: ${e.id}`)):s.open?Promise.reject(new Error(`Session is already open: ${e.id}`)):(s.open=!0,Promise.resolve(this.openRecord(s)))}list(e,t){return this.assertOpen(),Promise.resolve([...this.sessions.values()].map(({metadata:s})=>s))}async delete(e,t){this.assertOpen();const s=this.sessions.get(e.id);if(s===void 0)throw new Error(`Unknown session: ${e.id}`);if(s.open)throw new Error(`Session is open: ${e.id}`);await s.session.close(t),this.sessions.delete(e.id)}async fork(e,t,s){this.assertOpen();const i=this.sessions.get(e.id);if(i===void 0)throw new Error(`Unknown session: ${e.id}`);const a=this.now(),r=t.id??u(a);this.reserveId(r);try{const n=await i.storage.fork(t),d={id:r,createdAt:a,storageVersion:p,parentSessionId:i.metadata.id},g=new l(d,n),m={metadata:d,storage:n,session:g,open:!0};return this.sessions.set(r,m),this.openRecord(m)}finally{this.pendingIds.delete(r)}}close(e){return this.closePromise!==void 0?this.closePromise:(this.closed=!0,this.closePromise=Promise.all([...this.sessions.values()].map(({session:t})=>t.close(e))).then(()=>{}),this.closePromise)}openRecord(e){return new S(e.session,()=>{e.open=!1})}reserveId(e){if(this.sessions.has(e)||this.pendingIds.has(e))throw new Error(`Session already exists: ${e}`);this.pendingIds.add(e)}assertOpen(){if(this.closed)throw new Error("MemorySessionRepo is closed")}}export{V as MemorySessionRepo,c as MemoryStorage};
@@ -1 +0,0 @@
1
- var s=Object.defineProperty;var i=(r,e)=>s(r,"name",{value:e,configurable:!0});class d{static{i(this,"MutationLine")}tail=Promise.resolve();sealedError;run(e){if(this.sealedError!==void 0)return Promise.reject(this.sealedError);const t=this.tail.then(()=>{if(this.sealedError!==void 0)throw this.sealedError;return e()});return this.tail=t.then(()=>{},()=>{}),t}seal(e){return this.sealedError??=e,this.tail}}export{d as MutationLine};
@@ -1 +0,0 @@
1
- var a=Object.defineProperty;var n=(e,r)=>a(e,"name",{value:r,configurable:!0});import{uuidv7 as f}from"@earendil-works/pi-ai";import{SessionError as i}from"../types.js";import{Session as s}from"./session.js";function g(){return f()}n(g,"createSessionId");function w(){return new Date().toISOString()}n(w,"createTimestamp");function y(e){return new s(e)}n(y,"toSession");function p(e,r){if(!e.ok){const t=e.error.code==="not_found"?"not_found":"storage";throw new i(t,`${r}: ${e.error.message}`,e.error)}return e.value}n(p,"getFileSystemResultOrThrow");async function I(e,r){if(!r.entryId)return e.getEntries();const t=await e.getEntry(r.entryId);if(!t)throw new i("invalid_fork_target",`Entry ${r.entryId} not found`);let o;if((r.position??"before")==="at")o=t.id;else{if(t.type!=="message"||t.message.role!=="user")throw new i("invalid_fork_target",`Entry ${r.entryId} is not a user message`);o=t.parentId}return e.getPathToRootOrCompaction(o)}n(I,"getEntriesToFork");export{g as createSessionId,w as createTimestamp,I as getEntriesToFork,p as getFileSystemResultOrThrow,y as toSession};
@@ -1 +0,0 @@
1
- var w=Object.defineProperty;var n=(i,e)=>w(i,"name",{value:e,configurable:!0});import{uuidv7 as E}from"@earendil-works/pi-ai/utils/uuid";import{insertEntry as y}from"./commit.js";import{MutationLine as V}from"./mutation-line.js";import{appendList as B,branchTip as a,deleteList as S,deleteValue as b,entryLabel as l,sessionName as u,setValue as d}from"./values.js";class m extends Error{static{n(this,"SessionInvariantError")}constructor(e){super(e),this.name="SessionInvariantError"}}class g extends Error{static{n(this,"SessionInvalidBranchError")}branch;reason;constructor(e,t){super(`Invalid branch ${JSON.stringify(e)}: ${t}`),this.name="SessionInvalidBranchError",this.branch=e,this.reason=t}}class v extends Error{static{n(this,"SessionBranchExistsError")}branch;constructor(e){super(`Branch already exists: ${e}`),this.name="SessionBranchExistsError",this.branch=e}}class p extends Error{static{n(this,"SessionPendingAssistantMessageError")}constructor(){super("Cannot persist a pending assistant message"),this.name="SessionPendingAssistantMessageError"}}class L extends Error{static{n(this,"SessionUnknownTargetError")}targetId;constructor(e){super(`Unknown target: ${e}`),this.name="SessionUnknownTargetError",this.targetId=e}}class O{static{n(this,"StorageBackedSessionMutation")}storage;release;active=!0;commitResult;endPromise;constructor(e,t){this.storage=e,this.release=t}commit(e,t){if(this.assertActive(),this.commitResult!==void 0)return Promise.reject(new Error("SessionMutator commit already attempted"));try{for(const s of e)if(s.kind==="entry"&&s.entry.type==="message"&&s.entry.message.role==="assistant"&&s.entry.message.stopReason==="pending")throw new p;this.commitResult=this.storage.commit(e,t)}catch(s){this.commitResult=Promise.reject(s)}return this.commitResult}end(e){return this.endPromise!==void 0?this.endPromise:(this.active=!1,this.endPromise=this.settle().finally(this.release),this.endPromise)}getEntries(e,t){return this.assertActive(),this.storage.getEntries(e,t)}getStats(e){return this.assertActive(),this.storage.getStats(e)}getValue(e,t){return this.assertActive(),this.storage.getValue(e,t)}scanValues(e,t){return this.assertActive(),this.storage.scanValues(e,t)}readList(e,t,s){return this.assertActive(),this.storage.readList(e,t,s)}scanBranch(e,t){return this.assertActive(),this.storage.scanBranch(e,t)}settle(){return this.commitResult?.then(()=>{},()=>{})??Promise.resolve()}assertActive(){if(!this.active)throw new Error("SessionMutator cannot be used outside its mutation callback")}}class P{static{n(this,"StorageBackedBranch")}name;session;constructor(e,t){this.name=e,this.session=t}getTipId(e){return this.session.getBranchTip(this.name,e)}async findEntries(e,t){e??={};const s=e.start??await this.getTipId(t);return s===null?[]:this.session.scanBranch({...e,start:s,order:e.order??"newestFirst"},t)}async findEntry(e,t){return e??={},(await this.findEntries({...e,limit:e.limit===void 0?1:Math.min(e.limit,1)},t))[0]}appendMessage(e,t){return this.session.appendToBranch(this.name,{type:"message",message:e},t)}appendCustomEntry(e,t,s){return this.session.appendToBranch(this.name,{type:"custom",customType:e,...t===void 0?{}:{data:t}},s)}}class N{static{n(this,"StorageBackedSession")}metadata;idGenerator;storage;mutationLine;onClose;branches=new Map;closedError=new Error("Session is closed");state="open";closePromise;constructor(e,t,s={}){this.metadata=e,this.idGenerator=s.idGenerator??{next:E},this.storage=t,this.mutationLine=s.mutationLine??new V,this.onClose=s.onClose}async beginMutation(e){this.assertOpen();let t,s;const r=new Promise((h,f)=>{t=h,s=f});let o;const c=new Promise(h=>{o=h});return this.mutationLine.run(async()=>{t(new O(this.storage,o)),await c}).catch(s),r}async mutate(e,t){const s=await this.beginMutation(t);try{return await e(s,t)}finally{await s.end(t)}}async getEntries(e,t){return this.assertOpen(),this.storage.getEntries(e,t)}async getEntry(e,t){return(await this.getEntries([e],t)).get(e)}async getValue(e,t){return this.assertOpen(),this.storage.getValue(e,t)}async scanValues(e,t){return this.assertOpen(),this.storage.scanValues(e,t)}async readList(e,t,s){return this.assertOpen(),this.storage.readList(e,t,s)}async scanBranch(e,t){return this.assertOpen(),this.storage.scanBranch(e,t)}async getStats(e){return this.assertOpen(),this.storage.getStats(e)}async getName(e){return(await this.getValue(u,e))?.value}async getLabel(e,t){return(await this.getValue(l(e),t))?.value}async findEntries(e,t){e??={},this.assertOpen();const s=e.order??"desc";if(e.cursor!==void 0){if(s==="asc"&&e.cursor.seq===Number.MAX_SAFE_INTEGER)return[];if(s==="desc"&&e.cursor.seq<=1)return[]}return this.storage.scanEntries({type:e.type,customType:e.customType,order:s,limit:e.limit,...e.cursor===void 0?{}:s==="asc"?{fromSeq:e.cursor.seq+1}:{toSeq:e.cursor.seq-1}},t)}async findEntry(e,t){return e??={},(await this.findEntries({...e,limit:e.limit===void 0?1:Math.min(e.limit,1)},t))[0]}async branch(e,t){if(this.assertValidBranchName(e),await this.getValue(a(e),t)!==void 0)return this.getOrCreateBranchObject(e)}async createBranch(e,t,s){return this.assertOpen(),this.assertValidBranchName(e),await this.mutate(async r=>{if(await r.getValue(a(e),s)!==void 0)throw new v(e);if(t!==null&&!(await r.getEntries([t],s)).has(t))throw new L(t);await r.commit([d(a(e),t)],s)},s),this.getOrCreateBranchObject(e)}setValue(e,t,s){return this.mutate(async r=>{await r.commit([d(e,t)],s)},s)}deleteValue(e,t){return this.mutate(async s=>{await s.commit([b(e)],t)},t)}appendList(e,t,s){return this.mutate(async r=>{await r.commit([B(e,t)],s)},s)}deleteList(e,t){return this.mutate(async s=>{await s.commit([S(e)],t)},t)}setName(e,t){return e===void 0?this.deleteValue(u,t):this.setValue(u,e,t)}setLabel(e,t,s){const r=l(e);return t===void 0?this.deleteValue(r,s):this.setValue(r,t,s)}close(e){return this.closePromise!==void 0?this.closePromise:(this.state="closing",this.closePromise=this.mutationLine.seal(this.closedError).then(()=>this.storage.close(e)).finally(()=>{this.state="closed",this.onClose?.()}),this.closePromise)}async getBranchTip(e,t){const s=await this.getValue(a(e),t);if(s===void 0)throw new m(`Unknown branch: ${e}`);return s.value}async appendToBranch(e,t,s){if(this.assertOpen(),t.type==="message"&&t.message.role==="assistant"&&t.message.stopReason==="pending")throw new p;const r=this.idGenerator.next();return await this.mutate(async o=>{const c=await o.getValue(a(e),s);if(c===void 0)throw new m(`Unknown branch: ${e}`);await o.commit([y(t.type==="message"?{id:r,parentId:c.value,type:"message",message:t.message}:{id:r,parentId:c.value,type:"custom",customType:t.customType,...t.data===void 0?{}:{data:t.data}}),d(a(e),r)],s)},s),r}getOrCreateBranchObject(e){let t=this.branches.get(e);return t===void 0&&(t=new P(e,this),this.branches.set(e,t)),t}assertValidBranchName(e){if(e.length===0)throw new g(e,"branch name must not be empty");if(e.includes("\0"))throw new g(e,"branch name must not contain \\u0000")}assertOpen(){if(this.state!=="open")throw this.closedError}}export{v as SessionBranchExistsError,g as SessionInvalidBranchError,m as SessionInvariantError,p as SessionPendingAssistantMessageError,L as SessionUnknownTargetError,N as StorageBackedSession};
@@ -1 +0,0 @@
1
- var g=Object.defineProperty;var o=(r,e)=>g(r,"name",{value:e,configurable:!0});import{SessionError as d}from"./types.js";function I(r){throw new d("invalid_entry",`Invalid session mutation: ${r}`)}o(I,"invalidMutation");function c(r){if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new d("invalid_query","limit must be a positive integer")}o(c,"assertValidLimit");function h(r){if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new d("invalid_query","cursor sequence must be a non-negative integer")}o(h,"assertValidCursor");function*p(r,e){if(e==="oldestFirst"){yield*r;return}for(let s=r.length-1;s>=0;s--)yield r[s]}o(p,"ordered");class w{static{o(this,"SessionState")}sequence=0;usedIds=new Set;entries=[];entriesById=new Map;records=[];openOperationsByLane=new Map;lanes=new Map([["main",null]]);log=[];stats={messageCount:0,cachedTokens:0,uncachedTokens:0,totalTokens:0,costTotal:0};name;labels=new Map;get nextSequence(){return this.sequence+1}getLanes(){return[...this.lanes].map(([e,s])=>({lane:e,leafId:s}))}requireLane(e){const s=this.lanes.get(e);if(s===void 0)throw new d("invalid_lane",`Lane not found: ${e}`);return s}validateNewLane(e){if(this.lanes.has(e))throw new d("already_exists",`Lane already exists: ${e}`)}validateTarget(e){if(e!==null&&!this.entriesById.has(e))throw new d("not_found",`Entry not found: ${e}`)}validateUnusedId(e){if(this.usedIds.has(e))throw new d("already_exists",`Session id already exists: ${e}`)}applyMutation(e,s=I){const n=e.kind==="entry"?e.entry.seq:e.kind==="record"?e.record.seq:e.seq;switch(n!==this.sequence+1&&s(`has non-consecutive seq ${n}`),e.kind){case"entry":{if(this.usedIds.has(e.entry.id)&&s(`contains duplicate id ${e.entry.id}`),e.lane!==void 0){const t=this.lanes.get(e.lane);t===void 0&&s(`references missing lane ${e.lane}`),e.entry.parentId!==t&&s("does not chain to the lane leaf")}e.entry.parentId!==null&&!this.entriesById.has(e.entry.parentId)&&s(`references missing parent ${e.entry.parentId}`),this.sequence=n,this.usedIds.add(e.entry.id),this.entries.push(e.entry),this.entriesById.set(e.entry.id,e.entry),e.lane!==void 0&&this.lanes.set(e.lane,e.entry.id),this.log.push({kind:"entry",seq:n,entry:e.entry}),e.entry.type==="message"&&(this.stats.messageCount+=1);break}case"record":{if(this.lanes.has(e.record.lane)||s(`references missing lane ${e.record.lane}`),this.usedIds.has(e.record.id)&&s(`contains duplicate id ${e.record.id}`),this.sequence=n,this.usedIds.add(e.record.id),this.records.push(e.record),e.record.type==="operation_started"){let t=this.openOperationsByLane.get(e.record.lane);t||(t=new Map,this.openOperationsByLane.set(e.record.lane,t)),t.set(e.record.id,e.record)}else e.record.type==="operation_finished"&&this.openOperationsByLane.get(e.record.lane)?.delete(e.record.runId);this.log.push({kind:"record",seq:n,record:e.record}),e.record.type==="usage"&&(this.stats.cachedTokens+=e.record.usage.cacheRead,this.stats.uncachedTokens+=e.record.usage.input+e.record.usage.cacheWrite,this.stats.totalTokens+=e.record.usage.totalTokens,this.stats.costTotal+=e.record.usage.cost.total);break}case"lane":e.leafId!==null&&!this.entriesById.has(e.leafId)&&s(`references missing lane target ${e.leafId}`),this.sequence=n,this.lanes.set(e.lane,e.leafId),this.log.push({kind:"lane",seq:n,lane:e.lane,leafId:e.leafId});break;case"fact":e.fact==="label"&&!this.entriesById.has(e.targetId)&&s(`references missing label target ${e.targetId}`),this.sequence=n,e.fact==="name"?(this.name=e.name,this.log.push({kind:"fact",seq:n,fact:"name",name:e.name})):(e.label===void 0?this.labels.delete(e.targetId):this.labels.set(e.targetId,e.label),this.log.push({kind:"fact",seq:n,fact:"label",targetId:e.targetId,label:e.label}));break}}getEntry(e){return this.entriesById.get(e)}findEntries(e={}){c(e.limit),h(e.cursor?.afterSeq);const s=[];for(const n of p(this.entries,e.order))if(this.matchesEntryQuery(n,e)&&(s.push(n),s.length===e.limit))break;return s}findEntriesOnBranch(e){c(e.limit),h(e.cursor?.afterSeq);const s=[];if(e.order==="oldestFirst")for(const n of[...this.walkToRoot(e.start)].reverse()){const t=n.id===e.stopAtId||n.type===e.stopAtType;if(this.matchesEntryQuery(n,e)&&s.push(n),t||s.length===e.limit)break}else for(const n of this.walkToRoot(e.start,e))if(this.matchesEntryQuery(n,e)&&s.push(n),s.length===e.limit)break;return s}findRecords(e={}){c(e.limit),h(e.afterSeq);const s=[];for(const n of p(this.records,e.order))if(this.matchesRecordQuery(n,e)&&(s.push(n),s.length===e.limit))break;return s}findOpenOperations(e,s){c(s?.limit);const n=this.openOperationsByLane.get(e),t=n?[...n.values()].reverse():[];return s?.limit===void 0?t:t.slice(0,s.limit)}getLog(e={}){c(e.limit),h(e.afterSeq);const s=[];for(const n of this.log)if(!(e.afterSeq!==void 0&&n.seq<=e.afterSeq)&&(s.push(n),s.length===e.limit))break;return s}getName(){return this.name}getLabel(e){return this.labels.get(e)}getStats(){return this.stats}createForkMutations(e){let s,n;if(e.scope==="tree")s=this.findEntries({order:"oldestFirst"}),n=this.getLanes();else{const i=e.entryId??this.requireLane("main");let l=null;if(i!==null){const f=this.getEntry(i);if(!f||f.type!=="message")throw new d("invalid_fork_target",`Fork target is not a message entry: ${i}`);l=(e.position??(e.entryId===void 0?"at":"before"))==="at"?f.id:f.parentId}s=l===null?[]:this.findEntriesOnBranch({start:l,order:"oldestFirst"}),n=[{lane:"main",leafId:l}]}const t=[];let a=1;for(const i of s)t.push({kind:"entry",entry:{...structuredClone(i),seq:a++}});for(const i of n)t.push({kind:"lane",seq:a++,lane:i.lane,leafId:i.leafId});this.name!==void 0&&t.push({kind:"fact",seq:a++,fact:"name",name:this.name});for(const i of s){const l=this.labels.get(i.id);l!==void 0&&t.push({kind:"fact",seq:a++,fact:"label",targetId:i.id,label:l})}return t}*walkToRoot(e,s){if(e===null)return;const n=new Set;let t=this.entriesById.get(e);if(!t)throw new d("not_found",`Entry not found: ${e}`);for(;t;){if(n.has(t.id))throw new d("invalid_entry",`Session branch contains a cycle at ${t.id}`);if(n.add(t.id),yield t,t.id===s?.stopAtId||t.type===s?.stopAtType||t.parentId===null)break;const a=t.parentId;if(t=this.entriesById.get(a),!t)throw new d("invalid_entry",`Entry not found: ${a}`)}}matchesEntryQuery(e,s){return(s.type===void 0||e.type===s.type)&&(s.customType===void 0||e.type==="custom"&&e.customType===s.customType)&&(s.cursor===void 0||(s.order==="oldestFirst"?e.seq>s.cursor.afterSeq:e.seq<s.cursor.afterSeq))}matchesRecordQuery(e,s){return(s.lane===void 0||e.lane===s.lane)&&(s.type===void 0||e.type===s.type)&&(s.runId===void 0||(e.type==="operation_started"?e.id===s.runId:"runId"in e&&e.runId===s.runId))&&(s.operationKind===void 0||e.type==="operation_started"&&e.intent.kind===s.operationKind)&&(s.afterSeq===void 0||e.seq>s.afterSeq)}}export{w as SessionState};
@@ -1 +0,0 @@
1
- var i=Object.defineProperty;var r=(e,t)=>i(e,"name",{value:t,configurable:!0});function o(e){return`benchmark-entry-${e.toString().padStart(8,"0")}`}r(o,"storageBenchmarkEntryId");function n(e,t){const a=Math.min(100,t);return{name:`synthetic linear branch: ${e}, 256-byte payloads`,entryCount:t,payloadBytes:256,lookupIds:Array.from({length:a},(h,s)=>{const c=Math.floor(s*(t-1)/Math.max(1,a-1));return o(c)}),tipId:o(t-1)}}r(n,"createDataset");const d=[n("1k entries",1e3),n("10k entries",1e4),n("100k entries",1e5)];export{d as STORAGE_BENCHMARK_DATASETS,o as storageBenchmarkEntryId};
@@ -1 +0,0 @@
1
- var u=Object.defineProperty;var o=(e,t)=>u(e,"name",{value:t,configurable:!0});import{BACKGROUND_CONTEXT as n}from"../../../context.js";import{branchTip as l,laneConfig as _,laneState as E,setValue as c}from"../../values.js";import{STORAGE_BENCHMARK_DATASETS as S}from"./datasets.js";import{generateStorageBenchmarkSeedTransactions as R}from"./storage.js";function d(e){return`benchmark-session-${e.toString().padStart(8,"0")}`}o(d,"sessionRepoBenchmarkSessionId");const r=d(0),p=d(1);function m(e,t){return{name:`synthetic catalog: ${e} closed sessions`,sessionCount:t}}o(m,"createCatalogDataset");const T=[m("100",100),m("1k",1e3),m("10k",1e4)];async function f(e,t){const a=[];for(let s=0;s<t.sessionCount;s++){const i=await e.create({id:d(s)},n);a.push(i.metadata),await i.close(n)}return a}o(f,"seedSessionRepoCatalogBenchmark");const h=[{name:"list sessions",expectedResult(e){return e.sessionCount},async run(e){return(await e.list(void 0,n)).length}}],x=[{name:"create empty session",expectedResult:1,prepare(e){return Promise.resolve({async run(){return(await e.create({id:r},n)).metadata.id===r?1:0}})}},{name:"open closed empty session",expectedResult:1,async prepare(e){const t=await e.create({id:r},n),{metadata:a}=t;return await t.close(n),{async run(){return(await e.open(a,n)).metadata.id===a.id?1:0}}}},{name:"delete closed empty session",expectedResult:1,async prepare(e){const t=await e.create({id:r},n),{metadata:a}=t;return await t.close(n),{async run(){return await e.delete(a,n),1}}}}],y=[S[0],S[1]];async function k(e,t){const a=await e.create({id:r},n);for(const s of R(t))await a.mutate(i=>i.commit(s,n),n);return await a.mutate(s=>s.commit([c(l("main"),t.tipId),c(_("main"),{model:{provider:"benchmark",modelId:"benchmark"},thinkingLevel:"off",activeToolNames:[]}),c(E("main"),{currentOperationId:null,lastOperationId:null,inbox:[]})],n),n),a.metadata}o(k,"seedSessionRepoForkBenchmark");const w=[{name:"fork open current branch",expectedResult(e){return e.entryCount},async run(e,t,a){const s=await e.fork(t,{id:p,scope:"branch",branch:"main"},n);return s.metadata.id===p&&s.metadata.parentSessionId===t.id?a.entryCount:0}}];export{T as SESSION_REPO_CATALOG_BENCHMARK_DATASETS,h as SESSION_REPO_CATALOG_READ_BENCHMARK_SCENARIOS,x as SESSION_REPO_CATALOG_WRITE_BENCHMARK_SCENARIOS,y as SESSION_REPO_FORK_BENCHMARK_DATASETS,w as SESSION_REPO_FORK_WRITE_BENCHMARK_SCENARIOS,f as seedSessionRepoCatalogBenchmark,k as seedSessionRepoForkBenchmark,d as sessionRepoBenchmarkSessionId};
@@ -1 +0,0 @@
1
- var d=Object.defineProperty;var a=(t,e)=>d(t,"name",{value:e,configurable:!0});import{BACKGROUND_CONTEXT as n}from"../../../context.js";import{insertEntry as E,insertUsage as l}from"../../commit.js";import{branchTip as y,setValue as h}from"../../values.js";import{STORAGE_BENCHMARK_DATASETS as g,storageBenchmarkEntryId as i}from"./datasets.js";const S=165e10,u=250,s=g[0];function T(t,e){const r=i(t),c=`${r}:`;return{id:r,parentId:t===0?null:i(t-1),type:"message",message:{role:"user",content:[{type:"text",text:c+"x".repeat(Math.max(0,e-c.length))}],timestamp:S}}}a(T,"createEntry");function o(t,e,r){return Array.from({length:e},(c,p)=>E(T(t+p,r)))}a(o,"createStorageBenchmarkTransaction");function*_(t){for(let e=0;e<t.entryCount;e+=u)yield o(e,Math.min(u,t.entryCount-e),t.payloadBytes)}a(_,"generateStorageBenchmarkSeedTransactions");async function A(t,e){for(const r of _(e))await t.commit(r,n)}a(A,"seedStorageBenchmark");const C=o(0,1,256),R=o(0,100,256),m=i(s.entryCount),f=[...o(s.entryCount,1,s.payloadBytes),h(y("main"),m),l({id:"benchmark-usage",entryId:m,adjustment:!1,usage:{input:1e3,output:250,cacheRead:500,cacheWrite:0,totalTokens:1250,cost:{input:.001,output:.001,cacheRead:1e-4,cacheWrite:0,total:.0021}}})],k=[{name:"get 100 distributed entries",expectedResult(t){return t.lookupIds.length},async run(t,e){return(await t.getEntries([...e.lookupIds],n)).size}},{name:"scan latest 50 entries",expectedResult(t){return Math.min(50,t.entryCount)},async run(t){return(await t.scanEntries({order:"desc",limit:50},n)).length}},{name:"scan full branch structure",expectedResult(t){return t.entryCount},async run(t,e){return(await t.scanBranchStructure({start:e.tipId,order:"newestFirst"},n)).length}}],N=[{name:"commit one message entry",writeCount:1,async run(t){return(await t.commit(C,n)).seqs.length}},{name:"commit 100 message entries",writeCount:100,async run(t){return(await t.commit(R,n)).seqs.length}},{name:`commit mixed append (${s.name})`,writeCount:3,prepare(t){return A(t,s)},async run(t){return(await t.commit(f,n)).seqs.length}}];export{k as STORAGE_READ_BENCHMARK_SCENARIOS,N as STORAGE_WRITE_BENCHMARK_SCENARIOS,_ as generateStorageBenchmarkSeedTransactions,A as seedStorageBenchmark};
@@ -1 +0,0 @@
1
- var X=Object.defineProperty;var g=(c,d)=>X(c,"name",{value:d,configurable:!0});import{deepStrictEqual as u,rejects as R,strictEqual as o}from"node:assert/strict";import{BACKGROUND_CONTEXT as e}from"../../../context.js";import{insertEntry as S,insertUsage as J}from"../../commit.js";import{appendList as C,branchTip as P,deleteList as W,entryLabel as M,laneConfig as k,laneState as v,list as E,operationMeta as _,operationPreparation as $,operationResult as F,operationState as G,operationToolArgs as z,pendingEntry as K,sessionName as O,setValue as r,value as j}from"../../values.js";const p="00000000-0000-7000-8000-000000000001",b="00000000-0000-7000-8000-000000000002",x="00000000-0000-7000-8000-000000000003",Q="00000000-0000-7000-8000-000000000004",T="00000000-0000-7000-8000-000000000005",U="00000000-0000-7000-8000-000000000006",Y="00000000-0000-7000-8000-000000000007",V={currentOperationId:null,lastOperationId:null,inbox:[]},B=j("test.application.value"),A=E("test.application.list"),I={model:{provider:"provider",modelId:"model"},thinkingLevel:"off",activeToolNames:["read"]};async function L(c,d="main"){return(await c.branch(d,e))?.getTipId(e)}g(L,"getBranchTip");function q(c){return{role:"assistant",content:c==="toolUse"?[{type:"toolCall",id:"call",name:"read",arguments:{}}]:[{type:"text",text:c}],api:"anthropic-messages",provider:"anthropic",model:"claude-sonnet-4-5",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:c,...c==="deferred"?{deferred:{provider:"anthropic",modelId:"claude-sonnet-4-5",api:"anthropic-messages",id:"job"}}:{},timestamp:1}}g(q,"assistantMessage");function Z(){return{id:Q,adjustment:!0,usage:{input:1,output:2,cacheRead:0,cacheWrite:0,totalTokens:3,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}}g(Z,"usageRow");function N(c,d){return async()=>({repo:await c(),...d===void 0?{}:{close:d}})}g(N,"prepareRepoCaseFactory");function w(c,d,f,i){return{group:d,name:f,async run(){const t=await c();try{await i(t)}finally{await t.close?.()}}}}g(w,"createCase");function ee(c,d){const f=N(c,d);return[w(f,"lifecycle","creates a session with no implicit branch and rejects duplicate ids",async({repo:i})=>{const t=await i.create({id:"session"},e);o(t.metadata.id,"session"),o(Number.isSafeInteger(t.metadata.createdAt),!0),o(t.metadata.storageVersion,1),o(await t.branch("main",e),void 0),o(await t.getValue(v("main"),e),void 0),o(await t.getValue(k("main"),e),void 0),await R(i.create({id:"session"},e)),await t.close(e)}),w(f,"lifecycle","close drains an acquired scope and rejects a queued mutation callback",async({repo:i})=>{const t=await i.create({id:"session"},e),a=await t.beginMutation(e);let n=!1;const s=t.mutate(()=>{n=!0},e);s.catch(()=>{});const l=t.close(e);await a.end(e),await R(s),await l,o(n,!1)}),w(f,"lifecycle","lists metadata and preserves state across close and reopen",async({repo:i})=>{const t=await i.create({id:"first"},e);await t.setName("preserved",e),await(await i.create({id:"second",parentSessionId:"parent"},e)).close(e);const n=await i.list(void 0,e);u(n.map(({id:l,parentSessionId:m})=>({id:l,parentSessionId:m})).sort((l,m)=>l.id.localeCompare(m.id)),[{id:"first",parentSessionId:void 0},{id:"second",parentSessionId:"parent"}]),await t.close(e),await R(t.getName(e));const s=await i.open(t.metadata,e);o(s===t,!1),o(await s.getName(e),"preserved"),await s.close(e)}),w(f,"lifecycle","deletes closed sessions without affecting other sessions",async({repo:i})=>{const t=await i.create({id:"removed"},e),a=await i.create({id:"retained"},e);await Promise.all([t.close(e),a.close(e)]),await i.delete(t.metadata,e),u((await i.list(void 0,e)).map(({id:n})=>n),["retained"]),await R(i.open(t.metadata,e)),await R(i.delete(t.metadata,e))})]}g(ee,"createSessionRepoLifecycleConformance");function ae(c,d){const f=N(c,d);return[w(f,"ownership","rejects opening an already-open session",async({repo:i})=>{const t=await i.create({id:"session"},e);await R(i.open(t.metadata,e)),await t.close(e);const a=await i.open(t.metadata,e);await R(i.open(t.metadata,e)),await a.close(e)})]}g(ae,"createSessionRepoOwnershipConformance");function te(c,d){const f=N(c,d);return[w(f,"messages","rejects pending assistant messages without changing the tree",async({repo:i})=>{const t=await i.create({id:"session"},e),a=await t.createBranch("main",null,e);await R(a.appendMessage(q("pending"),e)),o(await L(t),null),u(await t.findEntries(void 0,e),[]),await t.close(e)}),w(f,"messages","preserves every settled assistant stop reason",async({repo:i})=>{const t=await i.create({id:"session"},e),a={stop:q("stop"),length:q("length"),toolUse:q("toolUse"),error:q("error"),aborted:q("aborted"),deferred:q("deferred")},n=await t.createBranch("main",null,e),s=Object.values(a),l=[];for(const h of s)l.push(await n.appendMessage(h,e));const m=await t.findEntries({order:"asc",type:"message"},e);u(m.map(h=>h.id),l);for(const[h,y]of m.entries()){if(y.type!=="message")throw new Error("Expected message entry");u(y.message,s[h])}o(await L(t),l.at(-1)),await t.close(e)})]}g(te,"createSessionRepoMessageConformance");function ie(c,d){const f=N(c,d);return[w(f,"forks","tree-forks a fresh session before first attachment",async({repo:i})=>{const t=await i.create({id:"source"},e),a=await i.fork(t.metadata,{id:"fork",scope:"tree"},e);o(a.metadata.id,"fork"),o(a.metadata.parentSessionId,"source"),o(await a.branch("main",e),void 0),o(await a.getValue(k("main"),e),void 0),o(await a.getValue(v("main"),e),void 0),u(await a.findEntries(void 0,e),[]),u(await a.getStats(e),{messageCount:0,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}),await Promise.all([t.close(e),a.close(e)])}),w(f,"forks","rejects a data-only branch and releases its destination id",async({repo:i})=>{const t=await i.create({id:"source"},e);await t.createBranch("data",null,e),await R(i.fork(t.metadata,{id:"destination",scope:"branch",branch:"data"},e)),u((await i.list(void 0,e)).map(({id:n})=>n),["source"]);const a=await i.create({id:"destination"},e);await Promise.all([t.close(e),a.close(e)])}),w(f,"forks","forks one named configured branch with scoped values and a zero ledger",async({repo:i})=>{const t=await i.create({id:"source"},e);await t.mutate(s=>s.commit([S({id:p,parentId:null,type:"custom",customType:"root"}),S({id:b,parentId:p,type:"message",message:{role:"user",content:"child",timestamp:1}}),S({id:x,parentId:p,type:"custom",customType:"sibling"}),r(P("main"),x),r(P("review"),b),r(k("review"),I),r(v("review"),{currentOperationId:T,lastOperationId:"previous",inbox:[{entryId:U,kind:"write"}]}),r(F("previous"),{operationId:"previous",kind:"navigation",status:"completed",fromTipId:p,tipId:b,startedAt:1,endedAt:2}),r(O,"source name"),r(B,{copied:!1}),C(A,{copied:!1}),r(M(p),"root label"),r(M(x),"sibling label"),r(K(U),{type:"custom",customType:"pending"}),r(_(T),{operationId:T,lane:"review",sourceTipId:b,startedAt:1,intent:{kind:"compaction"}}),r(G(T),{at:"summary.deciding",control:{status:"running"},settings:{compaction:{enabled:!0,reserveTokens:1,keepRecentTokens:1},steeringMode:"all",followUpMode:"all",toolExecution:"sequential"},latestAssistantEntryId:null,task:{taskId:T,reason:"manual",boundary:{kind:"finish"}}}),r(z(T,p,0),{argument:!0}),r($(T,T),{kind:"compaction",messagesToSummarize:[],turnPrefixMessages:[],retainedTail:[],isSplitTurn:!1,tokensBefore:0,fileOps:{read:[],written:[],edited:[]},settings:{enabled:!0,reserveTokens:1,keepRecentTokens:1}}),J(Z())],e),e);const a=await i.fork(t.metadata,{id:"fork",scope:"branch",branch:"review",entryId:b,position:"at"},e);u((await a.findEntries({order:"asc"},e)).map(({id:s})=>s),[p,b]),o(await a.branch("main",e),void 0),o(await L(a,"review"),b),u((await a.getValue(k("review"),e))?.value,I),u((await a.getValue(v("review"),e))?.value,V),o(await a.getValue(k("main"),e),void 0),o(await a.getValue(v("main"),e),void 0),o(await a.getName(e),"source name"),o(await a.getValue(B,e),void 0),u(await a.readList(A,void 0,e),[]),o(await a.getLabel(p,e),"root label"),o(await a.getLabel(x,e),void 0),o(await a.getValue(F("previous"),e),void 0),o(await a.getValue(K(U),e),void 0),o(await a.getValue(_(T),e),void 0),o(await a.getValue(G(T),e),void 0),o(await a.getValue(z(T,p,0),e),void 0),o(await a.getValue($(T,T),e),void 0);const n=await a.getStats(e);o(n.messageCount,1),u(n.usage,{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}),await Promise.all([t.close(e),a.close(e)])}),w(f,"forks","enforces branch ancestry for at and before placement",async({repo:i})=>{const t=await i.create({id:"source"},e);await t.mutate(m=>m.commit([S({id:p,parentId:null,type:"custom",customType:"root"}),S({id:b,parentId:p,type:"custom",customType:"child"}),S({id:x,parentId:p,type:"custom",customType:"sibling"}),r(P("main"),b),r(k("main"),I),r(v("main"),V),r(P("empty"),null),r(k("empty"),I),r(v("empty"),V)],e),e);const a=await i.fork(t.metadata,{id:"before",scope:"branch",branch:"main",entryId:b,position:"before"},e);o(await L(a),p),u((await a.findEntries({order:"asc"},e)).map(({id:m})=>m),[p]);const n=await i.fork(t.metadata,{id:"mid",scope:"branch",branch:"main",entryId:p,position:"at"},e);o(await L(n),p),u((await n.findEntries({order:"asc"},e)).map(({id:m})=>m),[p]);const s=await i.fork(t.metadata,{id:"before-root",scope:"branch",branch:"main",entryId:p,position:"before"},e);o(await L(s),null),u(await s.findEntries({order:"asc"},e),[]);const l=await i.fork(t.metadata,{id:"empty",scope:"branch",branch:"empty"},e);o(await L(l,"empty"),null),u(await l.findEntries({order:"asc"},e),[]);for(const[m,h,y]of[["off-branch","main",x],["unknown","main",Y],["null-tip","empty",p]])await R(i.fork(t.metadata,{id:m,scope:"branch",branch:h,entryId:y},e));u((await i.list(void 0,e)).map(({id:m})=>m).sort(),["before","before-root","empty","mid","source"]),await Promise.all([t.close(e),a.close(e),s.close(e),l.close(e),n.close(e)])}),w(f,"forks","forks a closed source session",async({repo:i})=>{const t=await i.create({id:"source"},e);await t.mutate(n=>n.commit([S({id:p,parentId:null,type:"custom",customType:"root"}),r(P("main"),p),r(k("main"),I),r(v("main"),V),r(B,"excluded"),C(A,"excluded")],e),e),await t.close(e);const a=await i.fork(t.metadata,{id:"fork",scope:"branch",branch:"main"},e);o(await L(a),p),u((await a.getValue(k("main"),e))?.value,I),u((await a.getValue(v("main"),e))?.value,V),o(await a.getValue(B,e),void 0),u(await a.readList(A,void 0,e),[]),await a.close(e)}),w(f,"forks","forks the whole configured tree with fresh lane state",async({repo:i})=>{const t=await i.create({id:"source"},e);await t.mutate(n=>n.commit([S({id:p,parentId:null,type:"custom",customType:"root"}),S({id:b,parentId:p,type:"custom",customType:"child"}),S({id:x,parentId:p,type:"custom",customType:"sibling"}),r(P("main"),b),r(k("main"),I),r(v("main"),V),r(P("review"),x),r(k("review"),I),r(v("review"),V),r(P("notes"),p),r(B,{copied:!0})],e),e);const a=await i.fork(t.metadata,{id:"fork",scope:"tree"},e);u((await a.findEntries({order:"asc"},e)).map(({id:n})=>n),[p,b,x]),o(await L(a),b),o(await L(a,"review"),x),o(await L(a,"notes"),p),o(await a.getValue(k("notes"),e),void 0),o(await a.getValue(v("notes"),e),void 0),u((await a.getValue(k("review"),e))?.value,I),u((await a.getValue(v("review"),e))?.value,V),u((await a.getValue(B,e))?.value,{copied:!0}),await Promise.all([t.close(e),a.close(e)])}),w(f,"forks","rejects only surviving unknown reserved scalar state",async({repo:i})=>{const t=await i.create({id:"source"},e);await t.createBranch("main",null,e),await t.mutate(s=>s.commit([r(k("main"),I),r(v("main"),V)],e),e);for(const s of["pi","pi.unknown"]){const l=j(s);await t.setValue(l,!0,e),await R(i.fork(t.metadata,{id:"tree",scope:"tree"},e)),await R(i.fork(t.metadata,{id:"branch",scope:"branch",branch:"main"},e)),await t.deleteValue(l,e)}await t.close(e);const a=await i.fork(t.metadata,{id:"tree",scope:"tree"},e),n=await i.fork(t.metadata,{id:"branch",scope:"branch",branch:"main"},e);await Promise.all([a.close(e),n.close(e)])})]}g(ie,"createSessionRepoForkBehaviorConformance");function he(c,d){return[...se(c,d),...oe(c,d),...ne(c,d)]}g(he,"createSessionRepoStreamingForkConformance");function ne(c,d){const f=N(c,d);return[w(f,"fork lane validation","ignores malformed unrelated lanes",async({repo:i})=>{const t=await i.create({id:"source"},e);let a,n;try{await t.createBranch("main",null,e),await t.mutate(s=>s.commit([r(k("main"),I),r(v("main"),V),r(k("unrelated"),I)],e),e),a=await i.fork(t.metadata,{id:"tree",scope:"tree"},e),n=await i.fork(t.metadata,{id:"branch",scope:"branch",branch:"main"},e),o(await L(n),null)}finally{await Promise.all([t.close(e),a?.close(e),n?.close(e)])}})]}g(ne,"createSessionRepoForkLaneValidationConformance");function se(c,d){const f=N(c,d);return["open","closed"].flatMap(i=>[w(f,`fork application lists (${i} source)`,"tree fork copies lists at distinct addresses",async({repo:t})=>{const a=await t.create({id:"source"},e);let n;try{const s=E("test.application.events"),l=E(s.namespace,"other"),m=E("pi2.events"),h=E(s.namespace,"absent");await a.appendList(s,"event",e),await a.appendList(l,"sibling",e),await a.appendList(m,"other namespace",e),i==="closed"&&await a.close(e),n=await t.fork(a.metadata,{id:"fork",scope:"tree"},e),u((await n.readList(s,void 0,e)).map(({value:y})=>y),["event"]),u((await n.readList(l,void 0,e)).map(({value:y})=>y),["sibling"]),u((await n.readList(m,void 0,e)).map(({value:y})=>y),["other namespace"]),u(await n.readList(h,void 0,e),[])}finally{await Promise.all([a.close(e),n?.close(e)])}}),w(f,`fork application lists (${i} source)`,"tree fork copies only survivors after list deletion and reappend",async({repo:t})=>{const a=await t.create({id:"source"},e);let n;try{const s=E("test.application.events"),l=E(s.namespace,"deleted");await a.appendList(s,"old",e),await a.appendList(l,"removed",e),await a.mutate(m=>m.commit([W(s),C(s,"temporary"),W(s),C(s,"first survivor"),W(l)],e),e),await a.appendList(s,"second survivor",e),i==="closed"&&await a.close(e),n=await t.fork(a.metadata,{id:"fork",scope:"tree"},e),u((await n.readList(s,void 0,e)).map(({value:m})=>m),["first survivor","second survivor"]),u(await n.readList(l,void 0,e),[])}finally{await Promise.all([a.close(e),n?.close(e)])}}),w(f,`fork application lists (${i} source)`,"tree fork preserves list element sequences including gaps",async({repo:t})=>{const a=await t.create({id:"source"},e);let n;try{const s=E("test.application.events"),l=await a.mutate(m=>m.commit([r(O,"before"),C(s,"first"),r(O,"between"),C(s,"second")],e),e);i==="closed"&&await a.close(e),n=await t.fork(a.metadata,{id:"fork",scope:"tree"},e),u(await n.readList(s,void 0,e),[{seq:l.seqs[1],value:"first"},{seq:l.seqs[3],value:"second"}])}finally{await Promise.all([a.close(e),n?.close(e)])}}),...["asc","desc"].map(t=>w(f,`fork application lists (${i} source)`,`tree fork continues ${t} pagination using source cursors`,async({repo:a})=>{const n=await a.create({id:"source"},e);let s;try{const l=E("test.application.events");for(const D of["first","second","third"])await n.appendList(l,D,e);const m=await n.readList(l,{order:t,limit:2},e);o(m.length,2);const h={seq:m[1].seq},y=await n.readList(l,{order:t,cursor:h,limit:2},e);u(y.map(({value:D})=>D),[t==="asc"?"third":"first"]);const H={seq:y[0].seq};i==="closed"&&await n.close(e),s=await a.fork(n.metadata,{id:"fork",scope:"tree"},e),u(await s.readList(l,{order:t,limit:2},e),m),u(await s.readList(l,{order:t,cursor:h,limit:2},e),y),u(await s.readList(l,{order:t,cursor:H,limit:2},e),[])}finally{await Promise.all([n.close(e),s?.close(e)])}}))])}g(se,"createSessionRepoForkApplicationListConformance");function oe(c,d){const f=N(c,d);return["open","closed"].flatMap(i=>[w(f,`branch fork application state (${i} source)`,"excludes overwritten and unchanged application values",async({repo:t})=>{const a=await t.create({id:"source"},e);let n;try{const s=j("test.application.state"),l=j("test.application.settings"),m=await a.createBranch("review",null,e);await a.mutate(y=>y.commit([r(k("review"),I),r(v("review"),V),r(s,"v1"),r(l,"predates fork point")],e),e);const h=await m.appendCustomEntry("fork-point",void 0,e);await a.setValue(s,"v2",e),o((await a.getValue(s,e))?.value,"v2"),i==="closed"&&await a.close(e),n=await t.fork(a.metadata,{scope:"branch",branch:"review",entryId:h},e),o(await L(n,"review"),h),o(await n.getValue(s,e),void 0),o(await n.getValue(l,e),void 0)}finally{await Promise.all([a.close(e),n?.close(e)])}}),w(f,`branch fork application state (${i} source)`,"excludes deleted/reappended and untouched application lists",async({repo:t})=>{const a=await t.create({id:"source"},e);let n;try{const s=E("test.application.events"),l=E(s.namespace,"untouched"),m=await a.createBranch("review",null,e);await a.mutate(y=>y.commit([r(k("review"),I),r(v("review"),V),C(s,"old first"),C(s,"old second"),C(l,"predates fork point")],e),e);const h=await m.appendCustomEntry("fork-point",void 0,e);await a.deleteList(s,e),await a.appendList(s,"new",e),u((await a.readList(s,void 0,e)).map(({value:y})=>y),["new"]),i==="closed"&&await a.close(e),n=await t.fork(a.metadata,{scope:"branch",branch:"review",entryId:h},e),o(await L(n,"review"),h),u(await n.readList(s,void 0,e),[]),u(await n.readList(l,void 0,e),[])}finally{await Promise.all([a.close(e),n?.close(e)])}})])}g(oe,"createSessionRepoBranchForkApplicationStateConformance");function re(c,d){const f=N(c,d);return[w(f,"fork coordination","publishes create when it reserves a shared destination id first",async({repo:i})=>{const t=await i.create({id:"source"},e),a=await Promise.allSettled([i.create({id:"destination"},e),i.fork(t.metadata,{id:"destination",scope:"tree"},e)]);o(a[0].status,"fulfilled"),o(a[1].status,"rejected"),a[0].status==="fulfilled"&&await a[0].value.close(e),await t.close(e)}),w(f,"fork coordination","publishes fork when it reserves a shared destination id first",async({repo:i})=>{const t=await i.create({id:"source"},e),a=await Promise.allSettled([i.fork(t.metadata,{id:"destination",scope:"tree"},e),i.create({id:"destination"},e)]);o(a[0].status,"fulfilled"),o(a[1].status,"rejected"),a[0].status==="fulfilled"&&await a[0].value.close(e),await t.close(e)})]}g(re,"createSessionRepoForkDestinationReservationConformance");function ce(c,d){const f=N(c,d);return[w(f,"fork coordination","captures one coherent boundary between source commits",async({repo:i})=>{const t=await i.create({id:"source"},e),a=await t.beginMutation(e),n=a.commit([S({id:p,parentId:null,type:"custom",customType:"first"}),r(P("main"),p),r(k("main"),I),r(v("main"),V),r(O,"first name"),r(M(p),"first label")],e),s=i.fork(t.metadata,{id:"fork",scope:"branch",branch:"main"},e),l=t.mutate(h=>h.commit([S({id:b,parentId:p,type:"custom",customType:"second"}),r(P("main"),b),r(O,"second name"),r(M(p),"second label")],e),e),[,m]=await Promise.all([n,s]);await a.end(e),await l,o(await L(m),p),u((await m.findEntries({order:"asc"},e)).map(({id:h})=>h),[p]),o(await m.getName(e),"first name"),o(await m.getLabel(p,e),"first label"),await Promise.all([t.close(e),m.close(e)])})]}g(ce,"createSessionRepoForkSourceSnapshotConformance");function de(c,d){return[...re(c,d),...ce(c,d)]}g(de,"createSessionRepoForkCoordinationConformance");function le(c,d){return[...ie(c,d),...de(c,d)]}g(le,"createSessionRepoForkConformance");function ye(c,d){return[...ee(c,d),...ae(c,d),...te(c,d),...le(c,d)]}g(ye,"createSessionRepoConformance");export{ye as createSessionRepoConformance,ie as createSessionRepoForkBehaviorConformance,le as createSessionRepoForkConformance,de as createSessionRepoForkCoordinationConformance,re as createSessionRepoForkDestinationReservationConformance,ce as createSessionRepoForkSourceSnapshotConformance,ee as createSessionRepoLifecycleConformance,te as createSessionRepoMessageConformance,ae as createSessionRepoOwnershipConformance,he as createSessionRepoStreamingForkConformance};
@@ -1 +0,0 @@
1
- var C=Object.defineProperty;var w=(i,e)=>C(i,"name",{value:e,configurable:!0});var A=function(i,e,a){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var s,c;if(a){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");s=e[Symbol.asyncDispose]}if(s===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");s=e[Symbol.dispose],a&&(c=s)}if(typeof s!="function")throw new TypeError("Object not disposable.");c&&(s=w(function(){try{c.call(this)}catch(o){return Promise.reject(o)}},"dispose")),i.stack.push({value:e,dispose:s,async:a})}else a&&i.stack.push({async:!0});return e},I=(function(i){return function(e){function a(k){e.error=e.hasError?new i(k,e.error,"An error was suppressed during disposal."):k,e.hasError=!0}w(a,"fail");var s,c=0;function o(){for(;s=e.stack.pop();)try{if(!s.async&&c===1)return c=0,e.stack.push(s),Promise.resolve().then(o);if(s.dispose){var k=s.dispose.call(s.value);if(s.async)return c|=2,Promise.resolve(k).then(o,function(L){return a(L),o()})}else c|=1}catch(L){a(L)}if(c===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return w(o,"next"),o()}})(typeof SuppressedError=="function"?SuppressedError:function(i,e,a){var s=new Error(a);return s.name="SuppressedError",s.error=i,s.suppressed=e,s});import{deepStrictEqual as n,ok as _,rejects as f,strictEqual as h}from"node:assert/strict";import{BACKGROUND_CONTEXT as t}from"../../../context.js";import{insertEntry as r,insertUsage as g}from"../../commit.js";import{appendList as E,branchTip as S,deleteList as V,deleteValue as x,entryLabel as W,list as P,pendingEntry as j,setValue as u,value as T}from"../../values.js";const M=165e10,q=T("test.session.name"),d=w(i=>T("test.value",i),"testValue"),D=w((i="")=>T("test.value",i),"testValuePrefix"),v=w(i=>P("test.list",i),"testList");function p(i,e,a,s){return{group:e,name:a,async run(){const c={stack:[],error:void 0,hasError:!1};try{const o=A(c,await i(),!0);await s(o)}catch(o){c.error=o,c.hasError=!0}finally{const o=I(c);o&&await o}}}}w(p,"createCase");function y(i,e,a={}){return{input:i,output:e,cacheRead:i+1,cacheWrite:e+1,...a.cacheWrite1h===void 0?{}:{cacheWrite1h:a.cacheWrite1h},...a.reasoning===void 0?{}:{reasoning:a.reasoning},totalTokens:i+e,cost:{input:i/100,output:e/100,cacheRead:(i+1)/100,cacheWrite:(e+1)/100,total:(i+e+2)/100}}}w(y,"usage");function R(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}w(R,"zeroUsage");function m(i,e=null,a=i){return{id:i,parentId:e,type:"message",message:{role:"user",content:[{type:"text",text:a}],timestamp:M}}}w(m,"userEntry");function l(i,e,a="note",s={id:i}){return{id:i,parentId:e,type:"custom",customType:a,data:s}}w(l,"customEntry");function U(i,e){return{id:i,parentId:e,type:"compaction",summary:`summary:${i}`,retainedTail:[],tokensBefore:10,fromHook:!1}}w(U,"compactionEntry");function b(i){return i.map(e=>e.id)}w(b,"ids");function F(i){for(let e=1;e<i.length;e++)_(i[e-1]<i[e],`Expected ${i.join(", ")} to be strictly increasing`)}w(F,"assertStrictlyIncreasing");async function B(i,e){n(e.stats,await i.getStats(t))}w(B,"assertCommitStats");function X(i){return[p(i,"transactions","commits mixed writes atomically in write order",async({storage:e})=>{const a=await e.commit([r(m("entry")),u(q,"session"),g({id:"usage",usage:y(2,3),adjustment:!1,entryId:"entry"})],t);h(a.seqs.length,3),h(a.firstSeq,a.seqs[0]),await B(e,a),F(a.seqs),_(Number.isSafeInteger(a.timestamp)&&a.timestamp>=0),n(await e.getEntries(["entry"],t),new Map([["entry",{...m("entry"),seq:a.seqs[0],timestamp:a.timestamp}]])),n(await e.getValue(q,t),{address:q,value:"session",seq:a.seqs[1]}),n(await e.scanUsage({order:"asc"},t),[{id:"usage",seq:a.seqs[2],usage:y(2,3),adjustment:!1,entryId:"entry"}])}),p(i,"transactions","rolls back every store when a mixed transaction fails",async({storage:e})=>{await e.commit([r(m("root")),g({id:"taken",usage:y(1,1),adjustment:!1})],t);const a=await e.scanEntries({order:"asc"},t),s=await e.scanUsage({order:"asc"},t),c=await e.getStats(t);await f(e.commit([u(q,"transient"),r(l("transient-entry","root")),g({id:"transient-usage",usage:y(5,8),adjustment:!0}),r(l("taken","root"))],t)),n(await e.scanEntries({order:"asc"},t),a),n(await e.scanUsage({order:"asc"},t),s),n(await e.getStats(t),c),h(await e.getValue(q,t),void 0)}),p(i,"transactions","preserves overwritten and deleted values when a transaction fails",async({storage:e})=>{await e.commit([u(d("overwritten"),"original"),u(d("deleted"),{kept:!0}),r(m("taken"))],t);const a=await e.getValue(d("overwritten"),t),s=await e.getValue(d("deleted"),t);await f(e.commit([u(d("overwritten"),"transient"),x(d("deleted")),r(l("transient","taken")),r(l("taken",null))],t)),n(await e.getValue(d("overwritten"),t),a),n(await e.getValue(d("deleted"),t),s),h((await e.getEntries(["transient"],t)).has("transient"),!1)}),p(i,"transactions","enforces one shared entry and usage id namespace",async({storage:e})=>{await e.commit([r(m("existing-entry")),g({id:"existing-usage",usage:y(1,1),adjustment:!1})],t),await f(e.commit([g({id:"existing-entry",usage:y(2,2),adjustment:!1})],t)),await f(e.commit([r(l("existing-usage",null))],t));for(const[a,s]of[["entry-then-usage",[r(l("entry-then-usage",null)),g({id:"entry-then-usage",usage:y(3,3),adjustment:!1})]],["usage-then-entry",[g({id:"usage-then-entry",usage:y(4,4),adjustment:!1}),r(l("usage-then-entry",null))]]])await f(e.commit(s,t),`Expected duplicate id ${a} to reject`);n(b(await e.scanEntries({order:"asc"},t)),["existing-entry"]),n((await e.scanUsage({order:"asc"},t)).map(a=>a.id),["existing-usage"])}),p(i,"transactions","resolves parents only from prior entries and earlier writes",async({storage:e})=>{await e.commit([r(m("root"))],t),await e.commit([r(l("child","root")),r(l("grandchild","child"))],t),n(b(await e.scanBranch({start:"grandchild",order:"oldestFirst"},t)),["root","child","grandchild"]),await f(e.commit([r(l("before-parent","later-parent")),r(l("later-parent","root")),u(W("before-parent"),"transient")],t)),await f(e.commit([r(l("orphan","missing"))],t)),await e.commit([g({id:"usage-is-not-parent",usage:y(1,1),adjustment:!1})],t),await f(e.commit([r(l("usage-child","usage-is-not-parent"))],t)),n(await e.getEntries(["before-parent","later-parent","orphan","usage-child"],t),new Map),h(await e.getValue(W("before-parent"),t),void 0)}),p(i,"transactions","places pending content under its reserved entry id",async({storage:e})=>{const a=m("reserved",null,"queued");await e.commit([u(j(a.id),{type:"message",payload:a.message}),u(S("main"),null)],t),h((await e.getEntries([a.id],t)).has(a.id),!1),n((await e.getValue(j(a.id),t))?.value,{type:"message",payload:a.message}),h((await e.getValue(S("main"),t))?.value,null);const s=await e.commit([r(a),x(j(a.id)),u(S("main"),a.id)],t);n(await e.getEntries([a.id],t),new Map([[a.id,{...a,seq:s.seqs[0],timestamp:s.timestamp}]])),h(await e.getValue(j(a.id),t),void 0),n(await e.getValue(S("main"),t),{address:S("main"),value:a.id,seq:s.seqs[2]})}),p(i,"values","sets, replaces, deletes, and recreates values without tombstones",async({storage:e})=>{const a=await e.commit([u(d("prefix/b"),1),u(d("prefix/a"),2),u(d("other"),3),u(d("prefix/\uE000"),4),u(d("prefix/\u{10000}"),5),u(d("prefix/a"),null)],t);n(await e.getValue(d("prefix/a"),t),{address:d("prefix/a"),value:null,seq:a.seqs[5]});const s=await e.commit([x(d("prefix/a")),x(d("absent")),u(d("prefix/a"),"recreated")],t);n(await e.scanValues(D("prefix/"),t),[{address:d("prefix/a"),value:"recreated",seq:s.seqs[2]},{address:d("prefix/b"),value:1,seq:a.seqs[0]},{address:d("prefix/\uE000"),value:4,seq:a.seqs[3]},{address:d("prefix/\u{10000}"),value:5,seq:a.seqs[4]}]),h(await e.getValue(d("absent"),t),void 0)}),p(i,"values","applies same-transaction value and list operations in write order",async({storage:e})=>{const a=d("write-order/kept"),s=d("write-order/deleted"),c=v("write-order/kept"),o=v("write-order/deleted"),k=await e.commit([u(s,"transient"),x(s),u(a,"transient"),u(a,"kept"),E(c,"transient"),V(c),E(c,"kept"),E(o,"transient"),V(o)],t);h(await e.getValue(s,t),void 0),n(await e.getValue(a,t),{address:a,value:"kept",seq:k.seqs[3]}),n(await e.readList(c,void 0,t),[{seq:k.seqs[6],value:"kept"}]),n(await e.readList(o,void 0,t),[])}),p(i,"values","does not change historical stores during value-only commits",async({storage:e})=>{await e.commit([r(m("root")),g({id:"historical-usage",usage:y(2,3),adjustment:!1})],t);const a=await e.scanEntries({order:"asc"},t),s=await e.scanUsage({order:"asc"},t),c=await e.getStats(t),o=await e.commit([u(q,"first"),u(q,"second")],t);n(await e.scanEntries({order:"asc"},t),a),n(await e.scanUsage({order:"asc"},t),s),n(await e.getStats(t),c),n(await e.getValue(q,t),{address:q,value:"second",seq:o.seqs[1]})}),p(i,"lists","pages appends by global sequence and deletes whole lists",async({storage:e})=>{const a=v("events");h((await e.readList(a,void 0,t)).length,0);const s=await e.commit([E(a,"a"),u(q,"gap"),E(a,"b"),E(a,"c")],t);n(await e.readList(a,void 0,t),[{seq:s.seqs[0],value:"a"},{seq:s.seqs[2],value:"b"},{seq:s.seqs[3],value:"c"}]),n(await e.readList(a,{limit:2},t),[{seq:s.seqs[0],value:"a"},{seq:s.seqs[2],value:"b"}]),n(await e.readList(a,{cursor:{seq:s.seqs[0]},limit:2},t),[{seq:s.seqs[2],value:"b"},{seq:s.seqs[3],value:"c"}]),n(await e.readList(a,{order:"desc",limit:2},t),[{seq:s.seqs[3],value:"c"},{seq:s.seqs[2],value:"b"}]),n(await e.readList(a,{order:"desc",cursor:{seq:s.seqs[3]},limit:2},t),[{seq:s.seqs[2],value:"b"},{seq:s.seqs[0],value:"a"}]),await f(e.readList(a,{limit:0},t)),await f(e.readList(a,{limit:Number.MAX_VALUE},t)),await e.commit([V(a),V(v("absent")),E(a,"new")],t),n((await e.readList(a,void 0,t)).map(({value:c})=>c),["new"])}),p(i,"lists","clamps one read page without limiting list growth",async({storage:e})=>{const a=v("large");await e.commit(Array.from({length:10001},(c,o)=>E(a,o)),t);const s=await e.readList(a,void 0,t);h(s.length,1e3),h((await e.readList(a,{limit:2e4},t)).length,1e4),h((await e.readList(a,{cursor:{seq:s.at(-1).seq}},t)).length,1e3)}),p(i,"lists","commits mixed list writes atomically and rolls them back with siblings",async({storage:e})=>{const a=v("atomic"),s=await e.commit([r(m("mixed")),E(a,"kept"),u(q,"kept"),g({id:"mixed-usage",usage:y(1,2),adjustment:!1})],t);n(await e.readList(a,void 0,t),[{seq:s.seqs[1],value:"kept"}]),await f(e.commit([E(a,"transient"),x(q),r(m("mixed"))],t)),n(await e.readList(a,void 0,t),[{seq:s.seqs[1],value:"kept"}]),h((await e.getValue(q,t))?.value,"kept")}),p(i,"entry queries","stores custom entries with and without data",async({storage:e})=>{const a=await e.commit([r({id:"without-data",parentId:null,type:"custom",customType:"marker"}),r(l("with-data","without-data","note",{nested:[1,2]}))],t);n(await e.getEntries(["without-data","with-data"],t),new Map([["without-data",{id:"without-data",parentId:null,type:"custom",customType:"marker",seq:a.seqs[0],timestamp:a.timestamp}],["with-data",{...l("with-data","without-data","note",{nested:[1,2]}),seq:a.seqs[1],timestamp:a.timestamp}]]))}),p(i,"entry queries","scans global entries with explicit ranges, filters, orders, and limits",async({storage:e})=>{const a=await e.commit([r(m("root")),r(l("note-1","root","note")),r(l("other","note-1","other")),r(l("note-2","other","note")),r(m("tail","note-2"))],t);n(b(await e.scanEntries({type:"custom",customType:"note",fromSeq:a.seqs[1],toSeq:a.seqs[3],order:"desc"},t)),["note-2","note-1"]),n(b(await e.scanEntries({order:"asc",limit:2},t)),["root","note-1"]),n(b(await e.scanEntries({order:"desc",limit:2},t)),["tail","note-2"])}),p(i,"branch queries","applies stops before filters and cursors before limits",async({storage:e})=>{const a=await e.commit([r(m("root")),r(l("marker","root","marker")),r(m("middle","marker")),r(U("compact","middle")),r(l("note","compact","note")),r(m("leaf","note"))],t);n(b(await e.scanBranch({start:"leaf",stopAtType:"compaction",type:"message"},t)),["leaf"]),n(b(await e.scanBranch({start:"leaf",order:"oldestFirst",stopAtId:"middle",type:"custom"},t)),["marker"]),n(b(await e.scanBranch({start:"leaf",order:"newestFirst",cursor:{seq:a.seqs[4]},limit:2},t)),["compact","middle"]),n(b(await e.scanBranch({start:"leaf",order:"oldestFirst",cursor:{seq:a.seqs[1]},limit:2},t)),["middle","compact"]),n(b(await e.scanBranch({start:"leaf",stopAtId:"leaf",type:"custom"},t)),[]),n(b(await e.scanBranch({start:"leaf",customType:"note"},t)),["note"]),await f(e.scanBranch({start:"missing"},t))}),p(i,"branch queries","returns branch structure without payload fields",async({storage:e})=>{const a=await e.commit([r(m("root")),r(l("child","root","note"))],t);n(await e.scanBranchStructure({start:"child",order:"oldestFirst"},t),[{id:"root",parentId:null,seq:a.seqs[0],timestamp:a.timestamp,type:"message"},{id:"child",parentId:"root",seq:a.seqs[1],timestamp:a.timestamp,type:"custom",customType:"note"}])}),p(i,"branch queries","applies branch query semantics to structure scans",async({storage:e})=>{const a=await e.commit([r(m("root")),r(l("marker","root","marker")),r(m("middle","marker")),r(U("compact","middle")),r(l("note","compact","note")),r(m("leaf","note"))],t);n(b(await e.scanBranchStructure({start:"leaf",stopAtType:"compaction",type:"message"},t)),["leaf"]),n(b(await e.scanBranchStructure({start:"leaf",order:"oldestFirst",cursor:{seq:a.seqs[1]},limit:2},t)),["middle","compact"]),await f(e.scanBranchStructure({start:"missing"},t))}),p(i,"usage and stats","scans the usage ledger with explicit ranges, orders, and limits",async({storage:e})=>{const a=await e.commit([g({id:"usage-1",usage:y(1,1),adjustment:!1}),u(q,"sequence gap"),g({id:"usage-2",usage:y(2,2),adjustment:!1}),g({id:"usage-3",usage:y(3,3),adjustment:!0})],t);n((await e.scanUsage({fromSeq:a.seqs[1],toSeq:a.seqs[2],order:"asc"},t)).map(s=>s.id),["usage-2"]),n((await e.scanUsage({order:"desc",limit:2},t)).map(s=>s.id),["usage-3","usage-2"]),n((await e.scanUsage({order:"asc",limit:2},t)).map(s=>s.id),["usage-1","usage-2"])}),p(i,"usage and stats","keeps stats equal to message count and ledger totals",async({storage:e})=>{n(await e.getStats(t),{messageCount:0,usage:R()});const a=y(2,3,{cacheWrite1h:4,reasoning:1}),s=await e.commit([r(m("message")),g({id:"usage-1",usage:a,adjustment:!1})],t);await B(e,s),n(s.stats,{messageCount:1,usage:a});const c=y(5,7,{cacheWrite1h:6,reasoning:2}),o=await e.commit([r(l("custom","message")),r(U("compaction","custom")),g({id:"usage-2",usage:c,adjustment:!0})],t);await B(e,o),n(o.stats,{messageCount:1,usage:{input:7,output:10,cacheRead:9,cacheWrite:12,cacheWrite1h:10,reasoning:3,totalTokens:17,cost:{input:a.cost.input+c.cost.input,output:a.cost.output+c.cost.output,cacheRead:a.cost.cacheRead+c.cost.cacheRead,cacheWrite:a.cost.cacheWrite+c.cost.cacheWrite,total:a.cost.total+c.cost.total}}})}),p(i,"serialization","serializes back-to-back commits in admission order",async({storage:e})=>{const a=e.commit([r(m("first"))],t),s=e.commit([r(m("second","first"))],t),[c,o]=await Promise.all([a,s]);_(c.seqs[0]<o.seqs[0]),n(c.stats,{messageCount:1,usage:R()}),n(o.stats,{messageCount:2,usage:R()}),await B(e,o),n(b(await e.scanEntries({order:"asc"},t)),["first","second"])}),p(i,"lifecycle","seals admission, drains admitted commits, and closes idempotently",async({storage:e})=>{const a=e.commit([r(m("admitted"))],t),s=e.close(t),c=e.close(t);await f(e.getStats(t)),await f(e.commit([],t)),h((await a).seqs.length,1),await Promise.all([s,c]);const o=[e.getEntries([],t),e.getValue(q,t),e.scanValues(q,t),e.readList(v("events"),void 0,t),e.scanBranch({start:"admitted"},t),e.scanBranchStructure({start:"admitted"},t),e.scanEntries({order:"asc"},t),e.scanUsage({order:"asc"},t),e.getStats(t)];for(const k of o)await f(k)})]}w(X,"createStorageConformance");export{X as createStorageConformance};
@@ -1 +0,0 @@
1
- var k=Object.defineProperty;var g=(r,t)=>k(r,"name",{value:t,configurable:!0});var q=function(r,t,e){if(t!=null){if(typeof t!="object"&&typeof t!="function")throw new TypeError("Object expected.");var a,n;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");a=t[Symbol.asyncDispose]}if(a===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");a=t[Symbol.dispose],e&&(n=a)}if(typeof a!="function")throw new TypeError("Object not disposable.");n&&(a=g(function(){try{n.call(this)}catch(s){return Promise.reject(s)}},"dispose")),r.stack.push({value:t,dispose:a,async:e})}else e&&r.stack.push({async:!0});return t},I=(function(r){return function(t){function e(d){t.error=t.hasError?new r(d,t.error,"An error was suppressed during disposal."):d,t.hasError=!0}g(e,"fail");var a,n=0;function s(){for(;a=t.stack.pop();)try{if(!a.async&&n===1)return n=0,t.stack.push(a),Promise.resolve().then(s);if(a.dispose){var d=a.dispose.call(a.value);if(a.async)return n|=2,Promise.resolve(d).then(s,function(l){return e(l),s()})}else n|=1}catch(l){e(l)}if(n===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return g(s,"next"),s()}})(typeof SuppressedError=="function"?SuppressedError:function(r,t,e){var a=new Error(e);return a.name="SuppressedError",a.error=r,a.suppressed=t,a});import{deepStrictEqual as i,ok as R,rejects as v,strictEqual as o}from"node:assert/strict";function u(r){return{role:"user",content:[{type:"text",text:r}],timestamp:1}}g(u,"createUserMessage");function E(r){return{role:"assistant",content:[{type:"text",text:r}],api:"anthropic-messages",provider:"anthropic",model:"claude-sonnet-4-5",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:1}}g(E,"createAssistantMessage");function m(r,{lane:t,kind:e}){let a;switch(e){case"run":a={kind:e,originalPrompt:[],initialMessages:[]};break;case"compaction":a={kind:e,resultEntryId:`${r}-result`};break;case"navigation":a={kind:e,targetId:null,summarize:!1};break}return{type:"operation_started",id:r,lane:t,sourceLeafId:null,intent:a}}g(m,"operationStarted");async function f(r){return(await r).map(t=>t.id)}g(f,"entryIds");async function p(r,t){await v(r,e=>typeof e=="object"&&e!==null&&"code"in e&&e.code===t,`Expected SessionError with code ${t}`)}g(p,"rejectsWithCode");function c(r,t,e,a){return{group:t,name:e,async run(){const n={stack:[],error:void 0,hasError:!1};try{const s=q(n,await r(),!0);await a(s.repository)}catch(s){n.error=s,n.hasError=!0}finally{const s=I(n);s&&await s}}}}g(c,"createCase");function b(r){return[c(r,"entries and lanes","assigns parents and one sequence across every mutation",async t=>{const e=await t.create({id:"session"}),a=await e.appendEntry({type:"message",id:"root",message:u("root")},"main");await e.createLane("thread",a.id);const n=await e.appendEntry({type:"custom",id:"child",customType:"note",data:{value:1}},"thread"),s=await e.appendRecord(m("run",{lane:"thread",kind:"run"}));await e.setName("Example"),await e.setLabel(a.id,"checkpoint"),await e.moveLane("main",n.id),i({parentId:a.parentId,seq:a.seq},{parentId:null,seq:1}),i({parentId:n.parentId,seq:n.seq},{parentId:"root",seq:3}),o(s.seq,4);for(const d of[a.timestamp,n.timestamp,s.timestamp])R(Number.isSafeInteger(d)&&d>=0,"storage-assigned timestamps must be Unix milliseconds");i((await e.getLog()).map(d=>[d.kind,d.seq]),[["entry",1],["lane",2],["entry",3],["record",4],["fact",5],["fact",6],["lane",7]]),i(await e.getLanes(),[{lane:"main",leafId:"child"},{lane:"thread",leafId:"child"}])}),c(r,"records and log","commits records and lane moves as separate mutations",async t=>{const e=await t.create({id:"session"}),a=await e.appendEntry({type:"message",id:"root",message:u("root")},"main"),n=await e.appendRecord({type:"operation_finished",id:"finish",lane:"main",runId:"run",outcome:"completed"});o(n.seq,2),i(await e.getLanes(),[{lane:"main",leafId:"root"}]),await e.moveLane("main",null),i(await e.getLanes(),[{lane:"main",leafId:null}]),i(await e.getLog(),[{kind:"entry",seq:1,entry:a},{kind:"record",seq:2,record:n},{kind:"lane",seq:3,lane:"main",leafId:null}]),await p(e.moveLane("main","missing"),"not_found"),o((await e.findRecords()).length,1),i((await e.getLog()).map(s=>s.seq),[1,2,3])}),c(r,"entries and lanes","rejects duplicate ids without changing state",async t=>{const e=await t.create({id:"session"});await e.appendEntry({type:"message",id:"shared",message:u("root")},"main"),await p(e.appendRecord(m("shared",{lane:"main",kind:"run"})),"already_exists"),await e.appendRecord(m("run",{lane:"main",kind:"run"})),await p(e.appendEntry({type:"custom",id:"run",customType:"note"},"main"),"already_exists"),i((await e.getLog()).map(a=>a.seq),[1,2])}),c(r,"entries and lanes","isolates lanes while sharing the tree",async t=>{const e=await t.create({id:"session"});await e.appendEntry({type:"message",id:"root",message:u("root")},"main"),await e.createLane("thread","root"),await e.appendEntry({type:"message",id:"main-child",message:u("main")},"main"),await e.appendEntry({type:"message",id:"thread-child",message:u("thread")},"thread"),i(await e.getLanes(),[{lane:"main",leafId:"main-child"},{lane:"thread",leafId:"thread-child"}]),i(await f(e.findEntriesOnBranch({start:"main-child",order:"oldestFirst"})),["root","main-child"]),i(await f(e.findEntriesOnBranch({start:"thread-child",order:"oldestFirst"})),["root","thread-child"])}),c(r,"queries and facts","rejects invalid queries before empty reads",async t=>{const e=await t.create({id:"invalid-queries"});await e.createLane("thread",null);const a=e.view("thread");await p(e.findEntries({limit:0}),"invalid_query"),await p(e.findEntry({limit:0}),"invalid_query"),await p(e.findEntriesOnBranch({limit:0}),"invalid_query"),await p(a.findEntriesOnBranch({cursor:{afterSeq:-1}}),"invalid_query"),await p(a.findEntryOnBranch({limit:0}),"invalid_query"),await p(e.findRecords({limit:0}),"invalid_query"),await p(e.findRecords({operationKind:"run"}),"invalid_query"),await p(e.findRecords({type:"step_attempt",operationKind:"run"}),"invalid_query"),await p(e.findOpenOperations("main",{limit:0}),"invalid_query"),await p(e.findOpenOperations("main",{limit:-1}),"invalid_query"),await p(e.getLog({afterSeq:-1}),"invalid_query")}),c(r,"queries and facts","supports bounded filtered and cursor-based queries",async t=>{const e=await t.create({id:"session"});await e.appendEntry({type:"message",id:"root",message:u("root")},"main"),await e.appendEntry({type:"custom",id:"old-note",customType:"note",data:1},"main"),await e.appendEntry({type:"compaction",id:"compact",summary:"summary",retainedTail:[],tokensBefore:10},"main"),await e.appendEntry({type:"custom",id:"new-note",customType:"note",data:2},"main"),await e.appendEntry({type:"message",id:"tail",message:E("tail")},"main"),i(await f(e.findEntries()),["tail","new-note","compact","old-note","root"]),i(await f(e.findEntries({order:"oldestFirst",cursor:{afterSeq:2},limit:2})),["compact","new-note"]),i(await f(e.findEntries({customType:"note"})),["new-note","old-note"]),i(await f(e.findEntriesOnBranch({start:"tail",customType:"note",limit:1})),["new-note"]),i(await f(e.findEntriesOnBranch({start:"tail",stopAtType:"compaction",type:"message"})),["tail"]),i(await f(e.findEntriesOnBranch({start:"tail",stopAtId:"tail",type:"custom"})),[]),i(await f(e.findEntriesOnBranch({start:"tail",stopAtType:"custom",order:"oldestFirst"})),["root","old-note"]),await p(e.findEntries({limit:0}),"invalid_query"),await p(e.findEntriesOnBranch({start:"missing"}),"not_found")}),c(r,"records and log","keeps lane names permanent with their recovery records",async t=>{const e=await t.create({id:"session"});await e.createLane("thread",null),await e.appendRecord(m("old-run",{lane:"thread",kind:"run"})),await e.appendRecord({type:"queue_enqueued",id:"old-next-run",lane:"thread",queue:"nextRun",target:{type:"message",id:"queued-message",message:u("queued")}}),i((await e.findRecords({lane:"thread"})).map(a=>a.id),["old-next-run","old-run"]),i((await e.getLog()).flatMap(a=>a.kind==="record"?[a.record.id]:[]),["old-run","old-next-run"]),await p(e.createLane("thread",null),"already_exists")}),c(r,"records and log","persists queue cancellation without consuming its target",async t=>{const e=await t.create({id:"session"}),a=await e.appendRecord({type:"queue_enqueued",id:"enqueue",lane:"main",queue:"nextRun",target:{type:"message",id:"queued-message",message:u("queued")}}),n=await e.appendRecord({type:"queue_cancelled",id:"cancel",lane:"main",entryId:"queued-message"});i({seq:n.seq,entryId:n.entryId},{seq:2,entryId:"queued-message"}),o("runId"in n,!1),o(await e.getEntry("queued-message"),void 0);const s=await e.findRecords({type:"queue_cancelled"});o(s[0]?.entryId,"queued-message"),i(s,[n]),i(await e.getLog(),[{kind:"record",seq:a.seq,record:a},{kind:"record",seq:n.seq,record:n}])}),c(r,"records and log","filters records by lane type run sequence and order",async t=>{const e=await t.create({id:"session"});await e.appendRecord(m("run-1",{lane:"main",kind:"run"})),await e.appendRecord({type:"step_attempt",id:"attempt-1",lane:"main",runId:"run-1",step:"assistant",attempt:1,resultEntryId:"assistant-1"}),await e.createLane("thread",null),await e.appendRecord(m("run-2",{lane:"thread",kind:"run"})),await e.appendRecord({type:"step_attempt",id:"attempt-2",lane:"thread",runId:"run-2",step:"assistant",attempt:1,resultEntryId:"assistant-2"}),i((await e.findRecords({lane:"thread"})).map(a=>a.id),["attempt-2","run-2"]),i((await e.findRecords({type:"step_attempt",order:"oldestFirst"})).map(a=>a.id),["attempt-1","attempt-2"]),i((await e.findRecords({runId:"run-1",afterSeq:1})).map(a=>a.id),["attempt-1"]),i((await e.findRecords({limit:1})).map(a=>a.id),["attempt-2"])}),c(r,"records and log","filters operation starts by operation kind",async t=>{const e=await t.create({id:"session"});await e.appendRecord(m("run-old",{lane:"main",kind:"run"})),await e.appendRecord({type:"operation_finished",id:"run-old-finished",lane:"main",runId:"run-old",outcome:"completed"}),await e.appendRecord(m("compaction",{lane:"main",kind:"compaction"})),await e.appendRecord({type:"operation_finished",id:"compaction-finished",lane:"main",runId:"compaction",outcome:"completed"}),await e.appendRecord(m("navigation",{lane:"main",kind:"navigation"})),await e.appendRecord({type:"operation_finished",id:"navigation-finished",lane:"main",runId:"navigation",outcome:"completed"}),await e.appendRecord(m("run-new",{lane:"main",kind:"run"})),i((await e.findRecords({type:"operation_started",operationKind:"run",order:"oldestFirst"})).map(a=>a.id),["run-old","run-new"]),i((await e.findRecords({type:"operation_started",operationKind:"compaction"})).map(a=>a.id),["compaction"]),i((await e.findRecords({type:"operation_started",operationKind:"navigation"})).map(a=>a.id),["navigation"]),i((await e.findRecords({type:"operation_started",operationKind:"run",limit:1})).map(a=>a.id),["run-new"])}),c(r,"records and log","tracks and enforces one open operation per lane",async t=>{const e=await t.create({id:"session"});i(await e.findOpenOperations("main",{limit:2}),[]);const a=await e.appendRecord(m("first",{lane:"main",kind:"run"}));i(await e.findOpenOperations("main",{limit:2}),[a]),await p(e.appendRecord(m("second",{lane:"main",kind:"run"})),"storage"),i(await e.findOpenOperations("main",{limit:2}),[a]),await e.appendRecord({type:"operation_finished",id:"finish-first",lane:"main",runId:a.id,outcome:"completed"}),i(await e.findOpenOperations("main",{limit:2}),[])}),c(r,"records and log","does not let an earlier finish close a later start",async t=>{const e=await t.create({id:"session"});await e.appendRecord({type:"operation_finished",id:"finish-before-start",lane:"main",runId:"run",outcome:"completed"});const a=await e.appendRecord(m("run",{lane:"main",kind:"run"}));i(await e.findOpenOperations("main",{limit:2}),[a])}),c(r,"records and log","scopes open operations by lane and limit",async t=>{const e=await t.create({id:"session"});await e.createLane("thread",null);const a=await e.appendRecord(m("main-run",{lane:"main",kind:"run"})),n=await e.appendRecord(m("thread-navigation",{lane:"thread",kind:"navigation"}));i(await e.findOpenOperations("main"),[a]),i(await e.findOpenOperations("main",{limit:1}),[a]),i(await e.findOpenOperations("thread",{limit:2}),[n])}),c(r,"validation and immutability","returns immutable open-operation records",async t=>{const e=await t.create({id:"session"}),a=await e.appendRecord(m("run",{lane:"main",kind:"run"})),[n]=await e.findOpenOperations("main");if(n?.intent.kind!=="run")throw new Error("Expected an open run operation");n.intent.originalPrompt.push(u("mutated")),i(await e.findOpenOperations("main"),[a])}),c(r,"queries and facts","keeps latest-value facts and computes ledger statistics across lanes",async t=>{const e=await t.create({id:"session"}),a=E("answer");if(a.role!=="assistant")throw new Error("Expected assistant message");a.usage={input:10,output:5,cacheRead:3,cacheWrite:2,totalTokens:20,cost:{input:1,output:2,cacheRead:3,cacheWrite:4,total:10}},await e.appendEntry({type:"message",id:"user",message:u("question")},"main"),await e.appendEntry({type:"message",id:"assistant",message:a},"main"),await e.appendRecord({type:"usage",id:"assistant-usage",lane:"main",cause:"assistant",runId:"run",entryId:"assistant",attempt:1,stopReason:"stop",usage:a.usage}),await e.appendRecord({type:"usage",id:"deferred-usage",lane:"main",cause:"deferred_fetch",runId:"run",entryId:"deferred-result",attempt:1,stopReason:"deferred",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}),await e.createLane("thread","assistant"),await e.appendRecord({type:"usage",id:"correction",lane:"thread",cause:"adjustment",details:{reason:"provider correction"},usage:{input:-2,output:0,cacheRead:0,cacheWrite:0,totalTokens:-2,cost:{input:-.5,output:0,cacheRead:0,cacheWrite:0,total:-.5}}}),await e.setName("First"),await e.setName("Second"),await e.setLabel("user","keep"),await e.setLabel("user",void 0),await p(e.setLabel("missing","checkpoint"),"not_found"),o(await e.getName(),"Second"),o(await e.getLabel("user"),void 0);const n=await e.findRecords({type:"usage",order:"oldestFirst"});i(n.map(d=>d.cause),["assistant","deferred_fetch","adjustment"]);const s=n.find(d=>d.cause==="deferred_fetch");if(s?.cause!=="deferred_fetch")throw new Error("Expected deferred usage record");o(s.stopReason,"deferred"),i(await e.getStats(),{messageCount:2,cachedTokens:3,uncachedTokens:10,totalTokens:18,costTotal:9.5})}),c(r,"queries and facts","clears session names durably",async t=>{const e=await t.create({id:"session"});await e.setName("Temporary"),await e.setName(void 0),o(await e.getName(),void 0),i(await e.getLog(),[{kind:"fact",seq:1,fact:"name",name:"Temporary"},{kind:"fact",seq:2,fact:"name",name:void 0}]);const a=await e.getMetadata(),n=await t.open(a);o(await n.getName(),void 0),i(await n.getLog(),[{kind:"fact",seq:1,fact:"name",name:"Temporary"},{kind:"fact",seq:2,fact:"name",name:void 0}]);const s=await t.fork(a,{id:"fork"});o(await s.getName(),void 0)}),c(r,"validation and immutability","returns immutable copies from reads",async t=>{const e=await t.create({id:"immutable"}),a=await e.getMetadata(),n={nested:{value:1}};await e.appendEntry({type:"custom",id:"custom",customType:"note",data:n},"main"),n.nested.value=50;const s=await e.getEntry("custom");if(s?.type!=="custom")throw new Error("Expected custom entry");s.data.nested.value=99;const d=await e.getMetadata();d.id="changed";const l=await e.getLog();if(l[0]?.kind!=="entry"||l[0].entry.type!=="custom")throw new Error("Expected entry log");l[0].entry.data.nested.value=100,i(await e.getMetadata(),a),i(await e.getEntry("custom"),{type:"custom",id:"custom",customType:"note",data:{nested:{value:1}},parentId:null,seq:1,timestamp:s.timestamp})}),c(r,"entries and lanes","validates lane lifecycle and targets",async t=>{const e=await t.create({id:"session"});await p(e.createLane("main",null),"already_exists"),await p(e.createLane("thread","missing"),"not_found"),await p(e.moveLane("missing",null),"invalid_lane")}),c(r,"entries and lanes","binds lane views without caching leaves",async t=>{const e=await t.create({id:"session"}),a=await e.appendMessage(u("root"));await e.createLane("thread",a);const n=e.view("thread"),[s,d]=await Promise.all([e.appendMessage(u("main")),n.appendMessage(u("thread"))]);o(await e.getLeafId(),s),o(await n.getLeafId(),d),i(await f(e.findEntriesOnBranch({order:"oldestFirst"})),[a,s]),i(await f(n.findEntriesOnBranch({order:"oldestFirst"})),[a,d]);const l=await t.create({id:"empty"});i(await l.findEntriesOnBranch(),[])}),c(r,"entries and lanes","appends provisioned entries with their existing ids",async t=>{const e=await t.create({id:"session"}),a=await e.appendEntry({type:"custom",id:"provisioned",customType:"note",data:{value:1}},"main");o(a.customType,"note"),i({id:a.id,parentId:a.parentId,seq:a.seq},{id:"provisioned",parentId:null,seq:1}),o(await e.getLeafId(),"provisioned")}),c(r,"entries and lanes","persists tool-result termination decisions",async t=>{const e=await t.create({id:"session"}),a=await e.appendEntry({type:"message",id:"tool-result",message:{role:"toolResult",toolCallId:"call-1",toolName:"example",content:[{type:"text",text:"done"}],isError:!1,timestamp:1},terminate:!0},"main");o(a.terminate,!0);const n=await e.getEntry(a.id);if(n?.type!=="message")throw new Error("Expected message entry");o(n.terminate,!0),i(await e.findEntries(),[a]),i(await e.getLog(),[{kind:"entry",seq:a.seq,entry:a}])}),c(r,"validation and immutability","rejects non-JSON entries before storage mutation",async t=>{const e=await t.create({id:"session"}),a={};a.self=a;for(const s of[{value:void 0},[void 0],{value:1n},{value:Number.NaN},{value:new Map},a])await p(e.appendCustomEntry("invalid",s),"invalid_payload");o(await e.getLeafId(),null),i(await e.findEntries(),[]),i(await e.getLog(),[]);const n=await e.appendCustomEntry("valid",{value:1});o((await e.getEntry(n))?.seq,1)}),c(r,"validation and immutability","rejects non-JSON records before storage mutation",async t=>{const e=await t.create({id:"session"});for(const[a,n]of[["undefined-record",void 0],["bigint-record",1n]])await p(e.appendRecord({type:"tool_started",id:a,lane:"main",runId:"run",assistantEntryId:"assistant",toolIndex:0,toolCallId:"call",toolName:"example",effectiveArgs:{value:n},resultEntryId:"result",replay:"never"}),"invalid_payload");i(await e.findRecords(),[]),i(await e.getLog(),[]),o((await e.appendRecord(m("valid-record",{lane:"main",kind:"run"}))).seq,1)}),c(r,"entries and lanes","linearizes concurrent writes across two lanes",async t=>{const e=await t.create({id:"session"});await e.appendEntry({type:"message",id:"root",message:u("root")},"main"),await e.createLane("thread","root");const a=[],n=[e.appendEntry({type:"custom",id:"main-1",customType:"note"},"main"),e.appendEntry({type:"custom",id:"thread-1",customType:"note"},"thread"),e.appendEntry({type:"custom",id:"main-2",customType:"note"},"main"),e.appendEntry({type:"custom",id:"thread-2",customType:"note"},"thread")].map(w=>w.then(y=>(a.push(y.id),y))),s=await Promise.all(n),d=[...s].sort((w,y)=>w.seq-y.seq).map(w=>w.id);o(new Set(s.map(w=>w.seq)).size,s.length),i(a,d);const l=new Set(s.map(w=>w.id));i((await e.getLog()).flatMap(w=>w.kind==="entry"&&l.has(w.entry.id)?[w.entry.id]:[]),d);const h=(await e.getLog()).map(w=>w.seq);i(h,[...h].sort((w,y)=>w-y))}),c(r,"repository and forks","creates lists and opens sessions",async t=>{const e=await t.create({id:"one"}),a=await e.appendMessage(u("persisted")),n=await e.getMetadata(),s=await t.list();o(s.length,1),o(s[0]?.id,n.id),o(s[0]?.createdAt,n.createdAt),o(s[0]?.parentSessionId,n.parentSessionId),i(await f((await t.open(n)).findEntries()),[a]),await p(t.create({id:"one"}),"already_exists")}),c(r,"repository and forks","deletes sessions idempotently",async t=>{const a=await(await t.create({id:"one"})).getMetadata();await t.delete(a),await p(t.open(a),"not_found"),await t.delete(a)}),c(r,"repository and forks","forks one branch with selected facts and no records",async t=>{const e=await t.create({id:"source"}),a=await e.appendMessage(u("root")),n=await e.appendMessage(E("shared"));await e.createLane("thread",n);const s=await e.view("thread").appendMessage(u("thread")),d=await e.appendMessage(u("main"));await e.setName("Source"),await e.setLabel(n,"copied"),await e.setLabel(s,"excluded"),await e.appendRecord(m("run",{lane:"main",kind:"run"})),await e.appendRecord({type:"usage",id:"source-usage",lane:"main",cause:"adjustment",usage:{input:10,output:5,cacheRead:3,cacheWrite:2,totalTokens:20,cost:{input:1,output:2,cacheRead:3,cacheWrite:4,total:10}}});const l=await t.fork(await e.getMetadata(),{scope:"branch",entryId:d,position:"at",id:"branch-fork"});i(await f(l.findEntries({order:"oldestFirst"})),[a,n,d]),i(await l.getLanes(),[{lane:"main",leafId:d}]),o(await l.getName(),"Source"),o(await l.getLabel(n),"copied"),o(await l.getLabel(s),void 0),i(await l.findRecords(),[]),i(await l.getStats(),{messageCount:3,cachedTokens:0,uncachedTokens:0,totalTokens:0,costTotal:0}),await l.appendMessage(u("after fork")),o((await l.getStats()).messageCount,4);const h=await l.getMetadata();i({id:h.id,parentSessionId:h.parentSessionId},{id:"branch-fork",parentSessionId:"source"})}),c(r,"repository and forks","forks a complete tree with lanes and facts",async t=>{const e=await t.create({id:"source"}),a=await e.appendMessage(u("root"));await e.createLane("thread",a);const n=await e.appendMessage(u("main")),s=await e.view("thread").appendMessage(u("thread"));await e.setLabel(s,"thread-tip");const d=await t.fork(await e.getMetadata(),{scope:"tree",id:"tree-fork"});i(await f(d.findEntries({order:"oldestFirst"})),[a,n,s]),i(await d.getLanes(),[{lane:"main",leafId:n},{lane:"thread",leafId:s}]),o(await d.getLabel(s),"thread-tip"),o((await d.getStats()).messageCount,3),i((await d.getLog()).filter(l=>l.kind==="lane"),[{kind:"lane",seq:4,lane:"main",leafId:n},{kind:"lane",seq:5,lane:"thread",leafId:s}])}),c(r,"repository and forks","forks before an entry without modifying the source",async t=>{const e=await t.create({id:"source"}),a=await e.appendMessage(u("root")),n=await e.appendMessage(u("tail")),s=await t.fork(await e.getMetadata(),{entryId:n,id:"fork"});i(await f(s.findEntries({order:"oldestFirst"})),[a]),o(await s.getLeafId(),a),o(await e.getLeafId(),n);const d=await t.fork(await e.getMetadata(),{position:"before",id:"before-default-target"});i(await f(d.findEntries({order:"oldestFirst"})),[a]),o(await d.getLeafId(),a);const l=await t.fork(await e.getMetadata(),{position:"at",id:"at-default-target"});i(await f(l.findEntries({order:"oldestFirst"})),[a,n]),o(await l.getLeafId(),n),await p(t.fork(await e.getMetadata(),{entryId:"missing"}),"invalid_fork_target")}),c(r,"repository and forks","validates the default fork target",async t=>{const e=await t.create({id:"source-with-custom-leaf"});await e.appendCustomEntry("not-a-message"),await p(t.fork(await e.getMetadata(),{id:"fork"}),"invalid_fork_target")})]}g(b,"createSessionBackendConformance");export{b as createSessionBackendConformance};
@@ -1 +0,0 @@
1
- var h=Object.defineProperty;var n=(o,e)=>h(o,"name",{value:e,configurable:!0});import{StorageDecorator as u}from"./storage-decorator.js";class a extends Error{static{n(this,"CommitDiscarded")}constructor(e){super(e),this.name="CommitDiscarded"}}class l extends u{static{n(this,"GatingStorage")}armed=!1;discarded=!1;queue=[];waiters=[];arm(){this.armed=!0}pending(){return this.queue.length}waitPending(e=1){return!Number.isSafeInteger(e)||e<1?Promise.reject(new RangeError("Pending commit count must be a positive safe integer")):this.discarded?Promise.reject(new a("storage discarded")):this.queue.length>=e?Promise.resolve():new Promise((r,i)=>{this.waiters.push({count:e,resolve:r,reject:i})})}async commit(e,r){if(this.discarded)throw new a("commit rejected: storage discarded");if(!this.armed)return super.commit(e,r);let i,d;const c=new Promise((t,s)=>{i=t,d=s});c.catch(()=>{});const m=new Promise((t,s)=>{this.queue.push({release:t,drop:s,landing:c})});this.notifyWaiters();try{if(await m,this.discarded)throw new a("commit rejected: storage discarded");const t=await super.commit(e,r);return i(),t}catch(t){const s=t instanceof Error?t:new Error(String(t));throw d(s),t}}async next(e=1){if(!Number.isSafeInteger(e)||e<1)throw new RangeError("Released commit count must be a positive safe integer");for(let r=0;r<e;r++){await this.waitPending();const i=this.queue.shift();if(i===void 0)throw new Error("No parked commit");i.release(),await i.landing}}discard(){if(this.discarded)return;this.discarded=!0;const e=new a("commit discarded");for(const r of this.queue.splice(0))r.drop(e);for(const r of this.waiters.splice(0))r.reject(e)}notifyWaiters(){for(let e=this.waiters.length-1;e>=0;e--){const r=this.waiters[e];this.queue.length<r.count||(this.waiters.splice(e,1),r.resolve())}}}export{a as CommitDiscarded,l as GatingStorage};
@@ -1 +0,0 @@
1
- import{STORAGE_BENCHMARK_DATASETS as r}from"./benchmark/datasets.js";import{SESSION_REPO_CATALOG_BENCHMARK_DATASETS as n,SESSION_REPO_CATALOG_READ_BENCHMARK_SCENARIOS as a,SESSION_REPO_CATALOG_WRITE_BENCHMARK_SCENARIOS as s,SESSION_REPO_FORK_BENCHMARK_DATASETS as R,SESSION_REPO_FORK_WRITE_BENCHMARK_SCENARIOS as t,seedSessionRepoCatalogBenchmark as E,seedSessionRepoForkBenchmark as c,sessionRepoBenchmarkSessionId as _}from"./benchmark/session-repo.js";import{generateStorageBenchmarkSeedTransactions as C,STORAGE_READ_BENCHMARK_SCENARIOS as m,STORAGE_WRITE_BENCHMARK_SCENARIOS as i,seedStorageBenchmark as O}from"./benchmark/storage.js";import{createSessionRepoConformance as f,createSessionRepoForkBehaviorConformance as N,createSessionRepoForkConformance as T,createSessionRepoForkCoordinationConformance as I,createSessionRepoForkDestinationReservationConformance as B,createSessionRepoForkSourceSnapshotConformance as k,createSessionRepoLifecycleConformance as g,createSessionRepoMessageConformance as K,createSessionRepoOwnershipConformance as d,createSessionRepoStreamingForkConformance as F}from"./conformance/session-repo.js";import{createStorageConformance as h}from"./conformance/storage.js";import{CommitDiscarded as D,GatingStorage as H}from"./gating-storage.js";import{InstrumentedStorage as P}from"./instrumented-storage.js";import{StorageDecorator as W}from"./storage-decorator.js";export{D as CommitDiscarded,H as GatingStorage,P as InstrumentedStorage,n as SESSION_REPO_CATALOG_BENCHMARK_DATASETS,a as SESSION_REPO_CATALOG_READ_BENCHMARK_SCENARIOS,s as SESSION_REPO_CATALOG_WRITE_BENCHMARK_SCENARIOS,R as SESSION_REPO_FORK_BENCHMARK_DATASETS,t as SESSION_REPO_FORK_WRITE_BENCHMARK_SCENARIOS,r as STORAGE_BENCHMARK_DATASETS,m as STORAGE_READ_BENCHMARK_SCENARIOS,i as STORAGE_WRITE_BENCHMARK_SCENARIOS,W as StorageDecorator,f as createSessionRepoConformance,N as createSessionRepoForkBehaviorConformance,T as createSessionRepoForkConformance,I as createSessionRepoForkCoordinationConformance,B as createSessionRepoForkDestinationReservationConformance,k as createSessionRepoForkSourceSnapshotConformance,g as createSessionRepoLifecycleConformance,K as createSessionRepoMessageConformance,d as createSessionRepoOwnershipConformance,F as createSessionRepoStreamingForkConformance,h as createStorageConformance,C as generateStorageBenchmarkSeedTransactions,E as seedSessionRepoCatalogBenchmark,c as seedSessionRepoForkBenchmark,O as seedStorageBenchmark,_ as sessionRepoBenchmarkSessionId};
@@ -1 +0,0 @@
1
- var s=Object.defineProperty;var e=(m,t)=>s(m,"name",{value:t,configurable:!0});import{StorageDecorator as i}from"./storage-decorator.js";class p extends i{static{e(this,"InstrumentedStorage")}commitAttempts=[];getCommitAttempts(){return this.commitAttempts.slice()}clearCommitAttempts(){this.commitAttempts.length=0}commit(t,o){return this.commitAttempts.push(t),this.delegate.commit(t,o)}}export{p as InstrumentedStorage};
@@ -1 +0,0 @@
1
- var n=Object.defineProperty;var a=(r,e)=>n(r,"name",{value:e,configurable:!0});class g{static{a(this,"StorageDecorator")}delegate;constructor(e){this.delegate=e}commit(e,t){return this.delegate.commit(e,t)}getEntries(e,t){return this.delegate.getEntries(e,t)}getValue(e,t){return this.delegate.getValue(e,t)}scanValues(e,t){return this.delegate.scanValues(e,t)}readList(e,t,s){return this.delegate.readList(e,t,s)}scanBranch(e,t){return this.delegate.scanBranch(e,t)}scanBranchStructure(e,t){return this.delegate.scanBranchStructure(e,t)}scanEntries(e,t){return this.delegate.scanEntries(e,t)}scanUsage(e,t){return this.delegate.scanUsage(e,t)}getStats(e){return this.delegate.getStats(e)}close(e){return this.delegate.close(e)}}export{g as StorageDecorator};
@@ -1 +0,0 @@
1
- var o=Object.defineProperty;var n=(t,s)=>o(t,"name",{value:s,configurable:!0});function e(t){return{control:t.control,settings:t.settings,latestAssistantEntryId:t.latestAssistantEntryId}}n(e,"operationScopeOf");export{e as operationScopeOf};
@@ -1 +0,0 @@
1
- var i=Object.defineProperty;var o=(e,t)=>i(e,"name",{value:t,configurable:!0});function p(e,t){if(e.length===0)throw new TypeError("Value namespace must not be empty");if(e.includes("\0"))throw new TypeError("Value namespace must not contain \\u0000");if(t.includes("\0"))throw new TypeError("Value key must not contain \\u0000")}o(p,"validateAddress");function n(e,t=""){return p(e,t),Object.freeze({namespace:e,key:t,kind:"value"})}o(n,"value");function a(e,t=""){return p(e,t),Object.freeze({namespace:e,key:t,kind:"list"})}o(a,"list");function u(e,t){return{kind:"value",op:"set",namespace:e.namespace,key:e.key,value:t}}o(u,"setValue");function c(e){return{kind:"value",op:"delete",namespace:e.namespace,key:e.key}}o(c,"deleteValue");function l(e,t){return{kind:"list",op:"append",namespace:e.namespace,key:e.key,value:t}}o(l,"appendList");function x(e){return{kind:"list",op:"delete",namespace:e.namespace,key:e.key}}o(x,"deleteList");function m(e={}){const t=e.limit??1e3;if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("List read limit must be a positive safe integer");return{...e.cursor===void 0?{}:{cursor:e.cursor},order:e.order??"asc",limit:Math.min(t,1e4)}}o(m,"resolveListReadOptions");const f=o(e=>n("pi.branch.tip",e),"branchTip"),d=o(()=>n("pi.branch.tip"),"branchTipInventoryPrefix"),$=o(e=>n("pi.lane.config",e),"laneConfig"),g=o(e=>n("pi.lane.state",e),"laneState"),y=o(e=>n("pi.result",e),"operationResult"),k=o(e=>n("pi.op.meta",e),"operationMeta"),T=o(e=>n("pi.op.state",e),"operationState"),b=o((e,t,r)=>n("pi.op.tool_args",`${e}:${t}:${r}`),"operationToolArgs"),h=o((e,t,r)=>n("pi.op.tool_memo",`${e}:${t}:${r}`),"operationToolMemo"),v=o((e,t)=>n("pi.op.preparation",`${e}:${t}`),"operationPreparation"),_=o((e,t)=>n("pi.op.tool_args",t===void 0?`${e}:`:`${e}:${t}:`),"operationToolArgsPrefix"),w=o((e,t)=>n("pi.op.tool_memo",t===void 0?`${e}:`:`${e}:${t}:`),"operationToolMemoPrefix"),P=o(e=>n("pi.op.preparation",`${e}:`),"operationPreparationPrefix"),L=o(e=>n("pi.pending.entry",e),"pendingEntry"),E=o((e,t)=>n("pi.pending.tool_output",`${e}:${t}`),"pendingToolOutput"),O=o((e,t)=>a("pi.pending.assistant_frame",`${e}:${t}`),"pendingAssistantFrames"),V=o(e=>n("pi.pending.tool_output",`${e}:`),"pendingToolOutputPrefix"),A=n("pi.session.name"),M=o(e=>n("pi.entry.label",e),"entryLabel");export{l as appendList,f as branchTip,d as branchTipInventoryPrefix,x as deleteList,c as deleteValue,M as entryLabel,$ as laneConfig,g as laneState,a as list,k as operationMeta,v as operationPreparation,P as operationPreparationPrefix,y as operationResult,T as operationState,b as operationToolArgs,_ as operationToolArgsPrefix,h as operationToolMemo,w as operationToolMemoPrefix,O as pendingAssistantFrames,L as pendingEntry,E as pendingToolOutput,V as pendingToolOutputPrefix,m as resolveListReadOptions,A as sessionName,u as setValue,n as value};
@@ -1,10 +0,0 @@
1
- var W=Object.defineProperty;var d=(t,e)=>W(t,"name",{value:e,configurable:!0});import E from"ignore";import{parse as R}from"yaml";import{toError as b}from"./types.js";const I=64,v=1024,F=[".gitignore",".ignore",".fdignore"];function H(t,e){const n=`<skill name="${t.name}" location="${t.filePath}">
2
- References are relative to ${C(t.filePath)}.
3
-
4
- ${t.content}
5
- </skill>`;return e?`${n}
6
-
7
- ${e}`:n}d(H,"formatSkillInvocation");async function L(t,e,n){const r=[],s=[];for(const i of Array.isArray(e)?e:[e]){const a=await t.fileInfo(i,n);if(!a.ok){a.error.code!=="not_found"&&s.push({type:"warning",code:"file_info_failed",message:a.error.message,path:i});continue}const o=a.value;if(await y(t,o,s,n)!=="directory")continue;const l=await P(t,o.path,!0,E(),o.path,n);r.push(...l.skills),s.push(...l.diagnostics)}return{skills:r,diagnostics:s}}d(L,"loadSkills");async function X(t,e,n,r){const s=[],i=[];for(const a of e){const o=await L(t,a.path,r);for(const l of o.skills)s.push({skill:n?n(l,a.source,r):l,source:a.source});for(const l of o.diagnostics)i.push({...l,source:a.source})}return{skills:s,diagnostics:i}}d(X,"loadSourcedSkills");async function P(t,e,n,r,s,i){const a=[],o=[],l=await t.fileInfo(e,i);if(!l.ok)return l.error.code!=="not_found"&&o.push({type:"warning",code:"file_info_failed",message:l.error.message,path:e}),{skills:a,diagnostics:o};const h=l.value;if(await y(t,h,o,i)!=="directory")return{skills:a,diagnostics:o};await N(t,r,e,s,o,i);const u=await t.listDir(e,i);if(!u.ok)return o.push({type:"warning",code:"list_failed",message:u.error.message,path:e}),{skills:a,diagnostics:o};const m=u.value;for(const c of m){if(c.name!=="SKILL.md")continue;const f=c.path;if(await y(t,c,o,i)!=="file")continue;const k=_(s,f);if(r.ignores(k))continue;const g=await S(t,f,h.name,i);return g.skill&&a.push(g.skill),o.push(...g.diagnostics),{skills:a,diagnostics:o}}for(const c of m.sort((f,p)=>f.name.localeCompare(p.name))){if(c.name.startsWith(".")||c.name==="node_modules")continue;const f=c.path,p=await y(t,c,o,i);if(!p)continue;const k=_(s,f),g=p==="directory"?`${k}/`:k;if(r.ignores(g))continue;if(p==="directory"){const $=await P(t,f,!1,r,s,i);a.push(...$.skills),o.push(...$.diagnostics);continue}if(p!=="file"||!n||!c.name.endsWith(".md"))continue;const w=await S(t,f,h.name,i);w.skill&&a.push(w.skill),o.push(...w.diagnostics)}return{skills:a,diagnostics:o}}d(P,"loadSkillsFromDirInternal");async function N(t,e,n,r,s,i){const a=_(r,n),o=a?`${a}/`:"";for(const l of F){const h=await t.joinPath([n,l],i);if(!h.ok){s.push({type:"warning",code:"file_info_failed",message:h.error.message,path:n});continue}const u=h.value,m=await t.fileInfo(u,i);if(!m.ok){m.error.code!=="not_found"&&s.push({type:"warning",code:"file_info_failed",message:m.error.message,path:u});continue}if(m.value.kind!=="file")continue;const c=await t.readTextFile(u,i);if(!c.ok){s.push({type:"warning",code:"read_failed",message:c.error.message,path:u});continue}const f=c.value.split(/\r?\n/).map(p=>z(p,o)).filter(p=>!!p);f.length>0&&e.add(f)}}d(N,"addIgnoreRules");function z(t,e){const n=t.trim();if(!n||n.startsWith("#")&&!n.startsWith("\\#"))return null;let r=t,s=!1;r.startsWith("!")?(s=!0,r=r.slice(1)):r.startsWith("\\!")&&(r=r.slice(1)),r.startsWith("/")&&(r=r.slice(1));const i=e?`${e}${r}`:r;return s?`!${i}`:i}d(z,"prefixIgnorePattern");async function S(t,e,n,r){const s=[],i=e.replace(/[\\/]+$/,"").split(/[\\/]/).pop()==="SKILL.md",a=await t.readTextFile(e,r);if(!a.ok)return s.push({type:"warning",code:"read_failed",message:a.error.message,path:e}),{skill:null,diagnostics:s};const o=T(a.value);if(!o.ok)return i&&s.push({type:"warning",code:"parse_failed",message:o.error.message,path:e}),{skill:null,diagnostics:s};const{frontmatter:l,body:h}=o.value,u=typeof l.description=="string"?l.description:void 0;if(!i&&(!u||u.trim()===""))return{skill:null,diagnostics:s};for(const f of O(u))s.push({type:"warning",code:"invalid_metadata",message:f,path:e});const c=(typeof l.name=="string"?l.name:void 0)||n;for(const f of A(c,n))s.push({type:"warning",code:"invalid_metadata",message:f,path:e});return!u||u.trim()===""?{skill:null,diagnostics:s}:{skill:{name:c,description:u,content:h,filePath:e,disableModelInvocation:l["disable-model-invocation"]===!0},diagnostics:s}}d(S,"loadSkillFromFile");function A(t,e){const n=[];return t!==e&&n.push(`name "${t}" does not match parent directory "${e}"`),t.length>I&&n.push(`name exceeds ${I} characters (${t.length})`),/^[a-z0-9-]+$/.test(t)||n.push("name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)"),(t.startsWith("-")||t.endsWith("-"))&&n.push("name must not start or end with a hyphen"),t.includes("--")&&n.push("name must not contain consecutive hyphens"),n}d(A,"validateName");function O(t){const e=[];return!t||t.trim()===""?e.push("description is required"):t.length>v&&e.push(`description exceeds ${v} characters (${t.length})`),e}d(O,"validateDescription");function T(t){try{const e=t.replace(/\r\n/g,`
8
- `).replace(/\r/g,`
9
- `);if(!e.startsWith("---"))return{ok:!0,value:{frontmatter:{},body:e}};const n=e.indexOf(`
10
- ---`,3);if(n===-1)return{ok:!0,value:{frontmatter:{},body:e}};const r=e.slice(4,n),s=e.slice(n+4).trim();return{ok:!0,value:{frontmatter:R(r)??{},body:s}}}catch(e){return{ok:!1,error:b(e)}}}d(T,"parseFrontmatter");async function y(t,e,n,r){if(e.kind==="file"||e.kind==="directory")return e.kind;const s=await t.canonicalPath(e.path,r);if(!s.ok){s.error.code!=="not_found"&&n.push({type:"warning",code:"file_info_failed",message:s.error.message,path:e.path});return}const i=await t.fileInfo(s.value,r);if(!i.ok){i.error.code!=="not_found"&&n.push({type:"warning",code:"file_info_failed",message:i.error.message,path:e.path});return}return i.value.kind==="file"||i.value.kind==="directory"?i.value.kind:void 0}d(y,"resolveKind");function C(t){const e=t.replace(/[\\/]+$/,""),n=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return n===2&&e[1]===":"?e.slice(0,3):n<=0?"/":e.slice(0,n)}d(C,"dirnameEnvPath");function _(t,e){const n=t.replace(/\\/g,"/").replace(/\/+$/,""),r=e.replace(/\\/g,"/").replace(/\/+$/,"");return r===n?"":r.startsWith(`${n}/`)?r.slice(n.length+1):r.replace(/^\/+/,"")}d(_,"relativeEnvPath");export{H as formatSkillInvocation,L as loadSkills,X as loadSourcedSkills};
@@ -1,2 +0,0 @@
1
- var o=Object.defineProperty;var t=(l,s)=>o(l,"name",{value:s,configurable:!0});function r(l){const s=l.filter(i=>!i.disableModelInvocation);if(s.length===0)return"";const e=["The following skills provide specialized instructions for specific tasks.","Read the full skill file when the task matches its description.","When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.","","<available_skills>"];for(const i of s)e.push(" <skill>"),e.push(` <name>${a(i.name)}</name>`),e.push(` <description>${a(i.description)}</description>`),e.push(` <location>${a(i.filePath)}</location>`),e.push(" </skill>");return e.push("</available_skills>"),e.join(`
2
- `)}t(r,"formatSkillsForSystemPrompt");function a(l){return l.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}t(a,"escapeXml");export{r as formatSkillsForSystemPrompt};