leaf-coding-agent 1.0.0

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 (598) hide show
  1. package/dist/cli/args.d.ts +55 -0
  2. package/dist/cli/args.d.ts.map +1 -0
  3. package/dist/cli/args.js +356 -0
  4. package/dist/cli/args.js.map +1 -0
  5. package/dist/cli/config-selector.d.ts +14 -0
  6. package/dist/cli/config-selector.d.ts.map +1 -0
  7. package/dist/cli/config-selector.js +31 -0
  8. package/dist/cli/config-selector.js.map +1 -0
  9. package/dist/cli/file-processor.d.ts +15 -0
  10. package/dist/cli/file-processor.d.ts.map +1 -0
  11. package/dist/cli/file-processor.js +82 -0
  12. package/dist/cli/file-processor.js.map +1 -0
  13. package/dist/cli/initial-message.d.ts +18 -0
  14. package/dist/cli/initial-message.d.ts.map +1 -0
  15. package/dist/cli/initial-message.js +22 -0
  16. package/dist/cli/initial-message.js.map +1 -0
  17. package/dist/cli/list-models.d.ts +9 -0
  18. package/dist/cli/list-models.d.ts.map +1 -0
  19. package/dist/cli/list-models.js +98 -0
  20. package/dist/cli/list-models.js.map +1 -0
  21. package/dist/cli/session-picker.d.ts +9 -0
  22. package/dist/cli/session-picker.d.ts.map +1 -0
  23. package/dist/cli/session-picker.js +35 -0
  24. package/dist/cli/session-picker.js.map +1 -0
  25. package/dist/cli.d.ts +3 -0
  26. package/dist/cli.d.ts.map +1 -0
  27. package/dist/cli.js +18 -0
  28. package/dist/cli.js.map +1 -0
  29. package/dist/config.d.ts +92 -0
  30. package/dist/config.d.ts.map +1 -0
  31. package/dist/config.js +428 -0
  32. package/dist/config.js.map +1 -0
  33. package/dist/core/agent-session-runtime.d.ts +117 -0
  34. package/dist/core/agent-session-runtime.d.ts.map +1 -0
  35. package/dist/core/agent-session-runtime.js +300 -0
  36. package/dist/core/agent-session-runtime.js.map +1 -0
  37. package/dist/core/agent-session-services.d.ts +87 -0
  38. package/dist/core/agent-session-services.d.ts.map +1 -0
  39. package/dist/core/agent-session-services.js +119 -0
  40. package/dist/core/agent-session-services.js.map +1 -0
  41. package/dist/core/agent-session.d.ts +602 -0
  42. package/dist/core/agent-session.d.ts.map +1 -0
  43. package/dist/core/agent-session.js +2523 -0
  44. package/dist/core/agent-session.js.map +1 -0
  45. package/dist/core/auth-guidance.d.ts +5 -0
  46. package/dist/core/auth-guidance.d.ts.map +1 -0
  47. package/dist/core/auth-guidance.js +21 -0
  48. package/dist/core/auth-guidance.js.map +1 -0
  49. package/dist/core/auth-storage.d.ts +141 -0
  50. package/dist/core/auth-storage.d.ts.map +1 -0
  51. package/dist/core/auth-storage.js +442 -0
  52. package/dist/core/auth-storage.js.map +1 -0
  53. package/dist/core/bash-executor.d.ts +32 -0
  54. package/dist/core/bash-executor.d.ts.map +1 -0
  55. package/dist/core/bash-executor.js +111 -0
  56. package/dist/core/bash-executor.js.map +1 -0
  57. package/dist/core/compaction/branch-summarization.d.ts +88 -0
  58. package/dist/core/compaction/branch-summarization.d.ts.map +1 -0
  59. package/dist/core/compaction/branch-summarization.js +243 -0
  60. package/dist/core/compaction/branch-summarization.js.map +1 -0
  61. package/dist/core/compaction/compaction.d.ts +121 -0
  62. package/dist/core/compaction/compaction.d.ts.map +1 -0
  63. package/dist/core/compaction/compaction.js +619 -0
  64. package/dist/core/compaction/compaction.js.map +1 -0
  65. package/dist/core/compaction/index.d.ts +7 -0
  66. package/dist/core/compaction/index.d.ts.map +1 -0
  67. package/dist/core/compaction/index.js +7 -0
  68. package/dist/core/compaction/index.js.map +1 -0
  69. package/dist/core/compaction/utils.d.ts +38 -0
  70. package/dist/core/compaction/utils.d.ts.map +1 -0
  71. package/dist/core/compaction/utils.js +153 -0
  72. package/dist/core/compaction/utils.js.map +1 -0
  73. package/dist/core/defaults.d.ts +3 -0
  74. package/dist/core/defaults.d.ts.map +1 -0
  75. package/dist/core/defaults.js +2 -0
  76. package/dist/core/defaults.js.map +1 -0
  77. package/dist/core/diagnostics.d.ts +15 -0
  78. package/dist/core/diagnostics.d.ts.map +1 -0
  79. package/dist/core/diagnostics.js +2 -0
  80. package/dist/core/diagnostics.js.map +1 -0
  81. package/dist/core/event-bus.d.ts +9 -0
  82. package/dist/core/event-bus.d.ts.map +1 -0
  83. package/dist/core/event-bus.js +25 -0
  84. package/dist/core/event-bus.js.map +1 -0
  85. package/dist/core/exec.d.ts +29 -0
  86. package/dist/core/exec.d.ts.map +1 -0
  87. package/dist/core/exec.js +75 -0
  88. package/dist/core/exec.js.map +1 -0
  89. package/dist/core/export-html/ansi-to-html.d.ts +22 -0
  90. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -0
  91. package/dist/core/export-html/ansi-to-html.js +249 -0
  92. package/dist/core/export-html/ansi-to-html.js.map +1 -0
  93. package/dist/core/export-html/index.d.ts +37 -0
  94. package/dist/core/export-html/index.d.ts.map +1 -0
  95. package/dist/core/export-html/index.js +226 -0
  96. package/dist/core/export-html/index.js.map +1 -0
  97. package/dist/core/export-html/template.css +1066 -0
  98. package/dist/core/export-html/template.html +55 -0
  99. package/dist/core/export-html/template.js +1851 -0
  100. package/dist/core/export-html/tool-renderer.d.ts +34 -0
  101. package/dist/core/export-html/tool-renderer.d.ts.map +1 -0
  102. package/dist/core/export-html/tool-renderer.js +108 -0
  103. package/dist/core/export-html/tool-renderer.js.map +1 -0
  104. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  105. package/dist/core/export-html/vendor/marked.min.js +6 -0
  106. package/dist/core/extensions/index.d.ts +12 -0
  107. package/dist/core/extensions/index.d.ts.map +1 -0
  108. package/dist/core/extensions/index.js +9 -0
  109. package/dist/core/extensions/index.js.map +1 -0
  110. package/dist/core/extensions/loader.d.ts +24 -0
  111. package/dist/core/extensions/loader.d.ts.map +1 -0
  112. package/dist/core/extensions/loader.js +481 -0
  113. package/dist/core/extensions/loader.js.map +1 -0
  114. package/dist/core/extensions/runner.d.ts +159 -0
  115. package/dist/core/extensions/runner.d.ts.map +1 -0
  116. package/dist/core/extensions/runner.js +830 -0
  117. package/dist/core/extensions/runner.js.map +1 -0
  118. package/dist/core/extensions/types.d.ts +1175 -0
  119. package/dist/core/extensions/types.d.ts.map +1 -0
  120. package/dist/core/extensions/types.js +45 -0
  121. package/dist/core/extensions/types.js.map +1 -0
  122. package/dist/core/extensions/wrapper.d.ts +20 -0
  123. package/dist/core/extensions/wrapper.d.ts.map +1 -0
  124. package/dist/core/extensions/wrapper.js +22 -0
  125. package/dist/core/extensions/wrapper.js.map +1 -0
  126. package/dist/core/footer-data-provider.d.ts +52 -0
  127. package/dist/core/footer-data-provider.d.ts.map +1 -0
  128. package/dist/core/footer-data-provider.js +310 -0
  129. package/dist/core/footer-data-provider.js.map +1 -0
  130. package/dist/core/http-dispatcher.d.ts +21 -0
  131. package/dist/core/http-dispatcher.d.ts.map +1 -0
  132. package/dist/core/http-dispatcher.js +48 -0
  133. package/dist/core/http-dispatcher.js.map +1 -0
  134. package/dist/core/index.d.ts +12 -0
  135. package/dist/core/index.d.ts.map +1 -0
  136. package/dist/core/index.js +12 -0
  137. package/dist/core/index.js.map +1 -0
  138. package/dist/core/keybindings.d.ts +353 -0
  139. package/dist/core/keybindings.d.ts.map +1 -0
  140. package/dist/core/keybindings.js +295 -0
  141. package/dist/core/keybindings.js.map +1 -0
  142. package/dist/core/messages.d.ts +77 -0
  143. package/dist/core/messages.d.ts.map +1 -0
  144. package/dist/core/messages.js +123 -0
  145. package/dist/core/messages.js.map +1 -0
  146. package/dist/core/model-registry.d.ts +150 -0
  147. package/dist/core/model-registry.d.ts.map +1 -0
  148. package/dist/core/model-registry.js +784 -0
  149. package/dist/core/model-registry.js.map +1 -0
  150. package/dist/core/model-resolver.d.ts +110 -0
  151. package/dist/core/model-resolver.d.ts.map +1 -0
  152. package/dist/core/model-resolver.js +495 -0
  153. package/dist/core/model-resolver.js.map +1 -0
  154. package/dist/core/output-guard.d.ts +7 -0
  155. package/dist/core/output-guard.d.ts.map +1 -0
  156. package/dist/core/output-guard.js +89 -0
  157. package/dist/core/output-guard.js.map +1 -0
  158. package/dist/core/package-manager.d.ts +204 -0
  159. package/dist/core/package-manager.d.ts.map +1 -0
  160. package/dist/core/package-manager.js +2040 -0
  161. package/dist/core/package-manager.js.map +1 -0
  162. package/dist/core/prompt-templates.d.ts +52 -0
  163. package/dist/core/prompt-templates.d.ts.map +1 -0
  164. package/dist/core/prompt-templates.js +238 -0
  165. package/dist/core/prompt-templates.js.map +1 -0
  166. package/dist/core/provider-display-names.d.ts +2 -0
  167. package/dist/core/provider-display-names.d.ts.map +1 -0
  168. package/dist/core/provider-display-names.js +33 -0
  169. package/dist/core/provider-display-names.js.map +1 -0
  170. package/dist/core/resolve-config-value.d.ts +31 -0
  171. package/dist/core/resolve-config-value.d.ts.map +1 -0
  172. package/dist/core/resolve-config-value.js +249 -0
  173. package/dist/core/resolve-config-value.js.map +1 -0
  174. package/dist/core/resource-loader.d.ts +194 -0
  175. package/dist/core/resource-loader.d.ts.map +1 -0
  176. package/dist/core/resource-loader.js +734 -0
  177. package/dist/core/resource-loader.js.map +1 -0
  178. package/dist/core/sdk.d.ts +109 -0
  179. package/dist/core/sdk.d.ts.map +1 -0
  180. package/dist/core/sdk.js +291 -0
  181. package/dist/core/sdk.js.map +1 -0
  182. package/dist/core/session-cwd.d.ts +19 -0
  183. package/dist/core/session-cwd.d.ts.map +1 -0
  184. package/dist/core/session-cwd.js +38 -0
  185. package/dist/core/session-cwd.js.map +1 -0
  186. package/dist/core/session-manager.d.ts +332 -0
  187. package/dist/core/session-manager.d.ts.map +1 -0
  188. package/dist/core/session-manager.js +1194 -0
  189. package/dist/core/session-manager.js.map +1 -0
  190. package/dist/core/settings-manager.d.ts +266 -0
  191. package/dist/core/settings-manager.d.ts.map +1 -0
  192. package/dist/core/settings-manager.js +800 -0
  193. package/dist/core/settings-manager.js.map +1 -0
  194. package/dist/core/skills.d.ts +60 -0
  195. package/dist/core/skills.d.ts.map +1 -0
  196. package/dist/core/skills.js +387 -0
  197. package/dist/core/skills.js.map +1 -0
  198. package/dist/core/slash-commands.d.ts +14 -0
  199. package/dist/core/slash-commands.d.ts.map +1 -0
  200. package/dist/core/slash-commands.js +25 -0
  201. package/dist/core/slash-commands.js.map +1 -0
  202. package/dist/core/source-info.d.ts +18 -0
  203. package/dist/core/source-info.d.ts.map +1 -0
  204. package/dist/core/source-info.js +19 -0
  205. package/dist/core/source-info.js.map +1 -0
  206. package/dist/core/system-prompt.d.ts +30 -0
  207. package/dist/core/system-prompt.d.ts.map +1 -0
  208. package/dist/core/system-prompt.js +117 -0
  209. package/dist/core/system-prompt.js.map +1 -0
  210. package/dist/core/telemetry.d.ts +3 -0
  211. package/dist/core/telemetry.d.ts.map +1 -0
  212. package/dist/core/telemetry.js +9 -0
  213. package/dist/core/telemetry.js.map +1 -0
  214. package/dist/core/timings.d.ts +8 -0
  215. package/dist/core/timings.d.ts.map +1 -0
  216. package/dist/core/timings.js +31 -0
  217. package/dist/core/timings.js.map +1 -0
  218. package/dist/core/tools/bash.d.ts +68 -0
  219. package/dist/core/tools/bash.d.ts.map +1 -0
  220. package/dist/core/tools/bash.js +337 -0
  221. package/dist/core/tools/bash.js.map +1 -0
  222. package/dist/core/tools/edit-diff.d.ts +87 -0
  223. package/dist/core/tools/edit-diff.d.ts.map +1 -0
  224. package/dist/core/tools/edit-diff.js +345 -0
  225. package/dist/core/tools/edit-diff.js.map +1 -0
  226. package/dist/core/tools/edit.d.ts +51 -0
  227. package/dist/core/tools/edit.d.ts.map +1 -0
  228. package/dist/core/tools/edit.js +287 -0
  229. package/dist/core/tools/edit.js.map +1 -0
  230. package/dist/core/tools/file-mutation-queue.d.ts +6 -0
  231. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -0
  232. package/dist/core/tools/file-mutation-queue.js +52 -0
  233. package/dist/core/tools/file-mutation-queue.js.map +1 -0
  234. package/dist/core/tools/find.d.ts +35 -0
  235. package/dist/core/tools/find.d.ts.map +1 -0
  236. package/dist/core/tools/find.js +297 -0
  237. package/dist/core/tools/find.js.map +1 -0
  238. package/dist/core/tools/grep.d.ts +37 -0
  239. package/dist/core/tools/grep.d.ts.map +1 -0
  240. package/dist/core/tools/grep.js +304 -0
  241. package/dist/core/tools/grep.js.map +1 -0
  242. package/dist/core/tools/index.d.ts +40 -0
  243. package/dist/core/tools/index.d.ts.map +1 -0
  244. package/dist/core/tools/index.js +112 -0
  245. package/dist/core/tools/index.js.map +1 -0
  246. package/dist/core/tools/ls.d.ts +37 -0
  247. package/dist/core/tools/ls.d.ts.map +1 -0
  248. package/dist/core/tools/ls.js +169 -0
  249. package/dist/core/tools/ls.js.map +1 -0
  250. package/dist/core/tools/output-accumulator.d.ts +52 -0
  251. package/dist/core/tools/output-accumulator.d.ts.map +1 -0
  252. package/dist/core/tools/output-accumulator.js +184 -0
  253. package/dist/core/tools/output-accumulator.js.map +1 -0
  254. package/dist/core/tools/path-utils.d.ts +10 -0
  255. package/dist/core/tools/path-utils.d.ts.map +1 -0
  256. package/dist/core/tools/path-utils.js +99 -0
  257. package/dist/core/tools/path-utils.js.map +1 -0
  258. package/dist/core/tools/read.d.ts +35 -0
  259. package/dist/core/tools/read.d.ts.map +1 -0
  260. package/dist/core/tools/read.js +290 -0
  261. package/dist/core/tools/read.js.map +1 -0
  262. package/dist/core/tools/render-utils.d.ts +21 -0
  263. package/dist/core/tools/render-utils.d.ts.map +1 -0
  264. package/dist/core/tools/render-utils.js +49 -0
  265. package/dist/core/tools/render-utils.js.map +1 -0
  266. package/dist/core/tools/tool-definition-wrapper.d.ts +14 -0
  267. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -0
  268. package/dist/core/tools/tool-definition-wrapper.js +34 -0
  269. package/dist/core/tools/tool-definition-wrapper.js.map +1 -0
  270. package/dist/core/tools/truncate.d.ts +70 -0
  271. package/dist/core/tools/truncate.d.ts.map +1 -0
  272. package/dist/core/tools/truncate.js +215 -0
  273. package/dist/core/tools/truncate.js.map +1 -0
  274. package/dist/core/tools/worker.d.ts +23 -0
  275. package/dist/core/tools/worker.d.ts.map +1 -0
  276. package/dist/core/tools/worker.js +150 -0
  277. package/dist/core/tools/worker.js.map +1 -0
  278. package/dist/core/tools/write.d.ts +26 -0
  279. package/dist/core/tools/write.d.ts.map +1 -0
  280. package/dist/core/tools/write.js +198 -0
  281. package/dist/core/tools/write.js.map +1 -0
  282. package/dist/core/worker-integration.d.ts +79 -0
  283. package/dist/core/worker-integration.d.ts.map +1 -0
  284. package/dist/core/worker-integration.js +108 -0
  285. package/dist/core/worker-integration.js.map +1 -0
  286. package/dist/index.d.ts +29 -0
  287. package/dist/index.d.ts.map +1 -0
  288. package/dist/index.js +42 -0
  289. package/dist/index.js.map +1 -0
  290. package/dist/main.d.ts +12 -0
  291. package/dist/main.d.ts.map +1 -0
  292. package/dist/main.js +623 -0
  293. package/dist/main.js.map +1 -0
  294. package/dist/migrations.d.ts +33 -0
  295. package/dist/migrations.d.ts.map +1 -0
  296. package/dist/migrations.js +398 -0
  297. package/dist/migrations.js.map +1 -0
  298. package/dist/modes/index.d.ts +9 -0
  299. package/dist/modes/index.d.ts.map +1 -0
  300. package/dist/modes/index.js +8 -0
  301. package/dist/modes/index.js.map +1 -0
  302. package/dist/modes/interactive/assets/clankolas.png +0 -0
  303. package/dist/modes/interactive/components/armin.d.ts +34 -0
  304. package/dist/modes/interactive/components/armin.d.ts.map +1 -0
  305. package/dist/modes/interactive/components/armin.js +333 -0
  306. package/dist/modes/interactive/components/armin.js.map +1 -0
  307. package/dist/modes/interactive/components/assistant-message.d.ts +20 -0
  308. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -0
  309. package/dist/modes/interactive/components/assistant-message.js +121 -0
  310. package/dist/modes/interactive/components/assistant-message.js.map +1 -0
  311. package/dist/modes/interactive/components/bash-execution.d.ts +34 -0
  312. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -0
  313. package/dist/modes/interactive/components/bash-execution.js +175 -0
  314. package/dist/modes/interactive/components/bash-execution.js.map +1 -0
  315. package/dist/modes/interactive/components/bordered-loader.d.ts +16 -0
  316. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -0
  317. package/dist/modes/interactive/components/bordered-loader.js +54 -0
  318. package/dist/modes/interactive/components/bordered-loader.js.map +1 -0
  319. package/dist/modes/interactive/components/branch-summary-message.d.ts +16 -0
  320. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -0
  321. package/dist/modes/interactive/components/branch-summary-message.js +44 -0
  322. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -0
  323. package/dist/modes/interactive/components/compaction-summary-message.d.ts +16 -0
  324. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -0
  325. package/dist/modes/interactive/components/compaction-summary-message.js +45 -0
  326. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -0
  327. package/dist/modes/interactive/components/config-selector.d.ts +71 -0
  328. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -0
  329. package/dist/modes/interactive/components/config-selector.js +506 -0
  330. package/dist/modes/interactive/components/config-selector.js.map +1 -0
  331. package/dist/modes/interactive/components/countdown-timer.d.ts +14 -0
  332. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -0
  333. package/dist/modes/interactive/components/countdown-timer.js +33 -0
  334. package/dist/modes/interactive/components/countdown-timer.js.map +1 -0
  335. package/dist/modes/interactive/components/custom-editor.d.ts +21 -0
  336. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -0
  337. package/dist/modes/interactive/components/custom-editor.js +70 -0
  338. package/dist/modes/interactive/components/custom-editor.js.map +1 -0
  339. package/dist/modes/interactive/components/custom-message.d.ts +20 -0
  340. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -0
  341. package/dist/modes/interactive/components/custom-message.js +79 -0
  342. package/dist/modes/interactive/components/custom-message.js.map +1 -0
  343. package/dist/modes/interactive/components/daxnuts.d.ts +23 -0
  344. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -0
  345. package/dist/modes/interactive/components/daxnuts.js +140 -0
  346. package/dist/modes/interactive/components/daxnuts.js.map +1 -0
  347. package/dist/modes/interactive/components/diff.d.ts +12 -0
  348. package/dist/modes/interactive/components/diff.d.ts.map +1 -0
  349. package/dist/modes/interactive/components/diff.js +133 -0
  350. package/dist/modes/interactive/components/diff.js.map +1 -0
  351. package/dist/modes/interactive/components/dynamic-border.d.ts +15 -0
  352. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -0
  353. package/dist/modes/interactive/components/dynamic-border.js +21 -0
  354. package/dist/modes/interactive/components/dynamic-border.js.map +1 -0
  355. package/dist/modes/interactive/components/earendil-announcement.d.ts +5 -0
  356. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -0
  357. package/dist/modes/interactive/components/earendil-announcement.js +40 -0
  358. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -0
  359. package/dist/modes/interactive/components/extension-editor.d.ts +20 -0
  360. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -0
  361. package/dist/modes/interactive/components/extension-editor.js +119 -0
  362. package/dist/modes/interactive/components/extension-editor.js.map +1 -0
  363. package/dist/modes/interactive/components/extension-input.d.ts +23 -0
  364. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -0
  365. package/dist/modes/interactive/components/extension-input.js +61 -0
  366. package/dist/modes/interactive/components/extension-input.js.map +1 -0
  367. package/dist/modes/interactive/components/extension-selector.d.ts +26 -0
  368. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -0
  369. package/dist/modes/interactive/components/extension-selector.js +83 -0
  370. package/dist/modes/interactive/components/extension-selector.js.map +1 -0
  371. package/dist/modes/interactive/components/footer.d.ts +28 -0
  372. package/dist/modes/interactive/components/footer.d.ts.map +1 -0
  373. package/dist/modes/interactive/components/footer.js +210 -0
  374. package/dist/modes/interactive/components/footer.js.map +1 -0
  375. package/dist/modes/interactive/components/index.d.ts +32 -0
  376. package/dist/modes/interactive/components/index.d.ts.map +1 -0
  377. package/dist/modes/interactive/components/index.js +33 -0
  378. package/dist/modes/interactive/components/index.js.map +1 -0
  379. package/dist/modes/interactive/components/keybinding-hints.d.ts +13 -0
  380. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -0
  381. package/dist/modes/interactive/components/keybinding-hints.js +36 -0
  382. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -0
  383. package/dist/modes/interactive/components/login-dialog.d.ts +52 -0
  384. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -0
  385. package/dist/modes/interactive/components/login-dialog.js +183 -0
  386. package/dist/modes/interactive/components/login-dialog.js.map +1 -0
  387. package/dist/modes/interactive/components/model-selector.d.ts +47 -0
  388. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -0
  389. package/dist/modes/interactive/components/model-selector.js +278 -0
  390. package/dist/modes/interactive/components/model-selector.js.map +1 -0
  391. package/dist/modes/interactive/components/oauth-selector.d.ts +31 -0
  392. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -0
  393. package/dist/modes/interactive/components/oauth-selector.js +165 -0
  394. package/dist/modes/interactive/components/oauth-selector.js.map +1 -0
  395. package/dist/modes/interactive/components/scoped-models-selector.d.ts +42 -0
  396. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -0
  397. package/dist/modes/interactive/components/scoped-models-selector.js +290 -0
  398. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -0
  399. package/dist/modes/interactive/components/session-selector-search.d.ts +23 -0
  400. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -0
  401. package/dist/modes/interactive/components/session-selector-search.js +155 -0
  402. package/dist/modes/interactive/components/session-selector-search.js.map +1 -0
  403. package/dist/modes/interactive/components/session-selector.d.ts +96 -0
  404. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -0
  405. package/dist/modes/interactive/components/session-selector.js +861 -0
  406. package/dist/modes/interactive/components/session-selector.js.map +1 -0
  407. package/dist/modes/interactive/components/settings-selector.d.ts +69 -0
  408. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -0
  409. package/dist/modes/interactive/components/settings-selector.js +390 -0
  410. package/dist/modes/interactive/components/settings-selector.js.map +1 -0
  411. package/dist/modes/interactive/components/show-images-selector.d.ts +10 -0
  412. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -0
  413. package/dist/modes/interactive/components/show-images-selector.js +39 -0
  414. package/dist/modes/interactive/components/show-images-selector.js.map +1 -0
  415. package/dist/modes/interactive/components/skill-invocation-message.d.ts +17 -0
  416. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -0
  417. package/dist/modes/interactive/components/skill-invocation-message.js +47 -0
  418. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -0
  419. package/dist/modes/interactive/components/theme-selector.d.ts +11 -0
  420. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -0
  421. package/dist/modes/interactive/components/theme-selector.js +50 -0
  422. package/dist/modes/interactive/components/theme-selector.js.map +1 -0
  423. package/dist/modes/interactive/components/thinking-selector.d.ts +11 -0
  424. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -0
  425. package/dist/modes/interactive/components/thinking-selector.js +51 -0
  426. package/dist/modes/interactive/components/thinking-selector.js.map +1 -0
  427. package/dist/modes/interactive/components/tool-execution.d.ts +63 -0
  428. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -0
  429. package/dist/modes/interactive/components/tool-execution.js +295 -0
  430. package/dist/modes/interactive/components/tool-execution.js.map +1 -0
  431. package/dist/modes/interactive/components/tree-selector.d.ts +89 -0
  432. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -0
  433. package/dist/modes/interactive/components/tree-selector.js +1093 -0
  434. package/dist/modes/interactive/components/tree-selector.js.map +1 -0
  435. package/dist/modes/interactive/components/user-message-selector.d.ts +30 -0
  436. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -0
  437. package/dist/modes/interactive/components/user-message-selector.js +114 -0
  438. package/dist/modes/interactive/components/user-message-selector.js.map +1 -0
  439. package/dist/modes/interactive/components/user-message.d.ts +10 -0
  440. package/dist/modes/interactive/components/user-message.d.ts.map +1 -0
  441. package/dist/modes/interactive/components/user-message.js +29 -0
  442. package/dist/modes/interactive/components/user-message.js.map +1 -0
  443. package/dist/modes/interactive/components/visual-truncate.d.ts +24 -0
  444. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -0
  445. package/dist/modes/interactive/components/visual-truncate.js +33 -0
  446. package/dist/modes/interactive/components/visual-truncate.js.map +1 -0
  447. package/dist/modes/interactive/components/worker-status.d.ts +23 -0
  448. package/dist/modes/interactive/components/worker-status.d.ts.map +1 -0
  449. package/dist/modes/interactive/components/worker-status.js +77 -0
  450. package/dist/modes/interactive/components/worker-status.js.map +1 -0
  451. package/dist/modes/interactive/interactive-mode.d.ts +370 -0
  452. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -0
  453. package/dist/modes/interactive/interactive-mode.js +4674 -0
  454. package/dist/modes/interactive/interactive-mode.js.map +1 -0
  455. package/dist/modes/interactive/theme/dark.json +86 -0
  456. package/dist/modes/interactive/theme/light.json +85 -0
  457. package/dist/modes/interactive/theme/theme-schema.json +335 -0
  458. package/dist/modes/interactive/theme/theme.d.ts +100 -0
  459. package/dist/modes/interactive/theme/theme.d.ts.map +1 -0
  460. package/dist/modes/interactive/theme/theme.js +1034 -0
  461. package/dist/modes/interactive/theme/theme.js.map +1 -0
  462. package/dist/modes/interactive/worker-ui-integration.d.ts +102 -0
  463. package/dist/modes/interactive/worker-ui-integration.d.ts.map +1 -0
  464. package/dist/modes/interactive/worker-ui-integration.js +147 -0
  465. package/dist/modes/interactive/worker-ui-integration.js.map +1 -0
  466. package/dist/modes/print-mode.d.ts +28 -0
  467. package/dist/modes/print-mode.d.ts.map +1 -0
  468. package/dist/modes/print-mode.js +131 -0
  469. package/dist/modes/print-mode.js.map +1 -0
  470. package/dist/modes/rpc/jsonl.d.ts +17 -0
  471. package/dist/modes/rpc/jsonl.d.ts.map +1 -0
  472. package/dist/modes/rpc/jsonl.js +49 -0
  473. package/dist/modes/rpc/jsonl.js.map +1 -0
  474. package/dist/modes/rpc/rpc-client.d.ts +227 -0
  475. package/dist/modes/rpc/rpc-client.d.ts.map +1 -0
  476. package/dist/modes/rpc/rpc-client.js +467 -0
  477. package/dist/modes/rpc/rpc-client.js.map +1 -0
  478. package/dist/modes/rpc/rpc-mode.d.ts +20 -0
  479. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -0
  480. package/dist/modes/rpc/rpc-mode.js +615 -0
  481. package/dist/modes/rpc/rpc-mode.js.map +1 -0
  482. package/dist/modes/rpc/rpc-types.d.ts +420 -0
  483. package/dist/modes/rpc/rpc-types.d.ts.map +1 -0
  484. package/dist/modes/rpc/rpc-types.js +8 -0
  485. package/dist/modes/rpc/rpc-types.js.map +1 -0
  486. package/dist/package-manager-cli.d.ts +4 -0
  487. package/dist/package-manager-cli.d.ts.map +1 -0
  488. package/dist/package-manager-cli.js +515 -0
  489. package/dist/package-manager-cli.js.map +1 -0
  490. package/dist/utils/ansi.d.ts +2 -0
  491. package/dist/utils/ansi.d.ts.map +1 -0
  492. package/dist/utils/ansi.js +52 -0
  493. package/dist/utils/ansi.js.map +1 -0
  494. package/dist/utils/changelog.d.ts +21 -0
  495. package/dist/utils/changelog.d.ts.map +1 -0
  496. package/dist/utils/changelog.js +87 -0
  497. package/dist/utils/changelog.js.map +1 -0
  498. package/dist/utils/child-process.d.ts +15 -0
  499. package/dist/utils/child-process.d.ts.map +1 -0
  500. package/dist/utils/child-process.js +88 -0
  501. package/dist/utils/child-process.js.map +1 -0
  502. package/dist/utils/clipboard-image.d.ts +11 -0
  503. package/dist/utils/clipboard-image.d.ts.map +1 -0
  504. package/dist/utils/clipboard-image.js +245 -0
  505. package/dist/utils/clipboard-image.js.map +1 -0
  506. package/dist/utils/clipboard-native.d.ts +10 -0
  507. package/dist/utils/clipboard-native.d.ts.map +1 -0
  508. package/dist/utils/clipboard-native.js +20 -0
  509. package/dist/utils/clipboard-native.js.map +1 -0
  510. package/dist/utils/clipboard.d.ts +2 -0
  511. package/dist/utils/clipboard.d.ts.map +1 -0
  512. package/dist/utils/clipboard.js +117 -0
  513. package/dist/utils/clipboard.js.map +1 -0
  514. package/dist/utils/deprecation.d.ts +4 -0
  515. package/dist/utils/deprecation.d.ts.map +1 -0
  516. package/dist/utils/deprecation.js +13 -0
  517. package/dist/utils/deprecation.js.map +1 -0
  518. package/dist/utils/exif-orientation.d.ts +5 -0
  519. package/dist/utils/exif-orientation.d.ts.map +1 -0
  520. package/dist/utils/exif-orientation.js +158 -0
  521. package/dist/utils/exif-orientation.js.map +1 -0
  522. package/dist/utils/frontmatter.d.ts +8 -0
  523. package/dist/utils/frontmatter.d.ts.map +1 -0
  524. package/dist/utils/frontmatter.js +26 -0
  525. package/dist/utils/frontmatter.js.map +1 -0
  526. package/dist/utils/fs-watch.d.ts +5 -0
  527. package/dist/utils/fs-watch.d.ts.map +1 -0
  528. package/dist/utils/fs-watch.js +25 -0
  529. package/dist/utils/fs-watch.js.map +1 -0
  530. package/dist/utils/git.d.ts +26 -0
  531. package/dist/utils/git.d.ts.map +1 -0
  532. package/dist/utils/git.js +163 -0
  533. package/dist/utils/git.js.map +1 -0
  534. package/dist/utils/html.d.ts +7 -0
  535. package/dist/utils/html.d.ts.map +1 -0
  536. package/dist/utils/html.js +40 -0
  537. package/dist/utils/html.js.map +1 -0
  538. package/dist/utils/image-convert.d.ts +9 -0
  539. package/dist/utils/image-convert.d.ts.map +1 -0
  540. package/dist/utils/image-convert.js +39 -0
  541. package/dist/utils/image-convert.js.map +1 -0
  542. package/dist/utils/image-resize-core.d.ts +30 -0
  543. package/dist/utils/image-resize-core.d.ts.map +1 -0
  544. package/dist/utils/image-resize-core.js +124 -0
  545. package/dist/utils/image-resize-core.js.map +1 -0
  546. package/dist/utils/image-resize-worker.d.ts +2 -0
  547. package/dist/utils/image-resize-worker.d.ts.map +1 -0
  548. package/dist/utils/image-resize-worker.js +31 -0
  549. package/dist/utils/image-resize-worker.js.map +1 -0
  550. package/dist/utils/image-resize.d.ts +16 -0
  551. package/dist/utils/image-resize.d.ts.map +1 -0
  552. package/dist/utils/image-resize.js +97 -0
  553. package/dist/utils/image-resize.js.map +1 -0
  554. package/dist/utils/json.d.ts +3 -0
  555. package/dist/utils/json.d.ts.map +1 -0
  556. package/dist/utils/json.js +7 -0
  557. package/dist/utils/json.js.map +1 -0
  558. package/dist/utils/leaf-user-agent.d.ts +2 -0
  559. package/dist/utils/leaf-user-agent.d.ts.map +1 -0
  560. package/dist/utils/leaf-user-agent.js +5 -0
  561. package/dist/utils/leaf-user-agent.js.map +1 -0
  562. package/dist/utils/mime.d.ts +3 -0
  563. package/dist/utils/mime.d.ts.map +1 -0
  564. package/dist/utils/mime.js +69 -0
  565. package/dist/utils/mime.js.map +1 -0
  566. package/dist/utils/paths.d.ts +31 -0
  567. package/dist/utils/paths.d.ts.map +1 -0
  568. package/dist/utils/paths.js +92 -0
  569. package/dist/utils/paths.js.map +1 -0
  570. package/dist/utils/photon.d.ts +21 -0
  571. package/dist/utils/photon.d.ts.map +1 -0
  572. package/dist/utils/photon.js +121 -0
  573. package/dist/utils/photon.js.map +1 -0
  574. package/dist/utils/shell.d.ts +30 -0
  575. package/dist/utils/shell.d.ts.map +1 -0
  576. package/dist/utils/shell.js +195 -0
  577. package/dist/utils/shell.js.map +1 -0
  578. package/dist/utils/sleep.d.ts +5 -0
  579. package/dist/utils/sleep.d.ts.map +1 -0
  580. package/dist/utils/sleep.js +17 -0
  581. package/dist/utils/sleep.js.map +1 -0
  582. package/dist/utils/syntax-highlight.d.ts +12 -0
  583. package/dist/utils/syntax-highlight.d.ts.map +1 -0
  584. package/dist/utils/syntax-highlight.js +118 -0
  585. package/dist/utils/syntax-highlight.js.map +1 -0
  586. package/dist/utils/tools-manager.d.ts +3 -0
  587. package/dist/utils/tools-manager.d.ts.map +1 -0
  588. package/dist/utils/tools-manager.js +328 -0
  589. package/dist/utils/tools-manager.js.map +1 -0
  590. package/dist/utils/version-check.d.ts +15 -0
  591. package/dist/utils/version-check.d.ts.map +1 -0
  592. package/dist/utils/version-check.js +82 -0
  593. package/dist/utils/version-check.js.map +1 -0
  594. package/dist/utils/windows-self-update.d.ts +3 -0
  595. package/dist/utils/windows-self-update.d.ts.map +1 -0
  596. package/dist/utils/windows-self-update.js +77 -0
  597. package/dist/utils/windows-self-update.js.map +1 -0
  598. package/package.json +100 -0
@@ -0,0 +1,1194 @@
1
+ import { uuidv7 } from "@looze/leaf-agent-core";
2
+ import { randomUUID } from "crypto";
3
+ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync, } from "fs";
4
+ import { readdir, readFile, stat } from "fs/promises";
5
+ import { join, resolve } from "path";
6
+ import { getAgentDir as getDefaultAgentDir, getSessionsDir } from "../config.js";
7
+ import { normalizePath, resolvePath } from "../utils/paths.js";
8
+ import { createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage, } from "./messages.js";
9
+ export const CURRENT_SESSION_VERSION = 3;
10
+ function createSessionId() {
11
+ return uuidv7();
12
+ }
13
+ export function assertValidSessionId(id) {
14
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) {
15
+ throw new Error("Session id must be non-empty, contain only alphanumeric characters, '-', '_', and '.', and start and end with an alphanumeric character");
16
+ }
17
+ }
18
+ /** Generate a unique short ID (8 hex chars, collision-checked) */
19
+ function generateId(byId) {
20
+ for (let i = 0; i < 100; i++) {
21
+ const id = randomUUID().slice(0, 8);
22
+ if (!byId.has(id))
23
+ return id;
24
+ }
25
+ // Fallback to full UUID if somehow we have collisions
26
+ return randomUUID();
27
+ }
28
+ /** Migrate v1 → v2: add id/parentId tree structure. Mutates in place. */
29
+ function migrateV1ToV2(entries) {
30
+ const ids = new Set();
31
+ let prevId = null;
32
+ for (const entry of entries) {
33
+ if (entry.type === "session") {
34
+ entry.version = 2;
35
+ continue;
36
+ }
37
+ entry.id = generateId(ids);
38
+ entry.parentId = prevId;
39
+ prevId = entry.id;
40
+ // Convert firstKeptEntryIndex to firstKeptEntryId for compaction
41
+ if (entry.type === "compaction") {
42
+ const comp = entry;
43
+ if (typeof comp.firstKeptEntryIndex === "number") {
44
+ const targetEntry = entries[comp.firstKeptEntryIndex];
45
+ if (targetEntry && targetEntry.type !== "session") {
46
+ comp.firstKeptEntryId = targetEntry.id;
47
+ }
48
+ delete comp.firstKeptEntryIndex;
49
+ }
50
+ }
51
+ }
52
+ }
53
+ /** Migrate v2 → v3: rename hookMessage role to custom. Mutates in place. */
54
+ function migrateV2ToV3(entries) {
55
+ for (const entry of entries) {
56
+ if (entry.type === "session") {
57
+ entry.version = 3;
58
+ continue;
59
+ }
60
+ // Update message entries with hookMessage role
61
+ if (entry.type === "message") {
62
+ const msgEntry = entry;
63
+ if (msgEntry.message && msgEntry.message.role === "hookMessage") {
64
+ msgEntry.message.role = "custom";
65
+ }
66
+ }
67
+ }
68
+ }
69
+ /**
70
+ * Run all necessary migrations to bring entries to current version.
71
+ * Mutates entries in place. Returns true if any migration was applied.
72
+ */
73
+ function migrateToCurrentVersion(entries) {
74
+ const header = entries.find((e) => e.type === "session");
75
+ const version = header?.version ?? 1;
76
+ if (version >= CURRENT_SESSION_VERSION)
77
+ return false;
78
+ if (version < 2)
79
+ migrateV1ToV2(entries);
80
+ if (version < 3)
81
+ migrateV2ToV3(entries);
82
+ return true;
83
+ }
84
+ /** Exported for testing */
85
+ export function migrateSessionEntries(entries) {
86
+ migrateToCurrentVersion(entries);
87
+ }
88
+ /** Exported for compaction.test.ts */
89
+ export function parseSessionEntries(content) {
90
+ const entries = [];
91
+ const lines = content.trim().split("\n");
92
+ for (const line of lines) {
93
+ if (!line.trim())
94
+ continue;
95
+ try {
96
+ const entry = JSON.parse(line);
97
+ entries.push(entry);
98
+ }
99
+ catch {
100
+ // Skip malformed lines
101
+ }
102
+ }
103
+ return entries;
104
+ }
105
+ export function getLatestCompactionEntry(entries) {
106
+ for (let i = entries.length - 1; i >= 0; i--) {
107
+ if (entries[i].type === "compaction") {
108
+ return entries[i];
109
+ }
110
+ }
111
+ return null;
112
+ }
113
+ /**
114
+ * Build the session context from entries using tree traversal.
115
+ * If leafId is provided, walks from that entry to root.
116
+ * Handles compaction and branch summaries along the path.
117
+ */
118
+ export function buildSessionContext(entries, leafId, byId) {
119
+ // Build uuid index if not available
120
+ if (!byId) {
121
+ byId = new Map();
122
+ for (const entry of entries) {
123
+ byId.set(entry.id, entry);
124
+ }
125
+ }
126
+ // Find leaf
127
+ let leaf;
128
+ if (leafId === null) {
129
+ // Explicitly null - return no messages (navigated to before first entry)
130
+ return { messages: [], thinkingLevel: "off", model: null };
131
+ }
132
+ if (leafId) {
133
+ leaf = byId.get(leafId);
134
+ }
135
+ if (!leaf) {
136
+ // Fallback to last entry (when leafId is undefined)
137
+ leaf = entries[entries.length - 1];
138
+ }
139
+ if (!leaf) {
140
+ return { messages: [], thinkingLevel: "off", model: null };
141
+ }
142
+ // Walk from leaf to root, collecting path
143
+ const path = [];
144
+ let current = leaf;
145
+ while (current) {
146
+ path.unshift(current);
147
+ current = current.parentId ? byId.get(current.parentId) : undefined;
148
+ }
149
+ // Extract settings and find compaction
150
+ let thinkingLevel = "off";
151
+ let model = null;
152
+ let compaction = null;
153
+ for (const entry of path) {
154
+ if (entry.type === "thinking_level_change") {
155
+ thinkingLevel = entry.thinkingLevel;
156
+ }
157
+ else if (entry.type === "model_change") {
158
+ model = { provider: entry.provider, modelId: entry.modelId };
159
+ }
160
+ else if (entry.type === "message" && entry.message.role === "assistant") {
161
+ model = { provider: entry.message.provider, modelId: entry.message.model };
162
+ }
163
+ else if (entry.type === "compaction") {
164
+ compaction = entry;
165
+ }
166
+ }
167
+ // Build messages and collect corresponding entries
168
+ // When there's a compaction, we need to:
169
+ // 1. Emit summary first (entry = compaction)
170
+ // 2. Emit kept messages (from firstKeptEntryId up to compaction)
171
+ // 3. Emit messages after compaction
172
+ const messages = [];
173
+ const appendMessage = (entry) => {
174
+ if (entry.type === "message") {
175
+ messages.push(entry.message);
176
+ }
177
+ else if (entry.type === "custom_message") {
178
+ messages.push(createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp));
179
+ }
180
+ else if (entry.type === "branch_summary" && entry.summary) {
181
+ messages.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));
182
+ }
183
+ };
184
+ if (compaction) {
185
+ // Emit summary first
186
+ messages.push(createCompactionSummaryMessage(compaction.summary, compaction.tokensBefore, compaction.timestamp));
187
+ // Find compaction index in path
188
+ const compactionIdx = path.findIndex((e) => e.type === "compaction" && e.id === compaction.id);
189
+ // Emit kept messages (before compaction, starting from firstKeptEntryId)
190
+ let foundFirstKept = false;
191
+ for (let i = 0; i < compactionIdx; i++) {
192
+ const entry = path[i];
193
+ if (entry.id === compaction.firstKeptEntryId) {
194
+ foundFirstKept = true;
195
+ }
196
+ if (foundFirstKept) {
197
+ appendMessage(entry);
198
+ }
199
+ }
200
+ // Emit messages after compaction
201
+ for (let i = compactionIdx + 1; i < path.length; i++) {
202
+ const entry = path[i];
203
+ appendMessage(entry);
204
+ }
205
+ }
206
+ else {
207
+ // No compaction - emit all messages, handle branch summaries and custom messages
208
+ for (const entry of path) {
209
+ appendMessage(entry);
210
+ }
211
+ }
212
+ return { messages, thinkingLevel, model };
213
+ }
214
+ /**
215
+ * Compute the default session directory for a cwd.
216
+ * Encodes cwd into a safe directory name under ~/.leaf/agent/sessions/.
217
+ */
218
+ function getDefaultSessionDirPath(cwd, agentDir = getDefaultAgentDir()) {
219
+ const resolvedCwd = resolvePath(cwd);
220
+ const resolvedAgentDir = resolvePath(agentDir);
221
+ const safePath = `--${resolvedCwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
222
+ return join(resolvedAgentDir, "sessions", safePath);
223
+ }
224
+ export function getDefaultSessionDir(cwd, agentDir = getDefaultAgentDir()) {
225
+ const sessionDir = getDefaultSessionDirPath(cwd, agentDir);
226
+ if (!existsSync(sessionDir)) {
227
+ mkdirSync(sessionDir, { recursive: true });
228
+ }
229
+ return sessionDir;
230
+ }
231
+ /** Exported for testing */
232
+ export function loadEntriesFromFile(filePath) {
233
+ const resolvedFilePath = normalizePath(filePath);
234
+ if (!existsSync(resolvedFilePath))
235
+ return [];
236
+ const content = readFileSync(resolvedFilePath, "utf8");
237
+ const entries = [];
238
+ const lines = content.trim().split("\n");
239
+ for (const line of lines) {
240
+ if (!line.trim())
241
+ continue;
242
+ try {
243
+ const entry = JSON.parse(line);
244
+ entries.push(entry);
245
+ }
246
+ catch {
247
+ // Skip malformed lines
248
+ }
249
+ }
250
+ // Validate session header
251
+ if (entries.length === 0)
252
+ return entries;
253
+ const header = entries[0];
254
+ if (header.type !== "session" || typeof header.id !== "string") {
255
+ return [];
256
+ }
257
+ return entries;
258
+ }
259
+ function readSessionHeader(filePath) {
260
+ try {
261
+ const fd = openSync(filePath, "r");
262
+ const buffer = Buffer.alloc(512);
263
+ const bytesRead = readSync(fd, buffer, 0, 512, 0);
264
+ closeSync(fd);
265
+ const firstLine = buffer.toString("utf8", 0, bytesRead).split("\n")[0];
266
+ if (!firstLine)
267
+ return null;
268
+ const header = JSON.parse(firstLine);
269
+ if (header.type !== "session" || typeof header.id !== "string") {
270
+ return null;
271
+ }
272
+ return header;
273
+ }
274
+ catch {
275
+ return null;
276
+ }
277
+ }
278
+ function getSessionHeaderCwd(header) {
279
+ const cwd = header.cwd;
280
+ return typeof cwd === "string" ? cwd : undefined;
281
+ }
282
+ function sessionCwdMatches(cwd, resolvedCwd) {
283
+ return cwd !== undefined && cwd !== "" && resolvePath(cwd) === resolvedCwd;
284
+ }
285
+ /** Exported for testing */
286
+ export function findMostRecentSession(sessionDir, cwd) {
287
+ const resolvedSessionDir = normalizePath(sessionDir);
288
+ const resolvedCwd = cwd ? resolvePath(cwd) : undefined;
289
+ try {
290
+ const files = readdirSync(resolvedSessionDir)
291
+ .filter((f) => f.endsWith(".jsonl"))
292
+ .map((f) => join(resolvedSessionDir, f))
293
+ .map((path) => ({ path, header: readSessionHeader(path) }))
294
+ .filter((file) => file.header !== null &&
295
+ (!resolvedCwd || sessionCwdMatches(getSessionHeaderCwd(file.header), resolvedCwd)))
296
+ .map(({ path }) => ({ path, mtime: statSync(path).mtime }))
297
+ .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
298
+ return files[0]?.path || null;
299
+ }
300
+ catch {
301
+ return null;
302
+ }
303
+ }
304
+ function isMessageWithContent(message) {
305
+ return typeof message.role === "string" && "content" in message;
306
+ }
307
+ function extractTextContent(message) {
308
+ const content = message.content;
309
+ if (typeof content === "string") {
310
+ return content;
311
+ }
312
+ return content
313
+ .filter((block) => block.type === "text")
314
+ .map((block) => block.text)
315
+ .join(" ");
316
+ }
317
+ function getLastActivityTime(entries) {
318
+ let lastActivityTime;
319
+ for (const entry of entries) {
320
+ if (entry.type !== "message")
321
+ continue;
322
+ const message = entry.message;
323
+ if (!isMessageWithContent(message))
324
+ continue;
325
+ if (message.role !== "user" && message.role !== "assistant")
326
+ continue;
327
+ const msgTimestamp = message.timestamp;
328
+ if (typeof msgTimestamp === "number") {
329
+ lastActivityTime = Math.max(lastActivityTime ?? 0, msgTimestamp);
330
+ continue;
331
+ }
332
+ const entryTimestamp = entry.timestamp;
333
+ if (typeof entryTimestamp === "string") {
334
+ const t = new Date(entryTimestamp).getTime();
335
+ if (!Number.isNaN(t)) {
336
+ lastActivityTime = Math.max(lastActivityTime ?? 0, t);
337
+ }
338
+ }
339
+ }
340
+ return lastActivityTime;
341
+ }
342
+ function getSessionModifiedDate(entries, header, statsMtime) {
343
+ const lastActivityTime = getLastActivityTime(entries);
344
+ if (typeof lastActivityTime === "number" && lastActivityTime > 0) {
345
+ return new Date(lastActivityTime);
346
+ }
347
+ const headerTime = typeof header.timestamp === "string" ? new Date(header.timestamp).getTime() : NaN;
348
+ return !Number.isNaN(headerTime) ? new Date(headerTime) : statsMtime;
349
+ }
350
+ async function buildSessionInfo(filePath) {
351
+ try {
352
+ const content = await readFile(filePath, "utf8");
353
+ const entries = [];
354
+ const lines = content.trim().split("\n");
355
+ for (const line of lines) {
356
+ if (!line.trim())
357
+ continue;
358
+ try {
359
+ entries.push(JSON.parse(line));
360
+ }
361
+ catch {
362
+ // Skip malformed lines
363
+ }
364
+ }
365
+ if (entries.length === 0)
366
+ return null;
367
+ const header = entries[0];
368
+ if (header.type !== "session")
369
+ return null;
370
+ const stats = await stat(filePath);
371
+ let messageCount = 0;
372
+ let firstMessage = "";
373
+ const allMessages = [];
374
+ let name;
375
+ for (const entry of entries) {
376
+ // Extract session name (use latest, including explicit clears)
377
+ if (entry.type === "session_info") {
378
+ const infoEntry = entry;
379
+ name = infoEntry.name?.trim() || undefined;
380
+ }
381
+ if (entry.type !== "message")
382
+ continue;
383
+ messageCount++;
384
+ const message = entry.message;
385
+ if (!isMessageWithContent(message))
386
+ continue;
387
+ if (message.role !== "user" && message.role !== "assistant")
388
+ continue;
389
+ const textContent = extractTextContent(message);
390
+ if (!textContent)
391
+ continue;
392
+ allMessages.push(textContent);
393
+ if (!firstMessage && message.role === "user") {
394
+ firstMessage = textContent;
395
+ }
396
+ }
397
+ const cwd = typeof header.cwd === "string" ? header.cwd : "";
398
+ const parentSessionPath = header.parentSession;
399
+ const modified = getSessionModifiedDate(entries, header, stats.mtime);
400
+ return {
401
+ path: filePath,
402
+ id: header.id,
403
+ cwd,
404
+ name,
405
+ parentSessionPath,
406
+ created: new Date(header.timestamp),
407
+ modified,
408
+ messageCount,
409
+ firstMessage: firstMessage || "(no messages)",
410
+ allMessagesText: allMessages.join(" "),
411
+ };
412
+ }
413
+ catch {
414
+ return null;
415
+ }
416
+ }
417
+ const MAX_CONCURRENT_SESSION_INFO_LOADS = 10;
418
+ async function buildSessionInfosWithConcurrency(files, onLoaded) {
419
+ const results = new Array(files.length).fill(null);
420
+ const inFlight = new Set();
421
+ let nextIndex = 0;
422
+ const startNext = () => {
423
+ const index = nextIndex++;
424
+ const file = files[index];
425
+ if (!file)
426
+ return;
427
+ let task;
428
+ task = buildSessionInfo(file)
429
+ .then((info) => {
430
+ results[index] = info;
431
+ })
432
+ .catch(() => {
433
+ results[index] = null;
434
+ })
435
+ .finally(() => {
436
+ inFlight.delete(task);
437
+ onLoaded();
438
+ });
439
+ inFlight.add(task);
440
+ };
441
+ while (nextIndex < files.length || inFlight.size > 0) {
442
+ while (nextIndex < files.length && inFlight.size < MAX_CONCURRENT_SESSION_INFO_LOADS) {
443
+ startNext();
444
+ }
445
+ if (inFlight.size > 0) {
446
+ await Promise.race(inFlight);
447
+ }
448
+ }
449
+ return results;
450
+ }
451
+ async function listSessionsFromDir(dir, onProgress, progressOffset = 0, progressTotal) {
452
+ const sessions = [];
453
+ if (!existsSync(dir)) {
454
+ return sessions;
455
+ }
456
+ try {
457
+ const dirEntries = await readdir(dir);
458
+ const files = dirEntries.filter((f) => f.endsWith(".jsonl")).map((f) => join(dir, f));
459
+ const total = progressTotal ?? files.length;
460
+ let loaded = 0;
461
+ const results = await buildSessionInfosWithConcurrency(files, () => {
462
+ loaded++;
463
+ onProgress?.(progressOffset + loaded, total);
464
+ });
465
+ for (const info of results) {
466
+ if (info) {
467
+ sessions.push(info);
468
+ }
469
+ }
470
+ }
471
+ catch {
472
+ // Return empty list on error
473
+ }
474
+ return sessions;
475
+ }
476
+ /**
477
+ * Manages conversation sessions as append-only trees stored in JSONL files.
478
+ *
479
+ * Each session entry has an id and parentId forming a tree structure. The "leaf"
480
+ * pointer tracks the current position. Appending creates a child of the current leaf.
481
+ * Branching moves the leaf to an earlier entry, allowing new branches without
482
+ * modifying history.
483
+ *
484
+ * Use buildSessionContext() to get the resolved message list for the LLM, which
485
+ * handles compaction summaries and follows the path from root to current leaf.
486
+ */
487
+ export class SessionManager {
488
+ sessionId = "";
489
+ sessionFile;
490
+ sessionDir;
491
+ cwd;
492
+ persist;
493
+ flushed = false;
494
+ fileEntries = [];
495
+ byId = new Map();
496
+ labelsById = new Map();
497
+ labelTimestampsById = new Map();
498
+ leafId = null;
499
+ constructor(cwd, sessionDir, sessionFile, persist, newSessionOptions) {
500
+ this.cwd = resolvePath(cwd);
501
+ this.sessionDir = normalizePath(sessionDir);
502
+ this.persist = persist;
503
+ if (persist && this.sessionDir && !existsSync(this.sessionDir)) {
504
+ mkdirSync(this.sessionDir, { recursive: true });
505
+ }
506
+ if (sessionFile) {
507
+ this.setSessionFile(sessionFile);
508
+ }
509
+ else {
510
+ this.newSession(newSessionOptions);
511
+ }
512
+ }
513
+ /** Switch to a different session file (used for resume and branching) */
514
+ setSessionFile(sessionFile) {
515
+ this.sessionFile = resolvePath(sessionFile);
516
+ if (existsSync(this.sessionFile)) {
517
+ this.fileEntries = loadEntriesFromFile(this.sessionFile);
518
+ // If file was empty or corrupted (no valid header), truncate and start fresh
519
+ // to avoid appending messages without a session header (which breaks the session)
520
+ if (this.fileEntries.length === 0) {
521
+ const explicitPath = this.sessionFile;
522
+ this.newSession();
523
+ this.sessionFile = explicitPath;
524
+ this._rewriteFile();
525
+ this.flushed = true;
526
+ return;
527
+ }
528
+ const header = this.fileEntries.find((e) => e.type === "session");
529
+ this.sessionId = header?.id ?? createSessionId();
530
+ if (migrateToCurrentVersion(this.fileEntries)) {
531
+ this._rewriteFile();
532
+ }
533
+ this._buildIndex();
534
+ this.flushed = true;
535
+ }
536
+ else {
537
+ const explicitPath = this.sessionFile;
538
+ this.newSession();
539
+ this.sessionFile = explicitPath; // preserve explicit path from --session flag
540
+ }
541
+ }
542
+ newSession(options) {
543
+ if (options?.id !== undefined) {
544
+ assertValidSessionId(options.id);
545
+ }
546
+ this.sessionId = options?.id ?? createSessionId();
547
+ const timestamp = new Date().toISOString();
548
+ const header = {
549
+ type: "session",
550
+ version: CURRENT_SESSION_VERSION,
551
+ id: this.sessionId,
552
+ timestamp,
553
+ cwd: this.cwd,
554
+ parentSession: options?.parentSession,
555
+ };
556
+ this.fileEntries = [header];
557
+ this.byId.clear();
558
+ this.labelsById.clear();
559
+ this.leafId = null;
560
+ this.flushed = false;
561
+ if (this.persist) {
562
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
563
+ this.sessionFile = join(this.getSessionDir(), `${fileTimestamp}_${this.sessionId}.jsonl`);
564
+ }
565
+ return this.sessionFile;
566
+ }
567
+ _buildIndex() {
568
+ this.byId.clear();
569
+ this.labelsById.clear();
570
+ this.labelTimestampsById.clear();
571
+ this.leafId = null;
572
+ for (const entry of this.fileEntries) {
573
+ if (entry.type === "session")
574
+ continue;
575
+ this.byId.set(entry.id, entry);
576
+ this.leafId = entry.id;
577
+ if (entry.type === "label") {
578
+ if (entry.label) {
579
+ this.labelsById.set(entry.targetId, entry.label);
580
+ this.labelTimestampsById.set(entry.targetId, entry.timestamp);
581
+ }
582
+ else {
583
+ this.labelsById.delete(entry.targetId);
584
+ this.labelTimestampsById.delete(entry.targetId);
585
+ }
586
+ }
587
+ }
588
+ }
589
+ _rewriteFile() {
590
+ if (!this.persist || !this.sessionFile)
591
+ return;
592
+ const content = `${this.fileEntries.map((e) => JSON.stringify(e)).join("\n")}\n`;
593
+ writeFileSync(this.sessionFile, content);
594
+ }
595
+ isPersisted() {
596
+ return this.persist;
597
+ }
598
+ getCwd() {
599
+ return this.cwd;
600
+ }
601
+ getSessionDir() {
602
+ return this.sessionDir;
603
+ }
604
+ usesDefaultSessionDir() {
605
+ return this.sessionDir === getDefaultSessionDirPath(this.cwd);
606
+ }
607
+ getSessionId() {
608
+ return this.sessionId;
609
+ }
610
+ getSessionFile() {
611
+ return this.sessionFile;
612
+ }
613
+ _persist(entry) {
614
+ if (!this.persist || !this.sessionFile)
615
+ return;
616
+ const hasAssistant = this.fileEntries.some((e) => e.type === "message" && e.message.role === "assistant");
617
+ if (!hasAssistant) {
618
+ if (this.flushed) {
619
+ appendFileSync(this.sessionFile, `${JSON.stringify(entry)}\n`);
620
+ }
621
+ else {
622
+ // Mark as not flushed so when assistant arrives, all entries get written
623
+ this.flushed = false;
624
+ }
625
+ return;
626
+ }
627
+ if (!this.flushed) {
628
+ const fd = openSync(this.sessionFile, "wx");
629
+ try {
630
+ for (const e of this.fileEntries) {
631
+ writeFileSync(fd, `${JSON.stringify(e)}\n`);
632
+ }
633
+ }
634
+ finally {
635
+ closeSync(fd);
636
+ }
637
+ this.flushed = true;
638
+ }
639
+ else {
640
+ appendFileSync(this.sessionFile, `${JSON.stringify(entry)}\n`);
641
+ }
642
+ }
643
+ _appendEntry(entry) {
644
+ this.fileEntries.push(entry);
645
+ this.byId.set(entry.id, entry);
646
+ this.leafId = entry.id;
647
+ this._persist(entry);
648
+ }
649
+ /** Append a message as child of current leaf, then advance leaf. Returns entry id.
650
+ * Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly.
651
+ * Reason: we want these to be top-level entries in the session, not message session entries,
652
+ * so it is easier to find them.
653
+ * These need to be appended via appendCompaction() and appendBranchSummary() methods.
654
+ */
655
+ appendMessage(message) {
656
+ const entry = {
657
+ type: "message",
658
+ id: generateId(this.byId),
659
+ parentId: this.leafId,
660
+ timestamp: new Date().toISOString(),
661
+ message,
662
+ };
663
+ this._appendEntry(entry);
664
+ return entry.id;
665
+ }
666
+ /** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */
667
+ appendThinkingLevelChange(thinkingLevel) {
668
+ const entry = {
669
+ type: "thinking_level_change",
670
+ id: generateId(this.byId),
671
+ parentId: this.leafId,
672
+ timestamp: new Date().toISOString(),
673
+ thinkingLevel,
674
+ };
675
+ this._appendEntry(entry);
676
+ return entry.id;
677
+ }
678
+ /** Append a model change as child of current leaf, then advance leaf. Returns entry id. */
679
+ appendModelChange(provider, modelId) {
680
+ const entry = {
681
+ type: "model_change",
682
+ id: generateId(this.byId),
683
+ parentId: this.leafId,
684
+ timestamp: new Date().toISOString(),
685
+ provider,
686
+ modelId,
687
+ };
688
+ this._appendEntry(entry);
689
+ return entry.id;
690
+ }
691
+ /** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */
692
+ appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook) {
693
+ const entry = {
694
+ type: "compaction",
695
+ id: generateId(this.byId),
696
+ parentId: this.leafId,
697
+ timestamp: new Date().toISOString(),
698
+ summary,
699
+ firstKeptEntryId,
700
+ tokensBefore,
701
+ details,
702
+ fromHook,
703
+ };
704
+ this._appendEntry(entry);
705
+ return entry.id;
706
+ }
707
+ /** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */
708
+ appendCustomEntry(customType, data) {
709
+ const entry = {
710
+ type: "custom",
711
+ customType,
712
+ data,
713
+ id: generateId(this.byId),
714
+ parentId: this.leafId,
715
+ timestamp: new Date().toISOString(),
716
+ };
717
+ this._appendEntry(entry);
718
+ return entry.id;
719
+ }
720
+ /** Append a session info entry (e.g., display name). Returns entry id. */
721
+ appendSessionInfo(name) {
722
+ const entry = {
723
+ type: "session_info",
724
+ id: generateId(this.byId),
725
+ parentId: this.leafId,
726
+ timestamp: new Date().toISOString(),
727
+ name: name.trim(),
728
+ };
729
+ this._appendEntry(entry);
730
+ return entry.id;
731
+ }
732
+ /** Get the current session name from the latest session_info entry, if any. */
733
+ getSessionName() {
734
+ // Walk entries in reverse to find the latest session_info entry.
735
+ // Empty names explicitly clear the session title.
736
+ const entries = this.getEntries();
737
+ for (let i = entries.length - 1; i >= 0; i--) {
738
+ const entry = entries[i];
739
+ if (entry.type === "session_info") {
740
+ return entry.name?.trim() || undefined;
741
+ }
742
+ }
743
+ return undefined;
744
+ }
745
+ /**
746
+ * Append a custom message entry (for extensions) that participates in LLM context.
747
+ * @param customType Extension identifier for filtering on reload
748
+ * @param content Message content (string or TextContent/ImageContent array)
749
+ * @param display Whether to show in TUI (true = styled display, false = hidden)
750
+ * @param details Optional extension-specific metadata (not sent to LLM)
751
+ * @returns Entry id
752
+ */
753
+ appendCustomMessageEntry(customType, content, display, details) {
754
+ const entry = {
755
+ type: "custom_message",
756
+ customType,
757
+ content,
758
+ display,
759
+ details,
760
+ id: generateId(this.byId),
761
+ parentId: this.leafId,
762
+ timestamp: new Date().toISOString(),
763
+ };
764
+ this._appendEntry(entry);
765
+ return entry.id;
766
+ }
767
+ // =========================================================================
768
+ // Tree Traversal
769
+ // =========================================================================
770
+ getLeafId() {
771
+ return this.leafId;
772
+ }
773
+ getLeafEntry() {
774
+ return this.leafId ? this.byId.get(this.leafId) : undefined;
775
+ }
776
+ getEntry(id) {
777
+ return this.byId.get(id);
778
+ }
779
+ /**
780
+ * Get all direct children of an entry.
781
+ */
782
+ getChildren(parentId) {
783
+ const children = [];
784
+ for (const entry of this.byId.values()) {
785
+ if (entry.parentId === parentId) {
786
+ children.push(entry);
787
+ }
788
+ }
789
+ return children;
790
+ }
791
+ /**
792
+ * Get the label for an entry, if any.
793
+ */
794
+ getLabel(id) {
795
+ return this.labelsById.get(id);
796
+ }
797
+ /**
798
+ * Set or clear a label on an entry.
799
+ * Labels are user-defined markers for bookmarking/navigation.
800
+ * Pass undefined or empty string to clear the label.
801
+ */
802
+ appendLabelChange(targetId, label) {
803
+ if (!this.byId.has(targetId)) {
804
+ throw new Error(`Entry ${targetId} not found`);
805
+ }
806
+ const entry = {
807
+ type: "label",
808
+ id: generateId(this.byId),
809
+ parentId: this.leafId,
810
+ timestamp: new Date().toISOString(),
811
+ targetId,
812
+ label,
813
+ };
814
+ this._appendEntry(entry);
815
+ if (label) {
816
+ this.labelsById.set(targetId, label);
817
+ this.labelTimestampsById.set(targetId, entry.timestamp);
818
+ }
819
+ else {
820
+ this.labelsById.delete(targetId);
821
+ this.labelTimestampsById.delete(targetId);
822
+ }
823
+ return entry.id;
824
+ }
825
+ /**
826
+ * Walk from entry to root, returning all entries in path order.
827
+ * Includes all entry types (messages, compaction, model changes, etc.).
828
+ * Use buildSessionContext() to get the resolved messages for the LLM.
829
+ */
830
+ getBranch(fromId) {
831
+ const path = [];
832
+ const startId = fromId ?? this.leafId;
833
+ let current = startId ? this.byId.get(startId) : undefined;
834
+ while (current) {
835
+ path.unshift(current);
836
+ current = current.parentId ? this.byId.get(current.parentId) : undefined;
837
+ }
838
+ return path;
839
+ }
840
+ /**
841
+ * Build the session context (what gets sent to the LLM).
842
+ * Uses tree traversal from current leaf.
843
+ */
844
+ buildSessionContext() {
845
+ return buildSessionContext(this.getEntries(), this.leafId, this.byId);
846
+ }
847
+ /**
848
+ * Get session header.
849
+ */
850
+ getHeader() {
851
+ const h = this.fileEntries.find((e) => e.type === "session");
852
+ return h ? h : null;
853
+ }
854
+ /**
855
+ * Get all session entries (excludes header). Returns a shallow copy.
856
+ * The session is append-only: use appendXXX() to add entries, branch() to
857
+ * change the leaf pointer. Entries cannot be modified or deleted.
858
+ */
859
+ getEntries() {
860
+ return this.fileEntries.filter((e) => e.type !== "session");
861
+ }
862
+ /**
863
+ * Get the session as a tree structure. Returns a shallow defensive copy of all entries.
864
+ * A well-formed session has exactly one root (first entry with parentId === null).
865
+ * Orphaned entries (broken parent chain) are also returned as roots.
866
+ */
867
+ getTree() {
868
+ const entries = this.getEntries();
869
+ const nodeMap = new Map();
870
+ const roots = [];
871
+ // Create nodes with resolved labels
872
+ for (const entry of entries) {
873
+ const label = this.labelsById.get(entry.id);
874
+ const labelTimestamp = this.labelTimestampsById.get(entry.id);
875
+ nodeMap.set(entry.id, { entry, children: [], label, labelTimestamp });
876
+ }
877
+ // Build tree
878
+ for (const entry of entries) {
879
+ const node = nodeMap.get(entry.id);
880
+ if (entry.parentId === null || entry.parentId === entry.id) {
881
+ roots.push(node);
882
+ }
883
+ else {
884
+ const parent = nodeMap.get(entry.parentId);
885
+ if (parent) {
886
+ parent.children.push(node);
887
+ }
888
+ else {
889
+ // Orphan - treat as root
890
+ roots.push(node);
891
+ }
892
+ }
893
+ }
894
+ // Sort children by timestamp (oldest first, newest at bottom)
895
+ // Use iterative approach to avoid stack overflow on deep trees
896
+ const stack = [...roots];
897
+ while (stack.length > 0) {
898
+ const node = stack.pop();
899
+ node.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());
900
+ stack.push(...node.children);
901
+ }
902
+ return roots;
903
+ }
904
+ // =========================================================================
905
+ // Branching
906
+ // =========================================================================
907
+ /**
908
+ * Start a new branch from an earlier entry.
909
+ * Moves the leaf pointer to the specified entry. The next appendXXX() call
910
+ * will create a child of that entry, forming a new branch. Existing entries
911
+ * are not modified or deleted.
912
+ */
913
+ branch(branchFromId) {
914
+ if (!this.byId.has(branchFromId)) {
915
+ throw new Error(`Entry ${branchFromId} not found`);
916
+ }
917
+ this.leafId = branchFromId;
918
+ }
919
+ /**
920
+ * Reset the leaf pointer to null (before any entries).
921
+ * The next appendXXX() call will create a new root entry (parentId = null).
922
+ * Use this when navigating to re-edit the first user message.
923
+ */
924
+ resetLeaf() {
925
+ this.leafId = null;
926
+ }
927
+ /**
928
+ * Start a new branch with a summary of the abandoned path.
929
+ * Same as branch(), but also appends a branch_summary entry that captures
930
+ * context from the abandoned conversation path.
931
+ */
932
+ branchWithSummary(branchFromId, summary, details, fromHook) {
933
+ if (branchFromId !== null && !this.byId.has(branchFromId)) {
934
+ throw new Error(`Entry ${branchFromId} not found`);
935
+ }
936
+ this.leafId = branchFromId;
937
+ const entry = {
938
+ type: "branch_summary",
939
+ id: generateId(this.byId),
940
+ parentId: branchFromId,
941
+ timestamp: new Date().toISOString(),
942
+ fromId: branchFromId ?? "root",
943
+ summary,
944
+ details,
945
+ fromHook,
946
+ };
947
+ this._appendEntry(entry);
948
+ return entry.id;
949
+ }
950
+ /**
951
+ * Create a new session file containing only the path from root to the specified leaf.
952
+ * Useful for extracting a single conversation path from a branched session.
953
+ * Returns the new session file path, or undefined if not persisting.
954
+ */
955
+ createBranchedSession(leafId) {
956
+ const previousSessionFile = this.sessionFile;
957
+ const path = this.getBranch(leafId);
958
+ if (path.length === 0) {
959
+ throw new Error(`Entry ${leafId} not found`);
960
+ }
961
+ // Filter out LabelEntry from path - we'll recreate them from the resolved map
962
+ const pathWithoutLabels = path.filter((e) => e.type !== "label");
963
+ const newSessionId = createSessionId();
964
+ const timestamp = new Date().toISOString();
965
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
966
+ const newSessionFile = join(this.getSessionDir(), `${fileTimestamp}_${newSessionId}.jsonl`);
967
+ const header = {
968
+ type: "session",
969
+ version: CURRENT_SESSION_VERSION,
970
+ id: newSessionId,
971
+ timestamp,
972
+ cwd: this.cwd,
973
+ parentSession: this.persist ? previousSessionFile : undefined,
974
+ };
975
+ // Collect labels for entries in the path
976
+ const pathEntryIds = new Set(pathWithoutLabels.map((e) => e.id));
977
+ const labelsToWrite = [];
978
+ for (const [targetId, label] of this.labelsById) {
979
+ if (pathEntryIds.has(targetId)) {
980
+ labelsToWrite.push({ targetId, label, timestamp: this.labelTimestampsById.get(targetId) });
981
+ }
982
+ }
983
+ if (this.persist) {
984
+ // Build label entries
985
+ const lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
986
+ let parentId = lastEntryId;
987
+ const labelEntries = [];
988
+ for (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {
989
+ const labelEntry = {
990
+ type: "label",
991
+ id: generateId(new Set(pathEntryIds)),
992
+ parentId,
993
+ timestamp: labelTimestamp,
994
+ targetId,
995
+ label,
996
+ };
997
+ pathEntryIds.add(labelEntry.id);
998
+ labelEntries.push(labelEntry);
999
+ parentId = labelEntry.id;
1000
+ }
1001
+ this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
1002
+ this.sessionId = newSessionId;
1003
+ this.sessionFile = newSessionFile;
1004
+ this._buildIndex();
1005
+ // Only write the file now if it contains an assistant message.
1006
+ // Otherwise defer to _persist(), which creates the file on the
1007
+ // first assistant response, matching the newSession() contract
1008
+ // and avoiding the duplicate-header bug when _persist()'s
1009
+ // no-assistant guard later resets flushed to false.
1010
+ const hasAssistant = this.fileEntries.some((e) => e.type === "message" && e.message.role === "assistant");
1011
+ if (hasAssistant) {
1012
+ this._rewriteFile();
1013
+ this.flushed = true;
1014
+ }
1015
+ else {
1016
+ this.flushed = false;
1017
+ }
1018
+ return newSessionFile;
1019
+ }
1020
+ // In-memory mode: replace current session with the path + labels
1021
+ const labelEntries = [];
1022
+ let parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
1023
+ for (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {
1024
+ const labelEntry = {
1025
+ type: "label",
1026
+ id: generateId(new Set([...pathEntryIds, ...labelEntries.map((e) => e.id)])),
1027
+ parentId,
1028
+ timestamp: labelTimestamp,
1029
+ targetId,
1030
+ label,
1031
+ };
1032
+ labelEntries.push(labelEntry);
1033
+ parentId = labelEntry.id;
1034
+ }
1035
+ this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
1036
+ this.sessionId = newSessionId;
1037
+ this._buildIndex();
1038
+ return undefined;
1039
+ }
1040
+ /**
1041
+ * Create a new session.
1042
+ * @param cwd Working directory (stored in session header)
1043
+ * @param sessionDir Optional session directory. If omitted, uses default (~/.leaf/agent/sessions/<encoded-cwd>/).
1044
+ */
1045
+ static create(cwd, sessionDir, options) {
1046
+ const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);
1047
+ return new SessionManager(cwd, dir, undefined, true, options);
1048
+ }
1049
+ /**
1050
+ * Open a specific session file.
1051
+ * @param path Path to session file
1052
+ * @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent.
1053
+ * @param cwdOverride Optional cwd override instead of the session header cwd.
1054
+ */
1055
+ static open(path, sessionDir, cwdOverride) {
1056
+ const resolvedPath = resolvePath(path);
1057
+ // Extract cwd from session header if possible, otherwise use process.cwd()
1058
+ const entries = loadEntriesFromFile(resolvedPath);
1059
+ const header = entries.find((e) => e.type === "session");
1060
+ const cwd = cwdOverride ?? header?.cwd ?? process.cwd();
1061
+ // If no sessionDir provided, derive from file's parent directory
1062
+ const dir = sessionDir ? normalizePath(sessionDir) : resolve(resolvedPath, "..");
1063
+ return new SessionManager(cwd, dir, resolvedPath, true);
1064
+ }
1065
+ /**
1066
+ * Continue the most recent session, or create new if none.
1067
+ * @param cwd Working directory
1068
+ * @param sessionDir Optional session directory. If omitted, uses default (~/.leaf/agent/sessions/<encoded-cwd>/).
1069
+ */
1070
+ static continueRecent(cwd, sessionDir) {
1071
+ const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);
1072
+ const filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);
1073
+ const mostRecent = findMostRecentSession(dir, filterCwd ? cwd : undefined);
1074
+ if (mostRecent) {
1075
+ return new SessionManager(cwd, dir, mostRecent, true);
1076
+ }
1077
+ return new SessionManager(cwd, dir, undefined, true);
1078
+ }
1079
+ /** Create an in-memory session (no file persistence) */
1080
+ static inMemory(cwd = process.cwd()) {
1081
+ return new SessionManager(cwd, "", undefined, false);
1082
+ }
1083
+ /**
1084
+ * Fork a session from another project directory into the current project.
1085
+ * Creates a new session in the target cwd with the full history from the source session.
1086
+ * @param sourcePath Path to the source session file
1087
+ * @param targetCwd Target working directory (where the new session will be stored)
1088
+ * @param sessionDir Optional session directory. If omitted, uses default for targetCwd.
1089
+ */
1090
+ static forkFrom(sourcePath, targetCwd, sessionDir, options) {
1091
+ const resolvedSourcePath = resolvePath(sourcePath);
1092
+ const resolvedTargetCwd = resolvePath(targetCwd);
1093
+ const sourceEntries = loadEntriesFromFile(resolvedSourcePath);
1094
+ if (sourceEntries.length === 0) {
1095
+ throw new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);
1096
+ }
1097
+ const sourceHeader = sourceEntries.find((e) => e.type === "session");
1098
+ if (!sourceHeader) {
1099
+ throw new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);
1100
+ }
1101
+ const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(resolvedTargetCwd);
1102
+ if (!existsSync(dir)) {
1103
+ mkdirSync(dir, { recursive: true });
1104
+ }
1105
+ // Create new session file with new ID but forked content
1106
+ if (options?.id !== undefined) {
1107
+ assertValidSessionId(options.id);
1108
+ }
1109
+ const newSessionId = options?.id ?? createSessionId();
1110
+ const timestamp = new Date().toISOString();
1111
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
1112
+ const newSessionFile = join(dir, `${fileTimestamp}_${newSessionId}.jsonl`);
1113
+ // Write new header pointing to source as parent, with updated cwd
1114
+ const newHeader = {
1115
+ type: "session",
1116
+ version: CURRENT_SESSION_VERSION,
1117
+ id: newSessionId,
1118
+ timestamp,
1119
+ cwd: resolvedTargetCwd,
1120
+ parentSession: resolvedSourcePath,
1121
+ };
1122
+ writeFileSync(newSessionFile, `${JSON.stringify(newHeader)}\n`, { flag: "wx" });
1123
+ // Copy all non-header entries from source
1124
+ for (const entry of sourceEntries) {
1125
+ if (entry.type !== "session") {
1126
+ appendFileSync(newSessionFile, `${JSON.stringify(entry)}\n`);
1127
+ }
1128
+ }
1129
+ return new SessionManager(resolvedTargetCwd, dir, newSessionFile, true);
1130
+ }
1131
+ /**
1132
+ * List all sessions for a directory.
1133
+ * @param cwd Working directory (used to compute default session directory)
1134
+ * @param sessionDir Optional session directory. If omitted, uses default (~/.leaf/agent/sessions/<encoded-cwd>/).
1135
+ * @param onProgress Optional callback for progress updates (loaded, total)
1136
+ */
1137
+ static async list(cwd, sessionDir, onProgress) {
1138
+ const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);
1139
+ const filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);
1140
+ const resolvedCwd = resolvePath(cwd);
1141
+ const sessions = (await listSessionsFromDir(dir, onProgress)).filter((session) => !filterCwd || sessionCwdMatches(session.cwd, resolvedCwd));
1142
+ sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
1143
+ return sessions;
1144
+ }
1145
+ static async listAll(sessionDirOrOnProgress, onProgress) {
1146
+ const customSessionDir = typeof sessionDirOrOnProgress === "string" ? normalizePath(sessionDirOrOnProgress) : undefined;
1147
+ const progress = typeof sessionDirOrOnProgress === "function" ? sessionDirOrOnProgress : onProgress;
1148
+ if (customSessionDir) {
1149
+ const sessions = await listSessionsFromDir(customSessionDir, progress);
1150
+ sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
1151
+ return sessions;
1152
+ }
1153
+ const sessionsDir = getSessionsDir();
1154
+ try {
1155
+ if (!existsSync(sessionsDir)) {
1156
+ return [];
1157
+ }
1158
+ const entries = await readdir(sessionsDir, { withFileTypes: true });
1159
+ const dirs = entries.filter((e) => e.isDirectory()).map((e) => join(sessionsDir, e.name));
1160
+ // Count total files first for accurate progress
1161
+ let totalFiles = 0;
1162
+ const dirFiles = [];
1163
+ for (const dir of dirs) {
1164
+ try {
1165
+ const files = (await readdir(dir)).filter((f) => f.endsWith(".jsonl"));
1166
+ dirFiles.push(files.map((f) => join(dir, f)));
1167
+ totalFiles += files.length;
1168
+ }
1169
+ catch {
1170
+ dirFiles.push([]);
1171
+ }
1172
+ }
1173
+ // Process all files with progress tracking
1174
+ let loaded = 0;
1175
+ const sessions = [];
1176
+ const allFiles = dirFiles.flat();
1177
+ const results = await buildSessionInfosWithConcurrency(allFiles, () => {
1178
+ loaded++;
1179
+ progress?.(loaded, totalFiles);
1180
+ });
1181
+ for (const info of results) {
1182
+ if (info) {
1183
+ sessions.push(info);
1184
+ }
1185
+ }
1186
+ sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
1187
+ return sessions;
1188
+ }
1189
+ catch {
1190
+ return [];
1191
+ }
1192
+ }
1193
+ }
1194
+ //# sourceMappingURL=session-manager.js.map