@bastani/atomic 0.9.38-alpha.1 → 0.9.38-alpha.10

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