dal-code 1.0.56 → 1.0.57

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 (276) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/bun/register-bedrock.js +1 -0
  3. package/dist/bundle/chunks/{anthropic-messages-HHQLDDZH.js → anthropic-messages-ASQGS6BL.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-S7VKEJTH.js → azure-openai-responses-ZSCUJBSU.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  6. package/dist/bundle/chunks/{chunk-BCFLC6CK.js → chunk-2E7RGBKM.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-Z64M4Q7A.js → chunk-34D4KVPX.js} +1 -1
  8. package/dist/bundle/chunks/chunk-6PQZ4KMC.js +17 -0
  9. package/dist/bundle/chunks/chunk-6SPX3U36.js +1 -0
  10. package/dist/bundle/chunks/{chunk-UULAEZ3H.js → chunk-F577XLVZ.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-RX6CC5RH.js → chunk-FSX34SAZ.js} +443 -472
  12. package/dist/bundle/chunks/chunk-G5AMLGXC.js +1 -0
  13. package/dist/bundle/chunks/{chunk-F37JXTCY.js → chunk-GPI2GHBH.js} +1 -1
  14. package/dist/bundle/chunks/chunk-HF334NQU.js +21 -0
  15. package/dist/bundle/chunks/{chunk-3HGUIN22.js → chunk-IRSW3MVW.js} +2 -2
  16. package/dist/bundle/chunks/chunk-JPBJUBY4.js +17 -0
  17. package/dist/bundle/chunks/chunk-JPCWLZUZ.js +30 -0
  18. package/dist/bundle/chunks/chunk-JUUJCOIR.js +7 -0
  19. package/dist/bundle/chunks/{chunk-3XMZ5UC3.js → chunk-KP7CMLOT.js} +1 -1
  20. package/dist/bundle/chunks/chunk-LZTZWS3N.js +9 -0
  21. package/dist/bundle/chunks/{chunk-PH42AQ66.js → chunk-MAJODFX6.js} +1 -1
  22. package/dist/bundle/chunks/chunk-NJDCSLWK.js +1 -0
  23. package/dist/bundle/chunks/{chunk-P4IBZA6D.js → chunk-O3XFDBJ3.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-BIY5HTFI.js → chunk-PD6QS7YD.js} +1 -1
  25. package/dist/bundle/chunks/{chunk-ZR6PGIL7.js → chunk-S7K3JBWA.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-VGMP27KM.js → chunk-TNSXMGQB.js} +1 -1
  27. package/dist/bundle/chunks/chunk-XIJS4F22.js +14 -0
  28. package/dist/bundle/chunks/{chunk-QCT6OHUR.js → chunk-YTDTROS5.js} +1 -1
  29. package/dist/bundle/chunks/{cli-NGGC23SK.js → cli-IDAZVEZ2.js} +1 -1
  30. package/dist/bundle/chunks/{cli-TVPE43YN.js → cli-NP7QEFQE.js} +1 -1
  31. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-RK2YCJXC.js → cloudflare-workers-ai-system-one-WLKVTF6I.js} +1 -1
  32. package/dist/bundle/chunks/{execute-MGTKJB44.js → execute-VXSJSHXH.js} +2 -2
  33. package/dist/bundle/chunks/{google-generative-ai-ZPA4VBXP.js → google-generative-ai-3HIBMVL4.js} +1 -1
  34. package/dist/bundle/chunks/{google-vertex-IWHW2RX7.js → google-vertex-7PIUZFM3.js} +1 -1
  35. package/dist/bundle/chunks/{llama-cpp-classify-FXJM52Q3.js → llama-cpp-classify-5OLOZHKT.js} +1 -1
  36. package/dist/bundle/chunks/{mcp-RLFUDVHN.js → mcp-GHYUCPI4.js} +1 -1
  37. package/dist/bundle/chunks/{mistral-conversations-JXVPTO5Y.js → mistral-conversations-6Y33SI3U.js} +1 -1
  38. package/dist/bundle/chunks/{office-RTREQQ7W.js → office-2JSKOL7V.js} +1 -1
  39. package/dist/bundle/chunks/{openai-codex-responses-EYW27UUE.js → openai-codex-responses-BYGMMTPH.js} +1 -1
  40. package/dist/bundle/chunks/{openai-completions-ROBKXDOC.js → openai-completions-UWYQMOLR.js} +1 -1
  41. package/dist/bundle/chunks/{openai-decisions-4T5LPJRA.js → openai-decisions-I5J7OD62.js} +1 -1
  42. package/dist/bundle/chunks/{openai-responses-ZVFZ75QW.js → openai-responses-LWVKQGLT.js} +1 -1
  43. package/dist/bundle/chunks/{openrouter-images-6VJYTLAX.js → openrouter-images-BDUFN6XX.js} +1 -1
  44. package/dist/bundle/chunks/{pi-messages-Y6HBOGKH.js → pi-messages-64FHWMQR.js} +1 -1
  45. package/dist/bundle/chunks/{review-USSKCVWP.js → review-OQEOVDLP.js} +2 -2
  46. package/dist/bundle/chunks/{router-4JLK3BTT.js → router-3UQE4LBN.js} +1 -1
  47. package/dist/bundle/chunks/runtime-E7KOB62K.js +1 -0
  48. package/dist/bundle/chunks/sdk-5V64WBOZ.js +1 -0
  49. package/dist/bundle/chunks/{sync-UCHKAOUU.js → sync-INSWGFSB.js} +3 -3
  50. package/dist/bundle/chunks/{typesafe-system-one-XPDE7VYD.js → typesafe-system-one-7QFJ5JNW.js} +1 -1
  51. package/dist/bundle/chunks/usage-MG7QDPG2.js +1 -0
  52. package/dist/bundle/chunks/virtual-modules-73ZLFCNE.js +1 -0
  53. package/dist/bundle/cli-runtime.js +1 -1
  54. package/dist/bundle/index.js +1 -1
  55. package/dist/bundle/rpc-entry.js +1 -1
  56. package/dist/cli/experimental/auth.js +1 -0
  57. package/dist/cli/experimental/cli.js +1 -0
  58. package/dist/cli/experimental/command-options.js +1 -0
  59. package/dist/cli/experimental/command.js +1 -0
  60. package/dist/cli/experimental/commands/client.js +1 -0
  61. package/dist/cli/experimental/commands/pi.js +1 -0
  62. package/dist/cli/experimental/commands/server.js +1 -0
  63. package/dist/cli/experimental/transport-address.js +1 -0
  64. package/dist/client/index.js +1 -0
  65. package/dist/client/remote-session.js +1 -0
  66. package/dist/client/transcript.js +1 -0
  67. package/dist/core/provider-attribution.js +1 -0
  68. package/dist/modes/interactive/components/daxnuts.js +1 -0
  69. package/dist/modes/interactive/theme/theme-json.js +12 -0
  70. package/dist/modes/interactive/theme/theme-schema.json +356 -0
  71. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  72. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  73. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  74. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  75. package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
  76. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  77. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  78. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  79. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  80. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  81. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  82. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  83. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  84. package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
  85. package/dist/node_modules/@dalcode/dal-learn/src/store.js +3 -3
  86. package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -4
  87. package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -6
  88. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  89. package/dist/node_modules/@dalcode/dal-pi-kit/dist/agent-dir.js +1 -0
  90. package/dist/node_modules/@dalcode/dal-pi-kit/dist/index.js +1 -1
  91. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  92. package/dist/node_modules/@dalcode/dal-pi-kit/src/agent-dir.js +1 -0
  93. package/dist/node_modules/@dalcode/dal-pi-kit/src/index.js +1 -1
  94. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  95. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  96. package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
  97. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  98. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  99. package/dist/node_modules/@dalcode/dal-router/package.json +6 -6
  100. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  101. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  102. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  103. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  104. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  105. package/dist/node_modules/@dalcode/dal-sync/package.json +4 -4
  106. package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -4
  107. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  108. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  109. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  110. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  111. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  112. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  113. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js +1 -0
  114. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js +37 -0
  115. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js +104 -0
  116. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/utils.js +16 -0
  117. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/config.js +1 -0
  118. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/context.js +1 -0
  119. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js +10 -0
  120. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/events.js +1 -0
  121. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/assistant.js +1 -0
  122. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/effect-gate.js +1 -0
  123. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/tools.js +1 -0
  124. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/hooks.js +1 -0
  125. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.js +17 -0
  126. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bash.js +1 -0
  127. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bounded.js +1 -0
  128. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/chord.js +1 -0
  129. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/context.js +1 -0
  130. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/harness.js +1 -0
  131. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/hooks.js +1 -0
  132. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/index.js +1 -0
  133. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/jsonl.js +4 -0
  134. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/collapse.js +3 -0
  135. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/entries.js +1 -0
  136. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/frames.js +1 -0
  137. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/generation.js +1 -0
  138. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/job.js +1 -0
  139. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/plugin.js +1 -0
  140. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/post-tools.js +1 -0
  141. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/task-api.js +1 -0
  142. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/tool.js +3 -0
  143. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/membrane.js +1 -0
  144. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/memory.js +1 -0
  145. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/scheduler.js +1 -0
  146. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/session.js +1 -0
  147. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/system.js +8 -0
  148. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/types.js +1 -0
  149. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/view.js +1 -0
  150. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/prompt-templates.js +5 -0
  151. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js +1 -0
  152. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/result.js +1 -0
  153. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/boundary.js +1 -0
  154. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/checkpoint.js +1 -0
  155. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/deferred.js +1 -0
  156. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/generation.js +1 -0
  157. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/reconcile.js +1 -0
  158. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/recovery.js +1 -0
  159. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/response.js +1 -0
  160. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/retry.js +1 -0
  161. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/structural.js +1 -0
  162. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/terminal.js +1 -0
  163. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tool-placement.js +1 -0
  164. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tools.js +1 -0
  165. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive.js +1 -0
  166. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/harness.js +1 -0
  167. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/index.js +1 -0
  168. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/lane.js +1 -0
  169. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/progress.js +1 -0
  170. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/reducer.js +1 -0
  171. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/restore.js +1 -0
  172. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/transcript.js +1 -0
  173. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/types.js +1 -0
  174. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/commit.js +1 -0
  175. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.js +1 -0
  176. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork-policy.js +1 -0
  177. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork.js +1 -0
  178. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/in-memory-storage-state.js +1 -0
  179. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/index.js +1 -0
  180. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js +1 -0
  181. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.js +1 -0
  182. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/fork.js +1 -0
  183. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/index.js +1 -0
  184. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/io.js +3 -0
  185. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/legacy-v3.js +1 -0
  186. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/repo.js +1 -0
  187. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/storage.js +8 -0
  188. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/types.js +1 -0
  189. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-repo.js +1 -0
  190. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-storage.js +5 -0
  191. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl.js +1 -0
  192. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-repo.js +1 -0
  193. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-storage.js +1 -0
  194. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory.js +1 -0
  195. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/mutation-line.js +1 -0
  196. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/repo-utils.js +1 -0
  197. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.js +1 -0
  198. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/state.js +1 -0
  199. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/datasets.js +1 -0
  200. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/session-repo.js +1 -0
  201. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/storage.js +1 -0
  202. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/session-repo.js +1 -0
  203. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/storage.js +1 -0
  204. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance.js +1 -0
  205. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/gating-storage.js +1 -0
  206. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/index.js +1 -0
  207. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/instrumented-storage.js +1 -0
  208. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/storage-decorator.js +1 -0
  209. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/types.js +0 -0
  210. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.js +1 -0
  211. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/values.js +1 -0
  212. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/skills.js +10 -0
  213. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/system-prompt.js +2 -0
  214. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/telemetry.js +1 -0
  215. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/bash.js +12 -0
  216. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit-diff.js +16 -0
  217. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js +1 -0
  218. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/file-mutation-queue.js +1 -0
  219. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/image.js +1 -0
  220. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.js +1 -0
  221. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/path-utils.js +1 -0
  222. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/read.js +14 -0
  223. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.js +0 -0
  224. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js +1 -0
  225. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/types.js +1 -0
  226. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/adaptive-publisher.js +1 -0
  227. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/output-capture.js +5 -0
  228. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/shell-output.js +1 -0
  229. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/truncate.js +5 -0
  230. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/usage.js +1 -0
  231. package/dist/node_modules/@earendil-works/pi-agent-core/dist/node.js +1 -0
  232. package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/index.js +0 -0
  233. package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.js +1 -0
  234. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  235. package/dist/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.js +1 -0
  236. package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/oauth-page.js +74 -0
  237. package/dist/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
  238. package/dist/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +1 -0
  239. package/dist/node_modules/@earendil-works/pi-ai/dist/images-models.js +1 -0
  240. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.js +1 -0
  241. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.models.js +1 -0
  242. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  243. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  244. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter-images.js +1 -0
  245. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.js +1 -0
  246. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/deferred-tools.js +1 -0
  247. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js +1 -0
  248. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/typebox-helpers.js +1 -0
  249. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -1
  250. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -1
  251. package/dist/node_modules/@earendil-works/pi-ai/package.json +3 -3
  252. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  253. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  254. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  255. package/dist/node_modules/@earendil-works/pi-schema/package.json +1 -1
  256. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  257. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  258. package/dist/server/create-harness.js +1 -0
  259. package/dist/utils/clipboard-native.js +1 -0
  260. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  261. package/examples/extensions/gondolin/package-lock.json +2 -2
  262. package/examples/extensions/gondolin/package.json +1 -1
  263. package/examples/extensions/with-deps/package-lock.json +2 -2
  264. package/examples/extensions/with-deps/package.json +1 -1
  265. package/npm-shrinkwrap.json +2 -2
  266. package/package.json +1 -1
  267. package/dist/bundle/chunks/chunk-3YGHTGYM.js +0 -7
  268. package/dist/bundle/chunks/chunk-MKMLENQD.js +0 -17
  269. package/dist/bundle/chunks/chunk-SE42OS3U.js +0 -21
  270. package/dist/bundle/chunks/chunk-T3TEURLR.js +0 -30
  271. package/dist/bundle/chunks/chunk-XTN2LDU3.js +0 -9
  272. package/dist/bundle/chunks/runtime-G7F6UQLA.js +0 -1
  273. package/dist/bundle/chunks/sdk-CEIRR6KD.js +0 -1
  274. package/dist/bundle/chunks/usage-3ACOJWR3.js +0 -1
  275. package/dist/bundle/chunks/virtual-modules-P4JE2EA6.js +0 -1
  276. /package/dist/bundle/chunks/{chunk-SZZVJTVX.js → chunk-MZ7O6YLD.js} +0 -0
@@ -0,0 +1,5 @@
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};
@@ -0,0 +1 @@
1
+ import{JsonlSessionRepo as s}from"./jsonl/repo.js";export{s as JsonlSessionRepo};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1,10 @@
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};
@@ -0,0 +1,2 @@
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};
@@ -0,0 +1 @@
1
+ var u=Object.defineProperty;var o=(e,t)=>u(e,"name",{value:t,configurable:!0});import{getTelemetryContext as p,withTelemetryContext as d}from"./context.js";const c={version:1,spans:{"pi.ai.request":{description:"One logical request to an AI provider",parents:{kind:"any"},startAttributes:{"pi.ai.operation":{type:"string",required:!0,values:["stream","fetch_deferred","cancel_deferred","generate_images"],description:"Logical provider operation"},"pi.ai.provider":{type:"string",required:!0,description:"Selected provider id"},"pi.ai.model":{type:"string",required:!0,description:"Requested model id"},"pi.ai.api":{type:"string",required:!0,description:"Provider API id"},"pi.ai.streaming":{type:"boolean",required:!0,description:"Whether this operation returns a stream"},"pi.ai.deferred":{type:"boolean",required:!1,description:"Whether the operation requests or participates in deferred execution"}},endAttributes:{"pi.ai.response.model":{type:"string",description:"Concrete response model"},"pi.ai.response.id":{type:"string",cardinality:"high",description:"Provider response id"},"pi.ai.response.stop_reason":{type:"string",values:["stop","length","tool_use","error","aborted","deferred"],description:"Normalized terminal response reason"},"pi.ai.http.status_code":{type:"number",description:"Final HTTP status"},"pi.ai.usage.input_tokens":{type:"number",description:"Reported input tokens"},"pi.ai.usage.output_tokens":{type:"number",description:"Reported output tokens"},"pi.ai.usage.cache_read_tokens":{type:"number",description:"Reported cache-read tokens"},"pi.ai.usage.cache_write_tokens":{type:"number",description:"Reported cache-write tokens"},"pi.ai.usage.reasoning_tokens":{type:"number",description:"Reported reasoning tokens"},"pi.ai.usage.total_tokens":{type:"number",description:"Reported total tokens"},"pi.ai.usage.cost":{type:"number",description:"Reported total cost"},"pi.ai.stream.chunk_count":{type:"number",description:"Streamed update chunk count"},"pi.ai.stream.time_to_first_chunk_ms":{type:"number",description:"Elapsed milliseconds to first update chunk"},"pi.ai.error.type":{type:"string",cardinality:"low",description:"Provider or transport error class"}},status:{default:"ok",errorWhen:"The operation throws or returns an error result"}}}};function b(e,t,n,r){return p(r).startSpan({name:e,attributes:t},i=>n(i,d(i,r)))}o(b,"startAiSpan");const l=["before_run","before_drive","before_run_end","transform_context","before_request","before_payload","after_response","before_tool","after_tool","before_compaction","before_navigation"],h=["run_start","run_resume","run_suspend","operation_abort","run_end","fault","handler_error","turn_start","turn_end","retry_scheduled","retry_start","retry_end","message_start","message_update","message_end","tool_start","tool_update","tool_end","entry_added","queue_update","value_update","config_update","compaction_start","compaction_end","navigation_start","navigation_end","lane_created","usage"],s={"pi.session.id":{type:"string",required:!0,cardinality:"high",description:"Session id"},"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.operation.recovery":{type:"boolean",required:!0,description:"Whether this invocation resumes durable work"}},a={"pi.error.code":{type:"string",cardinality:"low",description:"Stable operation error code"},"pi.error.type":{type:"string",cardinality:"low",description:"Low-cardinality operation error class"}},y={version:1,spans:{"pi.harness.run":{description:"One admitted in-process run invocation",parents:{kind:"root_or_external"},startAttributes:{...s,"pi.operation.kind":{type:"string",required:!0,values:["run"],description:"Run operation kind"}},endAttributes:{"pi.operation.outcome":{type:"string",values:["completed","aborted","failed","suspended"],description:"Run invocation outcome"},...a},status:{default:"ok",errorWhen:"The run fails or throws"}},"pi.harness.compaction":{description:"One admitted in-process manual compaction invocation",parents:{kind:"root_or_external"},startAttributes:{...s,"pi.operation.kind":{type:"string",required:!0,values:["compaction"],description:"Compaction operation kind"}},endAttributes:{"pi.operation.outcome":{type:"string",values:["completed","declined","aborted","failed"],description:"Compaction invocation outcome"},...a},status:{default:"ok",errorWhen:"The compaction fails or throws"}},"pi.harness.navigation":{description:"One admitted in-process navigation invocation",parents:{kind:"root_or_external"},startAttributes:{...s,"pi.operation.kind":{type:"string",required:!0,values:["navigation"],description:"Navigation operation kind"}},endAttributes:{"pi.operation.outcome":{type:"string",values:["completed","declined","aborted","failed"],description:"Navigation invocation outcome"},...a},status:{default:"ok",errorWhen:"The navigation fails or throws"}},"pi.harness.checkpoint":{description:"One run checkpoint",parents:{kind:"spans",spans:["pi.harness.run"]},startAttributes:{"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.checkpoint.kind":{type:"string",required:!0,values:["normal","abort_reconcile"],description:"Checkpoint purpose"}},endAttributes:{},status:{default:"ok",errorWhen:"Checkpoint work throws"}},"pi.harness.turn":{description:"One assistant response and its tool batch",parents:{kind:"spans",spans:["pi.harness.run"]},startAttributes:{"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.turn.id":{type:"string",required:!0,cardinality:"high",description:"Invocation-local turn id"}},endAttributes:{},status:{default:"ok",errorWhen:"Turn work throws"}},"pi.harness.step":{description:"One durable retry attempt",parents:{kind:"spans",spans:["pi.harness.turn","pi.harness.checkpoint","pi.harness.compaction","pi.harness.navigation"]},startAttributes:{"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.step.kind":{type:"string",required:!0,values:["assistant","compaction","branch_summary"],description:"Retryable step kind"},"pi.step.attempt":{type:"number",required:!0,description:"One-based durable attempt number"},"pi.compaction.reason":{type:"string",required:!1,values:["manual","threshold","overflow"],description:"Compaction trigger"}},endAttributes:{"pi.step.outcome":{type:"string",values:["succeeded","retry","failed","aborted","deferred","overflow"],description:"Attempt outcome"}},status:{default:"ok",errorWhen:"The attempt retries, fails, or throws"}},"pi.harness.tool":{description:"One raw phase-2 tool execution",parents:{kind:"spans",spans:["pi.harness.turn","pi.harness.run"]},startAttributes:{"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.turn.id":{type:"string",required:!1,cardinality:"high",description:"Invocation-local live turn id"},"pi.tool.name":{type:"string",required:!0,description:"Tool name"},"pi.tool.call_id":{type:"string",required:!0,cardinality:"high",description:"Tool call id"},"pi.tool.replay":{type:"string",required:!0,values:["never","safe"],description:"Declared replay policy"},"pi.tool.recovery":{type:"boolean",required:!0,description:"Whether this is recovery execution"}},endAttributes:{"pi.tool.is_error":{type:"boolean",description:"Whether raw phase-2 execution returned an error"}},status:{default:"ok",errorWhen:"Raw phase-2 execution returns an error"}},"pi.harness.hook":{description:"One registered hook handler invocation",parents:{kind:"any"},startAttributes:{"pi.lane.name":{type:"string",required:!0,cardinality:"high",description:"Lane name"},"pi.operation.id":{type:"string",required:!1,cardinality:"high",description:"Durable operation id when accepted"},"pi.hook.name":{type:"string",required:!0,values:l,description:"Hook name"},"pi.hook.registration_id":{type:"string",required:!1,description:"Optional hook registration metadata"}},endAttributes:{"pi.hook.outcome":{type:"string",values:["completed","skipped","blocked","failed"],description:"Handler outcome"}},status:{default:"ok",errorWhen:"The handler throws"}},"pi.harness.sleep":{description:"One retry delay",parents:{kind:"spans",spans:["pi.harness.run","pi.harness.compaction","pi.harness.navigation","pi.harness.turn","pi.harness.checkpoint"]},startAttributes:{"pi.operation.id":{type:"string",required:!0,cardinality:"high",description:"Durable operation id"},"pi.sleep.delay_ms":{type:"number",required:!0,description:"Requested delay in milliseconds"}},endAttributes:{"pi.sleep.outcome":{type:"string",values:["elapsed","aborted"],description:"Delay outcome"}},status:{default:"ok",errorWhen:"Sleep work throws"}},"pi.harness.event_handler":{description:"One passive event listener invocation",parents:{kind:"any"},startAttributes:{"pi.event.type":{type:"string",required:!0,cardinality:"low",values:h,description:"Delivered harness event type"},"pi.lane.name":{type:"string",required:!1,cardinality:"high",description:"Lane name for lane-scoped events"}},endAttributes:{},status:{default:"ok",errorWhen:"The listener throws"}},"pi.session.write":{description:"One committed session transaction",parents:{kind:"any"},startAttributes:{"pi.session.id":{type:"string",required:!0,cardinality:"high",description:"Session id"},"pi.lane.name":{type:"string",required:!1,cardinality:"high",description:"Lane name when supplied by the caller"},"pi.operation.id":{type:"string",required:!1,cardinality:"high",description:"Durable operation id when supplied by the caller"},"pi.session.item_count":{type:"number",required:!0,description:"Number of writes in the transaction"},"pi.session.item_kinds":{type:"string[]",required:!0,elementValues:["entry","usage","value","list"],description:"Distinct write kinds in the transaction"}},endAttributes:{"pi.session.first_seq":{type:"number",description:"First committed sequence in the transaction"},"pi.session.last_seq":{type:"number",description:"Last committed sequence in the transaction"}},status:{default:"ok",errorWhen:"Storage rejects the transaction"}}}},_=[c,y];function k(e,t,n,r){return p(r).startSpan({name:e,attributes:t},i=>n(i,d(i,r)))}o(k,"startHarnessSpan");export{_ as AGENT_TELEMETRY_SCHEMAS,c as AI_TELEMETRY_SCHEMA,y as HARNESS_TELEMETRY_SCHEMA,b as startAiSpan,k as startHarnessSpan};
@@ -0,0 +1,12 @@
1
+ var P=Object.defineProperty;var c=(e,f)=>P(e,"name",{value:f,configurable:!0});import{Type as l}from"typebox";import{applyShellOutputUpdate as B}from"../utils/output-capture.js";import{DEFAULT_MAX_BYTES as p,DEFAULT_MAX_LINES as T,formatSize as m}from"../utils/truncate.js";const O=2147483647/1e3,C=2e3,g=l.Object({command:l.String({description:"Bash command to execute"}),timeout:l.Optional(l.Number({description:"Timeout in seconds (optional, no default timeout)"}))});function A(e){if(e!==void 0){if(!Number.isFinite(e)||e<=0)throw new Error("Invalid timeout: must be a finite number of seconds");if(e>O)throw new Error(`Invalid timeout: maximum is ${O} seconds`)}}c(A,"validateTimeout");function M(e){return{name:"bash",label:"bash",description:`Execute a bash command in the current working directory. Returns combined stdout and stderr. Output is truncated to last ${T} lines or ${p/1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,parameters:g,async execute(f,{command:h,timeout:d},w,$,I,x){A(d);const{env:v}=$,s={command:e?.commandPrefix?`${e.commandPrefix}
2
+ ${h}`:h,cwd:v.cwd,env:{},inheritEnv:!0};await e?.prepare?.(s,$,x);let o,E=Date.now(),L,S=!0;w({content:[],details:void 0});const n=await v.exec(s.command,{cwd:s.cwd,env:s.env,inheritEnv:s.inheritEnv,timeout:d,capture:{limits:{maxBytes:p,maxLines:T,retain:"tail"},spill:!0},onUpdate:c(a=>{if(!S)return;o=B(o,a);const r={content:[{type:"text",text:o.text}],details:{truncation:o.truncation.truncated?o.truncation:void 0,fullOutputPath:o.spillPath}},u=Date.now(),b=JSON.stringify(r),y=u-E>=C&&b!==L;w(r,y?{checkpoint:!0}:void 0),y&&(E=u,L=b)},"onUpdate")},x);S=!1;let i=o?.text??"";const t=n.ok?{text:i,...n.value}:o;let _;if(t?.truncation.truncated){_={truncation:t.truncation,fullOutputPath:t.spillPath};const a=t.truncation.totalLines-t.truncation.outputLines+1,r=t.truncation.totalLines;if(t.truncation.lastLinePartial){const u=m(t.lastLineBytes??t.truncation.outputBytes);i+=`
3
+
4
+ [Showing last ${m(t.truncation.outputBytes)} of line ${r} (line is ${u}). Full output: ${t.spillPath}]`}else t.truncation.truncatedBy==="lines"?i+=`
5
+
6
+ [Showing lines ${a}-${r} of ${t.truncation.totalLines}. Full output: ${t.spillPath}]`:i+=`
7
+
8
+ [Showing lines ${a}-${r} of ${t.truncation.totalLines} (${m(p)} limit). Full output: ${t.spillPath}]`}if(!n.ok){const a=n.error.code==="timeout"?`Command timed out after ${d} seconds`:n.error.code==="aborted"?"Command aborted":n.error.message;throw new Error(i?`${i}
9
+
10
+ ${a}`:a,{cause:n.error})}if(n.value.exitCode!==0)throw new Error(`${i?`${i}
11
+
12
+ `:""}Command exited with code ${n.value.exitCode}`);return{content:[{type:"text",text:i||"(no output)"}],details:_}}}}c(M,"createBashTool");export{M as createBashTool};
@@ -0,0 +1,16 @@
1
+ var O=Object.defineProperty;var u=(e,t)=>O(e,"name",{value:t,configurable:!0});import*as S from"diff";function W(e){const t=e.indexOf(`\r
2
+ `),i=e.indexOf(`
3
+ `);return i===-1||t===-1?`
4
+ `:t<i?`\r
5
+ `:`
6
+ `}u(W,"detectLineEnding");function y(e){return e.replace(/\r\n/g,`
7
+ `).replace(/\r/g,`
8
+ `)}u(y,"normalizeToLF");function B(e,t){return t===`\r
9
+ `?e.replace(/\n/g,`\r
10
+ `):e}u(B,"restoreLineEndings");function $(e){return e.normalize("NFKC").split(`
11
+ `).map(t=>t.trimEnd()).join(`
12
+ `).replace(/[\u2018\u2019\u201A\u201B]/g,"'").replace(/[\u201C\u201D\u201E\u201F]/g,'"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g,"-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g," ")}u($,"normalizeForFuzzyMatch");function N(e){return e.match(/[^\n]*\n|[^\n]+/g)??[]}u(N,"splitLinesWithEndings");function R(e){let t=0;return N(e).map(i=>{const r={start:t,end:t+i.length};return t=r.end,r})}u(R,"getLineSpans");function C(e,t){const i=t.matchIndex,r=t.matchIndex+t.matchLength;let s=-1;for(let d=0;d<e.length;d++){const h=e[d];if(i>=h.start&&i<h.end){s=d;break}}if(s===-1)throw new Error("Replacement range is outside the base content.");let c=s;for(;c<e.length&&e[c].end<r;)c++;if(c>=e.length)throw new Error("Replacement range is outside the base content.");return{startLine:s,endLine:c+1}}u(C,"getReplacementLineRange");function b(e,t,i=0){let r=e;for(let s=t.length-1;s>=0;s--){const c=t[s],d=c.matchIndex-i;r=r.substring(0,d)+c.newText+r.substring(d+c.matchLength)}return r}u(b,"applyReplacements");function v(e,t,i){const r=N(e),s=R(t);if(r.length!==s.length)throw new Error("Cannot preserve unchanged lines because the base content has a different line count.");const c=[],d=[...i].sort((o,n)=>o.matchIndex-n.matchIndex);for(const o of d){const n=C(s,o),a=c[c.length-1];if(a&&n.startLine<a.endLine){a.endLine=Math.max(a.endLine,n.endLine),a.replacements.push(o);continue}c.push({...n,replacements:[o]})}let h=0,l="";for(const o of c){l+=r.slice(h,o.startLine).join("");const n=s[o.startLine].start,a=s[o.endLine-1].end;l+=b(t.slice(n,a),o.replacements,n),h=o.endLine}return l+=r.slice(h).join(""),l}u(v,"applyReplacementsPreservingUnchangedLines");function M(e,t){const i=e.indexOf(t);if(i!==-1)return{found:!0,index:i,matchLength:t.length,usedFuzzyMatch:!1,contentForReplacement:e};const r=$(e),s=$(t),c=r.indexOf(s);return c===-1?{found:!1,index:-1,matchLength:0,usedFuzzyMatch:!1,contentForReplacement:e}:{found:!0,index:c,matchLength:s.length,usedFuzzyMatch:!0,contentForReplacement:r}}u(M,"fuzzyFindText");function U(e){return e.startsWith("\uFEFF")?{bom:"\uFEFF",text:e.slice(1)}:{bom:"",text:e}}u(U,"stripBom");function k(e,t){const i=$(e),r=$(t);return i.split(r).length-1}u(k,"countOccurrences");function P(e,t,i){return i===1?new Error(`Could not find the exact text in ${e}. The old text must match exactly including all whitespace and newlines.`):new Error(`Could not find edits[${t}] in ${e}. The oldText must match exactly including all whitespace and newlines.`)}u(P,"getNotFoundError");function j(e,t,i,r){return i===1?new Error(`Found ${r} occurrences of the text in ${e}. The text must be unique. Please provide more context to make it unique.`):new Error(`Found ${r} occurrences of edits[${t}] in ${e}. Each oldText must be unique. Please provide more context to make it unique.`)}u(j,"getDuplicateError");function D(e,t,i){return i===1?new Error(`oldText must not be empty in ${e}.`):new Error(`edits[${t}].oldText must not be empty in ${e}.`)}u(D,"getEmptyOldTextError");function q(e,t){return t===1?new Error(`No changes made to ${e}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`):new Error(`No changes made to ${e}. The replacements produced identical content.`)}u(q,"getNoChangeError");function _(e,t,i){const r=t.map(n=>({oldText:y(n.oldText),newText:y(n.newText)}));for(let n=0;n<r.length;n++)if(r[n].oldText.length===0)throw D(i,n,r.length);const c=r.map(n=>M(e,n.oldText)).some(n=>n.usedFuzzyMatch),d=c?$(e):e,h=[];for(let n=0;n<r.length;n++){const a=r[n],p=M(d,a.oldText);if(!p.found)throw P(i,n,r.length);const x=k(d,a.oldText);if(x>1)throw j(i,n,r.length,x);h.push({editIndex:n,matchIndex:p.index,matchLength:p.matchLength,newText:a.newText})}h.sort((n,a)=>n.matchIndex-a.matchIndex);for(let n=1;n<h.length;n++){const a=h[n-1],p=h[n];if(a.matchIndex+a.matchLength>p.matchIndex)throw new Error(`edits[${a.editIndex}] and edits[${p.editIndex}] overlap in ${i}. Merge them into one edit or target disjoint regions.`)}const l=e,o=c?v(e,d,h):b(d,h);if(l===o)throw q(i,r.length);return{baseContent:l,newContent:o}}u(_,"applyEditsToNormalizedContent");function H(e,t,i,r=4){return S.createTwoFilesPatch(e,e,t,i,void 0,void 0,{context:r,headerOptions:S.FILE_HEADERS_ONLY})}u(H,"generateUnifiedPatch");function K(e,t,i=4){const r=S.diffLines(e,t),s=[],c=e.split(`
13
+ `),d=t.split(`
14
+ `),h=Math.max(c.length,d.length),l=String(h).length;let o=1,n=1,a=!1,p;for(let x=0;x<r.length;x++){const F=r[x],f=F.value.split(`
15
+ `);if(f[f.length-1]===""&&f.pop(),F.added||F.removed){p===void 0&&(p=n);for(const T of f)if(F.added){const L=String(n).padStart(l," ");s.push(`+${L} ${T}`),n++}else{const L=String(o).padStart(l," ");s.push(`-${L} ${T}`),o++}a=!0}else{const T=x<r.length-1&&(r[x+1].added||r[x+1].removed),L=a,I=T;if(L&&I)if(f.length<=i*2)for(const g of f){const m=String(o).padStart(l," ");s.push(` ${m} ${g}`),o++,n++}else{const g=f.slice(0,i),m=f.slice(f.length-i),w=f.length-g.length-m.length;for(const E of g){const z=String(o).padStart(l," ");s.push(` ${z} ${E}`),o++,n++}s.push(` ${"".padStart(l," ")} ...`),o+=w,n+=w;for(const E of m){const z=String(o).padStart(l," ");s.push(` ${z} ${E}`),o++,n++}}else if(L){const g=f.slice(0,i),m=f.length-g.length;for(const w of g){const E=String(o).padStart(l," ");s.push(` ${E} ${w}`),o++,n++}m>0&&(s.push(` ${"".padStart(l," ")} ...`),o+=m,n+=m)}else if(I){const g=Math.max(0,f.length-i);g>0&&(s.push(` ${"".padStart(l," ")} ...`),o+=g,n+=g);for(const m of f.slice(g)){const w=String(o).padStart(l," ");s.push(` ${w} ${m}`),o++,n++}}else o+=f.length,n+=f.length;a=!1}}return{diff:s.join(`
16
+ `),firstChangedLine:p}}u(K,"generateDiffString");export{_ as applyEditsToNormalizedContent,v as applyReplacementsPreservingUnchangedLines,W as detectLineEnding,M as fuzzyFindText,K as generateDiffString,H as generateUnifiedPatch,$ as normalizeForFuzzyMatch,y as normalizeToLF,B as restoreLineEndings,U as stripBom};
@@ -0,0 +1 @@
1
+ var A=Object.defineProperty;var s=(e,t)=>A(e,"name",{value:t,configurable:!0});import{Type as d}from"typebox";import{applyEditsToNormalizedContent as C,detectLineEnding as k,generateDiffString as O,generateUnifiedPatch as I,normalizeToLF as v,restoreLineEndings as j,stripBom as L}from"./edit-diff.js";import{withFileMutationQueue as P}from"./file-mutation-queue.js";import{resolveToolPath as _}from"./path-utils.js";const $=d.Object({oldText:d.String({description:"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."}),newText:d.String({description:"Replacement text for this targeted edit."})},{}),F=d.Object({path:d.String({description:"Path to the file to edit (relative or absolute)"}),edits:d.Array($,{description:"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."})},{});function y(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.oldText=="string"&&typeof t.newText=="string"}s(y,"isSingleEditInput");function R(e){if(!e||typeof e!="object")return e;const t=e;if(typeof t.edits=="string")try{const a=JSON.parse(t.edits);Array.isArray(a)?t.edits=a:y(a)&&(t.edits=[a])}catch{}else y(t.edits)&&(t.edits=[t.edits]);const n=t;if(typeof n.oldText!="string"||typeof n.newText!="string")return t;const o=Array.isArray(n.edits)?[...n.edits]:[];o.push({oldText:n.oldText,newText:n.newText});const{oldText:b,newText:i,...r}=n;return{...r,edits:o}}s(R,"prepareEditArguments");function z(e){if(!Array.isArray(e.edits)||e.edits.length===0)throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");return{path:e.path,edits:e.edits}}s(z,"validateEditInput");function g(e,t){return new Error(`Could not edit file: ${e}. Error code: ${t.code}.`,{cause:t})}s(g,"editAccessError");function J(){return{name:"edit",label:"edit",description:"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.",parameters:F,prepareArguments:R,async execute(e,t,n,{env:o},b,i){const{path:r,edits:a}=z(t),l=await _(o,r,i);return P(o,l,async()=>{if(i.abortSignal?.aborted)throw new Error("Operation aborted");const c=await o.fileInfo(l,i);if(!c.ok)throw g(r,c.error);if(c.value.kind!=="file"&&c.value.kind!=="symlink")throw new Error(`Could not edit file: ${r}. Path is not a file.`);const f=await o.readTextFile(l,i);if(!f.ok)throw g(r,f.error);if(i.abortSignal?.aborted)throw new Error("Operation aborted");const{bom:E,text:h}=L(f.value),T=k(h),x=v(h),{baseContent:u,newContent:p}=C(x,a,r);if(i.abortSignal?.aborted)throw new Error("Operation aborted");const S=E+j(p,T),m=await o.writeFile(l,S,i);if(!m.ok)throw g(r,m.error);if(i.abortSignal?.aborted)throw new Error("Operation aborted");const w=O(u,p);return{content:[{type:"text",text:`Successfully replaced ${a.length} block(s) in ${r}.`}],details:{diff:w.diff,patch:I(r,u,p),firstChangedLine:w.firstChangedLine}}},i)}}}s(J,"createEditTool");export{J as createEditTool};
@@ -0,0 +1 @@
1
+ var Q=Object.defineProperty;var r=(t,n)=>Q(t,"name",{value:n,configurable:!0});import{getOrThrow as p}from"../types.js";const h=new WeakMap;function m(t){let n=h.get(t);return n||(n={queues:new Map,registration:Promise.resolve()},h.set(t,n)),n}r(m,"getState");async function q(t,n,a){const u=p(await t.absolutePath(n,a)),e=await t.canonicalPath(u,a);if(e.ok)return e.value;if(e.error.code==="not_found"||e.error.code==="not_supported")return u;throw e.error}r(q,"getMutationQueueKey");async function x(t,n,a,u){const e=m(t),s=e.registration.then(async()=>{const o=await q(t,n,u),c=e.queues.get(o)??Promise.resolve();let l=r(()=>{},"releaseNext");const y=new Promise(P=>{l=P}),f=c.then(()=>y);return e.queues.set(o,f),{key:o,currentQueue:c,chainedQueue:f,releaseNext:l}});e.registration=s.then(()=>{},()=>{});const{key:i,currentQueue:w,chainedQueue:d,releaseNext:g}=await s;await w;try{return await a()}finally{g(),e.queues.get(i)===d&&e.queues.delete(i)}}r(x,"withFileMutationQueue");export{x as withFileMutationQueue};
@@ -0,0 +1 @@
1
+ var u=Object.defineProperty;var l=(n,t)=>u(n,"name",{value:t,configurable:!0});const g=[137,80,78,71,13,10,26,10];function A(n){if(x(n,[255,216,255]))return n[3]===247?void 0:"image/jpeg";if(x(n,g))return p(n)&&!m(n)?"image/png":void 0;if(a(n,0,"GIF87a")||a(n,0,"GIF89a"))return"image/gif";if(a(n,0,"RIFF")&&a(n,8,"WEBP"))return"image/webp";if(a(n,0,"BM")&&I(n))return"image/bmp"}l(A,"detectSupportedImageMimeType");function B(n){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let i="";for(let e=0;e<n.length;e+=3){const r=n[e]??0,c=n[e+1],d=n[e+2];i+=t[r>>2],i+=t[(r&3)<<4|(c??0)>>4],i+=c===void 0?"=":t[(c&15)<<2|(d??0)>>6],i+=d===void 0?"=":t[d&63]}return i}l(B,"encodeBase64");function p(n){return n.length>=16&&h(n,g.length)===13&&a(n,12,"IHDR")}l(p,"isPng");function m(n){let t=g.length;for(;t+8<=n.length;){const i=h(n,t),e=t+4;if(a(n,e,"acTL"))return!0;if(a(n,e,"IDAT"))return!1;const r=t+8+i+4;if(r<=t||r>n.length)return!1;t=r}return!1}l(m,"isAnimatedPng");function I(n){if(n.length<26)return!1;const t=o(n,2),i=o(n,10),e=o(n,14);if(t!==0&&t<26||i<14+e||t!==0&&i>=t)return!1;let r,c;if(e===12)r=s(n,22),c=s(n,24);else if(e>=40&&e<=124){if(n.length<30)return!1;r=s(n,26),c=s(n,28)}else return!1;return r===1&&[1,4,8,16,24,32].includes(c)}l(I,"isBmp");function s(n,t){return(n[t]??0)+((n[t+1]??0)<<8)}l(s,"readUint16LE");function h(n,t){return(n[t]??0)*16777216+((n[t+1]??0)<<16)+((n[t+2]??0)<<8)+(n[t+3]??0)}l(h,"readUint32BE");function o(n,t){return(n[t]??0)+((n[t+1]??0)<<8)+((n[t+2]??0)<<16)+(n[t+3]??0)*16777216}l(o,"readUint32LE");function x(n,t){return n.length<t.length?!1:t.every((i,e)=>n[e]===i)}l(x,"startsWith");function a(n,t,i){if(n.length<t+i.length)return!1;for(let e=0;e<i.length;e++)if(n[t+e]!==i.charCodeAt(e))return!1;return!0}l(a,"startsWithAscii");export{A as detectSupportedImageMimeType,B as encodeBase64};
@@ -0,0 +1 @@
1
+ import{createBashTool as r}from"./bash.js";import{createEditTool as a}from"./edit.js";import{createReadTool as f}from"./read.js";import{createWriteTool as m}from"./write.js";export{r as createBashTool,a as createEditTool,f as createReadTool,m as createWriteTool};
@@ -0,0 +1 @@
1
+ var u=Object.defineProperty;var a=(e,t)=>u(e,"name",{value:t,configurable:!0});import{getOrThrow as i}from"../types.js";const l=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g,c="\u202F";function f(e){const t=e.replace(l," ");return t.startsWith("@")?t.slice(1):t}a(f,"normalizeToolPath");async function p(e,t,r){return i(await e.absolutePath(f(t),r))}a(p,"resolveToolPath");async function h(e,t,r){const o=await p(e,t,r),s=[o,o.replace(/ (AM|PM)\./gi,`${c}$1.`),o.normalize("NFD"),o.replace(/'/g,"\u2019"),o.normalize("NFD").replace(/'/g,"\u2019")];for(const n of new Set(s))if(i(await e.exists(n,r)))return n;return o}a(h,"resolveReadToolPath");export{h as resolveReadToolPath,p as resolveToolPath};
@@ -0,0 +1,14 @@
1
+ var R=Object.defineProperty;var w=(l,x)=>R(l,"name",{value:x,configurable:!0});import{Type as r}from"typebox";import{getOrThrow as U}from"../types.js";import{DEFAULT_MAX_BYTES as f,DEFAULT_MAX_LINES as E,formatSize as $,truncateHead as I}from"../utils/truncate.js";import{detectSupportedImageMimeType as M,encodeBase64 as O}from"./image.js";import{resolveReadToolPath as P}from"./path-utils.js";const _=r.Object({path:r.String({description:"Path to the file to read (relative or absolute)"}),offset:r.Optional(r.Number({description:"Line number to start reading from (1-indexed)"})),limit:r.Optional(r.Number({description:"Maximum number of lines to read"}))});function X(l){return{name:"read",label:"read",description:`Read the contents of a file. Supports text files and images (jpg, png, gif, webp, bmp). Images are sent as attachments. For text files, output is truncated to ${E} lines or ${f/1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,parameters:_,async execute(x,{path:y,offset:u,limit:L},B,{env:b},j,p){const S=await P(b,y,p),m=U(await b.readBinaryFile(S,p)),s=M(m);if(s){if(l?.imageProcessor){const e=await l.imageProcessor(m,s,{autoResizeImages:l.autoResizeImages??!0},p);if(!e.ok)return{content:[{type:"text",text:`Read image file [${s}]
2
+ ${e.message}`}],details:void 0};const a=e.hints.length>0?`
3
+ ${e.hints.join(`
4
+ `)}`:"";return{content:[{type:"text",text:`Read image file [${e.mimeType}]${a}`},{type:"image",data:e.data,mimeType:e.mimeType}],details:void 0}}return s==="image/bmp"?{content:[{type:"text",text:`Read image file [image/bmp]
5
+ [Image omitted: configure an imageProcessor to convert BMP images.]`}],details:void 0}:{content:[{type:"text",text:`Read image file [${s}]`},{type:"image",data:O(m),mimeType:s}],details:void 0}}const n=new TextDecoder().decode(m).split(`
6
+ `),T=n.length,t=u?Math.max(0,u-1):0,d=t+1;if(t>=n.length)throw new Error(`Offset ${u} is beyond end of file (${n.length} lines total)`);let g,c;if(L!==void 0){const e=Math.min(t+L,n.length);g=n.slice(t,e).join(`
7
+ `),c=e-t}else g=n.slice(t).join(`
8
+ `);const i=I(g);let o,h;if(i.firstLineExceedsLimit){const e=$(new TextEncoder().encode(n[t]).byteLength);o=`[Line ${d} is ${e}, exceeds ${$(f)} limit. Use bash: sed -n '${d}p' ${y} | head -c ${f}]`,h={truncation:i}}else if(i.truncated){const e=d+i.outputLines-1,a=e+1;o=i.content,i.truncatedBy==="lines"?o+=`
9
+
10
+ [Showing lines ${d}-${e} of ${T}. Use offset=${a} to continue.]`:o+=`
11
+
12
+ [Showing lines ${d}-${e} of ${T} (${$(f)} limit). Use offset=${a} to continue.]`,h={truncation:i}}else if(c!==void 0&&t+c<n.length){const e=n.length-(t+c),a=t+c+1;o=`${i.content}
13
+
14
+ [${e} more lines in file. Use offset=${a} to continue.]`}else o=i.content;return{content:[{type:"text",text:o}],details:h}}}}w(X,"createReadTool");export{X as createReadTool};
@@ -0,0 +1 @@
1
+ var s=Object.defineProperty;var n=(i,e)=>s(i,"name",{value:e,configurable:!0});import{Type as o}from"typebox";import{getOrThrow as c}from"../types.js";import{withFileMutationQueue as w}from"./file-mutation-queue.js";import{resolveToolPath as d}from"./path-utils.js";const f=o.Object({path:o.String({description:"Path to the file to write (relative or absolute)"}),content:o.String({description:"Content to write to the file"})});function g(){return{name:"write",label:"write",description:"Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",parameters:f,async execute(i,{path:e,content:l},p,{env:r},u,t){const a=await d(r,e,t);return w(r,a,async()=>{if(t.abortSignal?.aborted)throw new Error("Operation aborted");if(c(await r.writeFile(a,l,t)),t.abortSignal?.aborted)throw new Error("Operation aborted");return{content:[{type:"text",text:`Successfully wrote to ${e}`}],details:void 0}},t)}}}n(g,"createWriteTool");export{g as createWriteTool};
@@ -0,0 +1 @@
1
+ var d=Object.defineProperty;var n=(r,o)=>d(r,"name",{value:o,configurable:!0});function u(r){return{ok:!0,value:r}}n(u,"ok");function s(r){return{ok:!1,error:r}}n(s,"err");function f(r){if(!r.ok)throw r.error;return r.value}n(f,"getOrThrow");function E(r){return r.ok?r.value:void 0}n(E,"getOrUndefined");function p(r){if(r instanceof Error)return r;if(typeof r=="string")return new Error(r);try{return new Error(JSON.stringify(r))}catch{return new Error(String(r))}}n(p,"toError");class a extends Error{static{n(this,"FileError")}code;path;constructor(o,t,e,i){super(t,i===void 0?void 0:{cause:i}),this.name="FileError",this.code=o,this.path=e}}class h extends Error{static{n(this,"ExecutionError")}code;constructor(o,t,e){super(t,e===void 0?void 0:{cause:e}),this.name="ExecutionError",this.code=o}}class x extends Error{static{n(this,"CompactionError")}code;constructor(o,t,e){super(t,e===void 0?void 0:{cause:e}),this.name="CompactionError",this.code=o}}class m extends Error{static{n(this,"BranchSummaryError")}code;constructor(o,t,e){super(t,e===void 0?void 0:{cause:e}),this.name="BranchSummaryError",this.code=o}}export{m as BranchSummaryError,x as CompactionError,h as ExecutionError,a as FileError,s as err,f as getOrThrow,E as getOrUndefined,u as ok,p as toError};
@@ -0,0 +1 @@
1
+ var u=Object.defineProperty;var r=(h,t)=>u(h,"name",{value:t,configurable:!0});class a{static{r(this,"AdaptivePublisher")}#i;#n;#u;#h;#s=!1;#e=0;#t;#r=!1;constructor(t){this.#i=t,this.#n=t.minIntervalMs??100,this.#u=t.targetBytesPerSecond??100*1024}markDirty(){if(this.#r)return;this.#s=!0;const t=this.#e-Date.now();if(t<=0){this.flush();return}this.#d(t)}flush(t=!1){if(this.#r||!this.#s)return;const i=Date.now();if(!t&&i<this.#e){this.#d(this.#e-i);return}this.#t!==void 0&&clearTimeout(this.#t),this.#t=void 0;const s=this.#i.snapshot(),e=this.#i.update(this.#h,s);if(e===void 0){this.#h=s,this.#s=!1;return}const n=this.#i.measure(e);this.#h=s,this.#s=!1,this.#e=i+Math.max(this.#n,n*1e3/this.#u),this.#i.publish(e)}dispose(){this.#t!==void 0&&clearTimeout(this.#t),this.#t=void 0,this.#r=!0}#d(t){this.#t===void 0&&(this.#t=setTimeout(()=>{this.#t=void 0;try{this.flush()}catch(i){this.#i.onError(i)}},t))}}export{a as AdaptivePublisher};
@@ -0,0 +1,5 @@
1
+ var f=Object.defineProperty;var h=(e,t)=>f(e,"name",{value:t,configurable:!0});import{AdaptivePublisher as x}from"./adaptive-publisher.js";import{DEFAULT_MAX_BYTES as p,DEFAULT_MAX_LINES as m,truncateHead as y,truncateTail as g,utf8ByteLength as l}from"./truncate.js";const L=100,T=100*1024,B=/[\x00-\x08\x0b-\x1f\ufff9-\ufffb]/g,d=new TextEncoder,u=new TextDecoder;class D{static{h(this,"OutputCapture")}#t;#e;#l;#c;#f;#o=new TextDecoder;#i="";#d=0;#h=0;#x=0;#p=!0;#u=0;#r;#s=!1;#n;constructor(t,i,s){if(this.#t=t?.limits.maxBytes??p,this.#e=t?.limits.maxLines??m,this.#l=t?.limits.retain??"tail",this.#c=i,this.#f=s.onUpdate,!Number.isFinite(this.#t)||this.#t<=0)throw new TypeError("Output maxBytes must be a positive finite number");if(!Number.isInteger(this.#e)||this.#e<=0)throw new TypeError("Output maxLines must be a positive integer");this.#n=new x({snapshot:h(()=>this.snapshot(),"snapshot"),update:b,measure:h(n=>l(JSON.stringify(n)),"measure"),publish:h(n=>this.#f?.(n,this.#c),"publish"),onError:s.onError,minIntervalMs:L,targetBytesPerSecond:T})}get truncated(){return this.#h>this.#t||this.#m()>this.#e}push(t){if(!this.#s){if(typeof t=="string"){this.#a(this.#o.decode()),this.#a(t);return}this.#a(this.#o.decode(t,{stream:!0}))}}finish(){this.#s||this.#a(this.#o.decode())}setSpillPath(t){this.#s||this.#r===t||(this.#r=t,this.#n.markDirty(),this.flush())}snapshot(){const t=this.#l==="head"?y(this.#i,{maxBytes:this.#t,maxLines:this.#e}):g(this.#i,{maxBytes:this.#t,maxLines:this.#e}),i=this.#m(),s=this.truncated,{content:n,...a}=t;return{text:O(n),truncation:{...a,truncated:s,truncatedBy:s?i>this.#e?"lines":"bytes":null,totalBytes:this.#h,totalLines:i},...this.#r===void 0?{}:{spillPath:this.#r},...t.lastLinePartial?{lastLineBytes:this.#u}:{}}}flush(){this.#s||this.#n.flush(!0)}dispose(){this.#n.dispose(),this.#s=!0}#a(t){if(t==="")return;const i=l(t);this.#h+=i,this.#x+=w(t),this.#p=t.endsWith(`
2
+ `);const s=t.lastIndexOf(`
3
+ `);this.#u=s===-1?this.#u+i:l(t.slice(s+1)),this.#i+=t,this.#d+=i;const n=this.#t*2;this.#d>n*2&&(this.#i=this.#l==="tail"?P(this.#i,n):_(this.#i,n),this.#d=l(this.#i)),this.#n.markDirty()}#m(){return this.#x+(this.#p||this.#h===0?0:1)}}function I(e,t){switch(t.kind){case"replace":return t.output;case"append":return{text:`${e?.text??""}${t.text}`,...t.metadata};case"slide":return{text:`${e?.text.slice(t.drop)??""}${t.text}`,...t.metadata};case"metadata":return{text:e?.text??"",...t.metadata}}}h(I,"applyShellOutputUpdate");function b(e,t){if(e===void 0)return{kind:"replace",output:t};const i={truncation:t.truncation,...t.spillPath===void 0?{}:{spillPath:t.spillPath},...t.lastLineBytes===void 0?{}:{lastLineBytes:t.lastLineBytes}};if(t.text===e.text)return{kind:"metadata",metadata:i};if(t.text.length>e.text.length&&t.text.slice(0,e.text.length)===e.text)return{kind:"append",text:t.text.slice(e.text.length),metadata:i};const s=E(e.text,t.text,Math.min(e.text.length,t.text.length,t.truncation.maxBytes*2));return s>0?{kind:"slide",drop:e.text.length-s,text:t.text.slice(s),metadata:i}:{kind:"replace",output:t}}h(b,"updateFrom");function E(e,t,i){if(e.length===0||t.length===0||i===0)return 0;const s=e.length>i?e.slice(e.length-i):e;for(const n of[Math.min(64,t.length),1]){const a=t.slice(0,n);let c=0;for(let r=s.indexOf(a);r!==-1&&!(++c>8);r=s.indexOf(a,r+1)){const o=s.length-r;if(o<=t.length&&s.slice(r)===t.slice(0,o))return o}if(n===1)break}return 0}h(E,"suffixPrefixOverlap");function O(e){return e.replace(B,"")}h(O,"sanitizeShellOutput");function w(e){let t=0;for(let i=e.indexOf(`
4
+ `);i!==-1;i=e.indexOf(`
5
+ `,i+1))t++;return t}h(w,"countNewlines");function P(e,t){const i=d.encode(e);if(i.length<=t)return e;let s=i.length-t;for(;s<i.length&&((i[s]??0)&192)===128;)s++;return u.decode(i.subarray(s))}h(P,"trimToLastUtf8Bytes");function _(e,t){const i=d.encode(e);if(i.length<=t)return e;let s=t;for(;s>0&&((i[s]??0)&192)===128;)s--;return u.decode(i.subarray(0,s))}h(_,"trimToFirstUtf8Bytes");export{L as OUTPUT_MIN_EMIT_INTERVAL_MS,T as OUTPUT_TARGET_BYTES_PER_SECOND,D as OutputCapture,I as applyShellOutputUpdate,O as sanitizeShellOutput};
@@ -0,0 +1 @@
1
+ var m=Object.defineProperty;var u=(e,c)=>m(e,"name",{value:c,configurable:!0});import{err as p,ok as o}from"../types.js";import{applyShellOutputUpdate as h,sanitizeShellOutput as E}from"./output-capture.js";import{DEFAULT_MAX_BYTES as k,DEFAULT_MAX_LINES as v,truncateTail as y}from"./truncate.js";function f(e){return{output:e.text,truncation:{content:e.text,...e.truncation},...e.spillPath===void 0?{}:{fullOutputPath:e.spillPath},lastLineBytes:e.lastLineBytes??0}}u(f,"progressFrom");async function A(e,c,r,d){let t;const i=await e.exec(c,{cwd:r?.cwd,env:r?.env,inheritEnv:r?.inheritEnv,timeout:r?.timeout,capture:{limits:{maxBytes:k,maxLines:v,retain:"tail"},spill:!0},onUpdate:u((n,l)=>{const x=t;t=h(t,n);const s=n.kind==="append"||n.kind==="slide"?n.text:n.kind==="replace"&&x===void 0?t.text:void 0;s&&r?.onChunk?.(s,()=>f(t),l)},"onUpdate")},d);if(t===void 0){const{content:n,...l}=y("");t={text:n,truncation:l}}const a=f(t);return i.ok?o({...a,exitCode:i.value.exitCode,cancelled:!1,truncated:i.value.truncation.truncated}):i.error.code==="aborted"||d.abortSignal?.aborted?o({...a,exitCode:void 0,cancelled:!0,truncated:a.truncation.truncated}):r?.returnExecutionErrors?o({...a,exitCode:void 0,cancelled:!1,truncated:a.truncation.truncated,executionError:i.error}):p(i.error)}u(A,"executeShellWithCapture");export{A as executeShellWithCapture,E as sanitizeBinaryOutput};