@vandeepunk/pi-coding-agent 0.0.1

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