dal-code 1.0.57 → 1.0.58

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 (264) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/bundle/chunks/{anthropic-messages-ASQGS6BL.js → anthropic-messages-FOIJU7LX.js} +1 -1
  3. package/dist/bundle/chunks/{azure-openai-responses-ZSCUJBSU.js → azure-openai-responses-7NBJZKX5.js} +1 -1
  4. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  5. package/dist/bundle/chunks/{chunk-YTDTROS5.js → chunk-3QG7FIE4.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-6SPX3U36.js → chunk-4BOWD7PQ.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-F577XLVZ.js → chunk-4PBY6OYS.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-PD6QS7YD.js → chunk-5MF5GEDD.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-KP7CMLOT.js → chunk-B7KZDIWA.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-6PQZ4KMC.js → chunk-C5ELI234.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-FSX34SAZ.js → chunk-CCU76UL3.js} +6 -6
  12. package/dist/bundle/chunks/{chunk-MAJODFX6.js → chunk-DVEPGKL5.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-34D4KVPX.js → chunk-IONGABQF.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-GPI2GHBH.js → chunk-JK74OC6W.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-JPBJUBY4.js → chunk-JXAFVEE4.js} +2 -2
  16. package/dist/bundle/chunks/{chunk-XIJS4F22.js → chunk-LMZYTWXD.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-2E7RGBKM.js → chunk-NYSVXLKF.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-O3XFDBJ3.js → chunk-PMFHJN7I.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-JPCWLZUZ.js → chunk-QFBU27TM.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-MZ7O6YLD.js → chunk-QU2VEHMW.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-LZTZWS3N.js → chunk-SCZEDPDC.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-TNSXMGQB.js → chunk-T5PI6B5P.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-S7K3JBWA.js → chunk-X7I3V6OA.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-IRSW3MVW.js → chunk-XQF5XDEM.js} +2 -2
  25. package/dist/bundle/chunks/{cli-NP7QEFQE.js → cli-NQ7B7BGV.js} +1 -1
  26. package/dist/bundle/chunks/{cli-IDAZVEZ2.js → cli-RY666QAD.js} +1 -1
  27. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-WLKVTF6I.js → cloudflare-workers-ai-system-one-CFGOMWWZ.js} +1 -1
  28. package/dist/bundle/chunks/{execute-VXSJSHXH.js → execute-NJRE4WBO.js} +1 -1
  29. package/dist/bundle/chunks/{google-generative-ai-3HIBMVL4.js → google-generative-ai-ZA2RHPNE.js} +1 -1
  30. package/dist/bundle/chunks/{google-vertex-7PIUZFM3.js → google-vertex-Y2GRWOK7.js} +1 -1
  31. package/dist/bundle/chunks/{llama-cpp-classify-5OLOZHKT.js → llama-cpp-classify-G2JDOFHY.js} +1 -1
  32. package/dist/bundle/chunks/{mcp-GHYUCPI4.js → mcp-45D7KCZZ.js} +1 -1
  33. package/dist/bundle/chunks/{mistral-conversations-6Y33SI3U.js → mistral-conversations-MLV32BRV.js} +1 -1
  34. package/dist/bundle/chunks/{office-2JSKOL7V.js → office-UBOUFRAU.js} +1 -1
  35. package/dist/bundle/chunks/{openai-codex-responses-BYGMMTPH.js → openai-codex-responses-BDK3PY6G.js} +1 -1
  36. package/dist/bundle/chunks/{openai-completions-UWYQMOLR.js → openai-completions-BLXHKAB3.js} +1 -1
  37. package/dist/bundle/chunks/{openai-decisions-I5J7OD62.js → openai-decisions-IGVID576.js} +1 -1
  38. package/dist/bundle/chunks/{openai-responses-LWVKQGLT.js → openai-responses-KHZOEDF2.js} +1 -1
  39. package/dist/bundle/chunks/{openrouter-images-BDUFN6XX.js → openrouter-images-SA6PUASF.js} +1 -1
  40. package/dist/bundle/chunks/{pi-messages-64FHWMQR.js → pi-messages-3VAOLQ2Y.js} +1 -1
  41. package/dist/bundle/chunks/{review-OQEOVDLP.js → review-RZXLHPUZ.js} +1 -1
  42. package/dist/bundle/chunks/{router-3UQE4LBN.js → router-YBVXODIL.js} +1 -1
  43. package/dist/bundle/chunks/{runtime-E7KOB62K.js → runtime-FNCZJKOC.js} +1 -1
  44. package/dist/bundle/chunks/{sdk-5V64WBOZ.js → sdk-X6RX7FNE.js} +1 -1
  45. package/dist/bundle/chunks/{sync-INSWGFSB.js → sync-CRV6BXXC.js} +2 -2
  46. package/dist/bundle/chunks/{typesafe-system-one-7QFJ5JNW.js → typesafe-system-one-ER3DLYNF.js} +1 -1
  47. package/dist/bundle/chunks/{usage-MG7QDPG2.js → usage-LMRFS2HV.js} +1 -1
  48. package/dist/bundle/chunks/{virtual-modules-73ZLFCNE.js → virtual-modules-XIUNRFOZ.js} +1 -1
  49. package/dist/bundle/cli-runtime.js +1 -1
  50. package/dist/bundle/index.js +1 -1
  51. package/dist/bundle/rpc-entry.js +1 -1
  52. package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
  53. package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
  54. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  55. package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
  56. package/dist/node_modules/@dalcode/dal-codeindex/package.json +2 -2
  57. package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
  58. package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
  59. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  60. package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
  61. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  62. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  63. package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
  64. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  65. package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
  66. package/dist/node_modules/@dalcode/dal-learn/src/engine.js +3 -3
  67. package/dist/node_modules/@dalcode/dal-learn/src/index.js +11 -11
  68. package/dist/node_modules/@dalcode/dal-learn/src/lessons.js +4 -4
  69. package/dist/node_modules/@dalcode/dal-learn/src/project-map.js +2 -2
  70. package/dist/node_modules/@dalcode/dal-learn/src/signals.js +6 -6
  71. package/dist/node_modules/@dalcode/dal-lsp/package.json +4 -4
  72. package/dist/node_modules/@dalcode/dal-mcp/package.json +6 -6
  73. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  74. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +1 -1
  75. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  76. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
  77. package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
  78. package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
  79. package/dist/node_modules/@dalcode/dal-remote/package.json +2 -2
  80. package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
  81. package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
  82. package/dist/node_modules/@dalcode/dal-router/package.json +6 -6
  83. package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
  84. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  85. package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
  86. package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
  87. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  88. package/dist/node_modules/@dalcode/dal-sync/package.json +4 -4
  89. package/dist/node_modules/@dalcode/dal-telemetry/package.json +4 -4
  90. package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
  91. package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
  92. package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
  93. package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
  94. package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
  95. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  96. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  97. package/dist/node_modules/@earendil-works/pi-ai/dist/cli.js +0 -0
  98. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  99. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.d.ts +1 -1
  100. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/version.js +1 -1
  101. package/dist/node_modules/@earendil-works/pi-ai/package.json +3 -3
  102. package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
  103. package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
  104. package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
  105. package/dist/node_modules/@earendil-works/pi-schema/package.json +1 -1
  106. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  107. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  108. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  109. package/examples/extensions/gondolin/package-lock.json +2 -2
  110. package/examples/extensions/gondolin/package.json +1 -1
  111. package/examples/extensions/with-deps/package-lock.json +2 -2
  112. package/examples/extensions/with-deps/package.json +1 -1
  113. package/npm-shrinkwrap.json +2 -2
  114. package/package.json +1 -1
  115. package/dist/bun/register-bedrock.js +0 -1
  116. package/dist/cli/experimental/auth.js +0 -1
  117. package/dist/cli/experimental/cli.js +0 -1
  118. package/dist/cli/experimental/command-options.js +0 -1
  119. package/dist/cli/experimental/command.js +0 -1
  120. package/dist/cli/experimental/commands/client.js +0 -1
  121. package/dist/cli/experimental/commands/pi.js +0 -1
  122. package/dist/cli/experimental/commands/server.js +0 -1
  123. package/dist/cli/experimental/transport-address.js +0 -1
  124. package/dist/client/index.js +0 -1
  125. package/dist/client/remote-session.js +0 -1
  126. package/dist/client/transcript.js +0 -1
  127. package/dist/core/provider-attribution.js +0 -1
  128. package/dist/modes/interactive/components/daxnuts.js +0 -1
  129. package/dist/modes/interactive/theme/theme-json.js +0 -12
  130. package/dist/modes/interactive/theme/theme-schema.json +0 -356
  131. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/agent-harness.js +0 -1
  132. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/branch-summarization.js +0 -37
  133. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/compaction.js +0 -104
  134. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/compaction/utils.js +0 -16
  135. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/config.js +0 -1
  136. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/context.js +0 -1
  137. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/env/nodejs.js +0 -10
  138. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/events.js +0 -1
  139. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/assistant.js +0 -1
  140. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/effect-gate.js +0 -1
  141. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/execution/tools.js +0 -1
  142. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/hooks.js +0 -1
  143. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.js +0 -17
  144. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bash.js +0 -1
  145. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/bounded.js +0 -1
  146. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/chord.js +0 -1
  147. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/context.js +0 -1
  148. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/harness.js +0 -1
  149. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/hooks.js +0 -1
  150. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/index.js +0 -1
  151. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/jsonl.js +0 -4
  152. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/collapse.js +0 -3
  153. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/entries.js +0 -1
  154. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/frames.js +0 -1
  155. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/generation.js +0 -1
  156. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/job.js +0 -1
  157. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/plugin.js +0 -1
  158. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/post-tools.js +0 -1
  159. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/task-api.js +0 -1
  160. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/kinds/tool.js +0 -3
  161. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/membrane.js +0 -1
  162. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/memory.js +0 -1
  163. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/scheduler.js +0 -1
  164. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/session.js +0 -1
  165. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/system.js +0 -8
  166. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/types.js +0 -1
  167. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/pico3/view.js +0 -1
  168. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/prompt-templates.js +0 -5
  169. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/reducer.js +0 -1
  170. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/result.js +0 -1
  171. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/boundary.js +0 -1
  172. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/checkpoint.js +0 -1
  173. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/deferred.js +0 -1
  174. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/generation.js +0 -1
  175. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/reconcile.js +0 -1
  176. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/recovery.js +0 -1
  177. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/response.js +0 -1
  178. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/retry.js +0 -1
  179. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/structural.js +0 -1
  180. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/terminal.js +0 -1
  181. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tool-placement.js +0 -1
  182. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive/tools.js +0 -1
  183. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/drive.js +0 -1
  184. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/harness.js +0 -1
  185. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/index.js +0 -1
  186. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/lane.js +0 -1
  187. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/progress.js +0 -1
  188. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/reducer.js +0 -1
  189. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/restore.js +0 -1
  190. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/transcript.js +0 -1
  191. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/runtime/types.js +0 -1
  192. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/commit.js +0 -1
  193. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/context.js +0 -1
  194. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork-policy.js +0 -1
  195. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/fork.js +0 -1
  196. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/in-memory-storage-state.js +0 -1
  197. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/index.js +0 -1
  198. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/codec.js +0 -1
  199. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/errors.js +0 -1
  200. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/fork.js +0 -1
  201. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/index.js +0 -1
  202. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/io.js +0 -3
  203. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/legacy-v3.js +0 -1
  204. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/repo.js +0 -1
  205. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/storage.js +0 -8
  206. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl/types.js +0 -1
  207. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-repo.js +0 -1
  208. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl-storage.js +0 -5
  209. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/jsonl.js +0 -1
  210. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-repo.js +0 -1
  211. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory-storage.js +0 -1
  212. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/memory.js +0 -1
  213. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/mutation-line.js +0 -1
  214. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/repo-utils.js +0 -1
  215. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/session.js +0 -1
  216. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/state.js +0 -1
  217. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/datasets.js +0 -1
  218. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/session-repo.js +0 -1
  219. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/benchmark/storage.js +0 -1
  220. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/session-repo.js +0 -1
  221. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance/storage.js +0 -1
  222. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/conformance.js +0 -1
  223. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/gating-storage.js +0 -1
  224. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/index.js +0 -1
  225. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/instrumented-storage.js +0 -1
  226. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/storage-decorator.js +0 -1
  227. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/testing/types.js +0 -0
  228. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/types.js +0 -1
  229. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/session/values.js +0 -1
  230. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/skills.js +0 -10
  231. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/system-prompt.js +0 -2
  232. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/telemetry.js +0 -1
  233. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/bash.js +0 -12
  234. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit-diff.js +0 -16
  235. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/edit.js +0 -1
  236. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/file-mutation-queue.js +0 -1
  237. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/image.js +0 -1
  238. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/index.js +0 -1
  239. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/path-utils.js +0 -1
  240. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/read.js +0 -14
  241. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/tool-context.js +0 -0
  242. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/tools/write.js +0 -1
  243. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/types.js +0 -1
  244. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/adaptive-publisher.js +0 -1
  245. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/output-capture.js +0 -5
  246. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/shell-output.js +0 -1
  247. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/truncate.js +0 -5
  248. package/dist/node_modules/@earendil-works/pi-agent-core/dist/harness/utils/usage.js +0 -1
  249. package/dist/node_modules/@earendil-works/pi-agent-core/dist/node.js +0 -1
  250. package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/index.js +0 -0
  251. package/dist/node_modules/@earendil-works/pi-agent-core/dist/search/scanning.js +0 -1
  252. package/dist/node_modules/@earendil-works/pi-ai/dist/api/cloudflare-gateway-binding.js +0 -1
  253. package/dist/node_modules/@earendil-works/pi-ai/dist/auth/oauth/oauth-page.js +0 -74
  254. package/dist/node_modules/@earendil-works/pi-ai/dist/image-models.generated.js +0 -1
  255. package/dist/node_modules/@earendil-works/pi-ai/dist/images-models.js +0 -1
  256. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.js +0 -1
  257. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/azure-openai-responses.models.js +0 -1
  258. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/openrouter-images.js +0 -1
  259. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/assistant-message-frame.js +0 -1
  260. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/deferred-tools.js +0 -1
  261. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/pi-user-agent.js +0 -1
  262. package/dist/node_modules/@earendil-works/pi-ai/dist/utils/typebox-helpers.js +0 -1
  263. package/dist/server/create-harness.js +0 -1
  264. package/dist/utils/clipboard-native.js +0 -1
@@ -1,10 +0,0 @@
1
- var de=Object.defineProperty;var o=(i,r)=>de(i,"name",{value:r,configurable:!0});import{spawn as z}from"node:child_process";import{randomUUID as le}from"node:crypto";import{constants as Y,createWriteStream as fe}from"node:fs";import{access as J,appendFile as he,lstat as Z,mkdir as H,mkdtemp as me,open as we,readdir as pe,readFile as ee,realpath as be,rename as ye,rm as ge,writeFile as te}from"node:fs/promises";import{homedir as re,constants as ve,tmpdir as Se}from"node:os";import{basename as Ee,isAbsolute as xe,join as $,resolve as B}from"node:path";import{fileURLToPath as Te}from"node:url";import{ExecutionError as y,err as u,FileError as T,ok as d,toError as D}from"../types.js";import{OutputCapture as Pe}from"../utils/output-capture.js";const ne=2147483647,Le=ne/1e3,_e=100,ke=8*1024*1024;function Fe(i){if(i===void 0)return d(void 0);if(!Number.isFinite(i)||i<=0)return u(new y("timeout","Invalid timeout: must be a finite number of seconds"));const r=i*1e3;return r>ne?u(new y("timeout",`Invalid timeout: maximum is ${Le} seconds`)):d(r)}o(Fe,"resolveTimeoutMs");function b(i,r){let e=r;if(e==="~")e=re();else if(e.startsWith("~/")||process.platform==="win32"&&e.startsWith("~\\"))e=$(re(),e.slice(2));else if(e.startsWith("file://"))try{e=Te(e)}catch{}return xe(e)?B(e):B(i,e)}o(b,"resolvePath");function Ce(i){if(i.isFile())return"file";if(i.isDirectory())return"directory";if(i.isSymbolicLink())return"symlink"}o(Ce,"fileKindFromStats");function ie(i,r){const e=Ce(r);return e?d({name:Ee(i),path:i,kind:e,size:r.size,mtimeMs:r.mtimeMs}):u(new T("invalid","Unsupported file type",i))}o(ie,"fileInfoFromStats");function Ie(i){return i instanceof Error&&"code"in i}o(Ie,"isNodeError");function p(i,r){if(i instanceof T)return i;const e=D(i),n=Ie(i)?i:void 0,t=typeof n?.path=="string"?n.path:r;if(n){const s=n.message;switch(n.code){case"ABORT_ERR":return new T("aborted",s,t,e);case"ENOENT":return new T("not_found",s,t,e);case"EACCES":case"EPERM":return new T("permission_denied",s,t,e);case"ENOTDIR":return new T("not_directory",s,t,e);case"EISDIR":return new T("is_directory",s,t,e);case"EINVAL":return new T("invalid",s,t,e)}}return new T("unknown",e.message,t,e)}o(p,"toFileError");function m(i,r){return i?.aborted?u(new T("aborted","aborted",r)):void 0}o(m,"abortResult");async function W(i){try{return await J(i,Y.F_OK),!0}catch{return!1}}o(W,"pathExists");async function se(i,r,e){return await new Promise(n=>{let t="",s;try{s=z(i,r,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{n({stdout:"",status:null});return}const a=setTimeout(()=>{s.pid&&K(s.pid)},e);s.stdout?.setEncoding("utf8"),s.stdout?.on("data",l=>{t+=l}),s.on("error",()=>{clearTimeout(a),n({stdout:"",status:null})}),s.on("close",l=>{clearTimeout(a),n({stdout:t,status:l})})})}o(se,"runCommand");async function ae(){const i=process.platform==="win32"?await se("where",["bash.exe"],5e3):await se("which",["bash"],5e3);if(i.status!==0||!i.stdout)return null;const r=i.stdout.trim().split(/\r?\n/)[0];return r&&await W(r)?r:null}o(ae,"findBashOnPath");function Ae(i){const r=i.replace(/\//g,"\\").toLowerCase();return/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(r)}o(Ae,"isLegacyWslBashPath");function N(i){return Ae(i)?{shell:i,args:["-s"],commandTransport:"stdin"}:{shell:i,args:["-c"]}}o(N,"getBashShellConfig");async function Oe(i){if(i)return await W(i)?d(N(i)):u(new y("shell_unavailable",`Custom shell path not found: ${i}`));if(process.platform==="win32"){const e=[],n=process.env.ProgramFiles;n&&e.push(`${n}\\Git\\bin\\bash.exe`);const t=process.env["ProgramFiles(x86)"];t&&e.push(`${t}\\Git\\bin\\bash.exe`);for(const a of e)if(await W(a))return d(N(a));const s=await ae();return s?d(N(s)):u(new y("shell_unavailable",`No bash shell found. Options:
2
- 1. Install Git for Windows: https://git-scm.com/download/win
3
- 2. Add your bash to PATH (Cygwin, MSYS2, etc.)
4
- 3. Configure an explicit shellPath
5
-
6
- Searched Git Bash in:
7
- ${e.map(a=>` ${a}`).join(`
8
- `)}`))}if(await W("/bin/bash"))return d(N("/bin/bash"));const r=await ae();return r?d(N(r)):d({shell:"sh",args:["-c"]})}o(Oe,"getShellConfig");function Me(i,r,e=!0){return e?{...process.env,...i,...r}:{...r}}o(Me,"getShellEnv");function K(i){if(process.platform==="win32"){try{z($(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(i)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}return}try{process.kill(-i,"SIGKILL")}catch{try{process.kill(i,"SIGKILL")}catch{}}}o(K,"killProcessTree");function Re(i,r){return new Promise((e,n)=>{let t=!1,s=!1,a=null,l=null,w,P=i.stdout===null,v=i.stderr===null;const S=o(()=>{w&&clearTimeout(w),i.removeListener("error",R),i.removeListener("exit",A),i.removeListener("close",x),i.stdout?.removeListener("end",M),i.stderr?.removeListener("end",I),i.stdout?.removeListener("data",C),i.stderr?.removeListener("data",C)},"cleanup"),_=o(()=>{t||(t=!0,S(),i.stdout?.destroy(),i.stderr?.destroy(),e({code:a,signal:l}))},"finalize"),E=o(()=>{s&&P&&v&&_()},"maybeFinalizeAfterExit"),h=o(()=>{w&&clearTimeout(w),w=setTimeout(()=>{r()?h():_()},_e)},"armIdleTimer"),C=o(()=>{s&&!t&&h()},"onData"),M=o(()=>{P=!0,E()},"onStdoutEnd"),I=o(()=>{v=!0,E()},"onStderrEnd"),R=o(g=>{t||(t=!0,S(),n(g))},"onError"),A=o((g,L)=>{s=!0,a=g,l=L,E(),t||h()},"onExit"),x=o((g,L)=>{a=g,l=L,_()},"onClose");i.stdout?.once("end",M),i.stderr?.once("end",I),i.stdout?.on("data",C),i.stderr?.on("data",C),i.once("error",R),i.once("exit",A),i.once("close",x)})}o(Re,"waitForChildProcess");class De{static{o(this,"NodeTextLineReader")}file;path;decoder=new TextDecoder;chunk=new Uint8Array(64*1024);byteOffset=0;buffered="";ended=!1;closed=!1;constructor(r,e){this.file=r,this.path=e}async readLine(r){const e=m(r.abortSignal,this.path);if(e)return e;if(this.closed)return u(new T("invalid","Text line reader is closed",this.path));try{for(;;){const n=this.buffered.indexOf(`
9
- `);if(n!==-1){const a=this.buffered.slice(0,n);return this.buffered=this.buffered.slice(n+1),d({text:a,terminated:!0})}if(this.ended){if(this.buffered.length===0)return d(void 0);const a=this.buffered;return this.buffered="",d({text:a,terminated:!1})}const{bytesRead:t}=await this.file.read(this.chunk,0,this.chunk.length,this.byteOffset),s=m(r.abortSignal,this.path);if(s)return s;this.byteOffset+=t,t===0?(this.buffered+=this.decoder.decode(),this.ended=!0):this.buffered+=this.decoder.decode(this.chunk.subarray(0,t),{stream:!0})}}catch(n){return u(p(n,this.path))}}async close(r){if(!this.closed){this.closed=!0,this.buffered="";try{await this.file.close()}catch{}}}}class je{static{o(this,"NodeExecutionEnv")}cwd;shellPath;shellEnv;activeChildPids=new Set;constructor(r){this.cwd=r.cwd,this.shellPath=r.shellPath,this.shellEnv=r.shellEnv}async absolutePath(r,e){return d(b(this.cwd,r))}async joinPath(r,e){return d($(...r))}async exec(r,e,n){const t=n.abortSignal;if(t?.aborted)return u(new y("aborted","aborted"));const s=Fe(e?.timeout);if(!s.ok)return u(s.error);const a=s.value,l=e?.cwd?b(this.cwd,e.cwd):this.cwd,w=await Oe(this.shellPath);if(!w.ok)return w;try{await J(l,Y.F_OK)}catch(P){const v=D(P);return u(new y("spawn_error",`Working directory does not exist: ${l}
10
- Cannot execute bash commands.`,v))}return await new Promise(P=>{let v=!1,S=!1,_,E,h,C;const M=[];let I;const R=[];let A,x,g=!1;const L=o(()=>{h?.pid&&K(h.pid)},"onAbort"),U=o(c=>{if(_!==void 0)return;const f=D(c);_=new y("callback_error",f.message,f),L()},"failCallback");let k;try{k=new Pe(e?.capture,n,{onUpdate:e?.onUpdate,onError:U})}catch(c){const f=D(c);P(u(new y("unknown",f.message,f)));return}const O=o(c=>{v||(v=!0,C&&clearTimeout(C),t&&t.removeEventListener("abort",L),h?.pid&&this.activeChildPids.delete(h.pid),k.dispose(),P(c))},"settle"),X=o(()=>{h?.stdout?.pause(),h?.stderr?.pause()},"pauseOutput"),j=o(()=>{_||E||S||t?.aborted||g||(h?.stdout?.resume(),h?.stderr?.resume())},"resumeOutput"),q=o(c=>{if(E!==void 0)return;const f=D(c);E=new y("unknown",`Failed to preserve complete shell output: ${f.message}`,f),g=!1,L()},"failSpill"),Q=o(c=>{x===void 0||c.length===0||x.write(c)||g||(g=!0,X(),x.once("drain",()=>{g=!1,j()}))},"writeSpill"),G=o(c=>{if(x!==void 0){Q(c);return}R.push(c),A===void 0&&(X(),A=(async()=>{const f=await this.createTempFile({prefix:"pi-output-",suffix:".log"},n);if(!f.ok)throw f.error;I=f.value,k.setSpillPath(I),x=fe(I,{flags:"a",highWaterMark:ke}),x.on("error",q);for(const F of R)Q(F);R.length=0})().catch(q).finally(j))},"startSpill"),oe=o(async()=>{await A;const c=x;c===void 0||E!==void 0||c.destroyed||await new Promise(f=>{c.once("error",()=>f()),c.once("finish",f),c.end()})},"finishSpill");try{const c=w.value.commandTransport==="stdin";h=z(w.value.shell,c?w.value.args:[...w.value.args,r],{cwd:l,detached:process.platform!=="win32",env:Me(this.shellEnv,e?.env,e?.inheritEnv),stdio:[c?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),h.pid&&this.activeChildPids.add(h.pid),c&&(h.stdin?.on("error",()=>{}),h.stdin?.end(r))}catch(c){const f=D(c);O(u(new y("spawn_error",f.message,f)));return}C=a===void 0?void 0:setTimeout(()=>{S=!0,L()},a),t&&(t.aborted?L():t.addEventListener("abort",L,{once:!0}));const V=o(c=>{try{const f=k.truncated;if(k.push(c),!e?.capture?.spill||c.length===0)return;if(I!==void 0||f)G(c);else if(k.truncated){for(const F of M)G(F);M.length=0,G(c)}else M.push(c)}catch(f){U(f)}},"feed");h.stdout?.on("data",V),h.stderr?.on("data",V),Re(h,()=>E===void 0&&A!==void 0&&(x===void 0||g)).then(async({code:c,signal:f})=>{await oe();try{k.finish(),k.flush()}catch(ue){U(ue)}if(_){O(u(_));return}if(S){O(u(new y("timeout",`timeout:${e?.timeout}`)));return}if(t?.aborted){O(u(new y("aborted","aborted")));return}if(E){O(u(E));return}const F=k.snapshot(),ce=c??(f?128+(ve.signals[f]??0):1);O(d({exitCode:ce,truncation:F.truncation,...F.spillPath===void 0?{}:{spillPath:F.spillPath},...F.lastLineBytes===void 0?{}:{lastLineBytes:F.lastLineBytes}}))},c=>O(u(new y("spawn_error",c.message,c))))})}async openTextLineReader(r,e){const n=b(this.cwd,r),t=m(e.abortSignal,n);if(t)return t;try{const s=await we(n,"r"),a=m(e.abortSignal,n);return a?(await s.close().catch(()=>{}),a):d(new De(s,n))}catch(s){return u(p(s,n))}}async readTextFile(r,e){const n=b(this.cwd,r),t=e.abortSignal,s=m(t,n);if(s)return s;try{return d(await ee(n,{encoding:"utf8",signal:t}))}catch(a){return u(p(a,n))}}async readTextLines(r,e,n){if(e?.maxLines!==void 0&&e.maxLines<=0)return d([]);const t=await this.openTextLineReader(r,n);if(!t.ok)return t;const s=[];try{for(;e?.maxLines===void 0||s.length<e.maxLines;){const a=await t.value.readLine(n);if(!a.ok)return a;if(a.value===void 0)break;s.push(a.value.text)}return d(s)}finally{await t.value.close(n)}}async readBinaryFile(r,e){const n=b(this.cwd,r),t=e.abortSignal,s=m(t,n);if(s)return s;try{return d(await ee(n,{signal:t}))}catch(a){return u(p(a,n))}}async writeFile(r,e,n){const t=b(this.cwd,r),s=n.abortSignal,a=m(s,t);if(a)return a;try{await H(B(t,".."),{recursive:!0});const l=m(s,t);return l||(await te(t,e,{signal:s}),d(void 0))}catch(l){return u(p(l,t))}}async appendFile(r,e,n){const t=b(this.cwd,r),s=n.abortSignal,a=m(s,t);if(a)return a;try{await H(B(t,".."),{recursive:!0});const l=m(s,t);return l||(await he(t,e),m(s,t)??d(void 0))}catch(l){return u(p(l,t))}}async renameFile(r,e,n){const t=b(this.cwd,r),s=b(this.cwd,e),a=m(n.abortSignal,s);if(a)return a;try{return await ye(t,s),d(void 0)}catch(l){return u(p(l,t))}}async fileInfo(r,e){const n=b(this.cwd,r),t=m(e.abortSignal,n);if(t)return t;try{return ie(n,await Z(n))}catch(s){return u(p(s,n))}}async listDir(r,e){const n=b(this.cwd,r),t=e.abortSignal,s=m(t,n);if(s)return s;try{const a=await pe(n,{withFileTypes:!0}),l=[];for(const w of a){const P=m(t,n);if(P)return P;const v=B(n,w.name);try{const S=ie(v,await Z(v));S.ok&&l.push(S.value)}catch(S){return u(p(S,v))}}return d(l)}catch(a){return u(p(a,n))}}async canonicalPath(r,e){const n=b(this.cwd,r),t=m(e.abortSignal,n);if(t)return t;try{return d(await be(n))}catch(s){return u(p(s,n))}}async exists(r,e){const n=await this.fileInfo(r,e);return n.ok?d(!0):n.error.code==="not_found"?d(!1):u(n.error)}async createDir(r,e,n){const t=b(this.cwd,r),s=m(n.abortSignal,t);if(s)return s;try{return await H(t,{recursive:e?.recursive??!0}),d(void 0)}catch(a){return u(p(a,t))}}async remove(r,e,n){const t=b(this.cwd,r),s=m(n.abortSignal,t);if(s)return s;try{return await ge(t,{recursive:e?.recursive??!1,force:e?.force??!1}),d(void 0)}catch(a){return u(p(a,t))}}async createTempDir(r,e){const n=m(e.abortSignal);if(n)return n;try{return r??="tmp-",d(await me($(Se(),r)))}catch(t){return u(p(t))}}async createTempFile(r,e){const n=await this.createTempDir("tmp-",e);if(!n.ok)return n;const t=$(n.value,`${r?.prefix??""}${le()}${r?.suffix??""}`);try{return await te(t,""),d(t)}catch(s){return u(p(s,t))}}async cleanup(r){for(const e of this.activeChildPids)K(e);this.activeChildPids.clear()}}export{je as NodeExecutionEnv};
@@ -1 +0,0 @@
1
- var f=Object.defineProperty;var c=(d,e)=>f(d,"name",{value:e,configurable:!0});class w{static{c(this,"HarnessEventBus")}listeners=new Map;watchListeners=new Set;deliveryTail=Promise.resolve();closedError;on(e,s){if(this.closedError!==void 0)throw this.closedError;const r=c((n,i)=>s(n,i),"wrapped");let t=this.listeners.get(e);return t===void 0&&(t=new Set,this.listeners.set(e,t)),t.add(r),()=>t?.delete(r)}emit(e,s){return this.emitBatch([e],s)}emitBatch(e,s){if(this.closedError!==void 0||e.length===0)return Promise.resolve();const r=e.map(n=>{const i=structuredClone(n);return{payload:i,recipients:this.snapshotRecipients(i)}}),t=this.deliveryTail.then(async()=>{for(const{payload:n,recipients:i}of r)await this.deliver(n,i,!0,s)});return this.deliveryTail=t.catch(()=>{}),t}watch(e,s,r,t){if(this.closedError!==void 0)throw this.closedError;return this.installWatcher(e,s,t)}async watchFromSnapshot(e,s,r){if(this.closedError!==void 0)throw this.closedError;const t=this.installWatcher(void 0,s,async(n,i)=>{const a=await e(n);return i(),a});try{return t.setSnapshot(await e(r)),t}catch(n){throw t.unsubscribe(),n}}close(e){this.closedError??=e,this.deliveryTail.finally(()=>{this.listeners.clear(),this.watchListeners.clear()})}installWatcher(e,s,r){let t;const n=r===void 0?void 0:async a=>{let h=!1;const o=await r(a,()=>{if(h)throw new Error("Resnapshot boundary was already marked");h=!0,this.enqueueBarrier(()=>t.markResnapshotBoundary())});if(!h)throw new Error("Resnapshot capture did not mark its boundary");return o};t=new p(e,n,async(a,h,o)=>{if(h.type==="handler_error")return;const l=a instanceof Error?a:new Error(String(a)),u="lane"in h&&typeof h.lane=="string"?h.lane:void 0;await this.emit({type:"handler_error",kind:"event",event:h.type,error:l.message,...l.stack===void 0?{}:{stack:l.stack},...u===void 0?{}:{lane:u}},o)});const i=c((a,h)=>{s(a)&&t.push(a,h)},"watchListener");return this.watchListeners.add(i),t.setUnsubscribe(()=>this.watchListeners.delete(i)),t}enqueueBarrier(e){const s=this.deliveryTail.then(e);this.deliveryTail=s.catch(()=>{})}snapshotRecipients(e){return[...this.listeners.get(e.type)??[],...this.watchListeners]}async deliver(e,s,r,t){for(const n of s)try{await n(structuredClone(e),t)}catch(i){if(!r||e.type==="handler_error")continue;const a=i instanceof Error?i:new Error(String(i)),h="lane"in e&&typeof e.lane=="string"?e.lane:void 0,o={type:"handler_error",kind:"event",event:e.type,error:a.message,...a.stack===void 0?{}:{stack:a.stack},...h===void 0?{}:{lane:h}};await this.deliver(o,this.snapshotRecipients(o),!1,t)}}}class p{static{c(this,"BufferedEventWatcher")}snapshot;resnapshotCallback;onError;buffer=[];listener;unsubscribeCallback;deliveryTail=Promise.resolve();epoch=0;resnapshotState;state="buffering";constructor(e,s,r){this.snapshot=e,this.resnapshotCallback=s,this.onError=r}setSnapshot(e){this.snapshot=e}start(e){if(this.state!=="buffering")throw new Error("WatchHandle.start() may be called only once");this.state="started",this.listener=e;const s=this.buffer;this.buffer=[];for(const r of s)this.enqueue(r.event,r.context,r.epoch)}async resnapshot(e){if(this.state==="unsubscribed")throw new Error("WatchHandle is unsubscribed");if(this.resnapshotCallback===void 0)throw new Error("WatchHandle does not support resnapshot");if(this.resnapshotState!==void 0)throw new Error("WatchHandle resnapshot is already in progress");let s;const r=new Promise(n=>{s=n}),t={phase:"dropping",held:[],reached:r,resolveReached:s};this.epoch++,this.resnapshotState=t;try{const n=await this.resnapshotCallback(e);await r,this.snapshot=n,this.resnapshotState=void 0;for(const i of t.held)this.push(i.event,i.context);return n}catch(n){this.resnapshotState=void 0;for(const i of t.held)this.push(i.event,i.context);throw n}}markResnapshotBoundary(){const e=this.resnapshotState;e===void 0||e.phase!=="dropping"||(e.phase="holding",e.resolveReached())}unsubscribe(){this.state!=="unsubscribed"&&(this.state="unsubscribed",this.buffer=[],this.listener=void 0,this.unsubscribeCallback?.(),this.unsubscribeCallback=void 0)}push(e,s){if(this.state!=="unsubscribed"&&this.resnapshotState?.phase!=="dropping"){if(this.resnapshotState?.phase==="holding"){this.resnapshotState.held.push({event:e,context:s});return}if(this.state==="buffering"){this.buffer.push({event:e,context:s,epoch:this.epoch});return}this.enqueue(e,s,this.epoch)}}setUnsubscribe(e){this.unsubscribeCallback=e}enqueue(e,s,r){const t=this.listener;t!==void 0&&(this.deliveryTail=this.deliveryTail.then(async()=>{this.state==="started"&&r===this.epoch&&await t(e,s)}).catch(async n=>{try{await this.onError(n,e,s)}catch{}}))}}export{w as HarnessEventBus};
@@ -1 +0,0 @@
1
- var u=Object.defineProperty;var m=(s,t)=>u(s,"name",{value:t,configurable:!0});import{getTelemetryContext as f}from"../context.js";import{AbortRequested as y}from"./effect-gate.js";function w(s,t,r){const e=s.streamOptions;return{transport:e.transport,timeoutMs:e.timeoutMs,maxRetries:e.maxRetries,maxRetryDelayMs:e.maxRetryDelayMs,headers:e.headers,metadata:e.metadata,cacheRetention:e.cacheRetention,deferred:e.deferred,...s.thinkingLevel==="off"?{}:{reasoning:s.thinkingLevel},signal:r.abortSignal,telemetryContext:f(r),onPayload:s.beforePayload===void 0?void 0:(n,o)=>s.beforePayload?.(n,o,r),onResponse:m(n=>{t({status:n.status,headers:n.headers})},"onResponse")}}m(w,"createRequestOptions");function h(s){return s.type!=="start"&&s.type!=="done"&&s.type!=="error"}m(h,"isUpdateEvent");async function R(s,t,r,e){let n=!1;for await(const a of s)if(a.type==="start"){if(n)throw new Error("Assistant message stream emitted more than one start event");n=!0,await t.start({...a.partial},a,e)}else if(h(a)){if(!n)throw new Error(`Assistant message stream emitted ${a.type} before start`);await t.update({...a.partial},a,e)}else if(a.type==="done"&&!n)throw new Error("Assistant message stream emitted done before start");const o=await s.result();let i=o;if(r!==void 0)try{i=await r(o,e)}catch(a){if(!(a instanceof y))throw a;await a.cancellation}return await t.end(i,e),i}m(R,"consumeAssistantStream");async function C(s,t,r){let e={messages:s.slice(),systemPrompt:t.systemPrompt};t.transformContext&&(e=await t.transformContext(e,r));const n=await t.toProviderMessages(e.messages,r),o={systemPrompt:e.systemPrompt,messages:n,tools:t.tools};let i={};const a=await t.request(o,w(t,d=>{i=d},r),r),l=t.afterResponse;return R(a,t.observer,l===void 0?void 0:(d,p)=>l(d,i,p),r)}m(C,"streamHarnessAssistant");export{R as consumeAssistantStream,C as streamHarnessAssistant};
@@ -1 +0,0 @@
1
- var a=Object.defineProperty;var o=(t,e)=>a(t,"name",{value:e,configurable:!0});class s extends Error{static{o(this,"AbortRequested")}cancellation;constructor(e){super("Abort requested"),this.name="AbortRequested",this.cancellation=e}}function c(){let t={status:"open"};const e=new AbortController,n=o(()=>{if(t.status==="aborting")throw new s(t.cancellation);if(t.status==="closed")throw t.error},"check");return{gate:{admit(r){return n(),r()},signal:e.signal},control:{beginAbort(r){t.status==="open"&&(t={status:"aborting",cancellation:r})},signalAbort(){t.status!=="aborting"||e.signal.aborted||e.abort(new s(t.cancellation))},close(r){t.status!=="closed"&&(t={status:"closed",error:r},e.signal.aborted||e.abort(r))}}}}o(c,"createGate");export{s as AbortRequested,c as createGate};
@@ -1 +0,0 @@
1
- var E=Object.defineProperty;var n=(t,e)=>E(t,"name",{value:e,configurable:!0});import{validateToolArguments as m}from"@earendil-works/pi-ai";import{withAbortSignal as c}from"../context.js";function f(t){return{content:[{type:"text",text:t}],details:void 0}}n(f,"createErrorToolResult");function l(t,e,r=!1){return{kind:"immediate",toolCall:t,result:f(e),isError:!0,terminate:r}}n(l,"immediateError");function A(t,e){const r=e.find(o=>o.name===t.name);if(!r)return l(t,`Tool ${JSON.stringify(t.name)} is unavailable`);try{const o=r.prepareArguments?r.prepareArguments(t.arguments):t.arguments,i=o===t.arguments?t:{...t,arguments:o},u=m(r,i);return{toolCall:t,tool:r,args:u}}catch(o){return l(t,o instanceof Error?o.message:String(o))}}n(A,"prepareToolCall");function S(t,e){if(e?.block)return l(t.toolCall,e.block.reason,e.block.terminate===!0);if(!e?.args)return{toolCall:t.toolCall,tool:t.tool,args:t.args};try{const r=m(t.tool,{...t.toolCall,arguments:e.args});return{toolCall:t.toolCall,tool:t.tool,args:r}}catch(r){return l(t.toolCall,r instanceof Error?r.message:String(r))}}n(S,"applyBeforeToolDecision");function x(t,e,r,o,i,u){let a=!0;return e.admit(async()=>{const g=c(e.signal,u);g.abortSignal?.throwIfAborted();try{return{result:await t.tool.execute(t.toolCall.id,t.args,(d,C)=>{a&&r(d,C)},o,i,g),isError:!1}}catch(s){return{result:f(s instanceof Error?s.message:String(s)),isError:!0}}finally{a=!1}})}n(x,"executeToolCall");function k(t,e,r){const o=r?{...e.result,content:r.content===void 0?e.result.content:r.content,details:r.details===void 0?e.result.details:r.details,usage:r.usage===void 0?e.result.usage:r.usage,terminate:r.terminate===void 0?e.result.terminate:r.terminate}:e.result;return{toolCall:t.toolCall,result:o,isError:r?.isError??e.isError,terminate:o.terminate===!0}}n(k,"finalizeToolCall");function w(t,e){return{content:t.content,details:t.details,...t.usage===void 0?{}:{usage:t.usage},...e?{terminate:!0}:{}}}n(w,"toolResultFromMessage");function R(t){return{role:"toolResult",toolCallId:t.toolCall.id,toolName:t.toolCall.name,content:t.result.content??[],...t.result.details===void 0?{}:{details:t.result.details},...t.result.usage===void 0?{}:{usage:t.result.usage},isError:t.isError,timestamp:Date.now()}}n(R,"createToolResultMessage");export{S as applyBeforeToolDecision,R as createToolResultMessage,x as executeToolCall,k as finalizeToolCall,A as prepareToolCall,w as toolResultFromMessage};
@@ -1 +0,0 @@
1
- var c=Object.defineProperty;var d=(a,e)=>c(a,"name",{value:e,configurable:!0});import{withAbortSignal as f}from"./context.js";import{startHarnessSpan as u}from"./telemetry.js";class b{static{d(this,"HookRegistry")}registrations=new Map;reportError;closedError;constructor(e){this.reportError=e}on(e,o,r={}){if(this.closedError!==void 0)throw this.closedError;const s=this.registrations.get(e)??[],i={...r.id===void 0?{}:{id:r.id},handler:d((t,n)=>o(t,n),"handler")};return s.push(i),this.registrations.set(e,s),()=>{const t=s.indexOf(i);t!==-1&&s.splice(t,1)}}has(e){return(this.registrations.get(e)?.length??0)!==0}runWithGate(e,o,r,s){return r.admit(()=>{const i=f(r.signal,s);return i.abortSignal?.throwIfAborted(),this.runAdmitted(e,o,i)})}runToolWithGate(e,o,r,s){return r.admit(()=>{const i=f(r.signal,s);return i.abortSignal?.throwIfAborted(),e==="before_tool"?this.beforeTool(o,i):this.afterTool(o,i)})}close(e){this.closedError??=e}async runAdmitted(e,o,r){if(this.closedError!==void 0)throw this.closedError;return await this.aggregate(e,o,r)}async aggregate(e,o,r){switch(e){case"before_run":return this.beforeRun(o,r);case"before_drive":await this.invokeAllFailClosed(e,o,r);return;case"before_run_end":{let s;return await this.invokeAll(e,o,i=>{const t=i;t?.followUp!==void 0&&(s=t.followUp)},r),s===void 0?void 0:{followUp:s}}case"transform_context":return this.transformContext(o,r);case"before_request":return this.beforeRequest(o,r);case"before_payload":return this.beforePayload(o,r);case"after_response":return this.afterResponse(o,r);case"before_tool":return this.beforeTool(o,r);case"after_tool":return this.afterTool(o,r);case"before_compaction":return this.firstStructural(e,o,"compaction",r);case"before_navigation":return this.firstStructural(e,o,"summary",r)}}async beforeRun(e,o){let r=e.prompt,s=[];for(const i of this.registrationsFor("before_run"))try{const t=await i.handler({...e,prompt:r},o);t?.messages!==void 0&&(s=[...s,...t.messages],r=[...r,...t.messages])}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),"before_run",e.lane,o)}return s.length===0?void 0:{messages:s}}async beforeTool(e,o){let r=e.args,s;for(const i of this.registrationsFor("before_tool"))try{const t=await this.invokeToolRegistration("before_tool",i,{...e,args:r},o);if(t?.args!==void 0&&(r=t.args),t?.block!==void 0){s=t.block;break}}catch(t){const n=t instanceof Error?t:new Error(String(t));await this.reportError(n,"before_tool",e.lane,o),s={reason:n.message};break}return{...r===e.args?{}:{args:r},...s===void 0?{}:{block:s}}}async transformContext(e,o){let r=e.messages,s=e.systemPrompt;for(const i of this.registrationsFor("transform_context"))try{const t=await i.handler({...e,messages:r,systemPrompt:s},o);t?.messages!==void 0&&(r=t.messages),t?.systemPrompt!==void 0&&(s=t.systemPrompt)}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),"transform_context",e.lane,o)}return{messages:r,systemPrompt:s}}async beforeRequest(e,o){let r=e.streamOptions,s=!1;for(const i of this.registrationsFor("before_request"))try{const t=await i.handler({...e,streamOptions:r},o);t?.streamOptions!==void 0&&(r=h(r,t.streamOptions),s=!0)}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),"before_request",e.lane,o)}return s?{streamOptions:g(e.streamOptions,r)}:void 0}async beforePayload(e,o){let r=e.payload;for(const s of this.registrationsFor("before_payload"))try{const i=await s.handler({...e,payload:r},o);i?.payload!==void 0&&(r=i.payload)}catch(i){await this.reportError(i instanceof Error?i:new Error(String(i)),"before_payload",e.lane,o)}return{payload:r}}async afterResponse(e,o){let r=e.message;for(const s of this.registrationsFor("after_response"))try{const i=await s.handler({...e,message:r},o);i?.message!==void 0&&(r=i.message)}catch(i){await this.reportError(i instanceof Error?i:new Error(String(i)),"after_response",e.lane,o)}return{message:r}}async afterTool(e,o){let r={content:e.content,details:e.details,isError:e.isError,usage:e.usage};const s={};for(const i of this.registrationsFor("after_tool"))try{const t=await this.invokeToolRegistration("after_tool",i,{...e,...r},o);if(t===void 0)continue;t.content!==void 0&&(s.content=t.content),t.details!==void 0&&(s.details=t.details),t.isError!==void 0&&(s.isError=t.isError),t.usage!==void 0&&(s.usage=t.usage),t.terminate!==void 0&&(s.terminate=t.terminate),r={content:t.content===void 0?r.content:t.content,details:t.details===void 0?r.details:t.details,isError:t.isError===void 0?r.isError:t.isError,usage:t.usage===void 0?r.usage:t.usage}}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),"after_tool",e.lane,o)}return Object.keys(s).length===0?void 0:s}async firstStructural(e,o,r,s){for(const i of this.registrationsFor(e))try{const t=await i.handler(o,s);if(t==null||typeof t!="object")continue;const n=t;if(n.decline===!0&&n[r]!==void 0){await this.reportError(new Error(`${e} hook cannot return both decline and ${r}`),e,o.lane,s);continue}if(n.decline===!0||n[r]!==void 0)return t}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),e,o.lane,s)}}invokeToolRegistration(e,o,r,s){return u("pi.harness.hook",{"pi.lane.name":r.lane,"pi.operation.id":r.runId,"pi.hook.name":e,...o.id===void 0?{}:{"pi.hook.registration_id":o.id}},async(i,t)=>{try{const n=await o.handler(r,t),l=e==="before_tool"&&n!==null&&typeof n=="object"&&"block"in n&&n.block!==void 0;return i.setAttributes({"pi.hook.outcome":l?"blocked":"completed"}),n}catch(n){throw i.setAttributes({"pi.hook.outcome":"failed"}),i.setStatus({status:"error"}),n}},s)}registrationsFor(e){return[...this.registrations.get(e)??[]]}async invokeAllFailClosed(e,o,r){for(const s of this.registrationsFor(e))try{await s.handler(o,r)}catch(i){const t=i instanceof Error?i:new Error(String(i));throw await this.reportError(t,e,o.lane,r),t}}async invokeAll(e,o,r,s){for(const i of this.registrationsFor(e))try{r(await i.handler(o,s))}catch(t){await this.reportError(t instanceof Error?t:new Error(String(t)),e,o.lane,s)}}}function h(a,e){const o={...a};for(const r of["transport","timeoutMs","maxRetries","maxRetryDelayMs","cacheRetention","deferred"]){if(!(r in e))continue;const s=e[r];s===void 0?delete o[r]:Object.assign(o,{[r]:s})}if("headers"in e)if(e.headers===void 0)delete o.headers;else{const r={...o.headers};for(const[s,i]of Object.entries(e.headers))i===void 0?delete r[s]:r[s]=i;o.headers=r}if("metadata"in e)if(e.metadata===void 0)delete o.metadata;else{const r={...o.metadata};for(const[s,i]of Object.entries(e.metadata))i===void 0?delete r[s]:r[s]=i;o.metadata=r}return o}d(h,"applyStreamOptionsPatch");function g(a,e){const o={};for(const r of["transport","timeoutMs","maxRetries","maxRetryDelayMs","cacheRetention","deferred"])a[r]!==e[r]&&Object.assign(o,{[r]:e[r]});if(a.headers!==e.headers)if(e.headers===void 0)o.headers=void 0;else{const r={};for(const s of Object.keys(a.headers??{}))s in e.headers||(r[s]=void 0);for(const[s,i]of Object.entries(e.headers))a.headers?.[s]!==i&&(r[s]=i);a.headers===void 0&&Object.keys(r).length===0?o.headers={}:Object.keys(r).length!==0&&(o.headers=r)}if(a.metadata!==e.metadata)if(e.metadata===void 0)o.metadata=void 0;else{const r={};for(const s of Object.keys(a.metadata??{}))s in e.metadata||(r[s]=void 0);for(const[s,i]of Object.entries(e.metadata))a.metadata?.[s]!==i&&(r[s]=i);a.metadata===void 0&&Object.keys(r).length===0?o.metadata={}:Object.keys(r).length!==0&&(o.metadata=r)}return o}d(g,"createStreamOptionsPatch");export{b as HookRegistry,h as applyStreamOptionsPatch};
@@ -1,17 +0,0 @@
1
- var a=Object.defineProperty;var o=(e,t)=>a(e,"name",{value:t,configurable:!0});const c=`The conversation history before this point was compacted into the following summary:
2
-
3
- <summary>
4
- `,s=`
5
- </summary>`,i=`The following is a summary of a branch that this conversation came back from:
6
-
7
- <summary>
8
- `,m="</summary>";function p(e){let t=`Ran \`${e.command}\`
9
- `;return e.output?t+=`\`\`\`
10
- ${e.output}
11
- \`\`\``:t+="(no output)",e.cancelled?t+=`
12
-
13
- (command cancelled)`:e.exitCode!==null&&e.exitCode!==void 0&&e.exitCode!==0&&(t+=`
14
-
15
- Command exited with code ${e.exitCode}`),e.truncated&&e.fullOutputPath&&(t+=`
16
-
17
- [Output truncated. Full output: ${e.fullOutputPath}]`),t}o(p,"bashExecutionToText");function x(e,t,n){return{role:"branchSummary",summary:e,fromId:t,timestamp:typeof n=="number"?n:new Date(n).getTime()}}o(x,"createBranchSummaryMessage");function f(e,t,n){return{role:"compactionSummary",summary:e,tokensBefore:t,timestamp:typeof n=="number"?n:new Date(n).getTime()}}o(f,"createCompactionSummaryMessage");function d(e,t,n,u,r){return{role:"custom",customType:e,content:t,display:n,details:u,timestamp:typeof r=="number"?r:new Date(r).getTime()}}o(d,"createCustomMessage");function y(e){return e.map(t=>{switch(t.role){case"bashExecution":return t.excludeFromContext?void 0:{role:"user",content:[{type:"text",text:p(t)}],timestamp:t.timestamp};case"custom":return{role:"user",content:typeof t.content=="string"?[{type:"text",text:t.content}]:t.content,timestamp:t.timestamp};case"branchSummary":return{role:"user",content:[{type:"text",text:i+t.summary+m}],timestamp:t.timestamp};case"compactionSummary":return{role:"user",content:[{type:"text",text:c+t.summary+s}],timestamp:t.timestamp};case"system":case"user":case"assistant":case"toolResult":return t;default:return}}).filter(t=>t!==void 0)}o(y,"convertToLlm");export{i as BRANCH_SUMMARY_PREFIX,m as BRANCH_SUMMARY_SUFFIX,c as COMPACTION_SUMMARY_PREFIX,s as COMPACTION_SUMMARY_SUFFIX,p as bashExecutionToText,y as convertToLlm,x as createBranchSummaryMessage,f as createCompactionSummaryMessage,d as createCustomMessage};
@@ -1 +0,0 @@
1
- var g=Object.defineProperty;var r=(n,a)=>g(n,"name",{value:a,configurable:!0});import{spawn as w}from"node:child_process";import{Type as o}from"typebox";const h=o.Object({command:o.String(),cwd:o.Optional(o.String())});function v(n={}){return{name:"bash",description:"Run a shell command",parameters:h,replay:"unsafe",output:n,async execute({command:a,cwd:m},s,i){const l=Date.now(),e=w("bash",["-c",a],{cwd:m,stdio:["ignore","pipe","pipe"]}),c=r(()=>e.kill("SIGKILL"),"onAbort");i.abortSignal?.addEventListener("abort",c),e.stdout.on("data",t=>s.stream(t)),e.stderr.on("data",t=>s.stream(t));const{code:d,signal:p}=await new Promise(t=>e.on("close",(b,u)=>t({code:b,signal:u})));return i.abortSignal?.removeEventListener("abort",c),{isError:d!==0,details:{exitCode:d,signal:p,ms:Date.now()-l}}}}}r(v,"bashTool");export{v as bashTool};
@@ -1 +0,0 @@
1
- var p=Object.defineProperty;var n=(e,t)=>p(e,"name",{value:t,configurable:!0});class x{static{n(this,"Bounded")}bytes=new Uint8Array;maxBytes;maxLines;retain;droppedBytes=0;droppedLines=0;total=0;constructor(t,s,i){this.maxBytes=Math.max(0,t),this.maxLines=Math.max(0,s),this.retain=i}push(t){if(this.total+=t.length,t.length!==0){if(this.maxBytes===0||this.maxLines===0){this.drop(t);return}if(this.retain==="head"){this.pushHead(t);return}this.pushTail(t)}}pushHead(t){const s=this.maxBytes-this.bytes.length,i=this.maxLines-h(this.bytes);if(s<=0||i<=0){this.drop(t);return}let r=Math.min(t.length,s),o=0;for(let a=0;a<r;a++)if(t[a]===10&&(o++,o===i)){r=a+1;break}this.bytes=d(this.bytes,t.subarray(0,r)),this.drop(t.subarray(r))}pushTail(t){const s=l(t,this.maxBytes,this.maxLines);this.drop(t.subarray(0,s));const i=d(this.bytes,t.subarray(s)),r=l(i,this.maxBytes,this.maxLines);this.drop(i.subarray(0,r)),this.bytes=i.slice(r)}drop(t){this.droppedBytes+=t.length,this.droppedLines+=h(t)}get dropped(){return this.droppedBytes}text(){return new TextDecoder().decode(this.bytes)}}function l(e,t,s){let i=Math.max(0,e.length-t),r=h(e.subarray(i))-s;for(;i<e.length&&r>0;i++)e[i]===10&&r--;return i}n(l,"tailStart");function d(e,t){if(e.length===0)return t.slice();if(t.length===0)return e;const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s}n(d,"concat");function h(e){let t=0;for(const s of e)s===10&&t++;return t}n(h,"countNewlines");export{x as Bounded};
@@ -1 +0,0 @@
1
- var w=Object.defineProperty;var i=(c,n)=>w(c,"name",{value:n,configurable:!0});import{defineService as g}from"@earendil-works/chord";import{WATCH_CAPACITY as y}from"./view.js";const P=g("pi.harness",{local:!0}),S=g("pi.conversation");function E(c,n,r){return{view:r,send:i((e,t)=>n.send(e,t).then(o=>o.id),"send"),write:i((e,t)=>n.write(e,t),"write"),inputAbort:i((e,t)=>c.abortInput(e,t,n.id),"inputAbort"),configSet:i((e,t)=>n.config.set(e,t),"configSet"),abort:i(e=>n.abort(e),"abort"),reset:i((e,t)=>n.reset(e??void 0,t),"reset"),collapse:i((e,t)=>n.collapse(e??void 0,t),"collapse"),fork:i((e,t,o)=>n.fork(e,t,o).then(l=>l.id),"fork"),entries:i((e,t)=>c.entries({...e,conversationId:n.id},t),"entries")}}i(E,"createPicoConversationService");async function j(c,n,r,e={}){const t=await c.watch(r),o=n({...structuredClone(t.view),commit:{events:[]}});return v(t,o,r,e)}i(j,"attachChordView");function v(c,n,r,e){const t=e.capacity??y;if(!Number.isSafeInteger(t)||t<1)throw new RangeError("Chord view queue capacity must be positive");const o=[];let l=!1,s=!1;const f=i(a=>{if(!s){s=!0,o.length=0,c.stop();try{e.onFailure?.(a instanceof Error?a:new Error(String(a)))}catch{}}},"fail"),h=i(()=>{for(l=!1;!s&&o.length>0;){const a=o.shift();try{n.change(r,u=>{m(u,a.ops),u.commit.events=a.events})}catch(u){f(u)}}},"drain");return c.start(a=>{if(!s){if(o.length>=t){f(new Error(`Pico-to-Chord view queue exceeded ${t} envelopes`));return}o.push(a),!l&&(l=!0,queueMicrotask(h))}}),{view:n,get closed(){return s},close(){s||(s=!0,o.length=0,c.stop())}}}i(v,"bridgeWatch");function m(c,n){for(const r of n){if(r[0]==="r")throw new Error("live Pico envelope unexpectedly replaced the view root");const e=r[1];if(r[0]==="p"){const s=d(c,e);if(!Array.isArray(s))throw new Error(`Pico splice path is not an array: ${e.join(".")}`);s.splice(r[2],r[3],...r[4]);continue}if(r[0]==="m"){const s=d(c,e);if(!Array.isArray(s)||s.length!==r[2].length)throw new Error(`Pico permutation path is not a matching array: ${e.join(".")}`);const f=s,h=f.slice(),a=new Map;for(let u=0;u<r[2].length;u++){const p=h[r[2][u]];a.has(p)||a.set(p,u)}f.sort((u,p)=>a.get(u)-a.get(p));continue}const t=d(c,e.slice(0,-1));if(t===null||typeof t!="object")throw new Error(`Pico operation parent is not an object: ${e.join(".")}`);const o=e[e.length-1];if(r[0]==="d"){Array.isArray(t)?t.splice(o,1):delete t[o];continue}const l=t;r[0]==="s"?l[o]=r[2]:r[0]==="a"?l[o]=`${String(l[o])}${r[2]}`:l[o]=String(l[o]).slice(r[2])}}i(m,"applyTracked");function d(c,n){let r=c;for(const e of n){if(r===null||typeof r!="object")return;r=r[e]}return r}i(d,"resolve");export{S as PicoConversationService,P as PicoHarnessService,j as attachChordView,E as createPicoConversationService};
@@ -1 +0,0 @@
1
- var m=Object.defineProperty;var a=(n,l)=>m(n,"name",{value:l,configurable:!0});async function w(n,l,i,r){const[d]=await n.scanEntries({conversationId:l,withHead:!0,...i===void 0?{}:{before:i+1},limit:1},r),f=d?.head,o=[];let e=i===void 0?void 0:i+1;for(;;){const t=await n.scanEntries({conversationId:l,...e===void 0?{}:{before:e},limit:256},r);let s=t.length<256;for(const p of t){if(f!==void 0&&p.id<f){s=!0;break}o.push(p)}if(s)break;e=t[t.length-1].id}o.reverse();const u=new Map;for(const t of o)for(const s of t.edits??[])u.set(s.target,s);const h=d===void 0?o:[d,...o.filter(t=>t.head===void 0)],c=[];for(const t of h){const s=u.get(t.id);if(s?.action!=="omit"){if(s?.action==="replace"){c.push(...s.messages??[]);continue}t.model&&c.push(...t.model)}}return{head:d,entries:h,messages:g(c)}}a(w,"deriveContext");function g(n){const l=[];for(let i=0;i<n.length;i++){const r=n[i];if(l.push(r),r.role!=="assistant")continue;const d=r.content.filter(e=>e.type==="toolCall");if(d.length===0)continue;const f=new Map;let o=i+1;for(;o<n.length&&n[o].role==="toolResult";){const e=n[o];f.set(e.toolCallId,e),o++}for(const e of d)l.push(f.get(e.id)??{role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:"Tool result unavailable: history ends before this call completed."}],isError:!0,details:{reason:"missing_after_fork"},timestamp:r.timestamp});i=o-1}return l}a(g,"reorderToolResults");export{w as deriveContext};
@@ -1 +0,0 @@
1
- var S=Object.defineProperty;var l=(g,e)=>S(g,"name",{value:e,configurable:!0});import{withAbortSignal as x}from"@earendil-works/chord/context";import{createHookRunners as M}from"./hooks.js";import{chooseThrough as F,collapse as y}from"./kinds/collapse.js";import{entries as b}from"./kinds/entries.js";import{generation as I}from"./kinds/generation.js";import{job as T}from"./kinds/job.js";import{plugin as E}from"./kinds/plugin.js";import{postTools as R}from"./kinds/post-tools.js";import{tool as $}from"./kinds/tool.js";import{Scheduler as K}from"./scheduler.js";import{isCoreKind as H,Session as L}from"./session.js";import{systemSections as A}from"./system.js";import{Forbidden as k}from"./types.js";import{ViewManager as j}from"./view.js";const p={type:"kernel"};class O{static{l(this,"Harness")}session;scheduler;views;kinds;namespaces=new Map;tools=new Map;sectionMap=new Map;entryKinds=new Map;revisions={sections:0,tools:0};plugins;hookRegistrations=[];conversationListeners=new Set;onReport;now;ctx;options;resumed=!1;suspended=!1;static async open(e,s,n){const c=new O(e,s,n);return await c.init(),c}constructor(e,s,n){this.ctx=n,this.options=s,this.now=s.now??Date.now,this.onReport=r=>{try{s.onReport?.(r)}catch{}};const c=[I,$,R,y,T,E];this.kinds=new Map(c.map(r=>[r.name,r]));for(const r of s.taskKinds??[]){if(r.name.startsWith("pi."))throw new Error(`task kind "${r.name}": names beginning with "pi." are reserved`);if(this.kinds.has(r.name))throw new Error(`task kind "${r.name}" registered twice`);this.kinds.set(r.name,r)}for(const r of s.tools??[])this.registerTool(r,"open");for(const r of Object.values(A))this.sectionMap.set(r.key,r);for(const r of s.sections??[])this.registerSection(r,"open");for(const r of Object.values(b))this.entryKinds.set(r.kind,r);this.plugins=new Map(Object.entries(s.plugins??{})),this.session=new L(e,this.kinds,this.namespaces,this.now),this.session.onReport=this.onReport,this.views=new j(this.session,this.onReport),this.session.lineListeners.add(r=>this.views.update(r)),this.session.listeners.add(r=>{this.views.deliver();for(const w of r.changes.conversations)this.notifyConversation(w)});const t=this,h=M(()=>this.hookRegistrations,r=>this.session.index.ancestors(r),this.onReport);this.scheduler=new K({session:this.session,kinds:this.kinds,onReport:this.onReport,ctx:n,runtime(r,w,d){return{taskId:r.id,conversationId:r.conversationId,kind:w.kind,commit:l((i,o)=>{const u=(t.session.liveTasks.get(r.id)?.owns??[]).flatMap(m=>[{doc:"rewindable",conversationId:m},{doc:"sticky",conversationId:m}]);return t.session.commit(w,(m,v)=>i(m,t.session.liveTasks.get(r.id),v),o,{docs:u}).then(m=>m.value)},"commit"),hooks:h(w.kind,{taskId:r.id,conversationId:r.conversationId}),models:s.models,tools:t.tools,registries:{sections:{map:t.sectionMap,get revision(){return t.revisions.sections}},tools:{map:t.tools,get revision(){return t.revisions.tools}}},kinds:t.kinds,processHost:s.processHost,plugins:t.plugins,now:t.now,sleep:l((i,o)=>new Promise((a,u)=>{const m=Math.max(0,i-Date.now()),v=setTimeout(()=>{o.abortSignal?.removeEventListener("abort",f),a()},m),f=l(()=>{clearTimeout(v),u(o.abortSignal?.reason??new Error("aborted"))},"onAbort");o.abortSignal?.addEventListener("abort",f,{once:!0})}),"sleep"),waitForInput:l((i,o)=>t.scheduler.waitForInput(i,o),"waitForInput"),waitForTask:l((i,o)=>t.scheduler.waitForTask(i,o),"waitForTask"),abortTask:l(async(i,o)=>(await t.session.onLine(async a=>{t.assertInvocation(w);const u=t.session.liveTasks.get(i)??await t.session.storage.task(i,a);if(u===void 0)throw new Error(`task ${i} not found`);t.assertTaskConversationScope(r.id,u.conversationId)},o),t.scheduler.abortTask(i,o)),"abortTask"),abortConversation:l(async(i,o)=>{await t.session.onLine(()=>{t.assertInvocation(w),t.assertOwnedConversation(r.id,i)},o);const a=await t.conversation(i,o);a&&await a.abort(o)},"abortConversation"),createOwnedConversation:l((i,o)=>t.session.commit(p,a=>(t.assertInvocation(w),a.createOwnedConversation(r.id,r.conversationId,i)),o).then(a=>a.value),"createOwnedConversation"),sendOwned:l((i,o,a)=>t.session.commit(p,u=>(t.assertInvocation(w),t.assertOwnedConversation(r.id,i),u.send(i,o)),a,{docs:[{doc:"rewindable",conversationId:i},{doc:"sticky",conversationId:i}]}).then(u=>u.value),"sendOwned"),context:l((i,o,a)=>t.session.commit(w,u=>u.context(i,o),a).then(u=>u.value),"context"),newestEntry:l((i,o,a)=>t.session.commit(w,u=>u.newestEntry(i,o),a).then(u=>u.value),"newestEntry"),rewindable:l((i,o)=>t.session.commit(w,a=>a.snapshot({doc:"rewindable",conversationId:i}),o,{docs:[{doc:"rewindable",conversationId:i}]}).then(a=>a.value),"rewindable"),sticky:l((i,o)=>t.session.commit(w,a=>a.snapshot({doc:"sticky",conversationId:i}),o,{docs:[{doc:"sticky",conversationId:i}]}).then(a=>a.value),"sticky"),rewindableAsOf:l((i,o,a)=>t.session.commit(w,u=>u.rewindableAsOf(i,o),a).then(u=>u.value),"rewindableAsOf")}}})}notifyConversation(e){if(this.conversationListeners.size===0)return;const s=this.handle(e);for(const n of[...this.conversationListeners])try{n(s)}catch(c){this.onReport(c)}}assertInvocation(e){if(!e.token.alive)throw new k("operation from a finished invocation");const s=this.session.liveTasks.get(e.id);if(s===void 0)throw new k("operation from a task that is not live");if(e.mode==="run"&&s.abort===!0)throw new k("operation from a marked run invocation")}assertTaskConversationScope(e,s){const n=this.session.liveTasks.get(e);if(n?.conversationId!==s&&!n?.owns.some(c=>this.session.index.subtree(c).has(s)))throw new k(`conversation ${s} is outside task ${e}'s subtree`)}assertOwnedConversation(e,s){const n=this.session.liveTasks.get(e);if(n===void 0||!n.owns.some(c=>this.session.index.subtree(c).has(s)))throw new k(`conversation ${s} is not owned by task ${e}`)}async init(){const{session:e}=this,s=await e.read((t,h)=>t.conversations(h),this.ctx);for(const t of s)e.conversationRecords.set(t.id,t);const n=await e.read((t,h)=>t.scanTasks({status:["pending","running"]},h),this.ctx);for(const t of n)e.liveTasks.set(t.id,t);const c=new Set(s.map(t=>t.owner).filter(t=>t!==void 0));for(const t of c)if(!e.liveTasks.has(t)){const h=await e.read((r,w)=>r.task(t,w),this.ctx);h&&e.ownerTaskCache.set(t,h)}s.length===0&&await e.commit(p,t=>t.createConversation({rewindable:this.options.root?.rewindable,sticky:this.options.root?.sticky}),this.ctx)}resume(){if(this.suspended)throw new Error("cannot resume a suspended harness; reopen storage with a new harness");this.resumed||(this.resumed=!0,this.reconcileOrphans().then(()=>{this.suspended||this.scheduler.resume()}).catch(e=>this.onReport(e)))}async reconcileOrphans(){const e=[...this.session.liveTasks.values()].filter(n=>!this.kinds.has(n.kind));if(e.length===0)return;const s=[...new Set(e.map(n=>n.conversationId))].map(n=>({doc:"sticky",conversationId:n}));await this.session.commit(p,n=>{for(const c of e)n.setTask({...c,status:"terminal",outcome:{status:"orphaned"}})},this.ctx,{docs:s})}quiescent(){return this.scheduler.quiescent()}hold(){if(!this.scheduler.quiescent())throw new Error("cannot hold a non-quiescent harness; suspend it instead");return this.scheduler.hold()}async suspend(e){if(this.suspended)return;this.suspended=!0,await this.scheduler.joinAll();const s=[...this.session.liveTasks.values()].filter(n=>n.kind==="pi.tool");if(s.length>0){const n=[...new Set(s.map(c=>c.conversationId))].map(c=>({doc:"sticky",conversationId:c}));await this.session.commit(p,c=>{for(const t of s){const h=t.input.index,r=c.sticky(t.conversationId).turn.tools[h];r?.waitingOn!==void 0&&delete r.waitingOn}},e,{docs:n})}this.views.close(),await this.session.close(e)}registerTaskKind(e){if(e.name.startsWith("pi."))throw new Error(`task kind "${e.name}": names beginning with "pi." are reserved`);if(this.kinds.has(e.name))throw new Error(`task kind "${e.name}" already registered`);return this.session.defaults.register(e),this.kinds.set(e.name,e),this.scheduler.kick(),()=>{this.kinds.get(e.name)===e&&(this.kinds.delete(e.name),this.session.defaults.unregister(e))}}namespace(e,s,n={}){if(!/^[a-z][a-z0-9_.-]*$/i.test(e)||e.startsWith("pi."))throw new Error(`invalid namespace "${e}"`);if(this.namespaces.has(e))throw new Error(`namespace "${e}" already registered`);const c=JSON.parse(JSON.stringify(s)),t=new Map;for(const w of["rewindable","sticky","session"])for(const d of Object.keys(c[w]??{})){if(t.has(d))throw new Error(`namespace "${e}" key "${d}" is declared in more than one document`);t.set(d,w)}let h;h={id:e,unregister:l(()=>{if(this.namespaces.get(e)?.token===h){this.namespaces.delete(e);for(let w=this.hookRegistrations.length-1;w>=0;w--)this.hookRegistrations[w].namespace===h&&this.hookRegistrations.splice(w,1)}},"unregister")};const r={token:h,defaults:{rewindable:c.rewindable??{},sticky:c.sticky??{},session:c.session??{}},routes:t,project:n.view===void 0?void 0:w=>n.view(w)};return this.namespaces.set(e,r),h}registerTool(e,s="runtime"){if(this.tools.has(e.name))throw new Error(`tool "${e.name}" already registered`);return this.tools.set(e.name,e),this.revisions.tools++,()=>{this.tools.get(e.name)===e&&(this.tools.delete(e.name),this.revisions.tools++)}}registerSection(e,s="runtime"){if(this.sectionMap.has(e.key))throw new Error(`section "${e.key}" already registered`);return this.sectionMap.set(e.key,e),this.revisions.sections++,()=>{this.sectionMap.get(e.key)===e&&(this.sectionMap.delete(e.key),this.revisions.sections++)}}registerEntryKind(e){if(e.kind.startsWith("pi."))throw new Error(`entry kind "${e.kind}": names beginning with "pi." are reserved`);if(this.entryKinds.has(e.kind))throw new Error(`entry kind "${e.kind}" already registered`);return this.entryKinds.set(e.kind,e),()=>{this.entryKinds.get(e.kind)===e&&this.entryKinds.delete(e.kind)}}hooks(e,s,n,c){return this.addHooks({namespace:this.checkNamespace(e),kind:this.checkKind(s),handlers:n})}checkKind(e){if(this.kinds.get(e.name)!==e)throw new Error(`kind "${e.name}" is not the registered token`);return e}checkNamespace(e){if(this.namespaces.get(e.id)?.token!==e)throw new k(`namespace "${e.id}" is stale`);return e}addHooks(e){this.hookRegistrations.push(e);let s=!1;return()=>{if(s)return;s=!0;const n=this.hookRegistrations.indexOf(e);n>=0&&this.hookRegistrations.splice(n,1)}}async root(e){return this.conversation(1,e).then(s=>s)}onConversation(e){this.conversationListeners.add(e);for(const s of this.session.conversationRecords.values())try{e(this.handle(s))}catch(n){this.onReport(n)}return()=>this.conversationListeners.delete(e)}async conversation(e,s){const n=await this.session.read((c,t)=>c.conversation(e,t),s);return n===void 0?void 0:this.handle(n)}async createConversation(e,s){const{input:n,...c}=e,t=await this.session.commit(p,async h=>{const r=h.createConversation(c);return n!==void 0&&await h.send(r,{content:n}),r},s).then(h=>h.value);return await this.conversation(t,s)}entries(e,s){return this.session.read((n,c)=>n.scanEntries(e,c),s)}getTask(e,s){return this.session.read((n,c)=>n.task(e,c),s)}async abortInput(e,s,n){if(n!==void 0){const c=await this.session.read((t,h)=>t.input(e,h),s);if(c!==void 0&&c.conversationId!==n)throw new k(`input ${e} is outside conversation ${n}`)}return this.inputHandle(e).abort(s)}abortTask(e,s){return this.scheduler.abortTask(e,s)}markTask(e,s){return this.session.commit(p,async n=>{const c=await n.task(e);if(c===void 0)throw new Error(`task ${e} not found`);return c.status==="terminal"?"terminal":(n.markTask(e),"marked")},s).then(n=>n.value)}waitForIdle(e){return this.scheduler.waitForIdle(void 0,e)}waitForTask(e,s){return this.scheduler.waitForTask(e,s)}async close(e){await this.suspend(e)}handle(e){const s=this,n=[{doc:"rewindable",conversationId:e.id},{doc:"sticky",conversationId:e.id}],c={type:"host",conversationId:e.id},t={type:"kernel",conversationId:e.id},h=l((d,i)=>s.session.commit(c,(o,a)=>d(o,a),i,{docs:n}).then(o=>o.value),"host"),r=l((d,i)=>s.session.commit(t,d,i,{docs:n}).then(o=>o.value),"kernel"),w={get:l(d=>h(i=>{const o=i.config(e.id),a={};for(const u of s.session.defaults.route.keys())a[u]=o.get(u);return a},d),"get"),set:l((d,i)=>h(o=>{const a=o.config(e.id);for(const[u,m]of Object.entries(d)){if(m===void 0)throw new Error(`config.set(${u}): use config.reset()`);a.set(u,m)}},i),"set"),reset:l((d,i)=>h(o=>{const a=o.config(e.id);for(const u of d)a.reset(String(u))},i),"reset")};return{id:e.id,config:w,async send(d,i){const o=await r(a=>a.send(e.id,d),i);return s.inputHandle(o)},write:l((d,i)=>h(o=>o.write(e.id,d),i),"write"),commit:h,rewindable:l(d=>h(i=>i.snapshot({doc:"rewindable",conversationId:e.id}),d),"rewindable"),sticky:l(d=>h(i=>i.snapshot({doc:"sticky",conversationId:e.id}),d),"sticky"),context:l(d=>h(i=>i.context(e.id),d),"context"),async fork(d,i,o){const a=await s.session.fork(e.id,d,i,o);return await s.conversation(a,o)},collapse:l((d,i)=>r(async o=>{const{entries:a}=await o.context(e.id),u=o.rewindable(e.id),m=F(a,u.keepRecent);if(m===void 0)throw new Error("nothing to collapse");return o.createTask({kind:"pi.collapse",conversationId:e.id,background:!0,input:{reason:"manual",through:m,...d===void 0?{}:{instructions:d}}})},i),"collapse"),reset:l(async(d,i)=>{await r(o=>o.write(e.id,d===void 0?{kind:"pi.reset",head:"self"}:{kind:"pi.handoff",head:"self",model:[{role:"user",content:d,timestamp:s.now()}]}),i)},"reset"),async abort(d){const i=[],o=await r(async a=>{const u=a.sticky(e.id),m=u.inbox.filter(f=>f.mode!=="write").map(f=>f.id);for(let f=u.inbox.length-1;f>=0;f--)u.inbox[f].mode!=="write"&&u.inbox.splice(f,1);await a.resolveInputs(m,{status:"unanswered",reason:"aborted"});for(const f of m)a.emit({type:"input.aborted",input:f});const v=[];for(const f of[...s.session.liveTasks.values()])if(!(f.conversationId!==e.id||f.background)){for(const C of f.owns)i.push(C);f.abort!==!0&&a.markTask(f.id),v.push(f.id)}return v},d);for(const a of o)await s.scheduler.abortTask(a,d);await s.scheduler.waitForIdle(e.id,d),await Promise.all(i.map(a=>s.scheduler.waitForIdle(a,d)))},waitForIdle:l(d=>s.scheduler.waitForIdle(e.id,d),"waitForIdle"),hooks:l((d,i,o,a)=>s.addHooks({namespace:s.checkNamespace(d),kind:s.checkKind(i),handlers:o,conversationId:e.id,subtree:a?.subtree}),"hooks"),watch:l(d=>s.watch(e,d),"watch")}}async watch(e,s){return this.session.commit({type:"host",conversationId:e.id},async n=>{const c=await N(t=>n.scanEntries(t),e.id);return this.views.watch(e,c)},s,{docs:[{doc:"rewindable",conversationId:e.id},{doc:"sticky",conversationId:e.id}]}).then(n=>n.value)}inputHandle(e){return{id:e,result:l(s=>this.session.read((n,c)=>n.input(e,c),s),"result"),wait:l(s=>this.scheduler.waitForInput(e,s),"wait"),abort:l(s=>this.session.commit(p,n=>n.withdrawInput(e),s,{docs:[]}).then(n=>n.value),"abort")}}}async function N(g,e){const[s]=await g({conversationId:e,withHead:!0,limit:1}),n=s?.head,c=[];let t;for(;;){const h=await g({conversationId:e,...t===void 0?{}:{before:t},limit:256});let r=h.length<256;for(const w of h){if(n!==void 0&&w.id<n){r=!0;break}c.push(w)}if(r)break;t=h[h.length-1].id}return c.reverse()}l(N,"captureActiveTranscript");import{applyEnvelope as ie,WATCH_CAPACITY as oe}from"./view.js";const ee={generation:I,tool:$,postTools:R,collapse:y,job:T,plugin:E},se=b;export{O as Harness,oe as WATCH_CAPACITY,ie as applyEnvelope,N as captureActiveTranscript,se as entries,H as isCoreKind,ee as kinds,x as withAbortSignal};
@@ -1 +0,0 @@
1
- var f=Object.defineProperty;var d=(r,a)=>f(r,"name",{value:a,configurable:!0});function p(r,a,u){return(o,c)=>{const t=d(()=>r().filter(e=>e.kind===o).filter(e=>e.conversationId===void 0||e.conversationId===c.conversationId||e.subtree===!0&&a(c.conversationId).includes(e.conversationId)).map(e=>({handlers:e.handlers,namespace:e.namespace,api:{...c,kind:o.name}})),"handlers");return{handlers:t,async each(e,i,l){for(const s of t())try{const n=await i(s.handlers,s.api);if(n!==void 0&&l?.(n)===!0)return}catch(n){if(e.abortSignal?.aborted)throw n;u(n)}}}}}d(p,"createHookRunners");export{p as createHookRunners};
@@ -1 +0,0 @@
1
- import{bashTool as r}from"./bash.js";import{Bounded as n}from"./bounded.js";import{attachChordView as s,createPicoConversationService as a,PicoConversationService as c,PicoHarnessService as d}from"./chord.js";import{applyEnvelope as m,captureActiveTranscript as f,entries as C,Harness as l,isCoreKind as S,kinds as v,WATCH_CAPACITY as x,withAbortSignal as y}from"./harness.js";import{JsonlStorage as P}from"./jsonl.js";import{MemoryStorage as g}from"./memory.js";import{defineSystemSection as h,systemSections as b}from"./system.js";import{Closed as F,CollapseInProgress as H,ConversationBusy as I,defineEntry as w,defineTask as B,Faulted as E,Forbidden as W,GenerationInProgress as G,memoOnce as J,ReadAfterWrite as K,TaskContractFault as M,toStored as O}from"./types.js";export{n as Bounded,F as Closed,H as CollapseInProgress,I as ConversationBusy,E as Faulted,W as Forbidden,G as GenerationInProgress,l as Harness,P as JsonlStorage,g as MemoryStorage,c as PicoConversationService,d as PicoHarnessService,K as ReadAfterWrite,M as TaskContractFault,x as WATCH_CAPACITY,m as applyEnvelope,s as attachChordView,r as bashTool,f as captureActiveTranscript,a as createPicoConversationService,w as defineEntry,h as defineSystemSection,B as defineTask,C as entries,S as isCoreKind,v as kinds,J as memoOnce,b as systemSections,O as toStored,y as withAbortSignal};
@@ -1,4 +0,0 @@
1
- var F=Object.defineProperty;var q=(k,t)=>F(k,"name",{value:t,configurable:!0});import{closeSync as S,existsSync as M,fsyncSync as O,ftruncateSync as A,mkdirSync as W,openSync as g,readdirSync as $,readFileSync as I,renameSync as z,statSync as j,unlinkSync as b,writeSync as v}from"node:fs";import{join as h}from"node:path";import{BACKGROUND_CONTEXT as B}from"@earendil-works/chord/context";import{isBase as E}from"@earendil-works/chord/delta";import{MemoryStorage as J}from"./memory.js";class T extends J{static{q(this,"JsonlStorage")}mainFd;sidecars=new Map;taskSidecars=new Map;dir;fsync;closedOnce=!1;constructor(t,n){super(),this.dir=t,this.fsync=n,this.mainFd=g(h(t,"main.jsonl"),"a")}static async open(t,n={}){W(t,{recursive:!0});for(const o of $(t))o.endsWith(".jsonl")&&C(h(t,o));const r=new T(t,n.fsync??!0);try{return await r.replay(),r}catch(o){throw await r.close(),o}}sizes(){const t={};for(const n of $(this.dir))t[n]=j(h(this.dir,n)).size;return t}async replay(){const t=q(s=>{if(!M(s))return[];const e=I(s),i=[];let f=0,m=0;for(let w=e.indexOf(10,f);w>=0;w=e.indexOf(10,f)){const c=e.subarray(f,w).toString("utf8");if(f=w+1,c==="")continue;let l;try{l=JSON.parse(c)}catch(x){throw new Error(`${s}: malformed record: ${String(x)}`)}if(typeof l.seq!="number"||typeof l.maxId!="number"||!Array.isArray(l.writes))throw new Error(`${s}: record lacks seq/maxId/writes`);if(l.seq<=m)throw new Error(`${s}: sequence not increasing at ${l.seq}`);m=l.seq,i.push({record:l,end:f})}return i},"read");let n=0;const r=t(h(this.dir,"main.jsonl")).map(({record:s})=>s),o=new Map;for(const s of r)o.set(s.seq,new Set(s.refs??[]));const p=$(this.dir).filter(s=>s.startsWith("sticky-")||s.startsWith("task-")),u=new Map,d=new Map,y=new Map,a=new Map;for(const s of r){for(const e of s.writes)e.type==="task.patch"&&e.patch.status==="terminal"&&a.set(e.patch.id,s.seq);u.set(s.seq,[...s.writes]),n=Math.max(n,s.maxId)}for(const s of p){const e=h(this.dir,s),i=t(e),f=i[0]?.record;s.startsWith("sticky-")&&f!==void 0&&E(f.writes.flatMap(c=>c.type==="doc"?c.ops:[]))&&y.set(s,f.seq);let m=0,w=!1;for(const{record:c,end:l}of i){if(!o.get(c.seq)?.has(s)){w=!0;continue}if(w)throw new Error(`${e}: confirmed record follows an unconfirmed tail at ${c.seq}`);m=l;const x=d.get(c.seq)??new Set;x.add(s),d.set(c.seq,x),u.get(c.seq).push(...c.writes),n=Math.max(n,c.maxId)}w&&N(e,m)}for(const s of r)for(const e of s.refs??[]){if(d.get(s.seq)?.has(e))continue;const i=y.get(e);if(!(i!==void 0&&s.seq<i)){if(e.startsWith("task-")){const f=Number(e.slice(5,-6)),m=a.get(f);if(m!==void 0&&s.seq<m)continue}throw new Error(`${h(this.dir,e)}: missing record for published sequence ${s.seq}`)}}for(const s of[...u.keys()].sort((e,i)=>e-i))this.seq=s-1,await super.commit(u.get(s),B);this.setNextId(n+1);for(const s of p){if(!s.startsWith("task-"))continue;const e=Number(s.slice(5,-6)),i=await super.task(e);(i===void 0||i.status==="terminal")&&b(h(this.dir,s))}}async commit(t,n){if(this.closedOnce)throw new Error("storage closed");const r=this.seq+1,o=this.stage(t,r),p=this.nextIdAfter(t),u=[],d=new Map,y=new Map,a=[];for(const e of t)e.type==="doc"&&e.ref.doc==="sticky"?(d.get(e.ref.conversationId)??d.set(e.ref.conversationId,[]).get(e.ref.conversationId)).push(e):e.type==="task.patch"&&e.patch.status!=="terminal"?(y.get(e.patch.id)??y.set(e.patch.id,[]).get(e.patch.id)).push(e):(u.push(e),e.type==="task.patch"&&e.patch.status==="terminal"&&a.push(e.patch.id));const s=[];for(const[e,i]of y)this.append(this.taskSidecar(e),{seq:r,maxId:p,writes:i}),s.push(`task-${e}.jsonl`);for(const[e,i]of d)this.append(this.sidecar(e),{seq:r,maxId:p,writes:i}),s.push(`sticky-${e}.jsonl`);this.append(this.mainFd,{seq:r,maxId:p,writes:u,...s.length?{refs:s}:{}}),o(),this.seq=r;for(const e of a)this.retireTaskSidecar(e);return r}nextIdAfter(t){let n=this.nextIdValue-1;for(const r of t){const o=r.type==="conversation"?r.conversation.id:r.type==="entry"?r.entry.id:r.type==="task"?r.task.id:r.type==="input"?r.input.id:0;n=Math.max(n,o)}return n}append(t,n){v(t,`${JSON.stringify(n)}
2
- `),this.fsync&&O(t)}sidecar(t){let n=this.sidecars.get(t);return n===void 0&&(n=g(h(this.dir,`sticky-${t}.jsonl`),"a"),this.sidecars.set(t,n)),n}taskSidecar(t){let n=this.taskSidecars.get(t);return n===void 0&&(n=g(h(this.dir,`task-${t}.jsonl`),"a"),this.taskSidecars.set(t,n)),n}retireTaskSidecar(t){const n=this.taskSidecars.get(t);n!==void 0&&S(n),this.taskSidecars.delete(t);try{b(h(this.dir,`task-${t}.jsonl`))}catch{}}async truncate(t,n){if(await super.truncate(t),t.doc!=="sticky")return;const r=h(this.dir,`sticky-${t.conversationId}.jsonl`);if(!M(r))return;const o=I(r,"utf8").split(`
3
- `).filter(Boolean);let p=0;for(let a=o.length-1;a>=0;a--)if(E(JSON.parse(o[a]).writes.flatMap(s=>s.type==="doc"?s.ops:[]))){p=a;break}if(p===0)return;const u=`${r}.tmp`,d=g(u,"w");v(d,o.slice(p).map(a=>`${a}
4
- `).join("")),this.fsync&&O(d),S(d);const y=this.sidecars.get(t.conversationId);y!==void 0&&S(y),z(u,r),this.sidecars.set(t.conversationId,g(r,"a"))}async close(t){if(!this.closedOnce){this.closedOnce=!0,await super.close(),S(this.mainFd);for(const n of this.sidecars.values())S(n);for(const n of this.taskSidecars.values())S(n)}}}function N(k,t){const n=g(k,"r+");try{A(n,t)}finally{S(n)}}q(N,"truncateTo");function C(k){if(j(k).size===0)return;const n=I(k),r=n.lastIndexOf(10);r+1!==n.length&&N(k,r+1)}q(C,"truncateTornTail");export{T as JsonlStorage};
@@ -1,3 +0,0 @@
1
- var k=Object.defineProperty;var l=(e,n)=>k(e,"name",{value:n,configurable:!0});import{estimateContextTokens as I}from"@earendil-works/pi-ai/utils/estimate";import{effectiveTools as M}from"../system.js";import{toStored as C}from"../types.js";import{retryDecision as _}from"./generation.js";const b=l(e=>I(e.filter(n=>n.role!=="system")).tokens,"estimate"),z={rewindable:{threshold:0,keepRecent:2e4}},p=l((e,n)=>({status:"failed",failure:{reason:e,detail:n}}),"failed"),y=l(e=>{const{phase:n,...t}=e,{untilMs:o,lastError:d,summary:s,...i}=t;return i},"baseOf"),S={name:"pi.collapse",config:z,inflight:["summarizing"],async initial(e,n,t){const o=await n.rewindable(e.conversationId,t);if(o.model===void 0)return{done:l(()=>p("no_model","no model configured"),"done")};const d=await n.sticky(e.conversationId,t),s=await n.newestEntry(e.conversationId,{withHead:!0},t),{entries:i}=await n.context(e.conversationId,e.input.through,t);let u={};if(await n.hooks.each(t,(r,f)=>r.beforeCollapse?.(e.input.reason,e.input.through,i,f,t),r=>{if(r!==void 0)return u=r,!0}),"decline"in u)return{done:l(()=>p("declined","declined by beforeCollapse"),"done")};const c=u,m={expectedHead:s?.id??null,...c.instructions??e.input.instructions?{instructions:c.instructions??e.input.instructions}:{},model:o.model,thinkingLevel:o.thinkingLevel,retry:d.retry,attempt:1};return c.summary!==void 0?{next:l(async(r,f)=>await g(r,f.conversationId,m)?p("stale","head moved during beforeCollapse"):{phase:"prepared",summary:c.summary,...m},"next")}:w(e,m,n,t,"check head")},phases:{async summarizing(e,n){return h(y(e.checkpoint),null,"interrupted",n)},async retrying(e,n,t){return await n.sleep(e.checkpoint.untilMs,t),w(e,{...y(e.checkpoint),attempt:e.checkpoint.attempt+1},n,t)},async prepared(e,n){const{summary:t}=e.checkpoint,o=y(e.checkpoint);return{done:l(async(d,s)=>{const{head:i,entries:u}=await d.context(s.conversationId);if((i?.id??null)!==o.expectedHead)return p("stale","head moved during collapse");const c=u.find(r=>r.id>e.input.through);return{status:"completed",result:{summary:d.appendEntry(s.conversationId,{kind:"pi.summary",data:{through:e.input.through},model:[{role:"user",content:t,timestamp:n.now()}],head:c?.id??"self"})}}},"done")}}},async abort(){return async()=>null}},g=l(async(e,n,t)=>((await e.newestEntry(n,{withHead:!0}))?.id??null)!==t.expectedHead,"headMoved");async function w(e,n,t,o,d){if(await t.commit(async(a,v)=>d&&await g(a,v.conversationId,n)?!0:(a.checkpoint({phase:"summarizing",...n}),!1),o))return{done:l(()=>p("stale","head moved during beforeCollapse"),"done")};const i=t.models.resolve(n.model);if(i===void 0)return{done:l(()=>p("no_model","model unavailable"),"done")};const{messages:u}=await t.context(e.conversationId,e.input.through,o),c=M(u),m=[...u,...c.length>0?[C({role:"system",content:"",toolsRemoved:c,timestamp:t.now()})]:[],{role:"user",content:`${n.instructions??"Summarize the conversation so far for continuation."}
2
-
3
- Respond with the summary only.`,timestamp:t.now()}];let r;try{for await(const a of t.models.stream(i,{messages:m,thinkingLevel:n.thinkingLevel},o)){if(a.type==="done"){r=a.message;break}if(a.type==="error"){r=a.error;break}}}catch(a){if(o.abortSignal?.aborted)throw a;return h(n,null,String(a),t)}return r===void 0?h(n,null,"no message",t):r.content.some(a=>a.type==="toolCall")?h(n,{...r,stopReason:"error"},"summarizer returned tool calls",t):r.stopReason==="error"?h(n,r,r.errorMessage??"provider error",t):{next:{phase:"prepared",summary:r.content.filter(a=>a.type==="text").map(a=>a.text).join(""),...n}}}l(w,"summarizeNow");function h(e,n,t,o){const d=_(e,n,o.now());return d.kind==="fail"?{done:l(()=>p(d.reason,t),"done")}:{next:l((s,i)=>(s.emit({type:"compaction.retrying",taskId:i.id,attempt:e.attempt,retryAt:d.untilMs,error:t}),{phase:"retrying",...e,untilMs:d.untilMs,lastError:t}),"next")}}l(h,"afterFailure");function T(e,n){const t=[];let o;for(const i of e){const u=i.model?.[0]?.role,c=b(i.model??[]);u==="assistant"?(o={last:i.id,tokens:c},t.push(o)):u==="toolResult"&&o?(o.last=i.id,o.tokens+=c):(o=void 0,t.push({last:i.id,tokens:c}))}let d=0,s=t.length-1;for(;s>=0&&d+t[s].tokens<=n;)d+=t[s--].tokens;if(!(s<0))return s===t.length-1?t[s-1]?.last:t[s].last}l(T,"chooseThrough");export{T as chooseThrough,S as collapse,z as collapseConfig};
@@ -1 +0,0 @@
1
- var o=Object.defineProperty;var i=(e,t)=>o(e,"name",{value:t,configurable:!0});const s=i(e=>Object.freeze({kind:e,is:i(t=>t?.kind===e,"is")}),"coreEntry"),a={user:s("pi.user"),assistant:s("pi.assistant"),toolResult:s("pi.tool_result"),system:s("pi.system"),notice:s("pi.notice"),usage:s("pi.usage"),summary:s("pi.summary"),handoff:s("pi.handoff"),reset:s("pi.reset")};export{a as entries};
@@ -1 +0,0 @@
1
- var o=Object.defineProperty;var c=(i,t)=>o(i,"name",{value:t,configurable:!0});function a(i,t){if(t.type==="start"){i.message=t.partial;return}const d=i.message;if(d===void 0)throw new Error(`${t.type} before start`);const e=d.content;switch(t.type){case"text_start":e[t.contentIndex]={...t.content};return;case"text_delta":e[t.contentIndex].text+=t.delta;return;case"text_end":{const n=e[t.contentIndex];n.text=t.content,delete n.textSignature,t.textSignature!==void 0&&(n.textSignature=t.textSignature);return}case"thinking_start":e[t.contentIndex]={...t.content};return;case"thinking_delta":e[t.contentIndex].thinking+=t.delta;return;case"thinking_end":{const n=e[t.contentIndex];n.thinking=t.content,delete n.thinkingSignature,delete n.redacted,t.thinkingSignature!==void 0&&(n.thinkingSignature=t.thinkingSignature),t.redacted!==void 0&&(n.redacted=t.redacted);return}case"toolcall_start":e[t.contentIndex]={...t.toolCall};return;case"toolcall_checkpoint":e[t.contentIndex].arguments=u(t.json);return;case"toolcall_delta":return;case"toolcall_end":{const n=e[t.contentIndex];n.id=t.id,n.name=t.name,n.arguments=t.arguments,t.thoughtSignature!==void 0&&(n.thoughtSignature=t.thoughtSignature),t.namespace!==void 0&&(n.namespace=t.namespace);return}}}c(a,"applyFrame");function u(i){try{return JSON.parse(i)}catch{return{}}}c(u,"safeParse");export{a as applyFrame};
@@ -1 +0,0 @@
1
- var q=Object.defineProperty;var f=(r,e)=>q(r,"name",{value:e,configurable:!0});import{AssistantMessageFrameEncoder as F,isRetryableAssistantError as L}from"@earendil-works/pi-ai";import{estimateContextTokens as $}from"@earendil-works/pi-ai/utils/estimate";import{planManagedEntry as H,prepareDraft as N,sameSnapshot as W,takeSnapshot as T}from"../system.js";import{toStored as k}from"../types.js";import{chooseThrough as R}from"./collapse.js";import{applyFrame as B}from"./frames.js";const G={rewindable:{model:void 0,thinkingLevel:"off",selectedTools:[],profile:"default"},sticky:{retry:{enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:6e4}}},v=f((r,e,t)=>({status:"failed",failure:{reason:r,detail:e,...t===void 0?{}:{assistant:t}}}),"fail"),I=f((r,e,t)=>({done:f(async(n,o)=>{const s=await n.newestEntry(o.conversationId,{withHead:!0});return n.emit({type:"generation.failed",taskId:o.id,reason:e,detail:t}),await E(n,o,r.input.inputs,t,s?.id),v(e,t)},"done")}),"failStep"),A=f(r=>$(r.filter(e=>e.role!=="system"&&!(e.role==="assistant"&&(e.stopReason==="aborted"||e.stopReason==="error")))).tokens,"estimate"),P=f(()=>({input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}),"emptyUsage"),Z={name:"pi.generation",turn:!0,config:G,inflight:["requesting"],async initial(r,e,t){const{snapshot:n,canonical:o,seed:s}=await e.commit((h,c)=>T(h,c.conversationId,e.registries.sections,e.registries.tools),t);if(n.settings.model===void 0)return I(r,"no_model","no model configured");const a=(await e.sticky(r.conversationId,t)).retry,l=[],{desired:i,tools:d}=await N(e,e.registries.sections,o,s,n.settings,h=>l.push(h),t),u=n.settings.model,y=n.settings.thinkingLevel;return{next:f(async(h,c)=>{const m=c.conversationId,w=await T(h,m,e.registries.sections,e.registries.tools);if(!W(w.snapshot,n))return"retry";const p=await H(h,m,n,o,i,d,e.now());for(const M of l)h.emit({type:"warning",source:"generation",message:M});const g=p===void 0?null:h.appendEntry(m,{kind:"pi.system",...p}),b=g??(await h.newestEntry(m)).id;return h.sticky(m).turn={tools:[]},{phase:"prepared",cutoff:b,system:g,model:u,thinkingLevel:y,tools:d.map(M=>M.name),retry:a,attempt:0}},"next")}},phases:{async prepared(r,e,t){const n=r.checkpoint,o=e.models.resolve(n.model);if(o===void 0)return I(r,"no_model",`model ${n.model.provider}/${n.model.modelId} unavailable`);const s=await U(r,n,e,t);if(A(s.messages)>o.contextWindow-o.maxTokens)return Y(r,e);const a=n.attempt+1;await e.commit(d=>{d.checkpoint({...n,phase:"requesting",attempt:a}),d.emit({type:"generation.started",taskId:r.id,attempt:a})},t);const{terminal:l,deferred:i}=await X(n,o,s.messages,e,t);if(i!==void 0){const d=e.now()+(i.pollAfterMs??5e3);return{next:f(u=>(u.emit({type:"generation.deferred",taskId:r.id,pollAt:d}),{...n,phase:"deferred",attempt:a,handle:k(i),pollAt:d}),"next")}}return _(r,{...n,attempt:a},l,e,t)},async requesting(r,e){const t=r.checkpoint,n=S(t,null,e.now());return n.kind==="fail"?I(r,n.reason,"interrupted"):{next:f((o,s)=>(o.appendEntry(s.conversationId,{kind:"pi.usage",data:{attempt:t.attempt,error:"interrupted"}}),o.emit({type:"generation.retrying",taskId:s.id,attempt:t.attempt,retryAt:n.untilMs,error:"interrupted"}),{...t,phase:"retrying",untilMs:n.untilMs,lastError:"interrupted"}),"next")}},async retrying(r,e,t){const n=r.checkpoint;await e.sleep(n.untilMs,t);const{untilMs:o,lastError:s,...a}=n;return{next:f((l,i)=>(l.sticky(i.conversationId).turn.message=void 0,{...a,phase:"prepared"}),"next")}},async deferred(r,e,t){const n=r.checkpoint,o=e.models.resolve(n.model);if(o===void 0)return I(r,"no_model","model disappeared");await e.sleep(n.pollAt,t);const s=await e.models.fetchDeferred(o,n.handle,t);if("deferred"in s&&s.deferred!==void 0){const u=e.now()+(s.deferred.pollAfterMs??5e3);return{next:f(y=>(y.emit({type:"generation.deferred",taskId:r.id,pollAt:u}),{...n,handle:k(s.deferred),pollAt:u}),"next")}}const a=s;await e.commit((u,y)=>{u.sticky(y.conversationId).turn.message=k(a)},t);const{handle:l,pollAt:i,...d}=n;return _(r,d,a,e,t)}},async abort(r,e,t){const n=r.checkpoint;if(n?.phase==="deferred"){const o=e.models.resolve(n.model);o&&await e.models.cancelDeferred(o,n.handle,t).catch(()=>{})}return async(o,s)=>{const a=o.sticky(s.conversationId).turn.message;let l;return a&&a.content.length>0&&(l=o.appendEntry(s.conversationId,{kind:"pi.assistant",data:{attempt:n?.attempt??0,display:{...k(a),stopReason:"aborted"},reason:"aborted"}})),o.sticky(s.conversationId).turn={tools:[]},await o.resolveInputs(r.input.inputs,{status:"unanswered",reason:"aborted"}),o.emit({type:"turn.ended",inputs:r.input.inputs,status:"unanswered",reason:"aborted"}),l===void 0?{}:{assistant:l}}}};async function U(r,e,t,n){const{messages:o}=await t.context(r.conversationId,e.cutoff,n);let s={messages:o};return await t.hooks.each(n,(a,l)=>a.beforeRequest?.(s,{...l,cutoff:e.cutoff},n),a=>{a!==void 0&&(s=a)}),s}f(U,"derive");async function X(r,e,t,n,o){const s=new F;let a=[],l=0,i=n.now(),d,u,y=!1;const h=f(async()=>{const c=a;c.length!==0&&(a=[],l=0,i=n.now(),c.some(m=>"delta"in m)&&(y=!0),await n.commit((m,w)=>{const p=m.sticky(w.conversationId).turn;for(const g of c)B(p,g)},o))},"flush");try{const c=n.models.stream(e,{messages:t,thinkingLevel:r.thinkingLevel},o)[Symbol.asyncIterator]();let m=c.next();for(;;){const w=a.length===0?{kind:"event",result:await m}:await Promise.race([m.then(b=>({kind:"event",result:b})),n.sleep(i+100,o).then(()=>({kind:"flush"}))]);if(w.kind==="flush"){await h();continue}if(w.result.done)break;const p=w.result.value;if(p.type==="done"){s.encode(p),p.reason==="deferred"&&p.message.deferred!==void 0?u=p.message.deferred:d=p.message;break}if(p.type==="error"){s.encode(p),d=p.error;break}const g=s.encode(p);m=c.next(),g!==void 0&&(a.push(g),l+="delta"in g?g.delta.length:64,(l>=256||!y&&"delta"in g)&&await h())}}catch(c){if(o.abortSignal?.aborted)throw c;d={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:P(),stopReason:"error",errorMessage:String(c),timestamp:n.now()}}if(a.length>0&&await h(),d===void 0&&u===void 0)throw new Error("stream ended without a terminal message");return{terminal:d,deferred:u}}f(X,"stream");async function _(r,e,t,n,o){if(await n.hooks.each(o,(i,d)=>i.afterResponse?.(t,{...d,attempt:e.attempt},o)),t.stopReason==="error"){const i=S(e,t,n.now());return i.kind==="retry"?{next:f((d,u)=>(d.appendEntry(u.conversationId,{kind:"pi.usage",data:{attempt:e.attempt,usage:k(t.usage),error:t.errorMessage??"provider error"}}),d.emit({type:"generation.retrying",taskId:u.id,attempt:e.attempt,retryAt:i.untilMs,error:t.errorMessage??"provider error"}),{...e,phase:"retrying",untilMs:i.untilMs,lastError:t.errorMessage??"provider error"}),"next")}:{done:D(r,e,t,i.reason)}}if(t.stopReason==="aborted")return{done:D(r,e,t,"provider")};const s=t.content.filter(i=>i.type==="toolCall"),a=k(t);if(s.length>0)return{done:f(async(i,d)=>{const u=d.conversationId,y=await C(i,u,t),h=i.appendEntry(u,{kind:"pi.assistant",model:[a],data:{attempt:e.attempt}}),c=i.sticky(u).turn;c.message=void 0,c.tools=s.map(p=>({callId:p.id,name:p.name,args:k(p.arguments),status:"pending"}));const m=s.map((p,g)=>i.createTask({kind:"pi.tool",input:{assistant:h,call:k(p),offered:e.tools,index:g}})),w=i.createTask({kind:"pi.post_tools",after:m,input:{inputs:r.input.inputs,assistant:h,tools:m}});return y!==void 0&&i.createTask({kind:"pi.collapse",input:{reason:"threshold",through:y}}),i.emit({type:"generation.completed",taskId:d.id,entry:h,toolCalls:s.length}),{status:"completed",result:{assistant:h,tools:m,postTools:w}}},"done")};let l;return await n.hooks.each(o,(i,d)=>i.onYield?.(t,d,o),i=>{if(i!==void 0)return l=i.continue,!0}),{done:f(async(i,d)=>{const u=d.conversationId,y=await C(i,u,t),h=await i.newestEntry(u,{withHead:!0}),c=i.appendEntry(u,{kind:"pi.assistant",model:[a],data:{attempt:e.attempt}});i.emit({type:"generation.completed",taskId:d.id,entry:c,toolCalls:0}),i.sticky(u).turn={tools:[]},y!==void 0&&i.createTask({kind:"pi.collapse",input:{reason:"threshold",through:y}});const{triggers:m,terminated:w}=await i.boundary(u,"final",h?.id);if(l!==void 0&&m.length===0&&!w){i.appendEntry(u,{kind:"pi.user",model:[{role:"user",content:l,timestamp:n.now()}],data:{continuation:!0,from:c}});const p=i.createTask({kind:"pi.generation",input:{inputs:r.input.inputs}});return{status:"completed",result:{assistant:c,tools:[],successor:p}}}if(await i.resolveInputs(r.input.inputs,{status:"done",answer:c}),i.emit({type:"turn.ended",inputs:r.input.inputs,status:"done",answer:c}),m.length>0){const p=i.createTask({kind:"pi.generation",input:{inputs:m}});return i.emit({type:"turn.started",inputs:m}),{status:"completed",result:{assistant:c,tools:[],successor:p}}}return{status:"completed",result:{assistant:c,tools:[]}}},"done")}}f(_,"classify");function D(r,e,t,n){return async(o,s)=>{const a=await o.newestEntry(s.conversationId,{withHead:!0}),l=o.appendEntry(s.conversationId,{kind:"pi.assistant",data:{attempt:e.attempt,display:k(t),reason:t.stopReason==="aborted"?"aborted":"error"}});return o.emit({type:"generation.failed",taskId:s.id,reason:n,detail:t.errorMessage??"provider error",entry:l}),await E(o,s,r.input.inputs,t.errorMessage??"provider error",a?.id),v(n,t.errorMessage??"provider error",l)}}f(D,"terminalError");async function E(r,e,t,n,o){r.sticky(e.conversationId).turn={tools:[]},await r.resolveInputs(t,{status:"unanswered",reason:"failed",detail:n}),r.emit({type:"turn.ended",inputs:[...t],status:"unanswered",reason:"failed",detail:n});const{triggers:s}=await r.boundary(e.conversationId,"final",o);s.length>0&&(r.createTask({kind:"pi.generation",conversationId:e.conversationId,input:{inputs:s}}),r.emit({type:"turn.started",inputs:s}))}f(E,"settleFailedTurn");function S(r,e,t){if(e!==null&&!L(e))return{kind:"fail",reason:"provider"};if(!r.retry.enabled)return{kind:"fail",reason:"provider"};if(r.attempt>r.retry.maxRetries)return{kind:"fail",reason:"retries_exhausted"};const n=r.retry.baseDelayMs*2**Math.max(0,r.attempt-1),o=Number.isSafeInteger(n)?n:Number.MAX_SAFE_INTEGER;return{kind:"retry",untilMs:t+Math.min(o,r.retry.maxAgentDelayMs??6e4)}}f(S,"retryDecision");async function C(r,e,t){if((await r.tasks({conversationId:e,kind:"pi.collapse",status:["pending","running"]})).length>0)return;const n=r.rewindable(e);if(n.threshold<=0)return;const{entries:o,messages:s}=await r.context(e);if(!(Math.max((t.usage?.input??0)+(t.usage?.output??0),A([...s,k(t)]))<=n.threshold))return R(o,n.keepRecent)}f(C,"thresholdCollapseThrough");function Y(r,e){return{done:f(async(t,n)=>{const o=n.conversationId,s=t.rewindable(o),{entries:a,head:l}=await t.context(o),i=R(a,s.keepRecent);if(t.sticky(o).turn={tools:[]},i===void 0)return await t.write(o,{kind:"pi.notice",model:[{role:"user",content:"Context too large; nothing to compact.",timestamp:e.now()}]}),t.emit({type:"generation.failed",taskId:n.id,reason:"overflow",detail:"request exceeds context window and nothing is collapsible"}),await E(t,n,r.input.inputs,"overflow",l?.id),v("overflow","request exceeds context window and nothing is collapsible");const d=t.createTask({kind:"pi.collapse",input:{reason:"overflow",through:i}});return t.createTask({kind:"pi.generation",after:[d],input:{inputs:r.input.inputs}}),t.emit({type:"generation.failed",taskId:n.id,reason:"overflow",detail:`collapsing through ${i}`}),v("overflow",`collapsing through ${i}`)},"done")}}f(Y,"overflow");export{Z as generation,G as generationConfig,S as retryDecision};
@@ -1 +0,0 @@
1
- var j=Object.defineProperty;var r=(t,e)=>j(t,"name",{value:e,configurable:!0});const c=r((t,e)=>({status:"failed",failure:{reason:t,detail:e}}),"failed"),g=r((t,e)=>({kind:"pi.notice",model:[{role:"user",content:t,timestamp:e}]}),"notice"),S={name:"pi.job",slot:r(()=>({}),"slot"),describe:r(t=>({stage:t.checkpoint?.phase??"starting",...t.slot??{}}),"describe"),inflight:["spawning","running"],phases:{async waiting(t,e,n){return await e.sleep(t.checkpoint.untilMs,n),y(t,t.checkpoint.occurrence,e,n)},async spawning(t,e,n){return b(t,t.checkpoint,e,n)},async running(t,e,n){return b(t,t.checkpoint,e,n)}},async initial(t,e,n){if(e.processHost===void 0)return{done:r(()=>c("spawn","no process host"),"done")};const o=e.now(),i=t.input.notBefore??o;return i>o?{next:{phase:"waiting",untilMs:i,occurrence:1}}:y(t,1,e,n)},async abort(t,e,n){const o=t.checkpoint;return o===void 0||o.phase==="waiting"||e.processHost===void 0?async()=>({killed:!1}):(await e.processHost.kill(o.key,"SIGTERM",n),await e.sleep(e.now()+5e3,n),await e.processHost.kill(o.key,"SIGKILL",n),async()=>({killed:!0}))}},M=Object.freeze(S);async function y(t,e,n,o){const i=`${t.id}:${e}`;await n.commit(s=>s.checkpoint({phase:"spawning",key:i,occurrence:e}),o);try{await n.processHost.start(i,t.input,o)}catch(s){if(o.abortSignal?.aborted)throw s;return{done:r(async(w,a)=>(t.input.notify&&await w.write(a.conversationId,g(`job ${t.id} failed to start: ${String(s)}`,n.now())),c("spawn",String(s))),"done")}}return await n.commit(s=>s.checkpoint({phase:"running",key:i,occurrence:e}),o),$(t,i,e,n,o)}r(y,"spawn");async function b(t,e,n,o){if(n.processHost===void 0)return{done:r(()=>c("interrupted","no process host after restart"),"done")};let i;try{i=await n.processHost.status(e.key,o)}catch(s){return{done:r(()=>c("interrupted",`host status failed: ${String(s)}`),"done")}}return i.status==="unknown"?t.input.rerun?y(t,e.occurrence,n,o):{done:r(()=>c("interrupted","process outcome unknown"),"done")}:(e.phase==="spawning"&&await n.commit(s=>s.checkpoint({phase:"running",key:e.key,occurrence:e.occurrence}),o),$(t,e.key,e.occurrence,n,o))}r(b,"reconcile");async function $(t,e,n,o,i){for(let s=0;;s++){let w;try{w=await o.processHost.status(e,i)}catch(d){return{done:r(()=>c("interrupted",`host status failed: ${String(d)}`),"done")}}if(w.status==="unknown")return t.input.rerun?y(t,n,o,i):{done:r(()=>c("interrupted","process outcome unknown"),"done")};const a=w;if(await o.commit((d,h)=>{const p=d.slot({id:h.id,kind:S});p.stdout=a.stdout,p.stderr=a.stderr,p.droppedStdout=a.droppedStdout,p.droppedStderr=a.droppedStderr,a.status==="exited"&&(p.exitCode=a.exitCode)},i),a.status==="exited"){const{exitCode:d,stdout:h,stderr:p}=a;if(t.input.every===void 0)return{done:r(async(f,l)=>(t.input.notify&&await f.write(l.conversationId,g(`job ${t.id} exited with code ${d}`,o.now())),{status:"completed",result:{exitCode:d,occurrences:n,stdout:h,stderr:p}}),"done")};const H=o.now()+t.input.every;return{next:r(async(f,l)=>{t.input.notify&&await f.write(l.conversationId,g(`job ${t.id} occurrence ${n} exited with code ${d}`,o.now()));const u=f.slot({id:l.id,kind:S});return u.stdout="",u.stderr="",u.droppedStdout=0,u.droppedStderr=0,delete u.exitCode,u.occurrence=n+1,{phase:"waiting",untilMs:H,occurrence:n+1}},"next")}}await o.sleep(o.now()+Math.min(1e3,100*2**Math.min(s,4)),i)}}r($,"poll");export{M as job};
@@ -1 +0,0 @@
1
- var s=Object.defineProperty;var r=(t,n)=>s(t,"name",{value:n,configurable:!0});import{toStored as u}from"../types.js";import{taskApi as l}from"./task-api.js";const d={name:"pi.plugin",inflight:["started"],phases:{async started(t,n,e){return o(t,n,e)}},async initial(t,n,e){return await n.commit(a=>a.checkpoint({phase:"started"}),e),o(t,n,e)},async abort(){return async()=>null}},h=Object.freeze(d);async function o(t,n,e){const a=n.plugins.get(t.input.handler);if(a===void 0)return{done:r(()=>({status:"failed",failure:{reason:"missing_handler",detail:t.input.handler}}),"done")};try{const i=u(await a(t.input.input,l(t,n),e));return{done:r(()=>({status:"completed",result:i}),"done")}}catch(i){if(e.abortSignal?.aborted)throw i;return{done:r(()=>({status:"failed",failure:{reason:"threw",detail:String(i)}}),"done")}}}r(o,"run");export{h as plugin};
@@ -1 +0,0 @@
1
- var T=Object.defineProperty;var g=(n,o)=>T(n,"name",{value:o,configurable:!0});import{toStored as b}from"../types.js";const v={sticky:{steeringMode:"one-at-a-time",followUpMode:"one-at-a-time"}},E={name:"pi.post_tools",turn:!0,config:v,phases:{},async initial(n,o,u){const m=await o.commit(async t=>{const i=((await t.entry(n.input.assistant))?.model?.[0]?.content??[]).filter(d=>d.type==="toolCall");return Promise.all(n.input.tools.map(async(d,l)=>{const r=await t.task(d),a=i[l];if(r.outcome?.status==="completed"){const s=r.outcome.result;return{call:a,entry:s.entry,control:s.control,missing:void 0}}if(r.outcome?.status==="aborted"){const s=r.outcome.result;return{call:a,entry:s.entry,control:void 0,missing:s.entry===void 0?"aborted":void 0}}return{call:a,entry:void 0,control:void 0,missing:"orphaned"}}))},u),w=m.map(t=>t.entry).filter(t=>t!==void 0);return await o.hooks.each(u,(t,f)=>t.afterTools?.(n.input.assistant,w,f,u)),{done:g(async(t,f)=>{const i=f.conversationId,d=await t.newestEntry(i,{withHead:!0}),l=t.rewindable(i),r=[...l.selectedTools];let a=!1,s;for(const e of m){for(const p of e.control?.addTools??[])r.includes(p)||r.push(p);e.control?.terminate&&(a=!0),e.control?.handoff!==void 0&&(s=e.control.handoff)}r.length!==l.selectedTools.length&&(l.selectedTools=r,t.emit({type:"config.changed",keys:["selectedTools"]}));for(const e of m)e.missing!==void 0&&(t.appendEntry(i,{kind:"pi.tool_result",model:[b({role:"toolResult",toolCallId:e.call.id,toolName:e.call.name,content:[{type:"text",text:`Tool result unavailable: task ${e.missing}.`}],isError:!0,timestamp:o.now()})],data:{diagnostics:[{severity:"error",message:e.missing,code:e.missing}]}}),t.emit({type:"warning",source:"post_tools",message:`synthesized ${e.missing} tool result for ${e.call.id}`}));let y=d?.id;if(s!==void 0&&(y=t.appendEntry(i,{kind:"pi.handoff",head:"self",model:[{role:"user",content:s,timestamp:o.now()}]})),s!==void 0||a){t.sticky(i).turn={tools:[]},await t.resolveInputs(n.input.inputs,{status:"done",answer:n.input.assistant}),t.emit({type:"turn.ended",inputs:n.input.inputs,status:"done",answer:n.input.assistant});const{triggers:e}=await t.boundary(i,"final",y);e.length>0&&t.emit({type:"turn.started",inputs:e});const p=s!==void 0?"handoff":"terminate";return{status:"completed",result:e.length>0?{ended:p,successor:t.createTask({kind:"pi.generation",input:{inputs:e}})}:{ended:p}}}const{triggers:c,terminated:h}=await t.boundary(i,"postTools",y);return h?(t.sticky(i).turn={tools:[]},await t.resolveInputs(n.input.inputs,{status:"unanswered",reason:"terminated"}),t.emit({type:"turn.ended",inputs:n.input.inputs,status:"unanswered",reason:"terminated"}),c.length>0&&t.emit({type:"turn.started",inputs:c}),{status:"completed",result:c.length>0?{successor:t.createTask({kind:"pi.generation",input:{inputs:c}})}:{}}):{status:"completed",result:{successor:t.createTask({kind:"pi.generation",input:{inputs:[...n.input.inputs,...c]}})}}},"done")}},async abort(n){return async(o,u)=>(o.sticky(u.conversationId).turn={tools:[]},await o.resolveInputs(n.input.inputs,{status:"unanswered",reason:"aborted"}),o.emit({type:"turn.ended",inputs:n.input.inputs,status:"unanswered",reason:"aborted"}),null)}};export{E as postTools,v as postToolsConfig};
@@ -1 +0,0 @@
1
- var k=Object.defineProperty;var t=(i,a)=>k(i,"name",{value:a,configurable:!0});function y(i,a){const w=t(o=>typeof o=="object"&&o!==null&&"name"in o&&"initial"in o,"isKind");return{taskId:i.id,conversationId:i.conversationId,callId:"",stream:t(()=>{throw new Error("stream is only available to tools")},"stream"),progress:t(()=>{throw new Error("progress is only available to tools")},"progress"),memo:t((()=>Promise.reject(new Error("memo is only available to tools"))),"memo"),async conversation(o,n){const s=await a.createOwnedConversation(o,n);return{id:s,send:t(async(r,e)=>{const d=await a.sendOwned(s,r,e);return{id:d,wait:t(c=>a.waitForInput(d,c),"wait"),result:t(c=>a.commit(l=>l.input(d),c),"result")}},"send"),abort:t(r=>a.abortConversation(s,r),"abort")}},task:t(((o,n,s,r)=>{if(!w(o))throw new Error("task(): pass a kind token");return a.commit(e=>e.createTask(o,n,s),r)}),"task"),getTask:t(async(o,n)=>await a.commit(s=>s.task(o.id),n),"getTask"),waitForTask:t((o,n)=>a.waitForTask(o.id,n),"waitForTask"),slot:t((o,n)=>a.commit(async s=>{const r=await s.task(o.id);if(r!==void 0)return s.snapshot({doc:"sticky",conversationId:r.conversationId}).tasks[o.id]??void 0},n),"slot")}}t(y,"taskApi");export{y as taskApi};
@@ -1,3 +0,0 @@
1
- var A=Object.defineProperty;var g=(e,n)=>A(e,"name",{value:n,configurable:!0});import{Errors as D}from"typebox/value";import{Bounded as F}from"../bounded.js";import{toStored as x}from"../types.js";import{taskApi as N}from"./task-api.js";const h=g((e,n)=>({content:[{type:"text",text:e}],isError:!0,diagnostics:[{severity:"error",message:e,code:n}]}),"synthetic");function k(e,n){const i=[...D(e.parameters,n.arguments)];return i.length===0?void 0:i.map(t=>`${t.instancePath||"/"}: ${t.message}`).join("; ")}g(k,"invalid");const P=g((e,n)=>e.id===n.id&&e.name===n.name&&e.namespace===n.namespace,"sameIdentity"),J={name:"pi.tool",turn:!0,inflight:["started"],async initial(e,n,i){const t=e.input.call;if(!e.input.offered.includes(t.name))return{done:$(e,h(`tool ${t.name} was not offered`,"not_offered"),void 0,n.now())};const o=n.tools.get(t.name);if(o===void 0)return{done:$(e,h(`tool ${t.name} is not registered`,"missing_tool"),void 0,n.now())};const s=k(o,t);if(s!==void 0)return{done:$(e,h(`invalid arguments: ${s}`,"invalid_arguments"),o,n.now())};const a=await U(e,n,t,i);if("block"in a)return{done:$(e,h(`blocked: ${a.block}`,"blocked"),o,n.now())};if(!P(t,a.call))return{done:$(e,h("blocked: call identity changed","blocked"),o,n.now())};const c=k(o,a.call);if(c!==void 0)return{done:$(e,h(`invalid arguments after hook: ${c}`,"invalid_arguments"),o,n.now())};const d=x(a.call);return await n.commit(r=>{r.checkpoint({phase:"started",replay:o.replay??"unsafe",call:d});const u=r.toolSlot(e);u.status="running",delete u.waitingOn,r.emit({type:"tool.started",taskId:e.id,callId:d.id,name:d.name})},i),{done:await T(e,d,o,n,i)}},phases:{async started(e,n,i){const t=e.checkpoint,o=n.tools.get(t.call.name);return o===void 0?{done:$(e,h(`tool ${t.call.name} unavailable after restart`,"unavailable"),void 0,n.now(),t.call)}:t.replay!=="safe"||(o.replay??"unsafe")!=="safe"?{done:$(e,h(`tool ${t.call.name} was interrupted`,"interrupted"),o,n.now(),t.call)}:k(o,t.call)!==void 0?{done:$(e,h(`tool ${t.call.name} was interrupted; arguments no longer validate`,"interrupted"),o,n.now(),t.call)}:{done:await T(e,t.call,o,n,i)}}},async abort(e,n,i){for(const t of e.owns){const o=await n.commit(s=>s.tasks({conversationId:t,status:["pending","running"]}),i);for(const s of o)s.background||await n.abortTask(s.id,i)}return(t,o)=>{const s=e.checkpoint?.call??e.input.call,a=t.appendEntry(o.conversationId,{kind:"pi.tool_result",model:[C(s,h("tool aborted","aborted"),n.now())],data:{diagnostics:[{severity:"error",message:"aborted",code:"aborted"}]}}),c=t.sticky(o.conversationId).turn.tools[e.input.index];return c!==void 0&&(c.status="aborted",c.entry=a,delete c.waitingOn),t.emit({type:"tool.aborted",taskId:o.id,callId:s.id,entry:a}),{entry:a}}}};async function U(e,n,i,t){let o=i;for(const s of n.hooks.handlers()){let a=function(d,r,u){const y=u??r;return n.commit(l=>{l.plugins(s.namespace);const m=l.toolSlot(e);Object.hasOwn(m,"memos")||(m.memos={});const v=m.memos,p=`hook:${s.namespace.id}:${d}`;if(Object.hasOwn(v,p))return structuredClone(v[p]);if(u===void 0)return;const I=structuredClone(r);return v[p]=I,I},y)};g(a,"memo");const c={...s.api,callId:i.id,waiting:g(d=>n.commit((r,u)=>{r.plugins(s.namespace);const y=r.toolSlot(u);y.waitingOn!==s.namespace.id&&(y.waitingOn=s.namespace.id,r.emit({type:"tool.waiting",taskId:u.id,callId:i.id,on:s.namespace.id}))},d),"waiting"),memo:a,emit:g((d,r,u)=>n.commit(y=>y.emit(s.namespace,d,r),u),"emit")};try{const d=await s.handlers.beforeTool?.(o,c,t);if(!d)continue;if(d.block!==void 0)return{block:d.block};d.call!==void 0&&(o=d.call)}catch(d){if(t.abortSignal?.aborted)throw d;return{block:`hook threw: ${String(d)}`}}}return{call:o}}g(U,"beforeTool");const _={maxBytes:64*1024,maxLines:200,retain:"head"};async function T(e,n,i,t,o){const s={..._,...i.output},a=new F(s.maxBytes,s.maxLines,s.retain);let c=!1,d=0,r=Promise.resolve(),u;const y=g(()=>{d=t.now();const f=a.text();r=r.then(()=>t.commit(w=>{w.toolSlot(e).output=f},o)).catch(w=>{u??=w})},"flush"),l={...N(e,t),progress:g((f,w)=>t.commit(E=>{const b=E.toolSlot(e),B={progress:b.progress,details:b.details,continuedBy:b.continuedBy};f(B),B.progress!==void 0?b.progress=B.progress:delete b.progress,B.details!==void 0?b.details=x(B.details):delete b.details,B.continuedBy!==void 0?b.continuedBy=B.continuedBy:delete b.continuedBy},w),"progress"),stream(f){c=!0,a.push(typeof f=="string"?new TextEncoder().encode(f):f),t.now()-d>=100&&y()}};function m(f,w,E){const b=E??w;return t.commit(B=>{const S=B.toolSlot(e);Object.hasOwn(S,"memos")||(S.memos={});const O=S.memos,L=`tool:${f}`;if(Object.hasOwn(O,L))return structuredClone(O[L]);if(E===void 0)return;const j=structuredClone(w);return O[L]=j,j},b)}g(m,"memo");const v={...l,callId:n.id,memo:m};let p;try{p=await i.execute(n.arguments,v,o)}catch(f){if(o.abortSignal?.aborted)throw f;p=h(`tool threw: ${String(f)}`,"threw")}if(c){if(y(),await r,u!==void 0)throw u;p.content===void 0&&(p={...p,content:[{type:"text",text:a.text()}],...a.dropped?{diagnostics:[...p.diagnostics??[],{severity:"warn",code:"truncated",message:`${a.droppedBytes} bytes / ${a.droppedLines} lines dropped (${s.retain} ${s.maxBytes} retained)`}]}:{}})}let I=p;return await t.hooks.each(o,(f,w)=>f.afterTool?.(n,I,{...w,callId:n.id},o),f=>{f!==void 0&&(I=f)}),$(e,I,i,t.now(),n,c?{bytes:a.droppedBytes,lines:a.droppedLines}:void 0)}g(T,"invoke");function $(e,n,i,t,o=e.input.call,s){return(a,c)=>{const d=M({...n,content:n.content??[]},i?.output),r=d.result,u=(d.truncated?.bytes??0)+(s?.bytes??0),y=(d.truncated?.lines??0)+(s?.lines??0),l=u>0||y>0?{bytes:u,lines:y}:void 0,m={};r.details!==void 0&&(m.details=x(r.details)),r.diagnostics!==void 0&&(m.diagnostics=x(r.diagnostics)),r.control!==void 0&&(m.control=x(r.control)),l!==void 0&&(m.truncated=l);const v=a.appendEntry(c.conversationId,{kind:"pi.tool_result",model:[C(o,r,t)],data:m}),p=a.toolSlot(e);return p.status=r.isError===!0?"error":"done",p.entry=v,delete p.waitingOn,a.emit({type:"tool.finished",taskId:c.id,callId:o.id,entry:v,isError:r.isError===!0,...r.control===void 0?{}:{control:r.control}}),l!==void 0&&a.emit({type:"warning",source:"tool",message:`tool output truncated: ${l.bytes} bytes / ${l.lines} lines dropped`}),{status:"completed",result:{entry:v,...r.control===void 0?{}:{control:x(r.control)}}}}}g($,"close");function C(e,n,i){return x({role:"toolResult",toolCallId:e.id,toolName:e.name,content:n.content??[],isError:n.isError??!1,timestamp:i})}g(C,"toMessage");function M(e,n){const i={..._,...n},t=e.content??[];let o=t.filter(l=>l.type==="text").map(l=>l.text).join(""),s=0,a=0;const c=o.split(`
2
- `);c.length>i.maxLines&&(s=c.length-i.maxLines,o=(i.retain==="head"?c.slice(0,i.maxLines):c.slice(-i.maxLines)).join(`
3
- `));const d=new TextEncoder().encode(o);if(d.length>i.maxBytes&&(a=d.length-i.maxBytes,o=new TextDecoder().decode(i.retain==="head"?d.subarray(0,i.maxBytes):d.subarray(-i.maxBytes))),a===0&&s===0)return{result:e};let r=-1;for(let l=0;l<t.length;l++)t[l].type==="text"&&(i.retain==="head"&&r>=0||(r=l));const u=[];for(let l=0;l<t.length;l++){const m=t[l];m.type!=="text"?u.push(m):l===r&&u.push({...m,text:o})}const y={severity:"warn",code:"truncated",message:`output truncated: ${s} lines, ${a} bytes dropped`};return{result:{...e,content:u,diagnostics:[...e.diagnostics??[],y]},truncated:{bytes:a,lines:s}}}g(M,"bound");export{_ as DEFAULT_BOUNDS,k as invalid,J as tool};
@@ -1 +0,0 @@
1
- var v=Object.defineProperty;var p=(h,n)=>v(h,"name",{value:n,configurable:!0});class x{static{p(this,"Membrane")}alive=!0;wrappers=new WeakMap;isWrapper=new WeakSet;what;constructor(n){this.what=n}revoke(){this.alive=!1}wrap(n){const a=this.wrappers.get(n);if(a!==void 0)return a;const t=this,o=p(()=>new TypeError(`document proxy (${t.what}) used outside its transaction`),"dead"),f=p(e=>typeof e=="object"&&e!==null?t.wrap(e):e,"out"),l=p(e=>typeof e!="object"||e===null?e:(t.assertPlainInput(e,new WeakSet),JSON.parse(JSON.stringify(e))),"inp"),c=new Proxy(n,{get(e,i,r){if(!t.alive)throw o();const s=Reflect.get(e,i,r===c?e:r);return typeof s=="function"?(...u)=>{if(!t.alive)throw o();const y=u.map(w=>typeof w!="function"?l(w):function(...d){if(!t.alive)throw o();return Reflect.apply(w,this,d.map(f))});return f(Reflect.apply(s,e,y))}:f(s)},set(e,i,r){if(!t.alive)throw o();if(i==="__proto__")throw new TypeError(`document proxy (${t.what}) cannot change prototypes`);return Reflect.set(e,i,l(r))},deleteProperty(e,i){if(!t.alive)throw o();return Reflect.deleteProperty(e,i)},has(e,i){if(!t.alive)throw o();return Reflect.has(e,i)},ownKeys(e){if(!t.alive)throw o();return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,i){if(!t.alive)throw o();const r=Reflect.getOwnPropertyDescriptor(e,i);if(r!==void 0)return"value"in r&&(r.value=f(r.value)),r},defineProperty(e,i,r){if(!t.alive)throw o();if("get"in r||"set"in r)throw new TypeError(`document proxy (${t.what}) cannot define accessors`);const s="value"in r?{...r,value:l(r.value)}:r;return Reflect.defineProperty(e,i,s)},getPrototypeOf(e){if(!t.alive)throw o();return Reflect.getPrototypeOf(e)},setPrototypeOf(){throw t.alive?new TypeError(`document proxy (${t.what}) cannot change prototypes`):o()},isExtensible(e){if(!t.alive)throw o();return Reflect.isExtensible(e)},preventExtensions(){throw t.alive?new TypeError(`document proxy (${t.what}) cannot change extensibility`):o()}});return this.wrappers.set(n,c),this.isWrapper.add(c),c}assertPlainInput(n,a){if(this.isWrapper.has(n))throw new TypeError(`assigning a document proxy into a document (${this.what}); assign a plain value`);if(a.has(n))throw new TypeError(`assigning a cyclic value into a document (${this.what})`);a.add(n);for(const t of Object.values(n))typeof t=="object"&&t!==null&&this.assertPlainInput(t,a);a.delete(n)}}export{x as Membrane};
@@ -1 +0,0 @@
1
- var v=Object.defineProperty;var f=(u,t)=>v(u,"name",{value:t,configurable:!0});import{applyImmutable as l,isBase as I}from"@earendil-works/chord/delta";class x{static{f(this,"MemoryStorage")}conversationsById=new Map;entriesById=new Map;entriesByConversation=new Map;tasksById=new Map;inputsById=new Map;inputsByRequest=new Map;rewindableLog=new Map;stickyLog=new Map;sessionDoc;entrySeq=new Map;nextIdValue=1;seq=0;closed=!1;mintId(){return this.nextIdValue++}setNextId(t){this.nextIdValue=Math.max(this.nextIdValue,t)}async commit(t,o){if(this.closed)throw new Error("storage closed");const n=this.seq+1;return this.stage(t,n)(),this.seq=n,n}stage(t,o){const n=[],i=new Set;let r=0;const a=f((s,e)=>{if(!Number.isSafeInteger(s)||s<=0)throw new Error(`${e}: invalid id ${s}`);if(i.has(s))throw new Error(`${e}: id ${s} created twice in one batch`);i.add(s),r=Math.max(r,s)},"claim");for(const s of t)switch(s.type){case"conversation":{if(this.conversationsById.has(s.conversation.id))throw new Error(`conversation ${s.conversation.id} exists`);a(s.conversation.id,"conversation");const e=c(s.conversation);n.push(()=>{this.conversationsById.set(e.id,e),this.entriesByConversation.set(e.id,[])});break}case"entry":{if(this.entriesById.has(s.entry.id))throw new Error(`entry ${s.entry.id} exists`);a(s.entry.id,"entry");const e=c(s.entry);n.push(()=>{this.entriesById.set(e.id,e),(this.entriesByConversation.get(e.conversationId)??this.entriesByConversation.set(e.conversationId,[]).get(e.conversationId)).push(e),this.entrySeq.set(e.id,o)});break}case"task":{if(this.tasksById.has(s.task.id))throw new Error(`task ${s.task.id} exists`);a(s.task.id,"task");const e=c(s.task);n.push(()=>this.tasksById.set(e.id,e));break}case"task.patch":{if((this.tasksById.get(s.patch.id)??[...t].filter(h=>h.type==="task").find(h=>h.task.id===s.patch.id)?.task)===void 0)throw new Error(`patch for unknown task ${s.patch.id}`);const d=c(s.patch);n.push(()=>{const h=this.tasksById.get(d.id),{id:k,...g}=d,y={...h,...g};d.checkpoint===null&&delete y.checkpoint,this.tasksById.set(d.id,y)});break}case"input":{const e=c(s.input);this.inputsById.has(e.id)||a(e.id,"input"),n.push(()=>{this.inputsById.set(e.id,e),e.requestId!==void 0&&this.inputsByRequest.set(`${e.conversationId}:${e.requestId}`,e)});break}case"doc":{const e=c(s.ref),d=c(s.ops);e.doc==="session"?n.push(()=>{this.sessionDoc=l(this.sessionDoc??{plugins:{}},d)}):e.doc==="rewindable"?n.push(()=>(this.rewindableLog.get(e.conversationId)??this.rewindableLog.set(e.conversationId,[]).get(e.conversationId)).push({seq:o,ops:d})):n.push(()=>(this.stickyLog.get(e.conversationId)??this.stickyLog.set(e.conversationId,[]).get(e.conversationId)).push(d));break}}return()=>{for(const s of n)s();this.setNextId(r+1)}}async conversation(t,o){return p(this.conversationsById.get(t))}async conversations(t){return[...this.conversationsById.values()].map(c)}async entries(t,o){const n=new Map;for(const i of t){const r=this.entriesById.get(i);r&&n.set(i,c(r))}return n}async scanEntries(t,o){const n=[];let i=t.conversationId,r=t.before;for(;i!==void 0&&n.length<t.limit;){const a=this.entriesByConversation.get(i)??[];for(let e=a.length-1;e>=0&&n.length<t.limit;e--){const d=a[e];r!==void 0&&d.id>=r||t.kind!==void 0&&d.kind!==t.kind||t.withHead&&d.head===void 0||n.push(c(d))}const s=this.conversationsById.get(i);i=s?.parent?.conversationId,r=s?.parent===void 0?void 0:Math.min(r??1/0,s.parent.at+1)}return n}async task(t,o){return p(this.tasksById.get(t))}async scanTasks(t,o){const n=[];for(const i of this.tasksById.values())t.conversationId!==void 0&&i.conversationId!==t.conversationId||t.status!==void 0&&!t.status.includes(i.status)||t.kind!==void 0&&i.kind!==t.kind||n.push(c(i));return n}async input(t,o){return p(this.inputsById.get(t))}async inputByRequest(t,o,n){return p(this.inputsByRequest.get(`${t}:${o}`))}async doc(t,o){if(t.doc==="session")return this.sessionDoc===void 0?{plugins:{}}:structuredClone(this.sessionDoc);const n=t.doc==="rewindable"?this.rewindableLog.get(t.conversationId)?.map(i=>i.ops):this.stickyLog.get(t.conversationId);if(n!==void 0)return c(this.fold(n))}async docAsOf(t,o,n){const i=this.entriesById.get(o)?.conversationId;if(i===void 0)return;const r=[];let a=this.conversationsById.get(t);for(;a!==void 0&&a.id!==i;)r.push(a.id),a=a.parent?this.conversationsById.get(a.parent.conversationId):void 0;if(a===void 0)return;const s=this.entrySeq.get(o)??0,e=(this.rewindableLog.get(i)??[]).filter(d=>d.seq<=s).map(d=>d.ops);return e.length===0?void 0:c(this.fold(e))}fold(t){let o=0;for(let i=t.length-1;i>=0;i--)if(I(t[i])){o=i;break}let n={};for(let i=o;i<t.length;i++)n=l(n,t[i]);return n}async truncate(t,o){if(t.doc!=="sticky")return;const n=this.stickyLog.get(t.conversationId);if(n===void 0)return;let i=0;for(let r=n.length-1;r>=0;r--)if(I(n[r])){i=r;break}n.splice(0,i)}async close(t){this.closed=!0}}function c(u){return JSON.parse(JSON.stringify(u))}f(c,"clone");function p(u){return u===void 0?void 0:c(u)}f(p,"optionalClone");export{x as MemoryStorage};
@@ -1 +0,0 @@
1
- var T=Object.defineProperty;var w=(a,e)=>T(a,"name",{value:e,configurable:!0});import{withAbortSignal as I}from"@earendil-works/chord/context";import{InvocationToken as S,TaskContractFault as v}from"./types.js";function E(a,e){const t=e===void 0?a.initial:a.phases[e];if(typeof t!="function")throw new v(a.name,`no handler for phase ${e??"initial"}`);return t}w(E,"handlerFor");function W(a,e){if(typeof e!="object"||e===null)throw new v(a.name,"handler returned a non-object step");if("done"in e&&typeof e.done=="function")return e;if("next"in e){const t=e.next;if(typeof t=="function")return e;if(typeof t=="object"&&t!==null&&typeof t.phase=="string"){if(!(t.phase in a.phases))throw new v(a.name,`transition to unknown phase ${t.phase}`);return e}}throw new v(a.name,"handler returned an invalid step")}w(W,"validateStep");function b(a,e){if(typeof e=="object"&&e!==null){const t=e.status;if(t==="completed"&&"result"in e||t==="failed"&&"failure"in e)return e}throw new v(a.name,"closure returned an invalid completion")}w(b,"validateCompletion");function L(a,e){if(typeof e!="object"||e===null||typeof e.phase!="string")throw new v(a.name,"invalid checkpoint");const t=e.phase;if(!(t in a.phases))throw new v(a.name,`checkpoint names unknown phase ${t}`);if(a.inflight?.includes(t))throw new v(a.name,`transition into in-flight phase ${t}; write it with rt.commit before the effect instead`);return JSON.stringify(e),e}w(L,"validateCheckpoint");class P{static{w(this,"Scheduler")}deps;enabled=!1;holds=0;dirty=!1;draining=!1;invocations=new Map;taskWaiters=new Map;inputWaiters=new Map;idleWaiters=new Set;constructor(e){this.deps=e,e.session.listeners.add(t=>{for(const n of t.changes.tasks){const i=this.invocations.get(n.id);n.abort===!0&&i?.mode==="run"&&i.controller.abort()}for(const n of t.changes.tasks)n.status==="terminal"&&this.taskWaiters.get(n.id)?.forEach(i=>{i(n)});for(const n of t.changes.inputs)(n.status==="done"||n.status==="unanswered")&&this.inputWaiters.get(n.id)?.forEach(i=>{i(n)});t.changes.tasks.length>0&&this.kick(),this.checkIdle()})}resume(){this.enabled=!0,this.kick()}stop(){this.enabled=!1}hold(){this.holds++;let e=!1;return()=>{e||(e=!0,this.holds--,this.holds===0&&this.kick())}}kick(){this.enabled&&(this.dirty=!0,this.holds===0&&!this.draining&&this.drain().catch(e=>this.deps.onReport(e)))}async drain(){this.draining=!0;try{for(;this.dirty&&this.enabled&&this.holds===0;){this.dirty=!1;const e=await this.reserveEligible();if(!this.enabled||this.holds>0){this.dirty=!0;break}for(const{task:t,mode:n}of e)this.dispatch(t,n)}}finally{this.draining=!1,this.checkIdle()}}async reserveEligible(){const{session:e}=this.deps,t=[];return await e.commit({type:"kernel"},async n=>{for(const i of[...e.liveTasks.values()]){if(!this.deps.kinds.has(i.kind))continue;const r=this.invocations.get(i.id);if(i.abort===!0){if(r?.mode==="abort"||r?.mode==="run")continue;const s=i.status==="pending"?{...i,status:"running"}:i;s!==i&&n.setTask(s),t.push({task:s,mode:"abort"});continue}if(r===void 0)if(i.status==="pending"){let s=!0;for(const d of i.after){const o=await n.task(d);if(o===void 0||o.status!=="terminal"){s=!1;break}}if(!s)continue;const l={...i,status:"running"};n.setTask(l),t.push({task:l,mode:"run"})}else i.status==="running"&&t.push({task:i,mode:"run"})}},this.deps.ctx),t}dispatch(e,t){const{session:n}=this.deps,i=this.deps.kinds.get(e.kind);if(i===void 0){this.deps.onReport(new Error(`unknown kind ${e.kind} for task ${e.id}`));return}const r=new AbortController,s=I(r.signal,this.deps.ctx),l=(async()=>{try{if(t==="run"){const d=await this.runPhases(e,i,s);if(d===void 0||r.signal.aborted)return;const o=this.lease(e,i,t,s);try{await n.commit(o.invoker,async(u,c,h)=>{const f=n.liveTasks.get(e.id);if(f===void 0||f.abort===!0)return;const g=b(i,await d(u,f,c)),p=await u.task(e.id)??f;h.setTask({...p,status:"terminal",outcome:g})},s,{closing:!0})}finally{o.token.revoke()}}else{const d=this.lease(e,i,t,s);let o;try{o=await i.abort(e,d.runtime,s)}finally{d.token.revoke()}const u=this.lease(e,i,t,s);try{await n.commit(u.invoker,async(c,h,f)=>{const g=n.liveTasks.get(e.id);if(g===void 0)return;const p=await o(c,g,h);JSON.stringify(p);const m=await c.task(e.id)??g;f.setTask({...m,status:"terminal",outcome:{status:"aborted",result:p}})},s,{closing:!0})}finally{u.token.revoke()}}}catch(d){if(r.signal.aborted)return;this.deps.onReport(d),await n.commit({type:"kernel"},async o=>{const u=n.liveTasks.get(e.id);if(u===void 0)return;const c={status:"faulted",error:d instanceof v?d.message:`${i.name}: ${String(d)}`};if(o.setTask({...u,status:"terminal",outcome:c}),i.turn){const h=u.input.inputs;Array.isArray(h)&&await o.resolveInputs(h.filter(f=>typeof f=="number"),{status:"unanswered",reason:"failed",detail:c.error}),o.sticky(u.conversationId).turn={tools:[]}}},this.deps.ctx,{docs:[{doc:"sticky",conversationId:e.conversationId}]}).catch(o=>this.deps.onReport(o))}finally{this.invocations.delete(e.id),n.liveTasks.get(e.id)===void 0&&await n.retire(e,this.deps.ctx).catch(o=>this.deps.onReport(o)),this.kick()}})();this.invocations.set(e.id,{task:e,mode:t,controller:r,done:l})}lease(e,t,n,i){const r=new S(e.id,n),s={type:"task",token:r,id:e.id,conversationId:e.conversationId,kind:t,core:e.kind.startsWith("pi.")&&["pi.generation","pi.tool","pi.post_tools","pi.collapse"].includes(e.kind),mode:n};return{token:r,invoker:s,runtime:this.deps.runtime(e,s,i)}}async runPhases(e,t,n){const{session:i}=this.deps;let r=e;for(;;){const s=r.checkpoint,l=E(t,s?.phase),d=this.lease(e,t,"run",n);let o;try{o=W(t,await l(r,d.runtime,n))}finally{d.token.revoke()}if("done"in o)return o.done;if(n.abortSignal?.aborted)return;const u=this.lease(e,t,"run",n);let c;try{c=await i.commit(u.invoker,async(h,f,g)=>{const p=i.liveTasks.get(e.id);if(p===void 0||p.abort===!0)return"discard";const m=typeof o.next=="function"?await o.next(h,p,f):o.next;if(m==="retry")return"retry";if(typeof m=="object"&&m!==null&&"status"in m){const k=await h.task(e.id)??p;return g.setTask({...k,status:"terminal",outcome:b(t,m)}),"terminal"}const y=L(t,m);return h.checkpoint(y),r={...p,checkpoint:y},"advanced"},n)}finally{u.token.revoke()}if(c.value==="retry"){r=i.liveTasks.get(e.id)??r;continue}if(c.value!=="advanced")return}}async abortTask(e,t){const{session:n}=this.deps;if((await n.commit({type:"kernel"},async s=>{const l=await s.task(e);if(l===void 0)throw new Error(`task ${e} not found`);return l.status==="terminal"?"terminal":(l.abort!==!0&&s.setTask({...l,abort:!0}),"marked")},t)).value==="terminal")return"terminal";const r=this.invocations.get(e);return r?.mode==="run"&&(r.controller.abort(),await r.done),this.kick(),"marked"}waitForTask(e,t){return this.waiter(t,this.taskWaiters,e,n=>this.deps.session.liveTasks.get(e)===void 0?this.deps.session.storage.task(e,n):Promise.resolve(void 0))}waitForInput(e,t){return this.waiter(t,this.inputWaiters,e,async n=>{const i=await this.deps.session.storage.input(e,n);return i!==void 0&&(i.status==="done"||i.status==="unanswered")?i:void 0})}async waiter(e,t,n,i){e.abortSignal?.throwIfAborted();const r=await this.deps.session.onLine(async s=>{const l=await i(s);return l!==void 0?{now:l}:{pending:new Promise((d,o)=>{const u=t.get(n)??t.set(n,new Set).get(n),c=w(f=>{u.delete(c),e.abortSignal?.removeEventListener("abort",h),d(f)},"w"),h=w(()=>{u.delete(c),o(e.abortSignal?.reason??new Error("aborted"))},"onAbort");u.add(c),e.abortSignal?.addEventListener("abort",h,{once:!0})})}},e);return"now"in r?r.now:r.pending}async waitForIdle(e,t){return t.abortSignal?.throwIfAborted(),(await this.deps.session.onLine(()=>this.isIdle(e)?{}:{pending:new Promise((i,r)=>{const s={conversationId:e,resolve:w(()=>{this.idleWaiters.delete(s),t.abortSignal?.removeEventListener("abort",l),i()},"resolve")},l=w(()=>{this.idleWaiters.delete(s),r(t.abortSignal?.reason??new Error("aborted"))},"onAbort");this.idleWaiters.add(s),t.abortSignal?.addEventListener("abort",l,{once:!0})})},t)).pending}isIdle(e){for(const t of this.deps.session.liveTasks.values())if((e===void 0||t.conversationId===e)&&!t.background)return!1;return!0}checkIdle(){for(const e of[...this.idleWaiters])this.isIdle(e.conversationId)&&!this.draining&&e.resolve()}async joinAll(){this.enabled=!1;for(const e of this.invocations.values())e.controller.abort();await Promise.allSettled([...this.invocations.values()].map(e=>e.done))}quiescent(){return this.invocations.size===0}get liveInvocations(){return this.invocations.size}}export{P as Scheduler};
@@ -1 +0,0 @@
1
- var A=Object.defineProperty;var d=(o,t)=>A(o,"name",{value:t,configurable:!0});import{isJsonValue as M}from"@earendil-works/chord";import{createContextKey as q,withContextValue as R,withoutAbortSignal as b}from"@earendil-works/chord/context";import{isBase as _,track as S}from"@earendil-works/chord/delta";import{deriveContext as B}from"./context.js";import{Membrane as N}from"./membrane.js";import{Closed as D,CollapseInProgress as j,ConversationBusy as L,Faulted as K,Forbidden as l,GenerationInProgress as F,ReadAfterWrite as C}from"./types.js";const k=d(o=>o.doc==="session"?"session":`${o.doc}:${o.conversationId}`,"docKey");function E(o,t){for(let e=o.length-1;e>=0;e--)t(o[e])&&o.splice(e,1)}d(E,"removeWhere");const W=new Set(["pi.generation","pi.tool","pi.post_tools","pi.collapse"]),U={model:d(o=>x(o,["provider","modelId"])&&o.provider!==""&&o.modelId!=="","model"),thinkingLevel:d(o=>typeof o=="string"&&["off","minimal","low","medium","high","xhigh","max"].includes(o),"thinkingLevel"),selectedTools:d(o=>Array.isArray(o)&&o.every(t=>typeof t=="string"),"selectedTools"),profile:d(o=>typeof o=="string","profile"),retry:d(o=>x(o,["enabled","maxRetries","baseDelayMs"],["maxAgentDelayMs"])&&typeof o.enabled=="boolean"&&typeof o.maxRetries=="number"&&Number.isSafeInteger(o.maxRetries)&&o.maxRetries>=0&&I(o.baseDelayMs)&&(o.maxAgentDelayMs===void 0||I(o.maxAgentDelayMs)),"retry"),threshold:d(o=>typeof o=="number"&&Number.isFinite(o),"threshold"),keepRecent:I,steeringMode:d(o=>o==="all"||o==="one-at-a-time","steeringMode"),followUpMode:d(o=>o==="all"||o==="one-at-a-time","followUpMode")};function I(o){return typeof o=="number"&&Number.isFinite(o)&&o>=0}d(I,"finiteNonnegative");function x(o,t,e=[]){if(o===null||typeof o!="object"||Array.isArray(o))return!1;const s=Object.keys(o);return t.every(n=>Object.hasOwn(o,n))&&s.every(n=>t.includes(n)||e.includes(n))}d(x,"exactObject");const H=d(o=>W.has(o),"isCoreKind");class J{static{d(this,"Defaults")}rewindable={};sticky={};route=new Map;owners=new Map;constructor(t){for(const e of t)this.register(e)}register(t){const e=["rewindable","sticky"].flatMap(n=>Object.entries(t.config?.[n]??{}).map(([i,r])=>({doc:n,key:i,value:r}))),s=new Set;for(const{key:n}of e){if(s.has(n)||this.route.has(n))throw new Error(`config key "${n}" declared by more than one kind`);s.add(n)}for(const{doc:n,key:i,value:r}of e)this.route.set(i,n),this.owners.set(i,t),r!==void 0&&(this[n][i]=structuredClone(r))}unregister(t){for(const[e,s]of this.owners){if(s!==t)continue;this.owners.delete(e);const n=this.route.get(e);this.route.delete(e),n!==void 0&&delete this[n][e]}}validate(t,e){if(!M(e))return!1;const s=U[t];return s!==void 0?s(e):this.route.has(t)}validateSeed(t,e){const s={};for(const[n,i]of Object.entries(e))if(i!==void 0){if(this.route.get(n)!==t||!this.validate(n,i))throw new TypeError(`invalid ${t} config value for "${n}"`);s[n]=structuredClone(i)}return s}fill(t,e){for(const[s,n]of Object.entries(this[t]))s in e||(e[s]=structuredClone(n))}freshRewindable(t={},e=!1){const s={plugins:{}};this.fill("rewindable",s);const{plugins:n,...i}=t,r=e?i:this.validateSeed("rewindable",i);return{...s,...r,...e&&n!==void 0?{plugins:structuredClone(n)}:{}}}freshSticky(t={}){const e={inbox:[],turn:{tools:[]},tasks:{},plugins:{}};this.fill("sticky",e);const{inbox:s,turn:n,tasks:i,plugins:r,...a}=t;return{...e,...this.validateSeed("sticky",a)}}}class V{static{d(this,"Docs")}trackers=new Map;storage;defaults;sinceBase=new Map;constructor(t,e){this.storage=t,this.defaults=e}noteOps(t,e){const s=k(t);this.sinceBase.set(s,_(e)?0:(this.sinceBase.get(s)??0)+JSON.stringify(e).length)}requestBase(t){this.trackers.get(k(t))?.rebase()}async get(t,e){const s=k(t),n=this.trackers.get(s);if(n!==void 0)return n;const i=await this.storage.doc(t,e);if(i===void 0)throw new Error(`document ${s} does not exist`);t.doc!=="session"&&this.defaults.fill(t.doc,i);const r=S(i);return r.flush(),this.trackers.set(s,r),r}evict(t){this.trackers.delete(k(t))}peek(t){return this.trackers.get(k(t))}loaded(t){return this.trackers.get(k(t))?.target}adopt(t,e){this.trackers.set(k(t),e)}}const P=["conversation","entry","entries","newestEntry","scanEntries","context","task","tasks","input","rewindableAsOf","snapshot","plugins","emit","config","write","createTask","createConversation"],z=["checkpoint","slot"],G=["rewindable","sticky","session","toolSlot","appendEntry","send","resolveInputs","boundary","markTask","setTask","withdrawInput","createOwnedConversation","createForkConversation"],X=new Set([...P,...z,...G]);class Y{static{d(this,"TxImpl")}writes=[];touched=new Map;membrane=new N("tx");createdTasks=new Map;createdEntries=new Map;createdConversations=new Map;inputsById=new Map;inputsByRequest=new Map;namespaceViews=new Map;changedConfig=new Map;wroteEntries=new Set;wroteTasks=!1;poisoned;surfaceActive=!0;closing=!1;changes={entries:[],tasks:[],inputs:[],conversations:[],docs:[],events:[]};invoker;storage;docs;defaults;kinds;namespaces;liveTasks;conversations;now;ctx;constructor(t,e,s,n,i,r,a,h,w,u){this.invoker=t,this.storage=e,this.docs=s,this.defaults=n,this.kinds=i,this.namespaces=r,this.liveTasks=a,this.conversations=h,this.now=w,this.ctx=u}callbackSurface(){const t=this,e=new Map,s=Object.freeze(Object.create(null));return new Proxy(s,{get:d((n,i)=>{if(typeof i!="string"||!X.has(i))return;const r=e.get(i);if(r!==void 0)return r;const a=t[i];if(typeof a!="function")throw new Error(`transaction method ${i} is missing`);const h=d((...w)=>(this.assertSurfaceActive(),Reflect.apply(a,this,w)),"bound");return e.set(i,h),h},"get")})}closeSurface(){this.surfaceActive=!1}assertSurfaceActive(){if(!this.surfaceActive)throw new TypeError("transaction used outside its callback")}get core(){return this.invoker.type==="kernel"||this.invoker.type==="task"&&this.invoker.core}assertCore(t){if(!this.core)throw new l(`${t}: core turn machinery only`)}assertNotHost(t){if(this.invoker.type!=="task")throw new l(`${t} outside a task`)}inScope(t){if(this.invoker.type!=="task"||this.invoker.core||t===this.invoker.conversationId||this.createdConversations.has(t))return!0;const e=this.createdTasks.get(this.invoker.id)??this.liveTasks.get(this.invoker.id);for(const s of e?.owns??[])if(this.conversations.subtree(s).has(t))return!0;return!1}assertScope(t,e){if(!this.inScope(t))throw new l(`${e}: conversation ${t} is outside this task's subtree`)}assertEntryScope(t,e){if(this.inScope(t.conversationId))return;if(this.invoker.type!=="task"||this.invoker.core)throw new l(`${e}: entry ${t.id} is outside this task's subtree`);const s=new Set([this.invoker.conversationId,...this.createdConversations.keys()]),n=this.createdTasks.get(this.invoker.id)??this.liveTasks.get(this.invoker.id);for(const i of n?.owns??[])for(const r of this.conversations.subtree(i))s.add(r);for(const i of s){let r=this.createdConversations.get(i)??this.conversations.get(i);for(;r?.parent!==void 0;){if(r.parent.conversationId===t.conversationId&&t.id<=r.parent.at)return;r=this.conversations.get(r.parent.conversationId)}}throw new l(`${e}: entry ${t.id} is not visible from this task's subtree`)}poison(t){throw this.poisoned??=t,t}assertNoEntryWrites(t,e){this.wroteEntries.has(t)&&this.poison(new C(e,"entry append"))}assertNoTaskWrites(t){this.wroteTasks&&this.poison(new C(t,"task write"))}get poison_(){return this.poisoned}async conversation(t){return this.assertScope(t,"conversation"),this.createdConversations.get(t)??await this.storage.conversation(t,this.ctx)}async entry(t,e){const s=typeof t=="number"?t:e,n=this.createdEntries.get(s)??(await this.storage.entries([s],this.ctx)).get(s);return n!==void 0&&this.assertEntryScope(n,"entry"),typeof t=="number"||t.is(n)?n:void 0}async entries(t){const e=await this.storage.entries(t.filter(s=>!this.createdEntries.has(s)),this.ctx);for(const s of t){const n=this.createdEntries.get(s);n&&e.set(s,n)}for(const s of e.values())this.assertEntryScope(s,"entries");return e}async newestEntry(t,e={}){this.assertScope(t,"newestEntry"),this.assertNoEntryWrites(t,"newestEntry");const s="is"in e?{kind:e.kind}:e,[n]=await this.storage.scanEntries({conversationId:t,...s,limit:1},this.ctx);return n}scanEntries(t){return this.assertScope(t.conversationId,"scanEntries"),this.assertNoEntryWrites(t.conversationId,"scanEntries"),this.storage.scanEntries(t,this.ctx)}async context(t,e){return this.assertScope(t,"context"),this.assertNoEntryWrites(t,"context"),B(this.storage,t,e,this.ctx)}async task(t){const e=typeof t=="number"?t:t.id,s=this.createdTasks.get(e)??this.liveTasks.get(e)??await this.storage.task(e,this.ctx);return s!==void 0&&this.assertScope(s.conversationId,"task"),s}async tasks(t){this.assertNoTaskWrites("tasks"),t.conversationId!==void 0&&this.assertScope(t.conversationId,"tasks");const e=await this.storage.scanTasks(t,this.ctx),s=new Set(e.map(n=>n.id));for(const n of this.liveTasks.values())!s.has(n.id)&&(t.conversationId===void 0||n.conversationId===t.conversationId)&&(t.kind===void 0||n.kind===t.kind)&&e.push(n);return e.filter(n=>t.status===void 0||t.status.includes(n.status))}async input(t){const e=this.inputsById.get(t)??await this.storage.input(t,this.ctx);return e!==void 0&&this.assertScope(e.conversationId,"input"),e}async inputByRequest(t,e){return this.assertScope(t,"inputByRequest"),this.inputsByRequest.get(`${t}:${e}`)??await this.storage.inputByRequest(t,e,this.ctx)}async rewindableAsOf(t,e){return this.assertScope(t,"rewindableAsOf"),this.storage.docAsOf(t,e,this.ctx)}snapshot(t){t.doc!=="session"&&this.assertScope(t.conversationId,"snapshot");const e=structuredClone(this.doc(t).target);if(t.doc!=="session"&&(this.defaults.fill(t.doc,e),this.invoker.type==="task"))for(const[s,n]of Object.entries(this.invoker.kind.config?.[t.doc]??{}))!(s in e)&&n!==void 0&&(e[s]=structuredClone(n));return e}doc(t){const e=k(t),s=this.touched.get(e);if(s!==void 0)return s.tracker;const n=this.docs.peek(t);if(n!==void 0)return this.touched.set(e,{ref:t,tracker:n}),n;throw new Error(`document ${e} not loaded; pass it in commit({ docs })`)}view(t){return this.membrane.wrap(this.doc(t).state)}async preload(t){for(const e of t){const s=k(e);this.touched.has(s)||this.touched.set(s,{ref:e,tracker:await this.docs.get(e,this.ctx)})}}rewindable(t){return this.assertCore("rewindable document"),this.view({doc:"rewindable",conversationId:t})}sticky(t){return this.assertCore("sticky document"),this.view({doc:"sticky",conversationId:t})}session(){return this.assertCore("session document"),this.view({doc:"session"})}raw(t){return this.view(t)}plugins(t){const e=this.namespaces.get(t.id);if(e?.token!==t)throw new l(`namespace "${t.id}" is stale`);const s=this.namespaceViews.get(t);if(s!==void 0)return s;const n=this.invocationConversationId(`plugins(${t.id})`),i={};for(const[a,h]of e.routes){const w=h==="session"?{doc:h}:{doc:h,conversationId:n},u=this.raw(w);Object.hasOwn(u.plugins,t.id)||(u.plugins[t.id]={});const f=u.plugins[t.id],g=e.defaults[h][a];!(a in f)&&g!==void 0&&(f[a]=y(g)),Object.defineProperty(i,a,{enumerable:!0,get:d(()=>f[a],"get"),set:d(c=>{f[a]=c},"set")})}Object.preventExtensions(i);const r=this.membrane.wrap(i);return this.namespaceViews.set(t,r),r}emit(t,e,s){const n=this.invocationConversationId("emit");if("id"in t&&"unregister"in t){if(this.namespaces.get(t.id)?.token!==t)throw new l(`namespace "${t.id}" is stale`);if(e===void 0||s===void 0||!/^[a-z][a-z0-9_.-]*$/i.test(e))throw new Error("invalid plugin event");this.changes.events.push({conversationId:n,event:{type:`plugin.${t.id}.${e}`,data:y(s)}});return}this.assertCore("core event"),this.changes.events.push({conversationId:n,event:y(t)})}invocationConversationId(t){const e=this.invoker.conversationId;if(e===void 0)throw new l(`${t}: no conversation is bound to this transaction`);return this.assertScope(e,t),e}config(t){this.assertScope(t,"config");const e=d(n=>{if(this.invoker.type==="task")for(const r of["rewindable","sticky"]){const a=this.invoker.kind.config?.[r];if(a!==void 0&&Object.hasOwn(a,n))return{doc:r,fallback:a[n]}}const i=this.defaults.route.get(n);if(i===void 0)throw new Error(`unknown config key "${n}"`);return{doc:i,fallback:this.defaults[i][n]}},"definition"),s=d(n=>{if(this.invoker.type==="task"&&!this.invoker.core)throw new l(`config(${n}): ordinary tasks cannot write config`)},"assertWritable");return{get:d(n=>{this.assertSurfaceActive();const{doc:i,fallback:r}=e(n),a=this.doc({doc:i,conversationId:t}).target;return n in a?structuredClone(a[n]):structuredClone(r)},"get"),set:d((n,i)=>{this.assertSurfaceActive(),s(n);const{doc:r}=e(n);if(!this.defaults.validate(n,i))throw new TypeError(`invalid config value for "${n}"`);this.raw({doc:r,conversationId:t})[n]=structuredClone(i);const a=this.changedConfig.get(t)??new Set;a.add(n),this.changedConfig.set(t,a)},"set"),reset:d(n=>{this.assertSurfaceActive(),s(n);const{doc:i}=e(n);delete this.raw({doc:i,conversationId:t})[n];const r=this.changedConfig.get(t)??new Set;r.add(n),this.changedConfig.set(t,r)},"reset")}}slot(t){this.assertNotHost("slot");const e=this.invoker,s=this.liveTasks.get(t.id)??this.createdTasks.get(t.id);if(s===void 0)throw new Error(`task ${t.id} is not live`);if(!e.core&&t.id!==e.id)throw new l("slot: another task's slot");const n=this.raw({doc:"sticky",conversationId:s.conversationId});return String(t.id)in n.tasks||(n.tasks[t.id]=(t.kind.slot??(()=>({})))(s.input)),n.tasks[t.id]}toolSlot(t){this.assertCore("toolSlot");const e=this.raw({doc:"sticky",conversationId:t.conversationId}).turn.tools[t.input.index];if(e===void 0)throw new Error(`no tool slot at index ${t.input.index}`);return e}appendEntry(t,e,s){return this.assertCore("appendEntry"),"is"in e?{id:this.appendEntryInternal(t,{...s,kind:e.kind}),kind:e}:this.appendEntryInternal(t,e)}appendEntryInternal(t,e){if(this.invoker.type==="task"&&!this.liveTasks.has(this.invoker.id)&&!this.closing)throw new l("appendEntry from a task that is not live");const s=this.storage.mintId(),n=e.head==="self"?s:e.head,{head:i,...r}=e,a=y({...r,id:s,conversationId:t,...n===void 0?{}:{head:n},...this.invoker.type==="task"?{byTaskId:this.invoker.id}:{}});return Q(a),this.writes.push({type:"entry",entry:a}),this.changes.entries.push(a),a.head!==void 0&&this.changes.events.push({conversationId:t,event:{type:"head.moved",entry:a}}),this.changes.events.push({conversationId:t,event:{type:"entry.added",entry:a}}),this.createdEntries.set(s,a),this.wroteEntries.add(t),s}async write(t,e,s){this.assertScope(t,"write");const n="is"in e?{...s,kind:e.kind}:e;if(!this.core){if(n.head!==void 0)throw new l("write: head entries are core only");if(n.edits!==void 0)throw new l("write: edits are core only");if(n.kind.startsWith("pi.")&&n.kind!=="pi.notice")throw new l(`write: kind ${n.kind} is reserved`);if(n.kind==="pi.notice"&&(n.model?.length!==1||n.model[0]?.role!=="user"))throw new l("write: pi.notice requires exactly one user model message")}if(this.busy(t)){const a=this.storage.mintId();return this.raw({doc:"sticky",conversationId:t}).inbox.push({id:a,mode:"write",entry:structuredClone(n)}),this.putInput({id:a,conversationId:t,status:"queued"}),this.changes.events.push({conversationId:t,event:{type:"input.queued",input:a,mode:"write"}}),a}const i=this.storage.mintId(),r=this.appendEntryInternal(t,n);return this.putInput({id:i,conversationId:t,status:"done",entry:r}),i}checkpoint(t){this.assertNotHost("checkpoint");const e=this.invoker;if(e.mode==="abort")throw new l("checkpoint from an abort invocation");const s=this.createdTasks.get(e.id)??this.liveTasks.get(e.id);if(s===void 0)throw new Error("task not live");this.setTaskInternal({...s,checkpoint:y(t)})}setTask(t){this.assertCore("setTask"),this.setTaskInternal(t)}setTaskInternalForControl(t){this.setTaskInternal(t)}setTaskInternal(t){t=y(t);const e=this.createdTasks.get(t.id)??this.liveTasks.get(t.id),s={id:t.id};for(const n of["status","checkpoint","abort","outcome","owns"])JSON.stringify(e?.[n])!==JSON.stringify(t[n])&&(s[n]=n==="checkpoint"&&t.checkpoint===void 0?null:t[n]);if(t.status==="terminal"&&(s.status="terminal",s.checkpoint=null,s.owns=t.owns,s.outcome=t.outcome,t.abort===!0&&(s.abort=!0),t={...t},delete t.checkpoint),Object.keys(s).length!==1){if(t.status==="terminal"&&delete this.raw({doc:"sticky",conversationId:t.conversationId}).tasks[t.id],this.writes.push({type:"task.patch",patch:s}),this.changes.tasks.push(t),t.status==="terminal"&&e?.status!=="terminal"){const n=this.kinds.get(t.kind);if(t.kind==="pi.collapse"){if(t.outcome?.status==="completed"){const i=t.outcome.result;this.changes.events.push({conversationId:t.conversationId,event:{type:"compaction.finished",taskId:t.id,summary:i.summary}})}else if(t.outcome?.status==="failed"){const i=t.outcome.failure;this.changes.events.push({conversationId:t.conversationId,event:{type:"compaction.failed",taskId:t.id,reason:i.reason,detail:i.detail}})}}else(n===void 0||n.turn!==!0)&&t.outcome!==void 0&&this.changes.events.push({conversationId:t.conversationId,event:{type:"task.ended",taskId:t.id,kind:t.kind,outcome:t.outcome.status}})}this.createdTasks.set(t.id,t),this.wroteTasks=!0}}createTask(t,e,s={}){if("initial"in t){if(this.kinds.get(t.name)!==t)throw new l(`createTask: kind "${t.name}" is not the registered token`);return{id:this.createTaskInternal({kind:t.name,input:e,...s}),kind:t}}return this.assertCore("createTask by name"),this.createTaskInternal(t)}createTaskInternal(t){const e=this.kinds.get(t.kind);if(e===void 0)throw new Error(`unknown task kind ${t.kind}`);if(H(t.kind)&&!this.core)throw new l(`create core task ${t.kind}`);const s=t.conversationId??(this.invoker.type==="task"?this.invoker.conversationId:void 0);if(s===void 0)throw new Error("createTask: conversationId required");if(this.assertScope(s,"createTask"),t.kind==="pi.generation"&&this.hasLiveKind(s,t.kind))throw new F(s);if(t.kind==="pi.collapse"&&this.hasLiveKind(s,t.kind))throw new j(s);const n=this.storage.mintId(),i={id:n,conversationId:s,kind:t.kind,input:y(t.input),status:"pending",after:[...t.after??[]],owns:[],...t.background?{background:!0}:{}};if(this.writes.push({type:"task",task:i}),this.changes.tasks.push(i),t.kind==="pi.collapse"){const r=t.input;this.changes.events.push({conversationId:s,event:{type:"compaction.started",taskId:n,reason:r.reason,through:r.through}})}else e.turn!==!0&&this.changes.events.push({conversationId:s,event:{type:"task.started",taskId:n,kind:i.kind,...i.background?{background:!0}:{}}});return this.createdTasks.set(n,i),this.wroteTasks=!0,n}hasLiveKind(t,e){for(const s of this.liveTasks.values())if(!(s.conversationId!==t||s.kind!==e||(this.createdTasks.get(s.id)??s).status==="terminal")&&!(this.closing&&this.invoker.type==="task"&&this.invoker.id===s.id))return!0;for(const s of this.createdTasks.values())if(s.conversationId===t&&s.kind===e&&s.status!=="terminal"&&!this.liveTasks.has(s.id))return!0;return!1}createConversation(t){const e=this.invoker.type==="task"?this.invoker.id:void 0;return t.parent!==void 0&&this.assertScope(t.parent.conversationId,"createConversation: parent"),this.insertConversation(t,e,!1)}createForkConversation(t){return this.assertCore("createForkConversation"),this.insertConversation(t,void 0,!0)}async createOwnedConversation(t,e,s){this.assertCore("createOwnedConversation");const n=this.liveTasks.get(t)??this.createdTasks.get(t);if(n===void 0||n.status==="terminal"||n.conversationId!==e)throw new l(`task ${t} cannot create an owned conversation`);const i=s.inherit?await this.newestEntry(e):void 0,r=i===void 0?void 0:await this.rewindableAsOf(e,i.id),a=structuredClone(s.rewindable??{});delete a.plugins;const h=this.defaults.validateSeed("rewindable",a),w=r===void 0?h:{...r,...h,plugins:structuredClone(r.plugins)};return this.insertConversation({...i===void 0?{}:{parent:{conversationId:e,at:i.id}},rewindable:w,sticky:s.sticky},t,r!==void 0)}insertConversation(t,e,s){const n=this.storage.mintId(),i=t.parent===void 0||t.parent.at==="start"?void 0:{conversationId:t.parent.conversationId,at:t.parent.at},r={id:n,...i?{parent:i}:{},...e===void 0?{}:{owner:e},...t.sections?.length?{sections:t.sections}:{}};if(this.writes.push({type:"conversation",conversation:r}),this.changes.conversations.push(r),this.createdConversations.set(n,r),this.seedDoc({doc:"rewindable",conversationId:n},this.defaults.freshRewindable(t.rewindable,s)),this.seedDoc({doc:"sticky",conversationId:n},this.defaults.freshSticky(t.sticky)),e!==void 0){const a=this.liveTasks.get(e)??this.createdTasks.get(e);a!==void 0&&this.setTaskInternal({...a,owns:[...a.owns,n]})}return n}seedDoc(t,e){const s=S(e);s.rebase();const n=s.flush();this.writes.push({type:"doc",ref:t,ops:n}),this.changes.docs.push({ref:t,ops:n}),this.docs.adopt(t,s),this.touched.set(k(t),{ref:t,tracker:s})}markTask(t){this.assertCore("markTask");const e=this.createdTasks.get(t)??this.liveTasks.get(t);if(e===void 0)throw new Error(`task ${t} not live`);e.abort!==!0&&this.setTaskInternal({...e,abort:!0})}busy(t){const e=d(s=>this.kinds.get(s.kind)?.turn===!0&&s.background!==!0,"isTurn");for(const s of this.liveTasks.values())if(!(s.conversationId!==t||!e(s)||this.createdTasks.get(s.id)?.status==="terminal")&&!(this.closing&&this.invoker.type==="task"&&s.id===this.invoker.id))return!0;for(const s of this.createdTasks.values())if(s.conversationId===t&&e(s)&&s.status!=="terminal"&&!this.liveTasks.has(s.id))return!0;return!1}putInput(t){t=y(t),this.writes.push({type:"input",input:t}),this.changes.inputs.push(t),this.inputsById.set(t.id,t),t.requestId!==void 0&&this.inputsByRequest.set(`${t.conversationId}:${t.requestId}`,t)}async send(t,e){if(this.assertCore("send"),e.requestId!==void 0){const u=await this.inputByRequest(t,e.requestId);if(u!==void 0)return u.id}if(this.busy(t)){const u=e.whenBusy??"followUp";if(u==="reject")throw new L(t);const f=this.storage.mintId();return this.raw({doc:"sticky",conversationId:t}).inbox.push({id:f,mode:u,input:structuredClone(e.content)}),this.putInput({id:f,conversationId:t,status:"queued",...e.requestId?{requestId:e.requestId}:{}}),this.changes.events.push({conversationId:t,event:{type:"input.queued",input:f,mode:u}}),f}const s=await this.newestEntry(t,{withHead:!0}),{triggers:n}=await this.boundary(t,"final",s?.id),i=this.storage.mintId(),r=this.changes.events.length,a=this.appendEntryInternal(t,{kind:"pi.user",model:[{role:"user",content:e.content,timestamp:this.now()}]}),h=this.changes.events.splice(r);this.putInput({id:i,conversationId:t,status:"placed",entry:a,...e.requestId?{requestId:e.requestId}:{}}),this.changes.events.push({conversationId:t,event:{type:"input.placed",input:i,entry:a}},...h);const w=[...n,i];return this.createTaskInternal({kind:"pi.generation",conversationId:t,input:{inputs:w}}),this.changes.events.push({conversationId:t,event:{type:"turn.started",inputs:w}}),i}async setInput(t,e){const s=await this.input(t);if(s===void 0)throw new Error(`input ${t} not found`);this.putInput({...s,...e})}async withdrawInput(t){this.assertCore("withdrawInput");const e=await this.input(t);return e===void 0?"not_found":e.status!=="queued"?"already_placed":(await this.preload([{doc:"sticky",conversationId:e.conversationId}]),E(this.raw({doc:"sticky",conversationId:e.conversationId}).inbox,s=>s.id===t),await this.setInput(t,{status:"unanswered",reason:"aborted"}),this.changes.events.push({conversationId:e.conversationId,event:{type:"input.aborted",input:t}}),"aborted")}async resolveInputs(t,e){this.assertCore("resolveInputs");for(const s of t)await this.setInput(s,e)}async boundary(t,e,s){this.assertCore("boundary");const n=this.raw({doc:"sticky",conversationId:t}),i=[...n.inbox].sort((c,v)=>c.id-v.id);let r;for(const c of i)c.mode==="write"&&c.entry.head==="self"&&(r=c.id);const a=r===void 0?[]:i.filter(c=>c.mode!=="write"&&c.id<r).map(c=>c.id);for(const c of a)await this.setInput(c,{status:"unanswered",reason:"stale"}),this.changes.events.push({conversationId:t,event:{type:"input.aborted",input:c}});const h=i.filter(c=>!a.includes(c.id)),w=d((c,v)=>{const p=h.filter(m=>m.mode===c);return v==="all"?p:p.slice(0,1)},"pick"),u=new Set(a);for(const c of h)c.mode==="write"&&u.add(c.id);for(const c of w("steer",n.steeringMode))u.add(c.id);if(e==="final")for(const c of w("followUp",n.followUpMode))u.add(c.id);let f=s;const g=[];for(const c of h)if(u.has(c.id))if(c.mode==="write"){if(c.entry.head!==void 0&&c.entry.head!=="self"&&f!==void 0&&c.entry.head<f){await this.setInput(c.id,{status:"unanswered",reason:"stale"}),this.changes.events.push({conversationId:t,event:{type:"input.aborted",input:c.id}});continue}const v=this.changes.events.length,p=this.appendEntryInternal(t,c.entry),m=this.changes.events.splice(v);c.entry.head!==void 0&&(f=c.entry.head==="self"?p:c.entry.head),await this.setInput(c.id,{status:"done",entry:p}),this.changes.events.push({conversationId:t,event:{type:"input.placed",input:c.id,entry:p}},...m)}else{const v=this.changes.events.length,p=this.appendEntryInternal(t,{kind:"pi.user",model:[{role:"user",content:c.input,timestamp:this.now()}]}),m=this.changes.events.splice(v);await this.setInput(c.id,{status:"placed",entry:p}),this.changes.events.push({conversationId:t,event:{type:"input.placed",input:c.id,entry:p}},...m),g.push(c.id)}return E(n.inbox,c=>u.has(c.id)),{triggers:g,terminated:r!==void 0}}finish(){if(this.poisoned!==void 0)throw this.poisoned;for(const[t,e]of this.changedConfig)this.changes.events.push({conversationId:t,event:{type:"config.changed",keys:[...e]}});for(const{ref:t,tracker:e}of this.touched.values()){const s=e.flush();s.length!==0&&(this.writes.push({type:"doc",ref:t,ops:s}),this.changes.docs.push({ref:t,ops:s}),this.docs.noteOps(t,s))}return this.writes}revoke(){this.membrane.revoke()}evictTouched(){for(const{ref:t}of this.touched.values())this.docs.evict(t)}}const y=d(o=>JSON.parse(JSON.stringify(o)),"plain");function Q(o){if(o.head!==void 0&&o.head>o.id)throw new Error(`entry ${o.id}: head ${o.head} is in the future`);if(o.model!==void 0){for(const t of o.model)if(typeof t!="object"||t===null||typeof t.role!="string")throw new Error(`entry ${o.id}: malformed model message`)}JSON.stringify(o)}d(Q,"validateEntry");const $=q("pico3.session.line"),T=new WeakMap;class Z extends Error{static{d(this,"NestedLineOperation")}constructor(){super("nested line operation"),this.name="NestedLineOperation"}}class O{static{d(this,"Session")}storage;kinds;namespaces;tail=Promise.resolve();closed=!1;fault;now;docs;defaults;liveTasks=new Map;conversationRecords=new Map;lineListeners=new Set;listeners=new Set;onReport=d(()=>{},"onReport");constructor(t,e,s,n=Date.now){if(this.storage=t,this.now=n,this.kinds=e,this.namespaces=s,T.has(t))throw new Error("this Storage already has an owning Session");this.defaults=new J(e.values()),this.docs=new V(t,this.defaults),T.set(t,this)}index={get:d(t=>this.conversationRecords.get(t),"get"),subtree:d(t=>{const e=new Set([t]);let s=!0;for(;s;){s=!1;for(const n of this.conversationRecords.values()){if(e.has(n.id)||n.owner===void 0)continue;const i=this.liveTasks.get(n.owner)??this.ownerTaskCache.get(n.owner);i&&e.has(i.conversationId)&&(e.add(n.id),s=!0)}}return e},"subtree"),ancestors:d(t=>{const e=[];let s=this.conversationRecords.get(t);for(;s?.owner!==void 0;){const n=this.liveTasks.get(s.owner)??this.ownerTaskCache.get(s.owner);if(n===void 0)break;e.unshift(n.conversationId),s=this.conversationRecords.get(n.conversationId)}return e},"ancestors")};ownerTaskCache=new Map;async commit(t,e,s,n={}){s.abortSignal?.throwIfAborted();const i=Object.freeze({...t}),r=await this.enter(s,async a=>{if(this.assertUsable(),a.abortSignal?.throwIfAborted(),i.type==="task"){if(!i.token.alive)throw new l("commit from a finished invocation");const f=this.liveTasks.get(i.id);if(f===void 0)throw new l("commit from a task that is not live");if(i.mode==="run"&&f.abort===!0)throw new l("commit from a marked run invocation")}const h=new Y(i,this.storage,this.docs,this.defaults,this.kinds,this.namespaces,this.liveTasks,this.index,this.now,a);h.closing=n.closing===!0;const w=[{doc:"session"},...n.docs??[]];i.type==="task"&&w.push({doc:"rewindable",conversationId:i.conversationId},{doc:"sticky",conversationId:i.conversationId});let u=!1;try{await h.preload(w);let f;try{f=await e(h.callbackSurface(),a,{setTask:d(p=>h.setTaskInternalForControl(p),"setTask")})}finally{h.closeSurface()}await h.preload([...new Set(h.changes.tasks.map(p=>p.conversationId))].map(p=>({doc:"sticky",conversationId:p})));const g=h.finish();let c;if(g.length>0||h.changes.events.length>0){u=!0;try{c=await this.storage.commit(g,b(a))}catch(p){this.fault=new K(p);try{await this.storage.close(b(a)),T.delete(this.storage)}catch{}throw this.fault}this.applyChanges(h.changes)}const v={value:f,seq:c,changes:h.changes};if(c!==void 0)for(const p of this.lineListeners)try{p(v)}catch(m){try{this.onReport(m)}catch{}}return v}catch(f){throw u||h.evictTouched(),f}finally{h.revoke()}});if(r.seq!==void 0)for(const a of this.listeners)try{a(r)}catch(h){this.onReport(h)}return r}read(t,e){return this.enter(e,s=>(this.assertUsable(),t(this.storage,s)))}onLine(t,e){return this.enter(e,s=>(this.assertUsable(),t(s)))}static STICKY_BASE_BUDGET=256*1024;async retire(t,e){const s={doc:"sticky",conversationId:t.conversationId},n=![...this.liveTasks.values()].some(r=>r.conversationId===t.conversationId),i=(this.docs.sinceBase.get(k(s))??0)>O.STICKY_BASE_BUDGET;await this.commit({type:"kernel"},r=>{delete r.sticky(t.conversationId).tasks[t.id],(n||i)&&this.docs.requestBase(s)},e,{docs:[s]}),(n||i)&&await this.enter(e,r=>this.storage.truncate(s,b(r)))}async fork(t,e,s,n){const i=e==="start"?void 0:await this.read(async(u,f)=>{const[g]=await u.scanEntries({conversationId:t,before:e+1,limit:1},f);if(g?.id!==e)throw new Error(`entry ${e} is not visible from conversation ${t}`);return u.docAsOf(t,e,f)},n),r=structuredClone(s.rewindable??{});delete r.plugins;const a=this.defaults.validateSeed("rewindable",r),h=i===void 0?a:{...i,...a,plugins:structuredClone(i.plugins)};return(await this.commit({type:"kernel"},u=>u.createForkConversation({parent:{conversationId:t,at:e},rewindable:h,sticky:s.sticky,sections:s.sections}),n)).value}async close(t){await this.enter(t,async e=>{this.closed||(await this.storage.close(b(e)),this.closed=!0,T.delete(this.storage))})}loadedDocument(t){return this.docs.loaded(t)}applyChanges(t){for(const e of t.tasks)e.status==="terminal"?(this.liveTasks.delete(e.id),e.owns.length&&this.ownerTaskCache.set(e.id,e)):this.liveTasks.set(e.id,e);for(const e of t.conversations)this.conversationRecords.set(e.id,e)}enter(t,e){if(t.value($)===!0)return Promise.reject(new Z);const s=this.tail;let n;return this.tail=new Promise(i=>{n=i}),(async()=>{await s;try{return await e(R($,!0,t))}finally{n()}})()}assertUsable(){if(this.fault!==void 0)throw this.fault;if(this.closed)throw new D}}export{J as Defaults,Z as NestedLineOperation,O as Session,H as isCoreKind,E as removeWhere};
@@ -1,8 +0,0 @@
1
- var $=Object.defineProperty;var l=(t,e)=>$(t,"name",{value:e,configurable:!0});function w(t){return Object.freeze(t)}l(w,"defineSystemSection");const j={identity:w({key:"identity",render:l(t=>t,"render")}),environment:w({key:"environment",render:l(t=>`Working directory: ${t.cwd}`,"render")}),skills:w({key:"skills",render:l(t=>t.map(e=>`- ${e.name}: ${e.description}`).join(`
2
- `),"render")})},A=l((t,e)=>({key:t.key,value:e}),"sectionSeed"),J=l(t=>({key:t,remove:!0}),"removeSection");async function x(t,e){const n=[];let r,a=null;e:for(;;){const i=await t.scanEntries({conversationId:e,kind:"pi.system",limit:64,...r===void 0?{}:{before:r}});for(const s of i)if(n.push(s),s.data.baseline){a=s.id;break e}if(i.length<64)break;r=i[i.length-1].id}n.reverse();const c=new Map;for(const i of n)for(const s of i.data.sections)s.action==="remove"?c.delete(s.key):c.set(s.key,{value:s.value,rendered:s.rendered});return{canonical:c,newestManaged:n[n.length-1]?.id??null,newestBaseline:a}}l(x,"foldCanonical");class T{static{l(this,"Draft")}values=new Map;wrappers=new Map;touched=new Set;constructor(e){for(const[n,r]of e)this.values.set(n,r.value)}get(e){const n=this.values.get(e.key);return n===void 0?void 0:structuredClone(n)}set(e,n){this.values.set(e.key,n),this.touched.add(e.key)}delete(e){this.values.delete(e.key),this.wrappers.delete(e.key),this.touched.add(e.key)}wrap(e,n){(this.wrappers.get(e.key)??this.wrappers.set(e.key,[]).get(e.key)).push(n),this.touched.add(e.key)}snapshot(){return{values:new Map(this.values),wrappers:new Map([...this.wrappers].map(([e,n])=>[e,[...n]])),touched:new Set(this.touched)}}restore(e){this.values=e.values,this.wrappers=e.wrappers,this.touched=e.touched}}function O(t,e,n){const r=new Map;for(const[a,c]of t.values){if(!t.touched.has(a)){const d=e.get(a);d&&r.set(a,d);continue}const i=n.get(a);if(i===void 0)continue;let s=i.render(c);for(const d of t.wrappers.get(a)??[])s=d(s);r.set(a,{value:c,rendered:s})}return r}l(O,"freeze");const N=l((t,e)=>JSON.stringify(t)===JSON.stringify(e),"sameSnapshot");async function R(t,e,n,r){const{canonical:a,newestManaged:c,newestBaseline:i}=await x(t,e),s=await t.newestEntry(e,{withHead:!0}),d=t.snapshot({doc:"rewindable",conversationId:e}),y=await t.conversation(e);return{snapshot:{newestManaged:c,newestBaseline:i,newestHead:s?.id??null,settings:{...d.model===void 0?{}:{model:d.model},thinkingLevel:d.thinkingLevel,selectedTools:[...d.selectedTools],profile:d.profile},sectionsRev:n.revision,toolsRev:r.revision},canonical:a,seed:c===null?y?.sections:void 0}}l(R,"takeSnapshot");async function E(t,e,n,r,a,c,i){const s=new T(n);for(const f of r??[])"remove"in f?s.delete({key:f.key}):s.set({key:f.key,render:l(()=>"","render")},f.value);const d=[];for(const f of a.selectedTools){const p=t.tools.get(f);p?d.push(p):c(`selected tool ${f} is not registered`)}let y=d;for(const f of t.hooks.handlers()){const p=s.snapshot();try{const m=await f.handlers.systemInstructions?.({sections:s,config:a,tools:d},f.api,i);m?.tools&&(y=m.tools)}catch(m){if(i.abortSignal?.aborted)throw m;s.restore(p),c(String(m))}}return{desired:O(s,n,e.map),tools:y}}l(E,"prepareDraft");async function z(t,e,n,r,a,c,i){const s=n.newestManaged===null||n.newestHead!==null&&(n.newestBaseline===null||n.newestHead>n.newestBaseline),d=l(o=>({name:o.name,description:o.description,parameters:structuredClone(o.parameters)}),"toolOf"),{messages:y}=await t.context(e),f=new Map;for(const o of y)if(o.role==="system"){for(const u of o.toolsRemoved??[])f.delete(u.name);for(const u of o.toolsAdded??[])f.set(u.name,u)}if(s){const o=[...a].map(([h,S])=>({key:h,action:"set",value:S.value,rendered:S.rendered})),u=o.map(h=>h.action==="set"?`## ${h.key}
3
- ${h.rendered}`:"").join(`
4
-
5
- `),{entries:g}=await t.context(e),k=g.filter(h=>h.kind==="pi.system"&&h.id>(n.newestHead??0)).map(h=>({target:h.id,action:"omit"})),M={role:"system",content:u,toolsAdded:c.map(d),timestamp:i};return{data:{baseline:!0,sections:o},model:[M],...k.length?{edits:k}:{}}}const p=[];for(const[o,u]of a){const g=r.get(o);(!g||g.rendered!==u.rendered||JSON.stringify(g.value)!==JSON.stringify(u.value))&&p.push({key:o,action:"set",value:u.value,rendered:u.rendered})}for(const o of r.keys())a.has(o)||p.push({key:o,action:"remove"});const m=c.filter(o=>!f.has(o.name)),v=[...f.values()].filter(o=>!c.some(u=>u.name===o.name));if(p.length===0&&m.length===0&&v.length===0)return;if(!p.some(o=>o.action==="remove"||r.get(o.key)?.rendered!==o.rendered)&&m.length===0&&v.length===0)return{data:{sections:p},model:[]};const b={role:"system",content:p.map(o=>o.action==="set"?`The ${o.key} section now reads:
6
- ${o.rendered}`:`The ${o.key} section no longer applies.`).join(`
7
-
8
- `),...m.length?{toolsAdded:m.map(d)}:{},...v.length?{toolsRemoved:v}:{},timestamp:i};return{data:{sections:p},model:[b]}}l(z,"planManagedEntry");function D(t){const e=new Map;for(const n of t)if(n.role==="system"){for(const r of n.toolsRemoved??[])e.delete(r.name);for(const r of n.toolsAdded??[])e.set(r.name,r)}return[...e.values()]}l(D,"effectiveTools");export{w as defineSystemSection,D as effectiveTools,x as foldCanonical,z as planManagedEntry,E as prepareDraft,J as removeSection,N as sameSnapshot,A as sectionSeed,j as systemSections,R as takeSnapshot};
@@ -1 +0,0 @@
1
- var o=Object.defineProperty;var t=(e,r)=>o(e,"name",{value:r,configurable:!0});const i=t(e=>JSON.parse(JSON.stringify(e)),"toStored");function c(e){if(e.startsWith("pi."))throw new Error(`entry kind names beginning with "pi." are reserved: ${e}`);return Object.freeze({kind:e,is:t(r=>r?.kind===e,"is")})}t(c,"defineEntry");function u(e,r,s){Object.hasOwn(e,"memos")||(e.memos={});const n=e.memos;return Object.hasOwn(n,r)?n[r]:(n[r]=s,s)}t(u,"memoOnce");function d(e){if(e.name.startsWith("pi."))throw new Error(`task kind names beginning with "pi." are reserved: ${e.name}`);return Object.freeze({...e})}t(d,"defineTask");class l extends Error{static{t(this,"ReadAfterWrite")}constructor(r,s){super(`${r} after ${s} in the same transaction: the answer would not include the buffered write`),this.name="ReadAfterWrite"}}class p{static{t(this,"InvocationToken")}#e=!0;taskId;mode;constructor(r,s){this.taskId=r,this.mode=s}get alive(){return this.#e}revoke(){this.#e=!1}}class h extends Error{static{t(this,"Forbidden")}constructor(r){super(`forbidden: ${r}`),this.name="Forbidden"}}class m extends Error{static{t(this,"ConversationBusy")}constructor(r){super(`conversation ${r} is busy`),this.name="ConversationBusy"}}class x extends Error{static{t(this,"GenerationInProgress")}constructor(r){super(`conversation ${r} already has a live generation`),this.name="GenerationInProgress"}}class f extends Error{static{t(this,"CollapseInProgress")}constructor(r){super(`conversation ${r} already has a live collapse`),this.name="CollapseInProgress"}}class v extends Error{static{t(this,"Faulted")}constructor(r){super(`Session faulted: ${String(r)}`),this.name="Faulted"}}class b extends Error{static{t(this,"Closed")}constructor(){super("Session is closed"),this.name="Closed"}}class g extends Error{static{t(this,"TaskContractFault")}constructor(r,s){super(`kind ${r} broke its contract: ${s}`),this.name="TaskContractFault"}}export{b as Closed,f as CollapseInProgress,m as ConversationBusy,v as Faulted,h as Forbidden,x as GenerationInProgress,p as InvocationToken,l as ReadAfterWrite,g as TaskContractFault,c as defineEntry,d as defineTask,u as memoOnce,i as toStored};
@@ -1 +0,0 @@
1
- var j=Object.defineProperty;var u=(s,t)=>j(s,"name",{value:t,configurable:!0});import{applyImmutable as T,track as E}from"@earendil-works/chord/delta";const I=256;function H(s,t){return T(s,t.ops)}u(H,"applyEnvelope");class K{static{u(this,"ViewManager")}records=new Map;deliveries=[];session;onReport;constructor(t,e){this.session=t,this.onReport=e}watch(t,e){let i=this.records.get(t.id);if(i===void 0){const o=E(this.build(t,e));o.flush(),i={conversationId:t.id,tracker:o,watchers:new Set,revision:0},this.records.set(t.id,i)}const n=new J(structuredClone(i.tracker.target),i.revision,this.onReport,()=>{i.watchers.delete(n),i.watchers.size===0&&this.records.get(t.id)===i&&this.records.delete(t.id)});return i.watchers.add(n),n}update(t){for(const e of[...this.records.values()])if(this.session.conversationRecords.get(e.conversationId)!==void 0)try{const n=t.changes,o=n.entries.filter(c=>c.conversationId===e.conversationId),r=n.docs.filter(c=>c.ref.doc==="session"||c.ref.conversationId===e.conversationId),d=n.tasks.some(c=>c.conversationId===e.conversationId),f=n.events.filter(c=>c.conversationId===e.conversationId).map(c=>c.event);if(o.length===0&&r.length===0&&!d&&f.length===0)continue;const k=z(e.tracker,o),a=e.tracker.state,R=r.some(c=>c.ref.doc==="rewindable"&&c.ref.conversationId===e.conversationId),g=r.some(c=>c.ref.doc==="sticky"&&c.ref.conversationId===e.conversationId),v=f.some(c=>c.type==="config.changed"),m=r.some(c=>P(c.ops,"plugins")),b=R||v||m?this.document({doc:"rewindable",conversationId:e.conversationId}):void 0,h=g||d||v||m?this.document({doc:"sticky",conversationId:e.conversationId}):void 0;if(v&&l(a.config,this.config(b,h)),g&&O(a.inbox,structuredClone(h.inbox)),(g||d)&&(A(a,"turn",this.turn(e.conversationId,h).turn),A(a,"compaction",this.compaction(e.conversationId).compaction),l(a.tasks,this.tasks(e.conversationId,h))),m){const c=this.document({doc:"session"});l(a.plugins,this.plugins(b,h,c))}const w=[...k,...e.tracker.flush()];if(w.length===0&&f.length===0)continue;const S=Object.freeze({revision:++e.revision,ops:Object.freeze(w),events:Object.freeze(f)});this.deliveries.push({envelope:S,watchers:[...e.watchers]})}catch(n){this.records.delete(e.conversationId);for(const o of[...e.watchers])o.fail(n)}}deliver(){for(const t of this.deliveries.splice(0))for(const e of t.watchers)e.accept(t.envelope)}close(){const t=[...this.records.values()];this.records.clear(),this.deliveries.length=0;for(const e of t)for(const i of[...e.watchers])i.stop()}build(t,e){const i=this.document({doc:"rewindable",conversationId:t.id}),n=this.document({doc:"sticky",conversationId:t.id}),o=this.document({doc:"session"}),{sections:r,...d}=t;return{conversation:structuredClone(d),entries:structuredClone(e),config:this.config(i,n),inbox:structuredClone(n.inbox),...this.turn(t.id,n),...this.compaction(t.id),tasks:this.tasks(t.id,n),plugins:this.plugins(i,n,o)}}document(t){const e=this.session.loadedDocument(t);if(e===void 0)throw new Error(`view document ${t.doc} is not loaded`);return e}config(t,e){const i={};for(const[n,o]of this.session.defaults.route){const r=o==="rewindable"?t:e,d=n in r?r[n]:this.session.defaults[o][n];d!==void 0&&(i[n]=structuredClone(d))}return i}turn(t,e){const n=[...this.session.liveTasks.values()].filter(a=>a.conversationId===t).filter(a=>this.session.kinds.get(a.kind)?.turn===!0);if(n.length===0)return{};const o=n.find(a=>a.kind==="pi.generation"),r=n.find(a=>a.kind==="pi.post_tools"),d=o??r;return{turn:{inputs:d===void 0?[]:M(d),...o===void 0?{}:{generation:N(o,e.turn.message!==void 0)},...e.turn.message===void 0?{}:{message:structuredClone(e.turn.message)},tools:e.turn.tools.map($)}}}compaction(t){const e=[...this.session.liveTasks.values()].find(o=>o.conversationId===t&&o.kind==="pi.collapse");if(e===void 0)return{};const i=e.input,n=e.checkpoint;return{compaction:{taskId:e.id,reason:i.reason,stage:n?.phase==="retrying"?"retrying":"summarizing",attempt:n?.attempt??1,...n?.phase==="retrying"&&n.untilMs!==void 0?{retryAt:n.untilMs}:{}}}}tasks(t,e){const i={};for(const n of this.session.liveTasks.values()){const o=this.session.kinds.get(n.kind);if(n.conversationId!==t||o===void 0||o.turn===!0||n.kind==="pi.collapse")continue;const r=e.tasks[n.id];i[n.id]={kind:n.kind,...n.background?{background:!0}:{},...n.abort?{marked:!0}:{},status:_(o,n,r)}}return i}plugins(t,e,i){const n={},o=i.plugins??{};for(const[r,d]of this.session.namespaces){if(d.project===void 0)continue;const f={...d.defaults.rewindable,...d.defaults.sticky,...d.defaults.session,...t.plugins[r]??{},...e.plugins[r]??{},...o[r]??{}};n[r]=C(d.project(structuredClone(f)),`namespace ${r} view`)}return n}}class J{static{u(this,"WatchImpl")}view;initialRevision;onReport;onStop;listener;buffer=[];stopped=!1;constructor(t,e,i,n){this.view=t,this.initialRevision=e,this.onReport=i,this.onStop=n}get revision(){return this.initialRevision}get closed(){return this.stopped}start(t){if(!(this.listener!==void 0||this.stopped)){this.listener=t;for(const e of this.buffer.splice(0)){if(this.stopped)break;this.deliver(e)}}}stop(){this.stopped||(this.stopped=!0,this.buffer.length=0,this.onStop())}accept(t){if(!this.stopped){if(this.listener===void 0){if(this.buffer.length>=I){this.stop(),this.report(new Error(`watch capacity ${I} exceeded before start()`));return}this.buffer.push(t);return}this.deliver(t)}}deliver(t){try{this.listener(t)}catch(e){this.fail(e)}}fail(t){this.stop(),this.report(t)}report(t){try{this.onReport(t)}catch{}}}function z(s,t){const e=[],i=s.state.entries;for(const n of t){if(n.head!==void 0){const o=i.findIndex(d=>d.id>=n.head),r=o<0?i.length:o;r>0&&(e.push(...s.flush()),i.splice(0,r),s.flush(),e.push(["p",["entries"],0,r,[]]))}i.push(structuredClone(n))}return e}u(z,"applyEntries");function M(s){const t=s.input.inputs;return Array.isArray(t)?t.filter(e=>typeof e=="number"):[]}u(M,"inputIds");function N(s,t){if(s.status==="pending"&&s.after.length>0)return{stage:"waiting",on:"compaction"};const e=s.checkpoint;return e?.phase==="requesting"?{stage:t?"streaming":"requesting",attempt:e.attempt??1}:e?.phase==="retrying"?{stage:"retrying",attempt:e.attempt??1,retryAt:e.untilMs??0,lastError:e.lastError??""}:e?.phase==="deferred"?{stage:"deferred",attempt:e.attempt??1,pollAt:e.pollAt??0}:{stage:"preparing"}}u(N,"generationStatus");function $(s){const{memos:t,...e}=structuredClone(s);return e}u($,"stripPrivateToolState");function _(s,t,e){if(typeof s.describe!="function")return{phase:t.checkpoint?.phase??(t.status==="pending"?"pending":"running")};const i=e===void 0?void 0:structuredClone(e);i!==void 0&&delete i.memos;const n=s.describe({...t,...i===void 0?{}:{slot:i}});return C(n,`task kind ${t.kind} describe`)}u(_,"describe");function C(s,t){const e=JSON.stringify(s);if(e===void 0)throw new Error(`${t} returned a non-JSON value`);return JSON.parse(e)}u(C,"strictJson");function P(s,t){return s.some(e=>e[0]==="r"||e[1][0]===t)}u(P,"touchesKey");function A(s,t,e){const i=s;if(e===void 0){delete i[t];return}const n=i[t];y(n,e)||(p(n)&&p(e)?l(n,e):i[t]=structuredClone(e))}u(A,"syncOptional");function l(s,t){for(const e of Object.keys(s))e in t||delete s[e];for(const[e,i]of Object.entries(t)){const n=s[e];if(!y(n,i)){if(Array.isArray(n)&&Array.isArray(i)){O(n,i);continue}if(p(n)&&p(i)){l(n,i);continue}s[e]=structuredClone(i)}}}u(l,"syncRecord");function O(s,t){let e=0;for(;e<s.length&&e<t.length;){if(y(s[e],t[e])){e++;continue}const i=s[e],n=t[e];if(!p(i)||!p(n)||!q(i,n))break;l(i,n),e++}if(!(e===s.length&&e===t.length)){if(e===s.length){s.push(...structuredClone(t.slice(e)));return}s.splice(e,s.length-e,...structuredClone(t.slice(e)))}}u(O,"syncArray");function q(s,t){return typeof s.id=="number"||typeof t.id=="number"?s.id===t.id:typeof s.callId=="string"||typeof t.callId=="string"?s.callId===t.callId:typeof s.type=="string"||typeof t.type=="string"?s.type===t.type:!1}u(q,"sameArrayItem");function p(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}u(p,"isRecord");function y(s,t){return Object.is(s,t)?!0:JSON.stringify(s)===JSON.stringify(t)}u(y,"same");export{K as ViewManager,I as WATCH_CAPACITY,H as applyEnvelope};
@@ -1,5 +0,0 @@
1
- var g=Object.defineProperty;var c=(o,e)=>g(o,"name",{value:e,configurable:!0});import{parse as h}from"yaml";import{toError as y}from"./types.js";async function T(o,e,t){const s=[],r=[];for(const n of Array.isArray(e)?e:[e]){const i=await o.fileInfo(n,t);if(!i.ok){i.error.code!=="not_found"&&r.push({type:"warning",code:"file_info_failed",message:i.error.message,path:n});continue}const a=i.value,l=await m(o,a,r,t);if(l==="directory"){const p=await k(o,a.path,t);s.push(...p.promptTemplates),r.push(...p.diagnostics)}else if(l==="file"&&a.name.endsWith(".md")){const p=await f(o,a.path,a.name,t);p.promptTemplate&&s.push(p.promptTemplate),r.push(...p.diagnostics)}}return{promptTemplates:s,diagnostics:r}}c(T,"loadPromptTemplates");async function b(o,e,t,s){const r=[],n=[];for(const i of e){const a=await T(o,i.path,s);for(const l of a.promptTemplates)r.push({promptTemplate:t?t(l,i.source,s):l,source:i.source});for(const l of a.diagnostics)n.push({...l,source:i.source})}return{promptTemplates:r,diagnostics:n}}c(b,"loadSourcedPromptTemplates");async function k(o,e,t){const s=[],r=[],n=await o.listDir(e,t);if(!n.ok)return r.push({type:"warning",code:"list_failed",message:n.error.message,path:e}),{promptTemplates:s,diagnostics:r};const i=n.value;for(const a of i.sort((l,p)=>l.name.localeCompare(p.name))){if(await m(o,a,r,t)!=="file"||!a.name.endsWith(".md"))continue;const p=await f(o,a.path,a.name,t);p.promptTemplate&&s.push(p.promptTemplate),r.push(...p.diagnostics)}return{promptTemplates:s,diagnostics:r}}c(k,"loadTemplatesFromDir");async function f(o,e,t,s){const r=[],n=await o.readTextFile(e,s);if(!n.ok)return r.push({type:"warning",code:"read_failed",message:n.error.message,path:e}),{promptTemplate:null,diagnostics:r};const i=w(n.value);if(!i.ok)return r.push({type:"warning",code:"parse_failed",message:i.error.message,path:e}),{promptTemplate:null,diagnostics:r};const{frontmatter:a,body:l}=i.value,p=l.split(`
2
- `).find(d=>d.trim());let u=typeof a.description=="string"?a.description:"";return!u&&p&&(u=p.slice(0,60),p.length>60&&(u+="...")),{promptTemplate:{name:t.replace(/\.md$/i,""),description:u,content:l},diagnostics:r}}c(f,"loadTemplateFromFile");async function m(o,e,t,s){if(e.kind==="file"||e.kind==="directory")return e.kind;const r=await o.canonicalPath(e.path,s);if(!r.ok){r.error.code!=="not_found"&&t.push({type:"warning",code:"file_info_failed",message:r.error.message,path:e.path});return}const n=await o.fileInfo(r.value,s);if(!n.ok){n.error.code!=="not_found"&&t.push({type:"warning",code:"file_info_failed",message:n.error.message,path:e.path});return}return n.value.kind==="file"||n.value.kind==="directory"?n.value.kind:void 0}c(m,"resolveKind");function w(o){try{const e=o.replace(/\r\n/g,`
3
- `).replace(/\r/g,`
4
- `);if(!e.startsWith("---"))return{ok:!0,value:{frontmatter:{},body:e}};const t=e.indexOf(`
5
- ---`,3);if(t===-1)return{ok:!0,value:{frontmatter:{},body:e}};const s=e.slice(4,t),r=e.slice(t+4).trim();return{ok:!0,value:{frontmatter:h(s)??{},body:r}}}catch(e){return{ok:!1,error:y(e)}}}c(w,"parseFrontmatter");function F(o){const e=[];let t="",s=null;for(let r=0;r<o.length;r++){const n=o[r];s?n===s?s=null:t+=n:n==='"'||n==="'"?s=n:n===" "||n===" "?t&&(e.push(t),t=""):t+=n}return t&&e.push(t),e}c(F,"parseCommandArgs");function _(o,e){let t=o;t=t.replace(/\$(\d+)/g,(r,n)=>e[parseInt(n,10)-1]??""),t=t.replace(/\$\{@:(\d+)(?::(\d+))?\}/g,(r,n,i)=>{let a=parseInt(n,10)-1;return a<0&&(a=0),i?e.slice(a,a+parseInt(i,10)).join(" "):e.slice(a).join(" ")});const s=e.join(" ");return t=t.replace(/\$ARGUMENTS/g,s),t=t.replace(/\$@/g,s),t}c(_,"substituteArgs");function $(o,e=[]){return _(o.content,e)}c($,"formatPromptTemplateInvocation");export{$ as formatPromptTemplateInvocation,T as loadPromptTemplates,b as loadSourcedPromptTemplates,F as parseCommandArgs,_ as substituteArgs};
@@ -1 +0,0 @@
1
- var F=Object.defineProperty;var l=(e,t)=>F(e,"name",{value:t,configurable:!0});import{Guard as D}from"typebox/guard";class P extends Error{static{l(this,"RecordLogCorruption")}reason;constructor(t,a){super(a),this.name="RecordLogCorruption",this.reason=t}}function c(e,t){throw new P(e,t)}l(c,"corrupt");function Q(e){return"runId"in e&&typeof e.runId=="string"}l(Q,"hasRunId");function U(e,t){const{parentId:a,seq:o,timestamp:u,...d}=e;return D.IsDeepEqual(d,t)}l(U,"matchesProvisionedEntry");function x(e,t){const a=e.get(t.id);a&&!U(a,t)&&c("provisioned_entry_mismatch",`Provisioned entry ${t.id} exists with content different from its intent`)}l(x,"validateExactProvisionedEntry");function q(e,t,a,o){const u=e.get(t);u&&!a(u)&&c("provisioned_entry_mismatch",`Provisioned ${o} entry ${t} exists with different content`)}l(q,"validateResultEntry");function B(e){const t=e.compactionReason;e.step==="compaction"?t!=="manual"&&t!=="threshold"&&t!=="overflow"&&c("invalid_compaction_reason",`Compaction attempt ${e.id} has no valid compaction reason`):t!==void 0&&c("invalid_compaction_reason",`${e.step} attempt ${e.id} has a compaction reason`)}l(B,"validateAttemptReason");function G(e,t,a){const o=t?.record,u=o?a.get(o.resultEntryId):void 0,d=o!==void 0&&o.step===e.step&&(u===void 0||u.seq>=e.seq),i=d?o.attempt+1:1;e.attempt!==i&&c("non_consecutive_attempt",`${e.step} attempt ${e.id} is ${e.attempt}; expected ${i}`),!(!d||e.step==="assistant"||o===void 0)&&(e.resultEntryId!==o.resultEntryId&&c("inconsistent_step",`${e.step} attempts disagree on their result entry id`),e.compactionReason!==o.compactionReason&&c("inconsistent_step",`${e.step} attempts disagree on their compaction reason`))}l(G,"validateAttemptSequence");function W(e,t){switch(t.step){case"assistant":q(e,t.resultEntryId,a=>a.type==="message"&&a.message.role==="assistant","assistant result");break;case"compaction":q(e,t.resultEntryId,a=>a.type==="compaction","compaction result");break;case"branch_summary":q(e,t.resultEntryId,a=>a.type==="branch_summary","branch-summary result");break}}l(W,"validateAttemptResult");function H(e,t,a){const o=`${e.assistantEntryId}\0${e.toolIndex}`;a.has(o)&&c("duplicate_tool_invocation",`Tool invocation ${e.assistantEntryId}:${e.toolIndex} is duplicated`),a.add(o);const u=t.get(e.assistantEntryId);(!u||u.type!=="message"||u.message.role!=="assistant")&&c("tool_call_mismatch",`Tool start ${e.id} does not reference an assistant entry`);const i=u.message.content.filter(m=>m.type==="toolCall")[e.toolIndex];(!i||i.id!==e.toolCallId||i.name!==e.toolName)&&c("tool_call_mismatch",`Tool start ${e.id} does not match its assistant tool-call ordinal`),q(t,e.resultEntryId,m=>m.type==="message"&&m.message.role==="toolResult"&&m.message.toolCallId===e.toolCallId&&m.message.toolName===e.toolName,"tool result")}l(H,"validateToolStart");function V(e){for(const t of e)t.type==="message"&&t.message.role==="assistant"&&t.message.stopReason==="deferred"&&!t.message.deferred&&c("invalid_deferred_handle",`Deferred assistant entry ${t.id} does not carry a handle`)}l(V,"validateDeferredHandles");function Y(e,t){switch(t.intent.kind){case"run":for(const a of t.intent.initialMessages)x(e,a);break;case"compaction":q(e,t.intent.resultEntryId,a=>a.type==="compaction","manual compaction");break;case"navigation":t.intent.summaryEntryId&&q(e,t.intent.summaryEntryId,a=>a.type==="branch_summary","navigation summary");break}}l(Y,"validateOperationResult");function j(e){e.openOperations.length>1&&c("multiple_open_operations",`Lane ${e.lane} has at least two open operations`);const t=new Map(e.entries.map(s=>[s.id,s]));V(t.values());const a=new Map,o=new Map,u=new Map,d=new Map,i=new Map,m=new Set,y=[...e.records].sort((s,r)=>s.seq-r.seq);for(const s of y){if(s.type==="operation_started"){a.set(s.id,s),Y(t,s);continue}if(Q(s)){a.has(s.runId)||c("unknown_operation",`Record ${s.id} references unknown operation ${s.runId}`);const r=o.get(s.runId);r!==void 0&&s.seq>r&&c("record_after_finish",`Record ${s.id} follows the finish of operation ${s.runId}`)}switch(s.type){case"operation_finished":o.set(s.runId,s.seq);break;case"abort_requested":u.set(s.runId,s.seq);break;case"step_attempt":B(s),G(s,i.get(s.runId),t),W(t,s),i.set(s.runId,{record:s});break;case"tool_started":H(s,t,m);break;case"queue_enqueued":s.queue!=="nextRun"&&u.get(s.runId)!==void 0&&s.seq>u.get(s.runId)&&c("queue_after_abort",`${s.queue} item ${s.target.id} was enqueued after abort`),d.set(s.target.id,s),x(t,s.target);break;case"queue_cancelled":{const r=d.get(s.entryId);(!r||r.seq>=s.seq||r.runId!==s.runId||t.has(s.entryId))&&c("invalid_queue_cancellation",`Queue cancellation ${s.id} has no pending matching enqueue`);break}case"write_deferred":x(t,s.target);break;case"usage":break}}}l(j,"validateRecordLog");function f(e){return structuredClone(e)}l(f,"clone");function C(e){return[...e].sort((t,a)=>t.seq-a.seq)}l(C,"bySequence");function z(e){let t=f(e.defaults);const a=new Map;for(const o of[...e.configurationEntries,...e.ownEntries])a.set(o.id,o);for(const o of C([...a.values()]))switch(o.type){case"model_change":t={...t,model:{provider:o.provider,modelId:o.modelId}};break;case"thinking_level_change":t={...t,thinkingLevel:o.thinkingLevel};break;case"active_tools_change":t={...t,activeToolNames:[...o.activeToolNames]};break;case"message":o.message.role==="assistant"&&(t={...t,model:{provider:o.message.provider,modelId:o.message.model}});break}return t}l(z,"deriveEffectiveConfiguration");function J(e){return e?e.type!=="message"?{entryId:e.id,type:e.type}:e.message.role!=="assistant"?{entryId:e.id,type:e.type,role:e.message.role}:{entryId:e.id,type:e.type,role:e.message.role,stopReason:e.message.stopReason}:null}l(J,"deriveNewestOwn");function K(e,t,a,o,u){const d=[...a].reverse().find(s=>s.type==="message"&&s.message.role==="assistant"&&s.message.content.some(r=>r.type==="toolCall"));if(!d||d.type!=="message"||d.message.role!=="assistant")return null;const i=d.message.content.filter(s=>s.type==="toolCall"),m=new Map;for(const s of t)s.type==="tool_started"&&s.runId===e&&s.assistantEntryId===d.id&&m.set(s.toolIndex,s);const y=i.map((s,r)=>{const g=m.get(r),E=g?o.get(g.resultEntryId):void 0,R=a.find(I=>I.seq>d.seq&&!u.has(I.id)&&I.type==="message"&&I.message.role==="toolResult"&&I.message.toolCallId===s.id),w=E??R;return{toolIndex:r,toolCall:f(s),...g?{started:f(g)}:{},resultExists:w!==void 0,...w?.type==="message"&&w.terminate===!0?{terminate:!0}:{}}});return{assistantEntryId:d.id,calls:y,truncated:d.message.stopReason==="length",unresolved:y.some(s=>!s.resultExists)}}l(K,"deriveToolBatch");function ee(e){j(e);const t=C(e.records),a=C(e.ownEntries),o=new Map;for(const n of[...e.entries,...a])o.set(n.id,n);const u=new Set(t.filter(n=>n.type==="queue_cancelled").map(n=>n.entryId)),d=t.filter(n=>n.type==="queue_enqueued"&&!o.has(n.target.id)&&!u.has(n.target.id)),i=e.openOperations[0],m=new Set(i?.intent.kind==="run"?i.intent.initialMessages.map(n=>n.id):[]),y=d.filter(n=>n.queue==="nextRun"&&!m.has(n.target.id)).map(n=>f(n.target)),s=z(e);if(!i)return{laneState:{lane:e.lane,leafId:e.leafId,operation:null,pendingNextRun:y},effectiveConfiguration:s,terminalFailure:null};const r=t.filter(n=>n.type==="operation_started"?n.id===i.id:"runId"in n&&n.runId===i.id),g=r.some(n=>n.type==="abort_requested"),E=g?[]:d.filter(n=>n.queue==="steer"&&n.runId===i.id).map(n=>f(n.target)),R=g?[]:d.filter(n=>n.queue==="followUp"&&n.runId===i.id).map(n=>f(n.target)),w=r.filter(n=>n.type==="write_deferred"&&!o.has(n.target.id)).map(n=>f(n.target)),I=i.intent.kind==="run"?i.intent.initialMessages.filter(n=>!o.has(n.id)).map(f):[],h=r.filter(n=>n.type==="step_attempt").at(-1),N=h&&!o.has(h.resultEntryId)?{kind:h.step,attempts:h.attempt,resultEntryId:h.resultEntryId,...h.step==="compaction"?{compactionReason:h.compactionReason}:{}}:null,k=new Set;if(i.intent.kind==="run")for(const n of i.intent.initialMessages)k.add(n.id);for(const n of r)n.type==="queue_enqueued"&&n.queue!=="nextRun"&&k.add(n.target.id);let b=Number.NEGATIVE_INFINITY;for(const n of k){const _=o.get(n);_?.type==="message"&&(b=Math.max(b,_.seq))}const A=r.some(n=>n.type==="step_attempt"&&n.step==="compaction"&&n.compactionReason==="overflow"&&n.seq>b),p=a.at(-1),T=J(p),L=p?.type==="message"&&p.message.role==="assistant"&&p.message.stopReason==="deferred"&&p.message.deferred?f(p.message.deferred):null,$={};i.intent.kind==="compaction"?$.result=o.has(i.intent.resultEntryId):i.intent.kind==="navigation"&&i.intent.summaryEntryId&&($.summary=o.has(i.intent.summaryEntryId));const M=new Set(r.filter(n=>n.type==="write_deferred").map(n=>n.target.id));let S=null;if(p?.type==="message"&&p.message.role==="assistant"&&p.message.stopReason==="error"&&!M.has(p.id)){const n=r.some(v=>v.type==="step_attempt"&&v.resultEntryId===p.id),_=a.at(-2),O=r.some(v=>v.type==="usage"&&v.cause==="deferred_fetch"&&v.entryId===p.id)||_?.type==="message"&&_.message.role==="assistant"&&_.message.stopReason==="deferred";(n||O)&&(S={entryId:p.id,source:n?"step":"deferred_fetch",message:f(p.message)})}return{laneState:{lane:e.lane,leafId:e.leafId,operation:{id:i.id,kind:i.intent.kind,intent:f(i.intent),aborting:g,step:N,toolBatch:K(i.id,r,a,o,M),missingInitialMessages:I,pendingSteer:E,pendingFollowUp:R,pendingWrites:w,deferred:L,overflowRecoveryUsed:A,newestOwn:T,targets:$},pendingNextRun:y},effectiveConfiguration:s,terminalFailure:S}}l(ee,"reduceLaneState");export{P as RecordLogCorruption,ee as reduceLaneState,j as validateRecordLog};