@bastani/atomic 0.9.38-alpha.4 → 0.9.38-alpha.6

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 (374) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +8 -6
  3. package/dist/builtin/intercom/CHANGELOG.md +15 -0
  4. package/dist/builtin/intercom/broker/broker.ts +6 -4
  5. package/dist/builtin/intercom/broker/delivered-message-cache.ts +50 -4
  6. package/dist/builtin/intercom/broker/send-handler.ts +6 -4
  7. package/dist/builtin/intercom/index.bundle.mjs +89 -40
  8. package/dist/builtin/intercom/package.json +1 -1
  9. package/dist/builtin/mcp/package.json +1 -1
  10. package/dist/builtin/subagents/package.json +1 -1
  11. package/dist/builtin/subagents/src/extension/index.bundle.mjs +29 -33
  12. package/dist/builtin/web-access/CHANGELOG.md +7 -0
  13. package/dist/builtin/web-access/index.bundle.mjs +53 -15
  14. package/dist/builtin/web-access/package.json +1 -1
  15. package/dist/builtin/workflows/CHANGELOG.md +36 -0
  16. package/dist/builtin/workflows/builtin/{chunk-qrrkfg9v.js → chunk-2qgfyvzs.js} +1 -1
  17. package/dist/builtin/workflows/builtin/{chunk-na3wpwzh.js → chunk-g1a4hw0s.js} +390 -345
  18. package/dist/builtin/workflows/builtin/{chunk-xg7kkgf8.js → chunk-neszcj53.js} +1 -1
  19. package/dist/builtin/workflows/builtin/goal.js +2 -2
  20. package/dist/builtin/workflows/builtin/index.js +3 -3
  21. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  22. package/dist/builtin/workflows/package.json +1 -1
  23. package/dist/builtin/workflows/src/authoring.d.ts +3 -8
  24. package/dist/builtin/workflows/src/durable/journal/conformance.d.ts +9 -1
  25. package/dist/builtin/workflows/src/durable/journal/internal.d.ts +20 -0
  26. package/dist/builtin/workflows/src/durable/journal/lease-expiry.d.ts +2 -0
  27. package/dist/builtin/workflows/src/durable/journal/memory-run-journal.d.ts +17 -1
  28. package/dist/builtin/workflows/src/durable/journal/resolution.d.ts +6 -1
  29. package/dist/builtin/workflows/src/durable/journal/sql-run-journal.d.ts +45 -0
  30. package/dist/builtin/workflows/src/durable/journal/sqlite-run-journal.d.ts +5 -47
  31. package/dist/builtin/workflows/src/durable/journal/types.d.ts +15 -30
  32. package/dist/builtin/workflows/src/durable/journal/values.d.ts +2 -0
  33. package/dist/builtin/workflows/src/extension/index.bundle.mjs +23390 -22820
  34. package/dist/builtin/workflows/src/index.js +7614 -7060
  35. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +7 -7
  36. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +0 -14
  37. package/dist/cli/args.d.ts +1 -0
  38. package/dist/cli/args.d.ts.map +1 -1
  39. package/dist/cli/args.js +6 -2
  40. package/dist/cli/args.js.map +1 -1
  41. package/dist/cli/session-picker.d.ts +2 -2
  42. package/dist/cli/session-picker.d.ts.map +1 -1
  43. package/dist/cli/session-picker.js +3 -3
  44. package/dist/cli/session-picker.js.map +1 -1
  45. package/dist/core/agent-session-auto-compaction.d.ts +1 -1
  46. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  47. package/dist/core/agent-session-auto-compaction.js +2 -2
  48. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  49. package/dist/core/agent-session-bash.d.ts +2 -3
  50. package/dist/core/agent-session-bash.d.ts.map +1 -1
  51. package/dist/core/agent-session-bash.js +18 -10
  52. package/dist/core/agent-session-bash.js.map +1 -1
  53. package/dist/core/agent-session-boundaries.d.ts +6 -6
  54. package/dist/core/agent-session-boundaries.d.ts.map +1 -1
  55. package/dist/core/agent-session-boundaries.js +22 -22
  56. package/dist/core/agent-session-boundaries.js.map +1 -1
  57. package/dist/core/agent-session-compaction.js +2 -2
  58. package/dist/core/agent-session-compaction.js.map +1 -1
  59. package/dist/core/agent-session-custom-message-commit.d.ts.map +1 -1
  60. package/dist/core/agent-session-custom-message-commit.js +10 -12
  61. package/dist/core/agent-session-custom-message-commit.js.map +1 -1
  62. package/dist/core/agent-session-events.d.ts.map +1 -1
  63. package/dist/core/agent-session-events.js +20 -13
  64. package/dist/core/agent-session-events.js.map +1 -1
  65. package/dist/core/agent-session-export.js +1 -1
  66. package/dist/core/agent-session-export.js.map +1 -1
  67. package/dist/core/agent-session-extension-bindings.d.ts +2 -2
  68. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  69. package/dist/core/agent-session-extension-bindings.js +75 -59
  70. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  71. package/dist/core/agent-session-message-queue.d.ts +2 -2
  72. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  73. package/dist/core/agent-session-message-queue.js +17 -8
  74. package/dist/core/agent-session-message-queue.js.map +1 -1
  75. package/dist/core/agent-session-methods.d.ts +15 -15
  76. package/dist/core/agent-session-methods.d.ts.map +1 -1
  77. package/dist/core/agent-session-methods.js.map +1 -1
  78. package/dist/core/agent-session-models.d.ts +2 -2
  79. package/dist/core/agent-session-models.d.ts.map +1 -1
  80. package/dist/core/agent-session-models.js +59 -42
  81. package/dist/core/agent-session-models.js.map +1 -1
  82. package/dist/core/agent-session-persistent-custom-messages.d.ts +4 -4
  83. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  84. package/dist/core/agent-session-persistent-custom-messages.js +16 -17
  85. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  86. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  87. package/dist/core/agent-session-prompt.js +6 -8
  88. package/dist/core/agent-session-prompt.js.map +1 -1
  89. package/dist/core/agent-session-retry.d.ts.map +1 -1
  90. package/dist/core/agent-session-retry.js +17 -15
  91. package/dist/core/agent-session-retry.js.map +1 -1
  92. package/dist/core/agent-session-runtime.d.ts +3 -8
  93. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  94. package/dist/core/agent-session-runtime.js +44 -96
  95. package/dist/core/agent-session-runtime.js.map +1 -1
  96. package/dist/core/agent-session-summary.js +1 -1
  97. package/dist/core/agent-session-summary.js.map +1 -1
  98. package/dist/core/agent-session-tree.d.ts +1 -1
  99. package/dist/core/agent-session-tree.d.ts.map +1 -1
  100. package/dist/core/agent-session-tree.js +7 -7
  101. package/dist/core/agent-session-tree.js.map +1 -1
  102. package/dist/core/cache-warmer.js +1 -1
  103. package/dist/core/cache-warmer.js.map +1 -1
  104. package/dist/core/export-html/index.js +1 -1
  105. package/dist/core/export-html/index.js.map +1 -1
  106. package/dist/core/export-html/template-js/entries-navigation.js +1 -1
  107. package/dist/core/export-html/template.js +1 -1
  108. package/dist/core/extensions/api-types.d.ts +12 -12
  109. package/dist/core/extensions/api-types.d.ts.map +1 -1
  110. package/dist/core/extensions/api-types.js.map +1 -1
  111. package/dist/core/extensions/context-types.d.ts +4 -2
  112. package/dist/core/extensions/context-types.d.ts.map +1 -1
  113. package/dist/core/extensions/context-types.js.map +1 -1
  114. package/dist/core/extensions/extension-work.d.ts +1 -0
  115. package/dist/core/extensions/extension-work.d.ts.map +1 -1
  116. package/dist/core/extensions/extension-work.js +5 -1
  117. package/dist/core/extensions/extension-work.js.map +1 -1
  118. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  119. package/dist/core/extensions/loader-api.js +40 -42
  120. package/dist/core/extensions/loader-api.js.map +1 -1
  121. package/dist/core/extensions/loader-host-modules.d.ts +1 -1
  122. package/dist/core/extensions/loader-host-modules.d.ts.map +1 -1
  123. package/dist/core/extensions/loader-host-modules.js +6 -2
  124. package/dist/core/extensions/loader-host-modules.js.map +1 -1
  125. package/dist/core/extensions/loader-rollback.d.ts.map +1 -1
  126. package/dist/core/extensions/loader-rollback.js +1 -0
  127. package/dist/core/extensions/loader-rollback.js.map +1 -1
  128. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  129. package/dist/core/extensions/loader-virtual-modules.js +1 -0
  130. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  131. package/dist/core/extensions/runner-context.d.ts +1 -0
  132. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  133. package/dist/core/extensions/runner-context.js +3 -2
  134. package/dist/core/extensions/runner-context.js.map +1 -1
  135. package/dist/core/extensions/runner-handlers.d.ts +1 -1
  136. package/dist/core/extensions/runner-handlers.d.ts.map +1 -1
  137. package/dist/core/extensions/runner-handlers.js.map +1 -1
  138. package/dist/core/extensions/runner.d.ts +3 -2
  139. package/dist/core/extensions/runner.d.ts.map +1 -1
  140. package/dist/core/extensions/runner.js +20 -12
  141. package/dist/core/extensions/runner.js.map +1 -1
  142. package/dist/core/extensions/runtime-types.d.ts +7 -7
  143. package/dist/core/extensions/runtime-types.d.ts.map +1 -1
  144. package/dist/core/extensions/runtime-types.js.map +1 -1
  145. package/dist/core/extensions/session-events.d.ts +5 -5
  146. package/dist/core/extensions/session-events.d.ts.map +1 -1
  147. package/dist/core/extensions/session-events.js.map +1 -1
  148. package/dist/core/fast-model-routing.d.ts.map +1 -1
  149. package/dist/core/fast-model-routing.js +1 -0
  150. package/dist/core/fast-model-routing.js.map +1 -1
  151. package/dist/core/intercom-runtime-group.js +1 -1
  152. package/dist/core/intercom-runtime-group.js.map +1 -1
  153. package/dist/core/provider-attribution.js +1 -1
  154. package/dist/core/provider-attribution.js.map +1 -1
  155. package/dist/core/sdk.d.ts.map +1 -1
  156. package/dist/core/sdk.js +7 -6
  157. package/dist/core/sdk.js.map +1 -1
  158. package/dist/core/session-manager-archive.d.ts +2 -16
  159. package/dist/core/session-manager-archive.d.ts.map +1 -1
  160. package/dist/core/session-manager-archive.js +8 -104
  161. package/dist/core/session-manager-archive.js.map +1 -1
  162. package/dist/core/session-manager-core.d.ts +48 -49
  163. package/dist/core/session-manager-core.d.ts.map +1 -1
  164. package/dist/core/session-manager-core.js +438 -306
  165. package/dist/core/session-manager-core.js.map +1 -1
  166. package/dist/core/session-manager-entries.d.ts.map +1 -1
  167. package/dist/core/session-manager-entries.js +5 -10
  168. package/dist/core/session-manager-entries.js.map +1 -1
  169. package/dist/core/session-manager-errors.d.ts +10 -0
  170. package/dist/core/session-manager-errors.d.ts.map +1 -0
  171. package/dist/core/session-manager-errors.js +27 -0
  172. package/dist/core/session-manager-errors.js.map +1 -0
  173. package/dist/core/session-manager-list.d.ts +1 -0
  174. package/dist/core/session-manager-list.d.ts.map +1 -1
  175. package/dist/core/session-manager-list.js +14 -7
  176. package/dist/core/session-manager-list.js.map +1 -1
  177. package/dist/core/session-manager-storage.d.ts +0 -11
  178. package/dist/core/session-manager-storage.d.ts.map +1 -1
  179. package/dist/core/session-manager-storage.js +4 -61
  180. package/dist/core/session-manager-storage.js.map +1 -1
  181. package/dist/core/session-manager-types.d.ts +2 -10
  182. package/dist/core/session-manager-types.d.ts.map +1 -1
  183. package/dist/core/session-manager-types.js.map +1 -1
  184. package/dist/core/session-manager-validation.d.ts.map +1 -1
  185. package/dist/core/session-manager-validation.js +3 -2
  186. package/dist/core/session-manager-validation.js.map +1 -1
  187. package/dist/core/session-manager.d.ts +1 -0
  188. package/dist/core/session-manager.d.ts.map +1 -1
  189. package/dist/core/session-manager.js +1 -0
  190. package/dist/core/session-manager.js.map +1 -1
  191. package/dist/core/session-mutation-queue.d.ts +3 -0
  192. package/dist/core/session-mutation-queue.d.ts.map +1 -0
  193. package/dist/core/session-mutation-queue.js +14 -0
  194. package/dist/core/session-mutation-queue.js.map +1 -0
  195. package/dist/core/settings-merge.d.ts.map +1 -1
  196. package/dist/core/settings-merge.js +3 -2
  197. package/dist/core/settings-merge.js.map +1 -1
  198. package/dist/core/settings-schema.d.ts +0 -5
  199. package/dist/core/settings-schema.d.ts.map +1 -1
  200. package/dist/core/settings-schema.js +1 -15
  201. package/dist/core/settings-schema.js.map +1 -1
  202. package/dist/core/storage/index.d.ts +1 -1
  203. package/dist/core/storage/index.d.ts.map +1 -1
  204. package/dist/core/storage/index.js +1 -1
  205. package/dist/core/storage/index.js.map +1 -1
  206. package/dist/core/storage/node-sqlite.d.ts +2 -0
  207. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  208. package/dist/core/storage/node-sqlite.js +47 -6
  209. package/dist/core/storage/node-sqlite.js.map +1 -1
  210. package/dist/core/storage/session/jsonl-session-store.d.ts +9 -2
  211. package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
  212. package/dist/core/storage/session/jsonl-session-store.js +71 -27
  213. package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
  214. package/dist/core/storage/session/validation.js +1 -1
  215. package/dist/core/storage/session/validation.js.map +1 -1
  216. package/dist/core/storage/testing.d.ts +2 -0
  217. package/dist/core/storage/testing.d.ts.map +1 -1
  218. package/dist/core/storage/testing.js +45 -0
  219. package/dist/core/storage/testing.js.map +1 -1
  220. package/dist/core/tasks/completion.d.ts.map +1 -1
  221. package/dist/core/tasks/completion.js +2 -4
  222. package/dist/core/tasks/completion.js.map +1 -1
  223. package/dist/core/tools/bash-session-environment.d.ts.map +1 -1
  224. package/dist/core/tools/bash-session-environment.js +0 -2
  225. package/dist/core/tools/bash-session-environment.js.map +1 -1
  226. package/dist/core/tools/todos-model.js +3 -3
  227. package/dist/core/tools/todos-model.js.map +1 -1
  228. package/dist/core/tools/todos-mutations.js +2 -2
  229. package/dist/core/tools/todos-mutations.js.map +1 -1
  230. package/dist/core/tools/todos-render.js +1 -1
  231. package/dist/core/tools/todos-render.js.map +1 -1
  232. package/dist/core/tools/todos-storage.js +2 -2
  233. package/dist/core/tools/todos-storage.js.map +1 -1
  234. package/dist/extensions/codemode/execute.js +1 -1
  235. package/dist/extensions/codemode/execute.js.map +1 -1
  236. package/dist/extensions/codemode/tool.d.ts +1 -1
  237. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  238. package/dist/extensions/codemode/tool.js.map +1 -1
  239. package/dist/extensions/herdr/index.d.ts.map +1 -1
  240. package/dist/extensions/herdr/index.js +1 -5
  241. package/dist/extensions/herdr/index.js.map +1 -1
  242. package/dist/extensions/mcp/index.js +1 -1
  243. package/dist/extensions/mcp/index.js.map +1 -1
  244. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  245. package/dist/extensions/mcp/tools.js +6 -1
  246. package/dist/extensions/mcp/tools.js.map +1 -1
  247. package/dist/index.d.ts +1 -1
  248. package/dist/index.d.ts.map +1 -1
  249. package/dist/index.js +1 -1
  250. package/dist/index.js.map +1 -1
  251. package/dist/main-session.d.ts +7 -1
  252. package/dist/main-session.d.ts.map +1 -1
  253. package/dist/main-session.js +86 -52
  254. package/dist/main-session.js.map +1 -1
  255. package/dist/main.d.ts.map +1 -1
  256. package/dist/main.js +51 -30
  257. package/dist/main.js.map +1 -1
  258. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  259. package/dist/modes/interactive/components/chat-session-host.js +1 -0
  260. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  261. package/dist/modes/interactive/components/extension-input.d.ts +1 -1
  262. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  263. package/dist/modes/interactive/components/extension-input.js +2 -2
  264. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  265. package/dist/modes/interactive/components/host-session-picker.js +1 -1
  266. package/dist/modes/interactive/components/host-session-picker.js.map +1 -1
  267. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  268. package/dist/modes/interactive/components/scoped-models-selector.js +4 -1
  269. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  270. package/dist/modes/interactive/components/session-selector-list.d.ts +9 -6
  271. package/dist/modes/interactive/components/session-selector-list.d.ts.map +1 -1
  272. package/dist/modes/interactive/components/session-selector-list.js +15 -14
  273. package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
  274. package/dist/modes/interactive/components/session-selector.d.ts +7 -4
  275. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  276. package/dist/modes/interactive/components/session-selector.js +12 -14
  277. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  278. package/dist/modes/interactive/components/tree-selector-component.d.ts +5 -1
  279. package/dist/modes/interactive/components/tree-selector-component.d.ts.map +1 -1
  280. package/dist/modes/interactive/components/tree-selector-component.js +20 -3
  281. package/dist/modes/interactive/components/tree-selector-component.js.map +1 -1
  282. package/dist/modes/interactive/interactive-bash-compact.js +1 -1
  283. package/dist/modes/interactive/interactive-bash-compact.js.map +1 -1
  284. package/dist/modes/interactive/interactive-deferred-startup.js +2 -2
  285. package/dist/modes/interactive/interactive-deferred-startup.js.map +1 -1
  286. package/dist/modes/interactive/interactive-editor-actions.js +2 -2
  287. package/dist/modes/interactive/interactive-editor-actions.js.map +1 -1
  288. package/dist/modes/interactive/interactive-extension-runtime.js +2 -0
  289. package/dist/modes/interactive/interactive-extension-runtime.js.map +1 -1
  290. package/dist/modes/interactive/interactive-input-handling.js +6 -4
  291. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  292. package/dist/modes/interactive/interactive-mode-helpers.js +1 -1
  293. package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
  294. package/dist/modes/interactive/interactive-mode-surface.d.ts +5 -5
  295. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  296. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  297. package/dist/modes/interactive/interactive-model-routing.js +12 -7
  298. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  299. package/dist/modes/interactive/interactive-selectors.js +2 -2
  300. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  301. package/dist/modes/interactive/interactive-session-routing.js +24 -12
  302. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  303. package/dist/modes/interactive/interactive-slash-commands.js +2 -2
  304. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  305. package/dist/modes/interactive-engine/engine-args.d.ts.map +1 -1
  306. package/dist/modes/interactive-engine/engine-args.js +7 -4
  307. package/dist/modes/interactive-engine/engine-args.js.map +1 -1
  308. package/dist/modes/interactive-engine/isolated-runtime.d.ts +1 -1
  309. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  310. package/dist/modes/interactive-engine/isolated-runtime.js +90 -71
  311. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  312. package/dist/modes/rpc/rpc-bash-request-owners.js +1 -1
  313. package/dist/modes/rpc/rpc-bash-request-owners.js.map +1 -1
  314. package/dist/modes/rpc/rpc-client-api.d.ts +1 -1
  315. package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
  316. package/dist/modes/rpc/rpc-client-api.js +2 -2
  317. package/dist/modes/rpc/rpc-client-api.js.map +1 -1
  318. package/dist/modes/rpc/rpc-client-process.d.ts +2 -2
  319. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  320. package/dist/modes/rpc/rpc-client-process.js +18 -7
  321. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  322. package/dist/modes/rpc/rpc-client.d.ts +4 -1
  323. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  324. package/dist/modes/rpc/rpc-client.js +6 -2
  325. package/dist/modes/rpc/rpc-client.js.map +1 -1
  326. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  327. package/dist/modes/rpc/rpc-command-handler.js +11 -8
  328. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  329. package/dist/modes/rpc/rpc-provider-auth.js +2 -2
  330. package/dist/modes/rpc/rpc-provider-auth.js.map +1 -1
  331. package/dist/modes/rpc/rpc-types.d.ts +6 -2
  332. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  333. package/dist/modes/rpc/rpc-types.js.map +1 -1
  334. package/docs/custom-provider/oauth.md +2 -2
  335. package/docs/custom-provider/override.md +3 -3
  336. package/docs/custom-provider/registration.md +7 -7
  337. package/docs/custom-provider/streaming.md +1 -1
  338. package/docs/custom-provider.md +5 -5
  339. package/docs/environment-variables.md +5 -1
  340. package/docs/extensions/api-reference.md +40 -19
  341. package/docs/extensions/authoring.md +1 -1
  342. package/docs/extensions/events.md +8 -8
  343. package/docs/extensions.md +2 -2
  344. package/docs/getting-started/installation.md +1 -2
  345. package/docs/providers.md +2 -2
  346. package/docs/quickstart.md +2 -1
  347. package/docs/reference/cli.md +3 -3
  348. package/docs/rpc/protocol.md +10 -4
  349. package/docs/sdk/reference.md +15 -13
  350. package/docs/sdk/web-server.md +5 -6
  351. package/docs/sdk.md +18 -1
  352. package/docs/session-format.md +7 -5
  353. package/docs/sessions.md +11 -2
  354. package/docs/settings.md +17 -2
  355. package/docs/storage.md +262 -1
  356. package/docs/usage.md +3 -2
  357. package/docs/workflows/api-reference.md +67 -11
  358. package/docs/workflows/operations.md +4 -2
  359. package/examples/extensions/bookmark.ts +2 -2
  360. package/examples/extensions/handoff.ts +2 -2
  361. package/examples/extensions/plan-mode/index.ts +15 -13
  362. package/examples/extensions/preset.ts +8 -8
  363. package/examples/extensions/session-name.ts +1 -1
  364. package/examples/extensions/snake.ts +3 -1
  365. package/examples/extensions/space-invaders.ts +3 -1
  366. package/examples/extensions/tic-tac-toe.ts +80 -80
  367. package/examples/sdk/11-sessions.ts +5 -5
  368. package/examples/sdk/13-session-runtime.ts +7 -7
  369. package/examples/sdk/README.md +1 -1
  370. package/npm-shrinkwrap.json +32 -32
  371. package/package.json +3 -3
  372. package/schemas/settings.schema.json +1 -22
  373. package/dist/builtin/workflows/builtin/chunk-h5fn47y5.js +0 -8
  374. package/dist/builtin/workflows/src/durable/journal/node-sqlite.d.ts +0 -20
@@ -1,119 +1,132 @@
1
+ import { writeFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
1
3
  import { getCurrentSystemMessage } from "@bastani/pi-ai";
2
- import { existsSync, readdirSync, statSync } from "fs";
3
- import { join, resolve } from "path";
4
+ import { getAgentDir } from "../config.js";
4
5
  import { normalizePath, resolvePath } from "../utils/paths.js";
5
- import { createBackupSnapshot, createBranchedSessionState, forkSessionFromFile, forkSessionFromFileAsync, } from "./session-manager-archive.js";
6
+ import { createBranchedSessionState } from "./session-manager-archive.js";
6
7
  import { classifiedWorkflowMetadata, validSessionWorkflowMetadata } from "./session-manager-classification.js";
7
8
  import { createBranchSummaryEntry, createCompactionEntry, createContextEditEntry, createCustomEntry, createCustomMessageEntry, createLabelEntry, createMessageEntry, createModelChangeEntry, createSessionFilePath, createSessionHeader, createSessionInfoEntry, createSessionSummaryEntry, createThinkingLevelChangeEntry, getEntriesWithoutHeader, getLatestSessionName, } from "./session-manager-entries.js";
9
+ import { SessionEntryError } from "./session-manager-errors.js";
8
10
  import { buildContextEntries, buildSessionIndex, buildSessionProjection, buildSessionTree, getBranchPath, } from "./session-manager-history.js";
9
- import { listAllSessions, listProjectSessions } from "./session-manager-list.js";
10
- import { getDefaultSessionDir, getDefaultSessionDirPath } from "./session-manager-paths.js";
11
- import { ensureDirectory, findMostRecentSession, getSessionHeaderCwd, hasConversationMessage, isInternalHeader, loadEntriesFromFile, persistAppendedEntry, readSessionHeader, sessionCwdMatches, writeSessionEntries, } from "./session-manager-storage.js";
11
+ import { listProjectSessions } from "./session-manager-list.js";
12
+ import { getDefaultSessionDirPath } from "./session-manager-paths.js";
12
13
  import { assertValidSessionId, createSessionId, generateId, validateSessionFileEntries, } from "./session-manager-validation.js";
13
- import { SessionFormatVersionError } from "./storage/session/errors.js";
14
- /** Manages conversation sessions as append-only trees stored in JSONL files. Each session entry has an id and parentId forming a tree structure. The "leaf" pointer tracks the current position. Appending creates a child of the current leaf. Branching moves the leaf to an earlier entry, allowing new branches without modifying history. Use buildSessionContext() to get the resolved message list for the LLM, which applies context-deletion filtering and follows the path from root to current leaf. */
14
+ import { SessionFormatVersionError, SessionIdMismatchError, SessionNotFoundError, StorageUnavailableError, } from "./storage/session/errors.js";
15
+ import { JsonlSessionStore } from "./storage/session/jsonl-session-store.js";
16
+ import { MemorySessionStore } from "./storage/session/memory-session-store.js";
17
+ /** An in-memory session tree whose mutations await the backing store. */
15
18
  export class SessionManager {
16
19
  sessionId = "";
17
20
  sessionFile;
18
21
  sessionDir;
19
22
  cwd;
20
- persist;
21
- flushed = false;
23
+ store;
24
+ lastSeq = 0;
25
+ mutation = Promise.resolve();
22
26
  fileEntries = [];
23
27
  byId = new Map();
24
28
  labelsById = new Map();
25
29
  labelTimestampsById = new Map();
26
30
  leafId = null;
27
- constructor(cwd, sessionDir, sessionFile, persist, newSessionOptions, preloadedFileEntries) {
31
+ constructor(store, cwd, sessionDir, options) {
32
+ this.store = store;
28
33
  this.cwd = resolvePath(cwd);
29
34
  this.sessionDir = normalizePath(sessionDir);
30
- this.persist = persist;
31
- if (persist && this.sessionDir && !preloadedFileEntries?.length) {
32
- ensureDirectory(this.sessionDir);
33
- }
34
- if (sessionFile) {
35
- this._setSessionFile(sessionFile, preloadedFileEntries);
36
- }
37
- else if (preloadedFileEntries?.length) {
38
- this._loadEntries(preloadedFileEntries, newSessionOptions);
39
- }
40
- else {
41
- this.newSession(newSessionOptions);
42
- }
35
+ this.start(options);
36
+ }
37
+ runMutation(operation) {
38
+ const result = this.mutation.then(operation);
39
+ this.mutation = result.then(() => { }, () => { });
40
+ return result;
41
+ }
42
+ recordHeader(header = this.getHeader()) {
43
+ const { type: _type, ...record } = header;
44
+ return record;
45
+ }
46
+ restore(snapshot, location) {
47
+ const header = snapshot.header;
48
+ this.fileEntries = [{ type: "session", ...header }, ...snapshot.entries];
49
+ this.sessionId = header.id;
50
+ this.lastSeq = snapshot.lastSeq;
51
+ this.sessionFile =
52
+ location ?? (this.store instanceof JsonlSessionStore ? this.store.locationFor(header) : undefined);
53
+ this._buildIndex();
43
54
  }
44
- _loadEntries(entries, options) {
45
- const header = entries[0]?.type === "session" ? entries[0] : undefined;
46
- if (header) {
47
- this.fileEntries = entries;
48
- this.sessionId = header.id;
49
- }
50
- else {
51
- this.newSession(options);
52
- this.fileEntries = this.fileEntries.concat(entries);
53
- }
55
+ start(options) {
56
+ if (options?.id !== undefined)
57
+ assertValidSessionId(options.id);
58
+ this.sessionId = options?.id ?? createSessionId();
59
+ this.fileEntries = [
60
+ createSessionHeader(this.sessionId, this.cwd, new Date().toISOString(), options?.parentSession, options?.internal, options?.workflow),
61
+ ];
62
+ this.lastSeq = 0;
54
63
  this._buildIndex();
64
+ this.sessionFile =
65
+ this.store instanceof JsonlSessionStore
66
+ ? this.sessionDir
67
+ ? createSessionFilePath(this.sessionDir, this.getHeader().createdAt, this.sessionId)
68
+ : this.store.locationFor(this.recordHeader())
69
+ : undefined;
70
+ return this.sessionFile;
55
71
  }
56
- /** Switch to a different session file (used for resume and branching) */
57
72
  setSessionFile(sessionFile) {
58
- this._setSessionFile(sessionFile);
59
- }
60
- _setSessionFile(sessionFile, preloadedFileEntries) {
61
- const explicitPath = resolvePath(sessionFile);
62
- if (preloadedFileEntries?.length || existsSync(explicitPath)) {
63
- const entries = preloadedFileEntries ?? loadEntriesFromFile(explicitPath);
64
- // Initialize only genuinely empty files, never an invalid non-empty session.
65
- if (entries.length === 0) {
66
- if (statSync(explicitPath).size > 0) {
67
- throw new SessionFormatVersionError(explicitPath, undefined);
68
- }
69
- this.newSession();
70
- this.sessionFile = explicitPath;
71
- this._rewriteFile();
72
- this.flushed = true;
73
- return;
74
- }
75
- const header = validateSessionFileEntries(entries, explicitPath);
76
- this.sessionFile = explicitPath;
77
- this.fileEntries = entries;
78
- this.sessionId = header.id;
79
- this._buildIndex();
80
- this.flushed = true;
81
- }
82
- else {
83
- this.newSession();
84
- this.sessionFile = explicitPath; // preserve explicit path from --session flag
73
+ return this.runMutation(async () => {
74
+ const opened = await SessionManager.open(sessionFile, this.sessionDir, this.cwd);
75
+ this.store = opened.store;
76
+ this.restore({ header: opened.recordHeader(), entries: opened.getEntries(), lastSeq: opened.lastSeq }, opened.sessionFile);
77
+ });
78
+ }
79
+ async initialize() {
80
+ this.lastSeq = (await (this.store instanceof JsonlSessionStore
81
+ ? this.store.create(this.recordHeader(), this.getEntries(), this.sessionFile)
82
+ : this.store.create(this.recordHeader(), this.getEntries()))).lastSeq;
83
+ }
84
+ async storeForNewSession() {
85
+ if (this.store instanceof JsonlSessionStore &&
86
+ this.sessionDir &&
87
+ this.store.descriptor.location !== resolvePath(this.sessionDir)) {
88
+ return JsonlSessionStore.open(this.sessionDir, { exactDirectory: true, scanExisting: false });
85
89
  }
90
+ return this.store;
86
91
  }
87
92
  newSession(options) {
88
- if (options?.id !== undefined) {
89
- assertValidSessionId(options.id);
90
- }
91
- this.sessionId = options?.id ?? createSessionId();
92
- const timestamp = new Date().toISOString();
93
- const header = createSessionHeader(this.sessionId, this.cwd, timestamp, options?.parentSession, options?.internal, options?.workflow);
94
- this.fileEntries = [header];
95
- this.byId.clear();
96
- this.labelsById.clear();
97
- this.labelTimestampsById.clear();
98
- this.leafId = null;
99
- this.flushed = false;
100
- if (this.persist) {
101
- this.sessionFile = createSessionFilePath(this.getSessionDir(), timestamp, this.sessionId);
102
- }
103
- return this.sessionFile;
93
+ return this.runMutation(async () => {
94
+ if (options?.id !== undefined)
95
+ assertValidSessionId(options.id);
96
+ const header = createSessionHeader(options?.id ?? createSessionId(), this.cwd, new Date().toISOString(), options?.parentSession, options?.internal, options?.workflow);
97
+ const record = this.recordHeader(header);
98
+ const store = await this.storeForNewSession();
99
+ const location = store instanceof JsonlSessionStore
100
+ ? this.sessionDir
101
+ ? createSessionFilePath(this.sessionDir, record.createdAt, record.id)
102
+ : store.locationFor(record)
103
+ : undefined;
104
+ const result = await (store instanceof JsonlSessionStore
105
+ ? store.create(record, [], location)
106
+ : store.create(record, []));
107
+ this.store = store;
108
+ this.byId.clear();
109
+ this.labelsById.clear();
110
+ this.labelTimestampsById.clear();
111
+ this.restore({ header: record, entries: [], lastSeq: result.lastSeq }, location);
112
+ return this.sessionFile;
113
+ });
104
114
  }
105
- /** Mark the session as workflow-owned, repairing malformed markers while preserving valid ownership. */
106
115
  markSessionInternal(workflow) {
107
- const header = this.fileEntries.find((entry) => entry.type === "session");
108
- if (!header || classifiedWorkflowMetadata(header))
109
- return;
110
- const validWorkflow = validSessionWorkflowMetadata(workflow);
111
- if (!validWorkflow)
112
- return;
113
- header.internal = true;
114
- header.workflow = validWorkflow;
115
- if (this.flushed)
116
- this._rewriteFile();
116
+ return this.runMutation(async () => {
117
+ const previous = this.getHeader();
118
+ if (classifiedWorkflowMetadata(previous))
119
+ return;
120
+ const validWorkflow = validSessionWorkflowMetadata(workflow);
121
+ if (!validWorkflow)
122
+ return;
123
+ const header = { ...previous, internal: true, workflow: validWorkflow };
124
+ const result = await this.store.replace(this.sessionId, this.recordHeader(header), this.getEntries(), {
125
+ expectSeq: this.lastSeq,
126
+ });
127
+ this.lastSeq = result.lastSeq;
128
+ this.fileEntries[0] = header;
129
+ });
117
130
  }
118
131
  _buildIndex() {
119
132
  validateSessionFileEntries(this.fileEntries, this.sessionFile ?? "in-memory session");
@@ -123,25 +136,8 @@ export class SessionManager {
123
136
  this.labelTimestampsById = index.labelTimestampsById;
124
137
  this.leafId = index.leafId;
125
138
  }
126
- _rewriteFile() {
127
- if (!this.persist || !this.sessionFile)
128
- return;
129
- writeSessionEntries(this.sessionFile, this.fileEntries);
130
- }
131
139
  isPersisted() {
132
- return this.persist;
133
- }
134
- /** Persist the current session tree before an in-process attempt is force-finalized. */
135
- flush() {
136
- if (!this.persist || !this.sessionFile)
137
- return;
138
- this._rewriteFile();
139
- this.flushed = true;
140
- }
141
- /** Flush only a session whose file has already been started, so closing an unsaved session writes nothing. */
142
- flushIfStarted() {
143
- if (this.flushed || hasConversationMessage(this.fileEntries))
144
- this.flush();
140
+ return !(this.store instanceof MemorySessionStore);
145
141
  }
146
142
  getCwd() {
147
143
  return this.cwd;
@@ -158,127 +154,188 @@ export class SessionManager {
158
154
  getSessionFile() {
159
155
  return this.sessionFile;
160
156
  }
161
- _persist(entry) {
162
- if (!this.persist || !this.sessionFile)
163
- return;
164
- this.flushed = persistAppendedEntry(this.sessionFile, this.fileEntries, entry, this.flushed);
157
+ getSessionStore() {
158
+ return this.store;
165
159
  }
166
- _appendEntry(entry) {
167
- const previousLeafId = this.leafId;
168
- this.fileEntries.push(entry);
169
- this.byId.set(entry.id, entry);
170
- this.leafId = entry.id;
160
+ async openSessionById(sessionId, cwdOverride, sessionDirectory) {
161
+ let store = sessionDirectory === undefined
162
+ ? this.store
163
+ : await JsonlSessionStore.open(sessionDirectory, { exactDirectory: true, scanExisting: false });
164
+ let snapshot;
171
165
  try {
172
- this._persist(entry);
166
+ snapshot = await store.load(sessionId);
173
167
  }
174
168
  catch (error) {
175
- // Unpublish on write failure, so retries cannot point at an unwritten parent.
176
- this.fileEntries.pop();
177
- this.byId.delete(entry.id);
178
- this.leafId = previousLeafId;
179
- throw error;
169
+ if (!(error instanceof SessionNotFoundError) ||
170
+ sessionDirectory !== undefined ||
171
+ !this.usesDefaultSessionDir())
172
+ throw error;
173
+ store = await JsonlSessionStore.open(join(getAgentDir(), "sessions"), { scanExisting: false });
174
+ snapshot = await store.load(sessionId);
180
175
  }
176
+ const location = store instanceof JsonlSessionStore ? await store.findFile(sessionId) : undefined;
177
+ if (location !== undefined) {
178
+ store = await JsonlSessionStore.open(dirname(location), { exactDirectory: true, scanExisting: false });
179
+ snapshot = await store.load(sessionId);
180
+ }
181
+ if (snapshot.header.id !== sessionId)
182
+ throw new SessionIdMismatchError(sessionId, snapshot.header.id);
183
+ const manager = new SessionManager(store, cwdOverride ?? snapshot.header.cwd, this.sessionDir);
184
+ manager.restore(snapshot, location);
185
+ if (location !== undefined)
186
+ manager.sessionDir = dirname(location);
187
+ return manager;
188
+ }
189
+ async importFromJsonl(inputPath, cwdOverride) {
190
+ const source = await JsonlSessionStore.open(dirname(resolvePath(inputPath)), {
191
+ exactDirectory: true,
192
+ scanExisting: false,
193
+ });
194
+ try {
195
+ const snapshot = await source.loadFile(inputPath);
196
+ const manager = new SessionManager(this.store, cwdOverride ?? snapshot.header.cwd, this.sessionDir);
197
+ manager.restore(snapshot);
198
+ await manager.initialize();
199
+ return manager;
200
+ }
201
+ finally {
202
+ await source.close();
203
+ }
204
+ }
205
+ async _appendEntry(entry) {
206
+ const result = await this.store.append(this.sessionId, [entry], { expectSeq: this.lastSeq });
207
+ this.lastSeq = result.lastSeq;
208
+ this.fileEntries.push(entry);
209
+ this.byId.set(entry.id, entry);
210
+ this.leafId = entry.id;
181
211
  }
182
212
  /** Append a message as child of current leaf, then advance leaf. Returns entry id. */
183
213
  appendMessage(message) {
184
- const entry = createMessageEntry(message, this.byId, this.leafId);
185
- this._appendEntry(entry);
186
- return entry.id;
214
+ return this.runMutation(async () => {
215
+ const entry = createMessageEntry(message, this.byId, this.leafId);
216
+ await this._appendEntry(entry);
217
+ return entry.id;
218
+ });
187
219
  }
188
220
  /** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */
189
221
  appendThinkingLevelChange(thinkingLevel) {
190
- const entry = createThinkingLevelChangeEntry(thinkingLevel, this.byId, this.leafId);
191
- this._appendEntry(entry);
192
- return entry.id;
222
+ return this.runMutation(async () => {
223
+ const entry = createThinkingLevelChangeEntry(thinkingLevel, this.byId, this.leafId);
224
+ await this._appendEntry(entry);
225
+ return entry.id;
226
+ });
193
227
  }
194
228
  /** Record auxiliary model usage without adding it to the LLM context. */
195
229
  appendUsage(kind, provider, model, usage, note) {
196
- const entry = {
197
- type: "usage",
198
- id: generateId(this.byId),
199
- parentId: this.leafId,
200
- timestamp: new Date().toISOString(),
201
- kind,
202
- provider,
203
- model,
204
- usage,
205
- ...(note === undefined ? {} : { note }),
206
- };
207
- this._appendEntry(entry);
208
- return entry;
230
+ return this.runMutation(async () => {
231
+ const entry = {
232
+ type: "usage",
233
+ id: generateId(this.byId),
234
+ parentId: this.leafId,
235
+ timestamp: new Date().toISOString(),
236
+ kind,
237
+ provider,
238
+ model,
239
+ usage,
240
+ ...(note === undefined ? {} : { note }),
241
+ };
242
+ await this._appendEntry(entry);
243
+ return entry;
244
+ });
209
245
  }
210
246
  /** Append a model change as child of current leaf, then advance leaf. Returns entry id. */
211
247
  appendModelChange(provider, modelId) {
212
- const entry = createModelChangeEntry(provider, modelId, this.byId, this.leafId);
213
- this._appendEntry(entry);
214
- return entry.id;
248
+ return this.runMutation(async () => {
249
+ const entry = createModelChangeEntry(provider, modelId, this.byId, this.leafId);
250
+ await this._appendEntry(entry);
251
+ return entry.id;
252
+ });
215
253
  }
216
254
  appendCompaction(compactedText, firstKeptEntryId, tokensBefore, details, usage) {
217
- if (firstKeptEntryId !== null && !this.byId.has(firstKeptEntryId))
218
- throw new Error(`Entry ${firstKeptEntryId} not found`);
219
- const entry = createCompactionEntry(compactedText, firstKeptEntryId, tokensBefore, details, usage, this.byId, this.leafId);
220
- const systemMessage = getCurrentSystemMessage(this.buildSessionProjection().messages);
221
- if (systemMessage)
222
- entry.systemMessage = { ...systemMessage, timestamp: new Date(entry.timestamp).getTime() };
223
- this._appendEntry(entry);
224
- return entry.id;
225
- }
226
- /** Write a recoverable snapshot of the current session entries without mutating the active JSONL. */
255
+ return this.runMutation(async () => {
256
+ if (firstKeptEntryId !== null && !this.byId.has(firstKeptEntryId))
257
+ throw new SessionEntryError(firstKeptEntryId, "missing");
258
+ const entry = createCompactionEntry(compactedText, firstKeptEntryId, tokensBefore, details, usage, this.byId, this.leafId);
259
+ const systemMessage = getCurrentSystemMessage(this.buildSessionProjection().messages);
260
+ if (systemMessage)
261
+ entry.systemMessage = { ...systemMessage, timestamp: new Date(entry.timestamp).getTime() };
262
+ await this._appendEntry(entry);
263
+ return entry.id;
264
+ });
265
+ }
266
+ /** Save a JSONL backup; database-backed sessions have no file snapshot. */
227
267
  writeBackupSnapshot(label = "compact") {
228
- if (!this.persist)
229
- return undefined;
230
- return createBackupSnapshot(this.sessionFile, this.fileEntries, label);
268
+ return this.runMutation(async () => {
269
+ if (!(this.store instanceof JsonlSessionStore) || !this.sessionFile)
270
+ return undefined;
271
+ const path = `${this.sessionFile}.${new Date().toISOString().replace(/[:.]/g, "-")}.${label.replace(/[^a-z0-9_-]/gi, "-") || "backup"}.bak`;
272
+ try {
273
+ await writeFile(path, `${[JSON.stringify({ type: "session", ...this.recordHeader() }), ...this.getEntries().map((entry) => JSON.stringify(entry))].join("\n")}\n`);
274
+ }
275
+ catch (cause) {
276
+ throw new StorageUnavailableError(this.store.descriptor, cause);
277
+ }
278
+ return path;
279
+ });
231
280
  }
232
281
  /** Append a branch-local edit to an earlier model-visible entry. */
233
282
  appendContextEdit(targetId, replacement) {
234
- if (replacement !== null &&
235
- (typeof replacement !== "object" ||
236
- !("content" in replacement) ||
237
- (typeof replacement.content !== "string" && !Array.isArray(replacement.content)))) {
238
- throw new Error("Context edit replacement must be null or contain string/array content");
239
- }
240
- const target = this.byId.get(targetId);
241
- if (!target)
242
- throw new Error(`Entry ${targetId} not found`);
243
- if (!this.getBranch().some((entry) => entry.id === targetId)) {
244
- throw new Error(`Entry ${targetId} is not on the active branch`);
245
- }
246
- const editable = target.type === "custom_message" ||
247
- (target.type === "message" &&
248
- (target.message.role === "user" ||
249
- target.message.role === "assistant" ||
250
- target.message.role === "toolResult"));
251
- if (!editable)
252
- throw new Error(`Entry ${targetId} does not contribute editable model content`);
253
- const targetRole = target.type === "message" ? target.message.role : "custom";
254
- const normalizedReplacement = replacement !== null &&
255
- (targetRole === "assistant" || targetRole === "toolResult") &&
256
- typeof replacement.content === "string"
257
- ? { content: [{ type: "text", text: replacement.content }] }
258
- : replacement;
259
- const entry = createContextEditEntry(targetId, normalizedReplacement, this.byId, this.leafId);
260
- this._appendEntry(entry);
261
- return entry.id;
283
+ return this.runMutation(async () => {
284
+ if (replacement !== null &&
285
+ (typeof replacement !== "object" ||
286
+ !("content" in replacement) ||
287
+ (typeof replacement.content !== "string" && !Array.isArray(replacement.content)))) {
288
+ throw new SessionEntryError(targetId, "invalid-replacement");
289
+ }
290
+ const target = this.byId.get(targetId);
291
+ if (!target)
292
+ throw new SessionEntryError(targetId, "missing");
293
+ if (!this.getBranch().some((entry) => entry.id === targetId)) {
294
+ throw new SessionEntryError(targetId, "inactive");
295
+ }
296
+ const editable = target.type === "custom_message" ||
297
+ (target.type === "message" &&
298
+ (target.message.role === "user" ||
299
+ target.message.role === "assistant" ||
300
+ target.message.role === "toolResult"));
301
+ if (!editable)
302
+ throw new SessionEntryError(targetId, "not-editable");
303
+ const targetRole = target.type === "message" ? target.message.role : "custom";
304
+ const normalizedReplacement = replacement !== null &&
305
+ (targetRole === "assistant" || targetRole === "toolResult") &&
306
+ typeof replacement.content === "string"
307
+ ? { content: [{ type: "text", text: replacement.content }] }
308
+ : replacement;
309
+ const entry = createContextEditEntry(targetId, normalizedReplacement, this.byId, this.leafId);
310
+ await this._appendEntry(entry);
311
+ return entry.id;
312
+ });
262
313
  }
263
314
  /** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */
264
315
  appendCustomEntry(customType, data) {
265
- const entry = createCustomEntry(customType, data, this.byId, this.leafId);
266
- this._appendEntry(entry);
267
- return entry.id;
316
+ return this.runMutation(async () => {
317
+ const entry = createCustomEntry(customType, data, this.byId, this.leafId);
318
+ await this._appendEntry(entry);
319
+ return entry.id;
320
+ });
268
321
  }
269
322
  /** Append a session info entry (e.g., display name). Returns entry id. */
270
323
  appendSessionInfo(name) {
271
- const entry = createSessionInfoEntry(name, this.byId, this.leafId);
272
- this._appendEntry(entry);
273
- return entry.id;
324
+ return this.runMutation(async () => {
325
+ const entry = createSessionInfoEntry(name, this.byId, this.leafId);
326
+ await this._appendEntry(entry);
327
+ return entry.id;
328
+ });
274
329
  }
275
330
  /** Append a generated resume summary anchored to the message it describes. Returns entry id. */
276
331
  appendSessionSummary(summary, summarizedThroughId, usage) {
277
- if (!this.byId.has(summarizedThroughId))
278
- throw new Error(`Entry ${summarizedThroughId} not found`);
279
- const entry = createSessionSummaryEntry(summary, summarizedThroughId, usage, this.byId, this.leafId);
280
- this._appendEntry(entry);
281
- return entry.id;
332
+ return this.runMutation(async () => {
333
+ if (!this.byId.has(summarizedThroughId))
334
+ throw new SessionEntryError(summarizedThroughId, "missing");
335
+ const entry = createSessionSummaryEntry(summary, summarizedThroughId, usage, this.byId, this.leafId);
336
+ await this._appendEntry(entry);
337
+ return entry.id;
338
+ });
282
339
  }
283
340
  /** Get the current session name from the latest session_info entry, if any. */
284
341
  getSessionName() {
@@ -294,9 +351,11 @@ export class SessionManager {
294
351
  }
295
352
  /** Append a custom message entry (for extensions) that participates in LLM context unless excluded. */
296
353
  appendCustomMessageEntry(customType, content, display, details, excludeFromContext, protectedReconciliation, stageAdmissionKey) {
297
- const entry = createCustomMessageEntry(customType, content, display, details, excludeFromContext, protectedReconciliation, this.byId, this.leafId, stageAdmissionKey);
298
- this._appendEntry(entry);
299
- return entry.id;
354
+ return this.runMutation(async () => {
355
+ const entry = createCustomMessageEntry(customType, content, display, details, excludeFromContext, protectedReconciliation, this.byId, this.leafId, stageAdmissionKey);
356
+ await this._appendEntry(entry);
357
+ return entry.id;
358
+ });
300
359
  }
301
360
  getLeafId() {
302
361
  return this.leafId;
@@ -323,20 +382,22 @@ export class SessionManager {
323
382
  }
324
383
  /** Set or clear a label on an entry. */
325
384
  appendLabelChange(targetId, label) {
326
- if (!this.byId.has(targetId)) {
327
- throw new Error(`Entry ${targetId} not found`);
328
- }
329
- const entry = createLabelEntry(targetId, label, this.byId, this.leafId);
330
- this._appendEntry(entry);
331
- if (label) {
332
- this.labelsById.set(targetId, label);
333
- this.labelTimestampsById.set(targetId, entry.timestamp);
334
- }
335
- else {
336
- this.labelsById.delete(targetId);
337
- this.labelTimestampsById.delete(targetId);
338
- }
339
- return entry.id;
385
+ return this.runMutation(async () => {
386
+ if (!this.byId.has(targetId)) {
387
+ throw new SessionEntryError(targetId, "missing");
388
+ }
389
+ const entry = createLabelEntry(targetId, label, this.byId, this.leafId);
390
+ await this._appendEntry(entry);
391
+ if (label) {
392
+ this.labelsById.set(targetId, label);
393
+ this.labelTimestampsById.set(targetId, entry.timestamp);
394
+ }
395
+ else {
396
+ this.labelsById.delete(targetId);
397
+ this.labelTimestampsById.delete(targetId);
398
+ }
399
+ return entry.id;
400
+ });
340
401
  }
341
402
  /** Walk from entry to root, returning all entries in path order. */
342
403
  getBranch(fromId) {
@@ -374,118 +435,189 @@ export class SessionManager {
374
435
  }
375
436
  /** Start a new branch from an earlier entry. */
376
437
  branch(branchFromId) {
377
- if (!this.byId.has(branchFromId)) {
378
- throw new Error(`Entry ${branchFromId} not found`);
379
- }
380
- this.leafId = branchFromId;
438
+ return this.runMutation(async () => {
439
+ if (!this.byId.has(branchFromId)) {
440
+ throw new SessionEntryError(branchFromId, "missing");
441
+ }
442
+ this.leafId = branchFromId;
443
+ });
381
444
  }
382
445
  /** Reset the leaf pointer to null (before any entries). */
383
446
  resetLeaf() {
384
- this.leafId = null;
447
+ return this.runMutation(async () => {
448
+ this.leafId = null;
449
+ });
385
450
  }
386
451
  /** Start a new branch with a summary of the abandoned path. */
387
- branchWithSummary(branchFromId, summary, details, fromHook, usage, fromId = this.leafId ?? "root") {
388
- if (branchFromId !== null && !this.byId.has(branchFromId)) {
389
- throw new Error(`Entry ${branchFromId} not found`);
390
- }
391
- this.leafId = branchFromId;
392
- const entry = createBranchSummaryEntry(branchFromId, fromId, summary, details, usage, fromHook, this.byId);
393
- this._appendEntry(entry);
394
- return entry.id;
452
+ branchWithSummary(branchFromId, summary, details, fromHook, usage, fromId) {
453
+ return this.runMutation(async () => {
454
+ if (branchFromId !== null && !this.byId.has(branchFromId)) {
455
+ throw new SessionEntryError(branchFromId, "missing");
456
+ }
457
+ const entry = createBranchSummaryEntry(branchFromId, fromId ?? this.leafId ?? "root", summary, details, usage, fromHook, this.byId);
458
+ await this._appendEntry(entry);
459
+ return entry.id;
460
+ });
395
461
  }
396
- /** Create a new session file containing only the path from root to the specified leaf. */
397
462
  createBranchedSession(leafId) {
398
- const result = createBranchedSessionState({
399
- leafId,
400
- persist: this.persist,
401
- sessionDir: this.getSessionDir(),
402
- cwd: this.cwd,
403
- previousSessionFile: this.sessionFile,
404
- workflow: classifiedWorkflowMetadata(this.getHeader()),
405
- path: this.getBranch(leafId),
406
- labelsById: this.labelsById,
407
- labelTimestampsById: this.labelTimestampsById,
463
+ return this.runMutation(async () => {
464
+ const result = createBranchedSessionState({
465
+ leafId,
466
+ cwd: this.cwd,
467
+ parentSessionId: this.sessionId,
468
+ workflow: classifiedWorkflowMetadata(this.getHeader()),
469
+ path: this.getBranch(leafId),
470
+ labelsById: this.labelsById,
471
+ labelTimestampsById: this.labelTimestampsById,
472
+ });
473
+ const header = result.fileEntries[0];
474
+ const entries = getEntriesWithoutHeader(result.fileEntries);
475
+ const record = this.recordHeader(header);
476
+ const store = await this.storeForNewSession();
477
+ const location = store instanceof JsonlSessionStore
478
+ ? this.sessionDir
479
+ ? createSessionFilePath(this.sessionDir, record.createdAt, record.id)
480
+ : store.locationFor(record)
481
+ : undefined;
482
+ const lastSeq = (await (store instanceof JsonlSessionStore
483
+ ? store.create(record, entries, location)
484
+ : store.create(record, entries))).lastSeq;
485
+ this.store = store;
486
+ this.fileEntries = result.fileEntries;
487
+ this.sessionId = header.id;
488
+ this.lastSeq = lastSeq;
489
+ this.sessionFile = location;
490
+ this._buildIndex();
491
+ return this.sessionFile;
408
492
  });
409
- this.fileEntries = result.fileEntries;
410
- this.sessionId = result.sessionId;
411
- if (result.sessionFile)
412
- this.sessionFile = result.sessionFile;
413
- this._buildIndex();
414
- if (this.persist) {
415
- if (result.shouldRewriteFile)
416
- this._rewriteFile();
417
- this.flushed = result.flushed ?? false;
418
- return result.sessionFile;
493
+ }
494
+ async forkTo(cwd, sessionDir, options) {
495
+ const directory = sessionDir ?? getDefaultSessionDirPath(cwd);
496
+ const store = await JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false });
497
+ const manager = new SessionManager(store, cwd, directory, { ...options, parentSession: this.sessionId });
498
+ manager.fileEntries.push(...this.getEntries());
499
+ await manager.initialize();
500
+ manager._buildIndex();
501
+ return manager;
502
+ }
503
+ static async importFromJsonl(inputPath, cwd, sessionDir) {
504
+ const directory = sessionDir ?? getDefaultSessionDirPath(cwd);
505
+ const store = await JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false });
506
+ return new SessionManager(store, cwd, directory).importFromJsonl(inputPath);
507
+ }
508
+ static async create(cwdOrStore, directoryOrCwd, options) {
509
+ const cwd = typeof cwdOrStore === "string" ? cwdOrStore : (directoryOrCwd ?? process.cwd());
510
+ const directory = typeof cwdOrStore === "string"
511
+ ? directoryOrCwd
512
+ ? normalizePath(directoryOrCwd)
513
+ : getDefaultSessionDirPath(cwd)
514
+ : cwdOrStore instanceof JsonlSessionStore
515
+ ? cwdOrStore.descriptor.location
516
+ : "";
517
+ const store = typeof cwdOrStore === "string"
518
+ ? await JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false })
519
+ : cwdOrStore;
520
+ const manager = new SessionManager(store, cwd, directory, options);
521
+ if (typeof cwdOrStore !== "string" && store instanceof JsonlSessionStore) {
522
+ manager.sessionFile = store.locationFor(manager.recordHeader());
523
+ manager.sessionDir = dirname(manager.sessionFile);
524
+ }
525
+ await manager.initialize();
526
+ return manager;
527
+ }
528
+ static async open(pathOrStore, directoryOrId, cwdOverride) {
529
+ if (typeof pathOrStore !== "string") {
530
+ const snapshot = await pathOrStore.load(directoryOrId);
531
+ if (snapshot.header.id !== directoryOrId)
532
+ throw new SessionIdMismatchError(directoryOrId, snapshot.header.id);
533
+ const manager = new SessionManager(pathOrStore, cwdOverride ?? snapshot.header.cwd, pathOrStore instanceof JsonlSessionStore ? pathOrStore.descriptor.location : "");
534
+ manager.restore(snapshot, pathOrStore instanceof JsonlSessionStore ? await pathOrStore.findFile(directoryOrId) : undefined);
535
+ if (manager.sessionFile)
536
+ manager.sessionDir = dirname(manager.sessionFile);
537
+ return manager;
419
538
  }
420
- return undefined;
421
- }
422
- /** Create a new session. */
423
- static create(cwd, sessionDir, options) {
424
- const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);
425
- return new SessionManager(cwd, dir, undefined, true, options);
426
- }
427
- /** Open a specific session file. */
428
- static open(path, sessionDir, cwdOverride) {
429
- const resolvedPath = resolvePath(path);
430
- const entries = loadEntriesFromFile(resolvedPath);
431
- const header = entries.find((entry) => entry.type === "session");
432
- const cwd = cwdOverride ?? header?.cwd ?? process.cwd();
433
- const dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, "..");
434
- return new SessionManager(cwd, dir, resolvedPath, true);
435
- }
436
- /** Continue the most recent session (skips internal workflow sessions unless `includeInternal: true`). */
437
- static continueRecent(cwd, sessionDir, options) {
438
- const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);
439
- const filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);
440
- const mostRecent = findMostRecentSession(dir, filterCwd ? cwd : undefined, options?.includeInternal === true);
441
- return new SessionManager(cwd, dir, mostRecent ?? undefined, true);
442
- }
443
- /** Create an in-memory session (no file persistence), optionally preloaded with entries. */
539
+ const path = resolvePath(pathOrStore);
540
+ const directory = directoryOrId ?? dirname(path);
541
+ const store = await JsonlSessionStore.open(dirname(path), { exactDirectory: true, scanExisting: false });
542
+ let snapshot;
543
+ try {
544
+ snapshot = await store.loadFile(path);
545
+ }
546
+ catch (error) {
547
+ if (!(error instanceof StorageUnavailableError) || error.cause.code !== "ENOENT")
548
+ throw error;
549
+ const manager = new SessionManager(store, cwdOverride ?? process.cwd(), directory);
550
+ manager.lastSeq = (await store.create(manager.recordHeader(), [], path)).lastSeq;
551
+ manager.sessionFile = path;
552
+ return manager;
553
+ }
554
+ const manager = new SessionManager(store, cwdOverride ?? snapshot.header.cwd, directory);
555
+ manager.restore(snapshot, path);
556
+ return manager;
557
+ }
558
+ static async continueRecent(cwdOrStore, directoryOrCwd, options) {
559
+ const cwd = typeof cwdOrStore === "string" ? cwdOrStore : directoryOrCwd;
560
+ const directory = typeof cwdOrStore === "string" ? (directoryOrCwd ?? getDefaultSessionDirPath(cwd)) : "";
561
+ const store = typeof cwdOrStore === "string"
562
+ ? await JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false })
563
+ : cwdOrStore;
564
+ const recent = await store.findMostRecent({ cwd: resolvePath(cwd), includeInternal: options?.includeInternal });
565
+ const manager = new SessionManager(store, cwd, directory);
566
+ if (recent)
567
+ manager.restore(await store.load(recent.id), recent.location);
568
+ else
569
+ await manager.initialize();
570
+ return manager;
571
+ }
444
572
  static inMemory(cwd = process.cwd(), options, entries) {
445
- return new SessionManager(cwd, "", undefined, false, options, entries);
446
- }
447
- /** Fork a session from another project directory into the current project. */
448
- static forkFrom(sourcePath, targetCwd, sessionDir, options) {
449
- const forked = forkSessionFromFile(sourcePath, targetCwd, sessionDir, options);
450
- return new SessionManager(forked.cwd, forked.sessionDir, forked.sessionFile, true);
451
- }
452
- static async forkFromAsync(sourcePath, targetCwd, sessionDir, options) {
453
- const forked = await forkSessionFromFileAsync(sourcePath, targetCwd, sessionDir, options);
454
- return new SessionManager(forked.cwd, forked.sessionDir, forked.sessionFile, true, undefined, forked.fileEntries);
455
- }
456
- /** Find an exact, non-internal session ID by reading headers, not transcripts. */
457
- static findById(cwd, id, sessionDir) {
458
- const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);
459
- const filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);
460
- const resolvedCwd = resolvePath(cwd);
573
+ const manager = new SessionManager(new MemorySessionStore(), cwd, "", options);
574
+ if (entries?.length) {
575
+ manager.fileEntries = entries[0].type === "session" ? entries : [...manager.fileEntries, ...entries];
576
+ manager.sessionId = manager.getHeader().id;
577
+ manager._buildIndex();
578
+ }
579
+ manager.mutation = manager.initialize();
580
+ return manager;
581
+ }
582
+ static async forkFrom(sourcePath, targetCwd, sessionDir, options) {
583
+ const sourceStore = await JsonlSessionStore.open(dirname(resolvePath(sourcePath)), {
584
+ exactDirectory: true,
585
+ scanExisting: false,
586
+ });
587
+ const source = await sourceStore.loadFile(resolvePath(sourcePath));
588
+ const directory = sessionDir ?? getDefaultSessionDirPath(targetCwd);
589
+ const store = await JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false });
590
+ const manager = new SessionManager(store, targetCwd, directory, { ...options, parentSession: source.header.id });
591
+ manager.fileEntries.push(...source.entries);
592
+ await manager.initialize();
593
+ manager._buildIndex();
594
+ return manager;
595
+ }
596
+ static async findById(cwd, id, sessionDir) {
597
+ const directory = sessionDir ?? getDefaultSessionDirPath(cwd);
598
+ const store = await JsonlSessionStore.open(directory, { exactDirectory: true, scanExisting: false });
599
+ let header;
461
600
  try {
462
- for (const file of readdirSync(dir)) {
463
- if (!file.endsWith(".jsonl"))
464
- continue;
465
- const path = join(dir, file);
466
- const header = readSessionHeader(path);
467
- if (header?.id !== id || isInternalHeader(header))
468
- continue;
469
- if (filterCwd && !sessionCwdMatches(getSessionHeaderCwd(header), resolvedCwd))
470
- continue;
471
- return path;
472
- }
601
+ header = await store.readHeader(id);
473
602
  }
474
- catch {
475
- // Discovery is best-effort, matching list().
603
+ catch (error) {
604
+ if (error instanceof SessionFormatVersionError)
605
+ return undefined;
606
+ throw error;
476
607
  }
477
- return undefined;
608
+ if (!header || classifiedWorkflowMetadata(header) || resolvePath(header.cwd) !== resolvePath(cwd))
609
+ return undefined;
610
+ return store.findFile(id);
478
611
  }
479
- /** List sessions for a directory. Internal (workflow) sessions are excluded unless `includeInternal: true`. */
480
612
  static async list(cwd, sessionDir, onProgress, options) {
481
613
  const signal = options && "aborted" in options ? options : options?.signal;
482
614
  return listProjectSessions(cwd, sessionDir, onProgress, options !== undefined && "includeInternal" in options && options.includeInternal === true, signal);
483
615
  }
484
- static async listAll(sessionDirOrOnProgress, onProgress, options) {
485
- const signal = options && "aborted" in options
616
+ static async listAll(directoryOrProgress, progressOrSignal, options) {
617
+ const { listAllSessions } = await import("./session-manager-list.js");
618
+ return listAllSessions(directoryOrProgress, typeof progressOrSignal === "function" ? progressOrSignal : undefined, options !== undefined && "includeInternal" in options && options.includeInternal === true, options && "aborted" in options
486
619
  ? options
487
- : (options?.signal ?? (typeof onProgress === "object" ? onProgress : undefined));
488
- return listAllSessions(sessionDirOrOnProgress, typeof onProgress === "function" ? onProgress : undefined, options !== undefined && "includeInternal" in options && options.includeInternal === true, signal);
620
+ : (options?.signal ?? (typeof progressOrSignal === "object" ? progressOrSignal : undefined)));
489
621
  }
490
622
  }
491
623
  //# sourceMappingURL=session-manager-core.js.map