@wahack/pi-coding-agent 15.11.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 (1152) hide show
  1. package/CHANGELOG.md +10031 -0
  2. package/README.md +36 -0
  3. package/examples/README.md +21 -0
  4. package/examples/custom-tools/README.md +104 -0
  5. package/examples/custom-tools/hello/index.ts +20 -0
  6. package/examples/extensions/README.md +142 -0
  7. package/examples/extensions/api-demo.ts +79 -0
  8. package/examples/extensions/chalk-logger.ts +25 -0
  9. package/examples/extensions/hello.ts +31 -0
  10. package/examples/extensions/pirate.ts +43 -0
  11. package/examples/extensions/plan-mode.ts +549 -0
  12. package/examples/extensions/reload-runtime.ts +38 -0
  13. package/examples/extensions/thinking-note.ts +13 -0
  14. package/examples/extensions/tools.ts +145 -0
  15. package/examples/extensions/with-deps/index.ts +36 -0
  16. package/examples/extensions/with-deps/package-lock.json +31 -0
  17. package/examples/extensions/with-deps/package.json +17 -0
  18. package/examples/hooks/README.md +56 -0
  19. package/examples/hooks/auto-commit-on-exit.ts +48 -0
  20. package/examples/hooks/confirm-destructive.ts +58 -0
  21. package/examples/hooks/custom-compaction.ts +115 -0
  22. package/examples/hooks/dirty-repo-guard.ts +51 -0
  23. package/examples/hooks/file-trigger.ts +40 -0
  24. package/examples/hooks/git-checkpoint.ts +52 -0
  25. package/examples/hooks/handoff.ts +149 -0
  26. package/examples/hooks/permission-gate.ts +33 -0
  27. package/examples/hooks/protected-paths.ts +29 -0
  28. package/examples/hooks/qna.ts +118 -0
  29. package/examples/hooks/status-line.ts +39 -0
  30. package/examples/sdk/01-minimal.ts +21 -0
  31. package/examples/sdk/02-custom-model.ts +49 -0
  32. package/examples/sdk/03-custom-prompt.ts +46 -0
  33. package/examples/sdk/04-skills.ts +43 -0
  34. package/examples/sdk/06-extensions.ts +82 -0
  35. package/examples/sdk/06-hooks.ts +61 -0
  36. package/examples/sdk/07-context-files.ts +35 -0
  37. package/examples/sdk/08-prompt-templates.ts +41 -0
  38. package/examples/sdk/08-slash-commands.ts +46 -0
  39. package/examples/sdk/09-api-keys-and-oauth.ts +54 -0
  40. package/examples/sdk/11-sessions.ts +47 -0
  41. package/examples/sdk/12-redis-sessions.ts +54 -0
  42. package/examples/sdk/13-sql-sessions.ts +61 -0
  43. package/examples/sdk/README.md +172 -0
  44. package/package.json +554 -0
  45. package/scripts/build-binary.ts +100 -0
  46. package/scripts/bundle-dist.ts +90 -0
  47. package/scripts/format-prompts.ts +68 -0
  48. package/scripts/generate-docs-index.ts +40 -0
  49. package/scripts/generate-template.ts +33 -0
  50. package/scripts/omp +42 -0
  51. package/scripts/omp.ts +19 -0
  52. package/src/async/index.ts +1 -0
  53. package/src/async/job-manager.ts +625 -0
  54. package/src/auto-thinking/classifier.ts +185 -0
  55. package/src/autoresearch/command-resume.md +14 -0
  56. package/src/autoresearch/dashboard.ts +436 -0
  57. package/src/autoresearch/git.ts +319 -0
  58. package/src/autoresearch/helpers.ts +218 -0
  59. package/src/autoresearch/index.ts +536 -0
  60. package/src/autoresearch/prompt-setup.md +43 -0
  61. package/src/autoresearch/prompt.md +103 -0
  62. package/src/autoresearch/resume-message.md +10 -0
  63. package/src/autoresearch/state.ts +273 -0
  64. package/src/autoresearch/storage.ts +699 -0
  65. package/src/autoresearch/tools/init-experiment.ts +272 -0
  66. package/src/autoresearch/tools/log-experiment.ts +524 -0
  67. package/src/autoresearch/tools/run-experiment.ts +407 -0
  68. package/src/autoresearch/tools/update-notes.ts +109 -0
  69. package/src/autoresearch/types.ts +168 -0
  70. package/src/bun-imports.d.ts +28 -0
  71. package/src/capability/context-file.ts +44 -0
  72. package/src/capability/extension-module.ts +34 -0
  73. package/src/capability/extension.ts +47 -0
  74. package/src/capability/fs.ts +117 -0
  75. package/src/capability/hook.ts +40 -0
  76. package/src/capability/index.ts +436 -0
  77. package/src/capability/instruction.ts +37 -0
  78. package/src/capability/mcp.ts +74 -0
  79. package/src/capability/prompt.ts +35 -0
  80. package/src/capability/rule-buckets.ts +66 -0
  81. package/src/capability/rule.ts +261 -0
  82. package/src/capability/settings.ts +34 -0
  83. package/src/capability/skill.ts +63 -0
  84. package/src/capability/slash-command.ts +40 -0
  85. package/src/capability/ssh.ts +41 -0
  86. package/src/capability/system-prompt.ts +34 -0
  87. package/src/capability/tool.ts +38 -0
  88. package/src/capability/types.ts +168 -0
  89. package/src/cli/agents-cli.ts +138 -0
  90. package/src/cli/args.ts +340 -0
  91. package/src/cli/auth-broker-cli.ts +895 -0
  92. package/src/cli/auth-gateway-cli.ts +611 -0
  93. package/src/cli/classify-install-target.ts +76 -0
  94. package/src/cli/claude-trace-cli.ts +795 -0
  95. package/src/cli/commands/init-xdg.ts +27 -0
  96. package/src/cli/completion-gen.ts +550 -0
  97. package/src/cli/config-cli.ts +418 -0
  98. package/src/cli/dry-balance-cli.ts +856 -0
  99. package/src/cli/extension-flags.ts +48 -0
  100. package/src/cli/file-processor.ts +133 -0
  101. package/src/cli/gallery-cli.ts +230 -0
  102. package/src/cli/gallery-fixtures/agentic.ts +407 -0
  103. package/src/cli/gallery-fixtures/codeintel.ts +187 -0
  104. package/src/cli/gallery-fixtures/edit.ts +194 -0
  105. package/src/cli/gallery-fixtures/fs.ts +220 -0
  106. package/src/cli/gallery-fixtures/index.ts +40 -0
  107. package/src/cli/gallery-fixtures/interaction.ts +49 -0
  108. package/src/cli/gallery-fixtures/memory.ts +81 -0
  109. package/src/cli/gallery-fixtures/misc.ts +250 -0
  110. package/src/cli/gallery-fixtures/search.ts +213 -0
  111. package/src/cli/gallery-fixtures/shell.ts +167 -0
  112. package/src/cli/gallery-fixtures/types.ts +57 -0
  113. package/src/cli/gallery-fixtures/web.ts +158 -0
  114. package/src/cli/gallery-screenshot.ts +279 -0
  115. package/src/cli/grep-cli.ts +160 -0
  116. package/src/cli/grievances-cli.ts +256 -0
  117. package/src/cli/initial-message.ts +58 -0
  118. package/src/cli/list-models.ts +194 -0
  119. package/src/cli/plugin-cli.ts +996 -0
  120. package/src/cli/read-cli.ts +57 -0
  121. package/src/cli/session-picker.ts +79 -0
  122. package/src/cli/setup-cli.ts +231 -0
  123. package/src/cli/shell-cli.ts +176 -0
  124. package/src/cli/ssh-cli.ts +179 -0
  125. package/src/cli/startup-cwd.ts +68 -0
  126. package/src/cli/stats-cli.ts +238 -0
  127. package/src/cli/tiny-models-cli.ts +127 -0
  128. package/src/cli/update-cli.ts +611 -0
  129. package/src/cli/usage-cli.ts +603 -0
  130. package/src/cli/web-search-cli.ts +132 -0
  131. package/src/cli/worktree-cli.ts +291 -0
  132. package/src/cli-commands.ts +79 -0
  133. package/src/cli.ts +200 -0
  134. package/src/commands/acp.ts +24 -0
  135. package/src/commands/agents.ts +57 -0
  136. package/src/commands/auth-broker.ts +99 -0
  137. package/src/commands/auth-gateway.ts +69 -0
  138. package/src/commands/commit.ts +46 -0
  139. package/src/commands/complete.ts +66 -0
  140. package/src/commands/completions.ts +60 -0
  141. package/src/commands/config.ts +51 -0
  142. package/src/commands/dry-balance.ts +43 -0
  143. package/src/commands/gallery.ts +52 -0
  144. package/src/commands/grep.ts +48 -0
  145. package/src/commands/grievances.ts +51 -0
  146. package/src/commands/install.ts +107 -0
  147. package/src/commands/launch.ts +169 -0
  148. package/src/commands/plugin.ts +78 -0
  149. package/src/commands/read.ts +38 -0
  150. package/src/commands/setup.ts +67 -0
  151. package/src/commands/shell.ts +29 -0
  152. package/src/commands/ssh.ts +60 -0
  153. package/src/commands/stats.ts +29 -0
  154. package/src/commands/tiny-models.ts +36 -0
  155. package/src/commands/update.ts +21 -0
  156. package/src/commands/usage.ts +35 -0
  157. package/src/commands/web-search.ts +42 -0
  158. package/src/commands/worktree.ts +56 -0
  159. package/src/commit/agentic/agent.ts +317 -0
  160. package/src/commit/agentic/fallback.ts +96 -0
  161. package/src/commit/agentic/index.ts +355 -0
  162. package/src/commit/agentic/prompts/analyze-file.md +22 -0
  163. package/src/commit/agentic/prompts/session-user.md +25 -0
  164. package/src/commit/agentic/prompts/split-confirm.md +1 -0
  165. package/src/commit/agentic/prompts/system.md +38 -0
  166. package/src/commit/agentic/state.ts +60 -0
  167. package/src/commit/agentic/tools/analyze-file.ts +146 -0
  168. package/src/commit/agentic/tools/git-file-diff.ts +191 -0
  169. package/src/commit/agentic/tools/git-hunk.ts +50 -0
  170. package/src/commit/agentic/tools/git-overview.ts +81 -0
  171. package/src/commit/agentic/tools/index.ts +54 -0
  172. package/src/commit/agentic/tools/propose-changelog.ts +144 -0
  173. package/src/commit/agentic/tools/propose-commit.ts +109 -0
  174. package/src/commit/agentic/tools/recent-commits.ts +81 -0
  175. package/src/commit/agentic/tools/schemas.ts +23 -0
  176. package/src/commit/agentic/tools/split-commit.ts +245 -0
  177. package/src/commit/agentic/topo-sort.ts +44 -0
  178. package/src/commit/agentic/trivial.ts +51 -0
  179. package/src/commit/agentic/validation.ts +183 -0
  180. package/src/commit/analysis/conventional.ts +64 -0
  181. package/src/commit/analysis/index.ts +4 -0
  182. package/src/commit/analysis/scope.ts +242 -0
  183. package/src/commit/analysis/summary.ts +105 -0
  184. package/src/commit/analysis/validation.ts +66 -0
  185. package/src/commit/changelog/detect.ts +40 -0
  186. package/src/commit/changelog/generate.ts +97 -0
  187. package/src/commit/changelog/index.ts +234 -0
  188. package/src/commit/changelog/parse.ts +44 -0
  189. package/src/commit/cli.ts +85 -0
  190. package/src/commit/git/diff.ts +148 -0
  191. package/src/commit/index.ts +5 -0
  192. package/src/commit/map-reduce/index.ts +69 -0
  193. package/src/commit/map-reduce/map-phase.ts +193 -0
  194. package/src/commit/map-reduce/reduce-phase.ts +49 -0
  195. package/src/commit/map-reduce/utils.ts +9 -0
  196. package/src/commit/message.ts +11 -0
  197. package/src/commit/model-selection.ts +92 -0
  198. package/src/commit/pipeline.ts +243 -0
  199. package/src/commit/prompts/analysis-system.md +148 -0
  200. package/src/commit/prompts/analysis-user.md +38 -0
  201. package/src/commit/prompts/changelog-system.md +50 -0
  202. package/src/commit/prompts/changelog-user.md +18 -0
  203. package/src/commit/prompts/file-observer-system.md +24 -0
  204. package/src/commit/prompts/file-observer-user.md +8 -0
  205. package/src/commit/prompts/reduce-system.md +50 -0
  206. package/src/commit/prompts/reduce-user.md +17 -0
  207. package/src/commit/prompts/summary-retry.md +3 -0
  208. package/src/commit/prompts/summary-system.md +38 -0
  209. package/src/commit/prompts/summary-user.md +13 -0
  210. package/src/commit/prompts/types-description.md +2 -0
  211. package/src/commit/shared-llm.ts +77 -0
  212. package/src/commit/types.ts +118 -0
  213. package/src/commit/utils/exclusions.ts +42 -0
  214. package/src/commit/utils.ts +58 -0
  215. package/src/config/api-key-resolver.ts +60 -0
  216. package/src/config/append-only-context-mode.ts +31 -0
  217. package/src/config/config-file.ts +317 -0
  218. package/src/config/file-lock.ts +164 -0
  219. package/src/config/keybindings.ts +628 -0
  220. package/src/config/mcp-schema.json +230 -0
  221. package/src/config/model-discovery.ts +554 -0
  222. package/src/config/model-registry.ts +2090 -0
  223. package/src/config/model-resolver.ts +1502 -0
  224. package/src/config/model-roles.ts +74 -0
  225. package/src/config/models-config-schema.ts +226 -0
  226. package/src/config/models-config.ts +129 -0
  227. package/src/config/prompt-templates.ts +185 -0
  228. package/src/config/resolve-config-value.ts +94 -0
  229. package/src/config/settings-schema.ts +3530 -0
  230. package/src/config/settings.ts +1178 -0
  231. package/src/config.ts +242 -0
  232. package/src/cursor.ts +340 -0
  233. package/src/dap/client.ts +760 -0
  234. package/src/dap/config.ts +189 -0
  235. package/src/dap/defaults.json +212 -0
  236. package/src/dap/index.ts +4 -0
  237. package/src/dap/session.ts +1441 -0
  238. package/src/dap/types.ts +610 -0
  239. package/src/debug/index.ts +515 -0
  240. package/src/debug/log-formatting.ts +58 -0
  241. package/src/debug/log-viewer.ts +908 -0
  242. package/src/debug/profiler.ts +162 -0
  243. package/src/debug/protocol-probe.ts +267 -0
  244. package/src/debug/raw-sse-buffer.ts +273 -0
  245. package/src/debug/raw-sse.ts +292 -0
  246. package/src/debug/report-bundle.ts +374 -0
  247. package/src/debug/system-info.ts +111 -0
  248. package/src/debug/terminal-info.ts +124 -0
  249. package/src/discovery/agents-md.ts +67 -0
  250. package/src/discovery/agents.ts +230 -0
  251. package/src/discovery/at-imports.ts +273 -0
  252. package/src/discovery/builtin-defaults.ts +39 -0
  253. package/src/discovery/builtin-rules/index.ts +54 -0
  254. package/src/discovery/builtin-rules/rs-box-leak.md +48 -0
  255. package/src/discovery/builtin-rules/rs-future-prelude.md +23 -0
  256. package/src/discovery/builtin-rules/rs-lazylock.md +51 -0
  257. package/src/discovery/builtin-rules/rs-match-ergonomics.md +67 -0
  258. package/src/discovery/builtin-rules/rs-parking-lot.md +44 -0
  259. package/src/discovery/builtin-rules/rs-result-type.md +19 -0
  260. package/src/discovery/builtin-rules/ts-bare-catch.md +38 -0
  261. package/src/discovery/builtin-rules/ts-import-type.md +42 -0
  262. package/src/discovery/builtin-rules/ts-no-any.md +56 -0
  263. package/src/discovery/builtin-rules/ts-no-deprecated-leftovers.md +44 -0
  264. package/src/discovery/builtin-rules/ts-no-dynamic-import.md +39 -0
  265. package/src/discovery/builtin-rules/ts-no-return-type.md +45 -0
  266. package/src/discovery/builtin-rules/ts-no-test-timers.md +55 -0
  267. package/src/discovery/builtin-rules/ts-no-tiny-functions.md +51 -0
  268. package/src/discovery/builtin-rules/ts-promise-with-resolvers.md +65 -0
  269. package/src/discovery/builtin-rules/ts-redundant-clear-guard.md +75 -0
  270. package/src/discovery/builtin-rules/ts-set-map.md +28 -0
  271. package/src/discovery/builtin.ts +906 -0
  272. package/src/discovery/claude-plugins.ts +386 -0
  273. package/src/discovery/claude.ts +584 -0
  274. package/src/discovery/cline.ts +83 -0
  275. package/src/discovery/codex.ts +522 -0
  276. package/src/discovery/cursor.ts +220 -0
  277. package/src/discovery/gemini.ts +383 -0
  278. package/src/discovery/github.ts +154 -0
  279. package/src/discovery/helpers.ts +1016 -0
  280. package/src/discovery/index.ts +81 -0
  281. package/src/discovery/mcp-json.ts +171 -0
  282. package/src/discovery/omp-extension-roots.ts +190 -0
  283. package/src/discovery/omp-plugins.ts +383 -0
  284. package/src/discovery/opencode.ts +398 -0
  285. package/src/discovery/plugin-dir-roots.ts +28 -0
  286. package/src/discovery/ssh.ts +153 -0
  287. package/src/discovery/substitute-plugin-root.ts +29 -0
  288. package/src/discovery/vscode.ts +105 -0
  289. package/src/discovery/windsurf.ts +147 -0
  290. package/src/edit/apply-patch/index.ts +87 -0
  291. package/src/edit/apply-patch/parser.ts +174 -0
  292. package/src/edit/diff.ts +999 -0
  293. package/src/edit/file-snapshot-store.ts +91 -0
  294. package/src/edit/hashline/block-resolver.ts +33 -0
  295. package/src/edit/hashline/diff.ts +290 -0
  296. package/src/edit/hashline/execute.ts +242 -0
  297. package/src/edit/hashline/filesystem.ts +130 -0
  298. package/src/edit/hashline/index.ts +5 -0
  299. package/src/edit/hashline/noop-loop-guard.ts +99 -0
  300. package/src/edit/hashline/params.ts +18 -0
  301. package/src/edit/index.ts +571 -0
  302. package/src/edit/modes/apply-patch.lark +19 -0
  303. package/src/edit/modes/apply-patch.ts +53 -0
  304. package/src/edit/modes/patch.ts +1891 -0
  305. package/src/edit/modes/replace.ts +1137 -0
  306. package/src/edit/normalize.ts +345 -0
  307. package/src/edit/notebook.ts +242 -0
  308. package/src/edit/read-file.ts +25 -0
  309. package/src/edit/renderer.ts +769 -0
  310. package/src/edit/streaming.ts +517 -0
  311. package/src/eval/__tests__/agent-bridge.test.ts +708 -0
  312. package/src/eval/__tests__/bridge-timeout.test.ts +64 -0
  313. package/src/eval/__tests__/budget-bridge.test.ts +69 -0
  314. package/src/eval/__tests__/completion-bridge.test.ts +412 -0
  315. package/src/eval/__tests__/helpers-local-roots.test.ts +58 -0
  316. package/src/eval/__tests__/idle-timeout.test.ts +80 -0
  317. package/src/eval/__tests__/js-context-manager.test.ts +241 -0
  318. package/src/eval/__tests__/kernel-spawn.test.ts +103 -0
  319. package/src/eval/agent-bridge.ts +319 -0
  320. package/src/eval/backend.ts +71 -0
  321. package/src/eval/bridge-timeout.ts +44 -0
  322. package/src/eval/budget-bridge.ts +48 -0
  323. package/src/eval/completion-bridge.ts +207 -0
  324. package/src/eval/concurrency-bridge.ts +34 -0
  325. package/src/eval/idle-timeout.ts +91 -0
  326. package/src/eval/index.ts +4 -0
  327. package/src/eval/js/context-manager.ts +502 -0
  328. package/src/eval/js/executor.ts +173 -0
  329. package/src/eval/js/index.ts +51 -0
  330. package/src/eval/js/shared/helpers.ts +283 -0
  331. package/src/eval/js/shared/indirect-eval.ts +30 -0
  332. package/src/eval/js/shared/local-module-loader.ts +342 -0
  333. package/src/eval/js/shared/prelude.ts +2 -0
  334. package/src/eval/js/shared/prelude.txt +246 -0
  335. package/src/eval/js/shared/rewrite-imports.ts +532 -0
  336. package/src/eval/js/shared/runtime.ts +352 -0
  337. package/src/eval/js/shared/types.ts +18 -0
  338. package/src/eval/js/tool-bridge.ts +162 -0
  339. package/src/eval/js/worker-core.ts +132 -0
  340. package/src/eval/js/worker-entry.ts +30 -0
  341. package/src/eval/js/worker-protocol.ts +47 -0
  342. package/src/eval/py/__tests__/prelude.test.ts +19 -0
  343. package/src/eval/py/display.ts +71 -0
  344. package/src/eval/py/executor.ts +742 -0
  345. package/src/eval/py/index.ts +68 -0
  346. package/src/eval/py/kernel.ts +748 -0
  347. package/src/eval/py/prelude.py +658 -0
  348. package/src/eval/py/prelude.ts +3 -0
  349. package/src/eval/py/runner.py +1133 -0
  350. package/src/eval/py/runtime.ts +276 -0
  351. package/src/eval/py/spawn-options.ts +126 -0
  352. package/src/eval/py/tool-bridge.ts +182 -0
  353. package/src/eval/session-id.ts +8 -0
  354. package/src/eval/types.ts +48 -0
  355. package/src/exa/index.ts +2 -0
  356. package/src/exa/mcp-client.ts +370 -0
  357. package/src/exa/types.ts +69 -0
  358. package/src/exec/bash-executor.ts +419 -0
  359. package/src/exec/exec.ts +53 -0
  360. package/src/exec/non-interactive-env.ts +48 -0
  361. package/src/export/custom-share.ts +65 -0
  362. package/src/export/html/index.ts +164 -0
  363. package/src/export/html/template.css +1051 -0
  364. package/src/export/html/template.generated.ts +2 -0
  365. package/src/export/html/template.html +46 -0
  366. package/src/export/html/template.js +2271 -0
  367. package/src/export/html/template.macro.ts +25 -0
  368. package/src/export/html/vendor/highlight.min.js +1213 -0
  369. package/src/export/html/vendor/marked.min.js +6 -0
  370. package/src/export/ttsr.ts +583 -0
  371. package/src/extensibility/custom-commands/bundled/ci-green/index.ts +54 -0
  372. package/src/extensibility/custom-commands/bundled/review/index.ts +489 -0
  373. package/src/extensibility/custom-commands/index.ts +2 -0
  374. package/src/extensibility/custom-commands/loader.ts +238 -0
  375. package/src/extensibility/custom-commands/types.ts +113 -0
  376. package/src/extensibility/custom-tools/index.ts +7 -0
  377. package/src/extensibility/custom-tools/loader.ts +269 -0
  378. package/src/extensibility/custom-tools/types.ts +270 -0
  379. package/src/extensibility/custom-tools/wrapper.ts +47 -0
  380. package/src/extensibility/extensions/compact-handler.ts +40 -0
  381. package/src/extensibility/extensions/get-commands-handler.ts +78 -0
  382. package/src/extensibility/extensions/index.ts +16 -0
  383. package/src/extensibility/extensions/loader.ts +572 -0
  384. package/src/extensibility/extensions/runner.ts +922 -0
  385. package/src/extensibility/extensions/types.ts +1322 -0
  386. package/src/extensibility/extensions/wrapper.ts +223 -0
  387. package/src/extensibility/hooks/index.ts +5 -0
  388. package/src/extensibility/hooks/loader.ts +257 -0
  389. package/src/extensibility/hooks/runner.ts +425 -0
  390. package/src/extensibility/hooks/tool-wrapper.ts +107 -0
  391. package/src/extensibility/hooks/types.ts +606 -0
  392. package/src/extensibility/legacy-pi-ai-shim.ts +24 -0
  393. package/src/extensibility/legacy-pi-coding-agent-shim.ts +15 -0
  394. package/src/extensibility/plugins/doctor.ts +65 -0
  395. package/src/extensibility/plugins/git-url.ts +367 -0
  396. package/src/extensibility/plugins/index.ts +9 -0
  397. package/src/extensibility/plugins/installer.ts +192 -0
  398. package/src/extensibility/plugins/legacy-pi-compat.ts +682 -0
  399. package/src/extensibility/plugins/loader.ts +313 -0
  400. package/src/extensibility/plugins/manager.ts +827 -0
  401. package/src/extensibility/plugins/marketplace/cache.ts +136 -0
  402. package/src/extensibility/plugins/marketplace/fetcher.ts +317 -0
  403. package/src/extensibility/plugins/marketplace/index.ts +6 -0
  404. package/src/extensibility/plugins/marketplace/manager.ts +770 -0
  405. package/src/extensibility/plugins/marketplace/registry.ts +196 -0
  406. package/src/extensibility/plugins/marketplace/source-resolver.ts +147 -0
  407. package/src/extensibility/plugins/marketplace/types.ts +191 -0
  408. package/src/extensibility/plugins/marketplace-auto-update.ts +49 -0
  409. package/src/extensibility/plugins/parser.ts +105 -0
  410. package/src/extensibility/plugins/types.ts +194 -0
  411. package/src/extensibility/shared-events.ts +343 -0
  412. package/src/extensibility/skills.ts +312 -0
  413. package/src/extensibility/slash-commands.ts +227 -0
  414. package/src/extensibility/tool-proxy.ts +25 -0
  415. package/src/extensibility/typebox.ts +418 -0
  416. package/src/extensibility/utils.ts +44 -0
  417. package/src/goals/index.ts +3 -0
  418. package/src/goals/runtime.ts +528 -0
  419. package/src/goals/state.ts +37 -0
  420. package/src/goals/tools/goal-tool.ts +251 -0
  421. package/src/hindsight/backend.ts +354 -0
  422. package/src/hindsight/bank.ts +156 -0
  423. package/src/hindsight/client.ts +598 -0
  424. package/src/hindsight/config.ts +175 -0
  425. package/src/hindsight/content.ts +210 -0
  426. package/src/hindsight/index.ts +8 -0
  427. package/src/hindsight/mental-models.ts +429 -0
  428. package/src/hindsight/seeds.json +32 -0
  429. package/src/hindsight/state.ts +488 -0
  430. package/src/hindsight/transcript.ts +71 -0
  431. package/src/index.ts +59 -0
  432. package/src/internal-urls/agent-protocol.ts +146 -0
  433. package/src/internal-urls/artifact-protocol.ts +107 -0
  434. package/src/internal-urls/docs-index.generated.ts +106 -0
  435. package/src/internal-urls/history-protocol.ts +113 -0
  436. package/src/internal-urls/index.ts +25 -0
  437. package/src/internal-urls/issue-pr-protocol.ts +584 -0
  438. package/src/internal-urls/json-query.ts +126 -0
  439. package/src/internal-urls/local-protocol.ts +287 -0
  440. package/src/internal-urls/mcp-protocol.ts +151 -0
  441. package/src/internal-urls/memory-protocol.ts +169 -0
  442. package/src/internal-urls/omp-protocol.ts +93 -0
  443. package/src/internal-urls/parse.ts +72 -0
  444. package/src/internal-urls/registry-helpers.ts +25 -0
  445. package/src/internal-urls/router.ts +105 -0
  446. package/src/internal-urls/rule-protocol.ts +45 -0
  447. package/src/internal-urls/skill-protocol.ts +96 -0
  448. package/src/internal-urls/types.ts +152 -0
  449. package/src/internal-urls/vault-protocol.ts +936 -0
  450. package/src/irc/bus.ts +292 -0
  451. package/src/lib/xai-http.ts +124 -0
  452. package/src/lsp/client.ts +1193 -0
  453. package/src/lsp/clients/biome-client.ts +264 -0
  454. package/src/lsp/clients/index.ts +50 -0
  455. package/src/lsp/clients/lsp-linter-client.ts +93 -0
  456. package/src/lsp/clients/swiftlint-client.ts +120 -0
  457. package/src/lsp/config.ts +502 -0
  458. package/src/lsp/defaults.json +493 -0
  459. package/src/lsp/diagnostics-ledger.ts +51 -0
  460. package/src/lsp/edits.ts +267 -0
  461. package/src/lsp/index.ts +2477 -0
  462. package/src/lsp/lspmux.ts +233 -0
  463. package/src/lsp/render.ts +694 -0
  464. package/src/lsp/startup-events.ts +13 -0
  465. package/src/lsp/types.ts +455 -0
  466. package/src/lsp/utils.ts +718 -0
  467. package/src/main.ts +1325 -0
  468. package/src/mcp/client.ts +484 -0
  469. package/src/mcp/config-writer.ts +225 -0
  470. package/src/mcp/config.ts +365 -0
  471. package/src/mcp/index.ts +29 -0
  472. package/src/mcp/json-rpc.ts +122 -0
  473. package/src/mcp/loader.ts +124 -0
  474. package/src/mcp/manager.ts +1275 -0
  475. package/src/mcp/oauth-discovery.ts +442 -0
  476. package/src/mcp/oauth-flow.ts +442 -0
  477. package/src/mcp/render.ts +132 -0
  478. package/src/mcp/smithery-auth.ts +104 -0
  479. package/src/mcp/smithery-connect.ts +145 -0
  480. package/src/mcp/smithery-registry.ts +477 -0
  481. package/src/mcp/timeout.ts +59 -0
  482. package/src/mcp/tool-bridge.ts +426 -0
  483. package/src/mcp/tool-cache.ts +117 -0
  484. package/src/mcp/transports/http.ts +519 -0
  485. package/src/mcp/transports/index.ts +6 -0
  486. package/src/mcp/transports/stdio.ts +528 -0
  487. package/src/mcp/types.ts +423 -0
  488. package/src/memories/index.ts +1150 -0
  489. package/src/memories/storage.ts +577 -0
  490. package/src/memory-backend/index.ts +18 -0
  491. package/src/memory-backend/local-backend.ts +39 -0
  492. package/src/memory-backend/off-backend.ts +25 -0
  493. package/src/memory-backend/resolve.ts +25 -0
  494. package/src/memory-backend/runtime.ts +66 -0
  495. package/src/memory-backend/types.ts +166 -0
  496. package/src/mnemopi/backend.ts +547 -0
  497. package/src/mnemopi/config.ts +160 -0
  498. package/src/mnemopi/index.ts +3 -0
  499. package/src/mnemopi/state.ts +584 -0
  500. package/src/modes/acp/acp-agent.ts +2407 -0
  501. package/src/modes/acp/acp-client-bridge.ts +154 -0
  502. package/src/modes/acp/acp-event-mapper.ts +929 -0
  503. package/src/modes/acp/acp-mode.ts +23 -0
  504. package/src/modes/acp/index.ts +2 -0
  505. package/src/modes/acp/terminal-auth.ts +37 -0
  506. package/src/modes/components/agent-dashboard.ts +1206 -0
  507. package/src/modes/components/agent-hub.ts +1071 -0
  508. package/src/modes/components/assistant-message.ts +307 -0
  509. package/src/modes/components/bash-execution.ts +220 -0
  510. package/src/modes/components/bordered-loader.ts +41 -0
  511. package/src/modes/components/branch-summary-message.ts +45 -0
  512. package/src/modes/components/btw-panel.ts +104 -0
  513. package/src/modes/components/chat-block.ts +111 -0
  514. package/src/modes/components/compaction-summary-message.ts +87 -0
  515. package/src/modes/components/copy-selector.ts +206 -0
  516. package/src/modes/components/countdown-timer.ts +75 -0
  517. package/src/modes/components/custom-editor.ts +398 -0
  518. package/src/modes/components/custom-message.ts +63 -0
  519. package/src/modes/components/diff.ts +277 -0
  520. package/src/modes/components/dynamic-border.ts +34 -0
  521. package/src/modes/components/error-banner.ts +33 -0
  522. package/src/modes/components/eval-execution.ts +158 -0
  523. package/src/modes/components/execution-shared.ts +101 -0
  524. package/src/modes/components/extensions/extension-dashboard.ts +399 -0
  525. package/src/modes/components/extensions/extension-list.ts +502 -0
  526. package/src/modes/components/extensions/index.ts +9 -0
  527. package/src/modes/components/extensions/inspector-panel.ts +317 -0
  528. package/src/modes/components/extensions/state-manager.ts +627 -0
  529. package/src/modes/components/extensions/types.ts +186 -0
  530. package/src/modes/components/footer.ts +274 -0
  531. package/src/modes/components/history-search.ts +280 -0
  532. package/src/modes/components/hook-editor.ts +167 -0
  533. package/src/modes/components/hook-input.ts +87 -0
  534. package/src/modes/components/hook-message.ts +66 -0
  535. package/src/modes/components/hook-selector.ts +660 -0
  536. package/src/modes/components/index.ts +38 -0
  537. package/src/modes/components/keybinding-hints.ts +65 -0
  538. package/src/modes/components/late-diagnostics-message.ts +60 -0
  539. package/src/modes/components/login-dialog.ts +164 -0
  540. package/src/modes/components/mcp-add-wizard.ts +1340 -0
  541. package/src/modes/components/message-frame.ts +88 -0
  542. package/src/modes/components/model-selector.ts +1271 -0
  543. package/src/modes/components/oauth-selector.ts +368 -0
  544. package/src/modes/components/omfg-panel.ts +141 -0
  545. package/src/modes/components/overlay-box.ts +108 -0
  546. package/src/modes/components/plan-review-overlay.ts +820 -0
  547. package/src/modes/components/plan-toc.ts +138 -0
  548. package/src/modes/components/plugin-selector.ts +95 -0
  549. package/src/modes/components/plugin-settings.ts +722 -0
  550. package/src/modes/components/queue-mode-selector.ts +56 -0
  551. package/src/modes/components/read-tool-group.ts +670 -0
  552. package/src/modes/components/segment-track.ts +52 -0
  553. package/src/modes/components/session-selector.ts +625 -0
  554. package/src/modes/components/settings-defs.ts +189 -0
  555. package/src/modes/components/settings-selector.ts +651 -0
  556. package/src/modes/components/show-images-selector.ts +45 -0
  557. package/src/modes/components/skill-message.ts +89 -0
  558. package/src/modes/components/status-line/component.ts +869 -0
  559. package/src/modes/components/status-line/context-thresholds.ts +79 -0
  560. package/src/modes/components/status-line/git-utils.ts +42 -0
  561. package/src/modes/components/status-line/index.ts +5 -0
  562. package/src/modes/components/status-line/presets.ts +106 -0
  563. package/src/modes/components/status-line/segments.ts +584 -0
  564. package/src/modes/components/status-line/separators.ts +55 -0
  565. package/src/modes/components/status-line/token-rate.ts +66 -0
  566. package/src/modes/components/status-line/types.ts +108 -0
  567. package/src/modes/components/theme-selector.ts +63 -0
  568. package/src/modes/components/thinking-selector.ts +52 -0
  569. package/src/modes/components/tiny-title-download-progress.ts +90 -0
  570. package/src/modes/components/tips.txt +19 -0
  571. package/src/modes/components/todo-reminder.ts +38 -0
  572. package/src/modes/components/tool-execution.ts +1024 -0
  573. package/src/modes/components/transcript-container.ts +608 -0
  574. package/src/modes/components/tree-selector.ts +978 -0
  575. package/src/modes/components/ttsr-notification.ts +122 -0
  576. package/src/modes/components/user-message-selector.ts +227 -0
  577. package/src/modes/components/user-message.ts +66 -0
  578. package/src/modes/components/visual-truncate.ts +63 -0
  579. package/src/modes/components/welcome.ts +493 -0
  580. package/src/modes/controllers/btw-controller.ts +105 -0
  581. package/src/modes/controllers/command-controller-shared.ts +109 -0
  582. package/src/modes/controllers/command-controller.ts +1566 -0
  583. package/src/modes/controllers/event-controller.ts +1054 -0
  584. package/src/modes/controllers/extension-ui-controller.ts +886 -0
  585. package/src/modes/controllers/input-controller.ts +1073 -0
  586. package/src/modes/controllers/mcp-command-controller.ts +2017 -0
  587. package/src/modes/controllers/omfg-controller.ts +283 -0
  588. package/src/modes/controllers/omfg-rule.ts +647 -0
  589. package/src/modes/controllers/selector-controller.ts +1108 -0
  590. package/src/modes/controllers/ssh-command-controller.ts +384 -0
  591. package/src/modes/controllers/streaming-reveal.ts +279 -0
  592. package/src/modes/controllers/tan-command-controller.ts +173 -0
  593. package/src/modes/controllers/todo-command-controller.ts +485 -0
  594. package/src/modes/data/emojis.json +1 -0
  595. package/src/modes/emoji-autocomplete.ts +285 -0
  596. package/src/modes/gradient-highlight.ts +87 -0
  597. package/src/modes/image-references.ts +117 -0
  598. package/src/modes/index.ts +17 -0
  599. package/src/modes/interactive-mode.ts +3370 -0
  600. package/src/modes/internal-url-autocomplete.ts +143 -0
  601. package/src/modes/loop-limit.ts +140 -0
  602. package/src/modes/magic-keywords.ts +20 -0
  603. package/src/modes/markdown-prose.ts +247 -0
  604. package/src/modes/oauth-manual-input.ts +69 -0
  605. package/src/modes/orchestrate.ts +42 -0
  606. package/src/modes/print-mode.ts +126 -0
  607. package/src/modes/prompt-action-autocomplete.ts +260 -0
  608. package/src/modes/rpc/host-tools.ts +186 -0
  609. package/src/modes/rpc/host-uris.ts +235 -0
  610. package/src/modes/rpc/rpc-client.ts +963 -0
  611. package/src/modes/rpc/rpc-mode.ts +947 -0
  612. package/src/modes/rpc/rpc-subagents.ts +265 -0
  613. package/src/modes/rpc/rpc-types.ts +458 -0
  614. package/src/modes/runtime-init.ts +116 -0
  615. package/src/modes/session-observer-registry.ts +146 -0
  616. package/src/modes/setup-version.ts +11 -0
  617. package/src/modes/setup-wizard/index.ts +99 -0
  618. package/src/modes/setup-wizard/lazy.ts +16 -0
  619. package/src/modes/setup-wizard/scenes/glyph.ts +96 -0
  620. package/src/modes/setup-wizard/scenes/outro.ts +35 -0
  621. package/src/modes/setup-wizard/scenes/providers.ts +69 -0
  622. package/src/modes/setup-wizard/scenes/sign-in.ts +205 -0
  623. package/src/modes/setup-wizard/scenes/splash.ts +201 -0
  624. package/src/modes/setup-wizard/scenes/theme.ts +299 -0
  625. package/src/modes/setup-wizard/scenes/types.ts +48 -0
  626. package/src/modes/setup-wizard/scenes/web-search.ts +129 -0
  627. package/src/modes/setup-wizard/wizard-overlay.ts +275 -0
  628. package/src/modes/shared.ts +47 -0
  629. package/src/modes/theme/dark.json +95 -0
  630. package/src/modes/theme/defaults/alabaster.json +93 -0
  631. package/src/modes/theme/defaults/amethyst.json +96 -0
  632. package/src/modes/theme/defaults/anthracite.json +93 -0
  633. package/src/modes/theme/defaults/basalt.json +91 -0
  634. package/src/modes/theme/defaults/birch.json +95 -0
  635. package/src/modes/theme/defaults/dark-abyss.json +91 -0
  636. package/src/modes/theme/defaults/dark-arctic.json +104 -0
  637. package/src/modes/theme/defaults/dark-aurora.json +95 -0
  638. package/src/modes/theme/defaults/dark-catppuccin.json +107 -0
  639. package/src/modes/theme/defaults/dark-cavern.json +91 -0
  640. package/src/modes/theme/defaults/dark-copper.json +95 -0
  641. package/src/modes/theme/defaults/dark-cosmos.json +90 -0
  642. package/src/modes/theme/defaults/dark-cyberpunk.json +102 -0
  643. package/src/modes/theme/defaults/dark-dracula.json +98 -0
  644. package/src/modes/theme/defaults/dark-eclipse.json +91 -0
  645. package/src/modes/theme/defaults/dark-ember.json +95 -0
  646. package/src/modes/theme/defaults/dark-equinox.json +90 -0
  647. package/src/modes/theme/defaults/dark-forest.json +96 -0
  648. package/src/modes/theme/defaults/dark-github.json +105 -0
  649. package/src/modes/theme/defaults/dark-gruvbox.json +112 -0
  650. package/src/modes/theme/defaults/dark-lavender.json +95 -0
  651. package/src/modes/theme/defaults/dark-lunar.json +89 -0
  652. package/src/modes/theme/defaults/dark-midnight.json +95 -0
  653. package/src/modes/theme/defaults/dark-monochrome.json +94 -0
  654. package/src/modes/theme/defaults/dark-monokai.json +98 -0
  655. package/src/modes/theme/defaults/dark-nebula.json +90 -0
  656. package/src/modes/theme/defaults/dark-nord.json +97 -0
  657. package/src/modes/theme/defaults/dark-ocean.json +101 -0
  658. package/src/modes/theme/defaults/dark-one.json +100 -0
  659. package/src/modes/theme/defaults/dark-poimandres.json +142 -0
  660. package/src/modes/theme/defaults/dark-rainforest.json +91 -0
  661. package/src/modes/theme/defaults/dark-reef.json +91 -0
  662. package/src/modes/theme/defaults/dark-retro.json +92 -0
  663. package/src/modes/theme/defaults/dark-rose-pine.json +96 -0
  664. package/src/modes/theme/defaults/dark-sakura.json +95 -0
  665. package/src/modes/theme/defaults/dark-slate.json +95 -0
  666. package/src/modes/theme/defaults/dark-solarized.json +97 -0
  667. package/src/modes/theme/defaults/dark-solstice.json +90 -0
  668. package/src/modes/theme/defaults/dark-starfall.json +91 -0
  669. package/src/modes/theme/defaults/dark-sunset.json +99 -0
  670. package/src/modes/theme/defaults/dark-swamp.json +90 -0
  671. package/src/modes/theme/defaults/dark-synthwave.json +103 -0
  672. package/src/modes/theme/defaults/dark-taiga.json +91 -0
  673. package/src/modes/theme/defaults/dark-terminal.json +95 -0
  674. package/src/modes/theme/defaults/dark-tokyo-night.json +101 -0
  675. package/src/modes/theme/defaults/dark-tundra.json +91 -0
  676. package/src/modes/theme/defaults/dark-twilight.json +91 -0
  677. package/src/modes/theme/defaults/dark-volcanic.json +91 -0
  678. package/src/modes/theme/defaults/graphite.json +92 -0
  679. package/src/modes/theme/defaults/index.ts +199 -0
  680. package/src/modes/theme/defaults/light-arctic.json +107 -0
  681. package/src/modes/theme/defaults/light-aurora-day.json +91 -0
  682. package/src/modes/theme/defaults/light-canyon.json +91 -0
  683. package/src/modes/theme/defaults/light-catppuccin.json +106 -0
  684. package/src/modes/theme/defaults/light-cirrus.json +90 -0
  685. package/src/modes/theme/defaults/light-coral.json +95 -0
  686. package/src/modes/theme/defaults/light-cyberpunk.json +96 -0
  687. package/src/modes/theme/defaults/light-dawn.json +90 -0
  688. package/src/modes/theme/defaults/light-dunes.json +91 -0
  689. package/src/modes/theme/defaults/light-eucalyptus.json +95 -0
  690. package/src/modes/theme/defaults/light-forest.json +100 -0
  691. package/src/modes/theme/defaults/light-frost.json +95 -0
  692. package/src/modes/theme/defaults/light-github.json +115 -0
  693. package/src/modes/theme/defaults/light-glacier.json +91 -0
  694. package/src/modes/theme/defaults/light-gruvbox.json +108 -0
  695. package/src/modes/theme/defaults/light-haze.json +90 -0
  696. package/src/modes/theme/defaults/light-honeycomb.json +95 -0
  697. package/src/modes/theme/defaults/light-lagoon.json +91 -0
  698. package/src/modes/theme/defaults/light-lavender.json +95 -0
  699. package/src/modes/theme/defaults/light-meadow.json +91 -0
  700. package/src/modes/theme/defaults/light-mint.json +95 -0
  701. package/src/modes/theme/defaults/light-monochrome.json +101 -0
  702. package/src/modes/theme/defaults/light-ocean.json +99 -0
  703. package/src/modes/theme/defaults/light-one.json +99 -0
  704. package/src/modes/theme/defaults/light-opal.json +91 -0
  705. package/src/modes/theme/defaults/light-orchard.json +91 -0
  706. package/src/modes/theme/defaults/light-paper.json +95 -0
  707. package/src/modes/theme/defaults/light-poimandres.json +142 -0
  708. package/src/modes/theme/defaults/light-prism.json +90 -0
  709. package/src/modes/theme/defaults/light-retro.json +98 -0
  710. package/src/modes/theme/defaults/light-sand.json +95 -0
  711. package/src/modes/theme/defaults/light-savanna.json +91 -0
  712. package/src/modes/theme/defaults/light-solarized.json +102 -0
  713. package/src/modes/theme/defaults/light-soleil.json +90 -0
  714. package/src/modes/theme/defaults/light-sunset.json +99 -0
  715. package/src/modes/theme/defaults/light-synthwave.json +98 -0
  716. package/src/modes/theme/defaults/light-tokyo-night.json +111 -0
  717. package/src/modes/theme/defaults/light-wetland.json +91 -0
  718. package/src/modes/theme/defaults/light-zenith.json +89 -0
  719. package/src/modes/theme/defaults/limestone.json +94 -0
  720. package/src/modes/theme/defaults/mahogany.json +97 -0
  721. package/src/modes/theme/defaults/marble.json +93 -0
  722. package/src/modes/theme/defaults/obsidian.json +91 -0
  723. package/src/modes/theme/defaults/onyx.json +91 -0
  724. package/src/modes/theme/defaults/pearl.json +93 -0
  725. package/src/modes/theme/defaults/porcelain.json +91 -0
  726. package/src/modes/theme/defaults/quartz.json +96 -0
  727. package/src/modes/theme/defaults/sandstone.json +95 -0
  728. package/src/modes/theme/defaults/titanium.json +90 -0
  729. package/src/modes/theme/light.json +93 -0
  730. package/src/modes/theme/mermaid-cache.ts +29 -0
  731. package/src/modes/theme/shimmer.ts +235 -0
  732. package/src/modes/theme/theme-schema.json +459 -0
  733. package/src/modes/theme/theme.ts +2676 -0
  734. package/src/modes/turn-budget.ts +31 -0
  735. package/src/modes/types.ts +359 -0
  736. package/src/modes/ultrathink.ts +41 -0
  737. package/src/modes/utils/context-usage.ts +339 -0
  738. package/src/modes/utils/copy-targets.ts +360 -0
  739. package/src/modes/utils/hotkeys-markdown.ts +61 -0
  740. package/src/modes/utils/keybinding-matchers.ts +51 -0
  741. package/src/modes/utils/tools-markdown.ts +27 -0
  742. package/src/modes/utils/ui-helpers.ts +801 -0
  743. package/src/modes/workflow.ts +42 -0
  744. package/src/plan-mode/approved-plan.ts +186 -0
  745. package/src/plan-mode/plan-handoff.ts +37 -0
  746. package/src/plan-mode/plan-protection.ts +31 -0
  747. package/src/plan-mode/state.ts +6 -0
  748. package/src/priority.json +41 -0
  749. package/src/prompts/agents/designer.md +66 -0
  750. package/src/prompts/agents/explore.md +58 -0
  751. package/src/prompts/agents/frontmatter.md +11 -0
  752. package/src/prompts/agents/init.md +33 -0
  753. package/src/prompts/agents/librarian.md +119 -0
  754. package/src/prompts/agents/oracle.md +55 -0
  755. package/src/prompts/agents/plan.md +48 -0
  756. package/src/prompts/agents/reviewer.md +140 -0
  757. package/src/prompts/agents/task.md +16 -0
  758. package/src/prompts/ci-green-request.md +36 -0
  759. package/src/prompts/dry-balance-bench.md +8 -0
  760. package/src/prompts/goals/goal-budget-limit.md +16 -0
  761. package/src/prompts/goals/goal-continuation.md +28 -0
  762. package/src/prompts/goals/goal-mode-active.md +23 -0
  763. package/src/prompts/memories/consolidation.md +30 -0
  764. package/src/prompts/memories/read-path.md +11 -0
  765. package/src/prompts/memories/stage_one_input.md +6 -0
  766. package/src/prompts/memories/stage_one_system.md +21 -0
  767. package/src/prompts/review-custom-request.md +22 -0
  768. package/src/prompts/review-headless-request.md +16 -0
  769. package/src/prompts/review-request.md +69 -0
  770. package/src/prompts/steering/user-interjection.md +10 -0
  771. package/src/prompts/system/agent-creation-architect.md +50 -0
  772. package/src/prompts/system/agent-creation-user.md +6 -0
  773. package/src/prompts/system/auto-continue.md +1 -0
  774. package/src/prompts/system/auto-thinking-difficulty-local.md +14 -0
  775. package/src/prompts/system/auto-thinking-difficulty.md +12 -0
  776. package/src/prompts/system/background-tan-dispatch.md +8 -0
  777. package/src/prompts/system/btw-user.md +8 -0
  778. package/src/prompts/system/commit-message-system.md +14 -0
  779. package/src/prompts/system/custom-system-prompt.md +64 -0
  780. package/src/prompts/system/eager-todo.md +13 -0
  781. package/src/prompts/system/empty-stop-retry.md +6 -0
  782. package/src/prompts/system/irc-incoming.md +7 -0
  783. package/src/prompts/system/manual-continue.md +7 -0
  784. package/src/prompts/system/memory-consolidation-system.md +8 -0
  785. package/src/prompts/system/memory-extraction-system.md +26 -0
  786. package/src/prompts/system/omfg-user.md +50 -0
  787. package/src/prompts/system/orchestrate-notice.md +40 -0
  788. package/src/prompts/system/plan-mode-active.md +109 -0
  789. package/src/prompts/system/plan-mode-approved.md +25 -0
  790. package/src/prompts/system/plan-mode-compact-instructions.md +16 -0
  791. package/src/prompts/system/plan-mode-reference.md +11 -0
  792. package/src/prompts/system/plan-mode-subagent.md +33 -0
  793. package/src/prompts/system/plan-mode-tool-decision-reminder.md +9 -0
  794. package/src/prompts/system/project-prompt.md +52 -0
  795. package/src/prompts/system/subagent-system-prompt.md +64 -0
  796. package/src/prompts/system/subagent-user-prompt.md +3 -0
  797. package/src/prompts/system/subagent-yield-reminder.md +12 -0
  798. package/src/prompts/system/system-prompt.md +258 -0
  799. package/src/prompts/system/tiny-title-system.md +8 -0
  800. package/src/prompts/system/title-system.md +16 -0
  801. package/src/prompts/system/ttsr-interrupt.md +7 -0
  802. package/src/prompts/system/ttsr-tool-reminder.md +5 -0
  803. package/src/prompts/system/ultrathink-notice.md +3 -0
  804. package/src/prompts/system/web-search.md +25 -0
  805. package/src/prompts/system/workflow-notice.md +70 -0
  806. package/src/prompts/tools/apply-patch.md +65 -0
  807. package/src/prompts/tools/ask.md +30 -0
  808. package/src/prompts/tools/ast-edit.md +39 -0
  809. package/src/prompts/tools/ast-grep.md +42 -0
  810. package/src/prompts/tools/async-result.md +8 -0
  811. package/src/prompts/tools/bash.md +46 -0
  812. package/src/prompts/tools/browser.md +73 -0
  813. package/src/prompts/tools/checkpoint.md +16 -0
  814. package/src/prompts/tools/debug.md +34 -0
  815. package/src/prompts/tools/eval.md +92 -0
  816. package/src/prompts/tools/find.md +36 -0
  817. package/src/prompts/tools/github.md +21 -0
  818. package/src/prompts/tools/goal.md +18 -0
  819. package/src/prompts/tools/image-gen.md +7 -0
  820. package/src/prompts/tools/inspect-image-system.md +20 -0
  821. package/src/prompts/tools/inspect-image.md +32 -0
  822. package/src/prompts/tools/irc.md +59 -0
  823. package/src/prompts/tools/job.md +19 -0
  824. package/src/prompts/tools/lsp-late-diagnostic.md +8 -0
  825. package/src/prompts/tools/lsp.md +42 -0
  826. package/src/prompts/tools/memory-edit.md +8 -0
  827. package/src/prompts/tools/patch.md +70 -0
  828. package/src/prompts/tools/read.md +84 -0
  829. package/src/prompts/tools/recall.md +5 -0
  830. package/src/prompts/tools/reflect.md +5 -0
  831. package/src/prompts/tools/render-mermaid.md +9 -0
  832. package/src/prompts/tools/replace.md +30 -0
  833. package/src/prompts/tools/resolve.md +9 -0
  834. package/src/prompts/tools/retain.md +6 -0
  835. package/src/prompts/tools/rewind.md +13 -0
  836. package/src/prompts/tools/search-tool-bm25.md +32 -0
  837. package/src/prompts/tools/search.md +24 -0
  838. package/src/prompts/tools/ssh.md +31 -0
  839. package/src/prompts/tools/task-summary.md +17 -0
  840. package/src/prompts/tools/task.md +88 -0
  841. package/src/prompts/tools/todo.md +62 -0
  842. package/src/prompts/tools/web-search.md +10 -0
  843. package/src/prompts/tools/write.md +14 -0
  844. package/src/registry/agent-lifecycle.ts +218 -0
  845. package/src/registry/agent-registry.ts +151 -0
  846. package/src/sdk.ts +2558 -0
  847. package/src/secrets/index.ts +123 -0
  848. package/src/secrets/obfuscator.ts +298 -0
  849. package/src/secrets/regex.ts +21 -0
  850. package/src/session/agent-session.ts +10121 -0
  851. package/src/session/agent-storage.ts +455 -0
  852. package/src/session/artifacts.ts +135 -0
  853. package/src/session/auth-broker-config.ts +131 -0
  854. package/src/session/auth-storage.ts +29 -0
  855. package/src/session/blob-store.ts +255 -0
  856. package/src/session/client-bridge.ts +85 -0
  857. package/src/session/history-storage.ts +348 -0
  858. package/src/session/indexed-session-storage.ts +430 -0
  859. package/src/session/messages.ts +541 -0
  860. package/src/session/redis-session-storage.ts +170 -0
  861. package/src/session/session-dump-format.ts +209 -0
  862. package/src/session/session-history-format.ts +246 -0
  863. package/src/session/session-manager.ts +3676 -0
  864. package/src/session/session-storage.ts +529 -0
  865. package/src/session/shake-types.ts +43 -0
  866. package/src/session/sql-session-storage.ts +314 -0
  867. package/src/session/streaming-output.ts +1330 -0
  868. package/src/session/tool-choice-queue.ts +213 -0
  869. package/src/session/yield-queue.ts +173 -0
  870. package/src/slash-commands/acp-builtins.ts +70 -0
  871. package/src/slash-commands/builtin-registry.ts +1798 -0
  872. package/src/slash-commands/helpers/context-report.ts +39 -0
  873. package/src/slash-commands/helpers/format.ts +46 -0
  874. package/src/slash-commands/helpers/marketplace-manager.ts +25 -0
  875. package/src/slash-commands/helpers/mcp.ts +532 -0
  876. package/src/slash-commands/helpers/parse.ts +85 -0
  877. package/src/slash-commands/helpers/ssh.ts +195 -0
  878. package/src/slash-commands/helpers/stats-dashboard.ts +85 -0
  879. package/src/slash-commands/helpers/todo.ts +279 -0
  880. package/src/slash-commands/helpers/usage-report.ts +95 -0
  881. package/src/slash-commands/marketplace-install-parser.ts +99 -0
  882. package/src/slash-commands/types.ts +135 -0
  883. package/src/ssh/config-writer.ts +183 -0
  884. package/src/ssh/connection-manager.ts +509 -0
  885. package/src/ssh/ssh-executor.ts +189 -0
  886. package/src/ssh/sshfs-mount.ts +140 -0
  887. package/src/ssh/utils.ts +8 -0
  888. package/src/stt/downloader.ts +71 -0
  889. package/src/stt/index.ts +3 -0
  890. package/src/stt/recorder.ts +351 -0
  891. package/src/stt/setup.ts +52 -0
  892. package/src/stt/stt-controller.ts +160 -0
  893. package/src/stt/transcribe.py +70 -0
  894. package/src/stt/transcriber.ts +91 -0
  895. package/src/stubs/natives/index.ts +814 -0
  896. package/src/stubs/natives/package.json +7 -0
  897. package/src/stubs/tui/index.ts +282 -0
  898. package/src/stubs/tui/package.json +7 -0
  899. package/src/system-prompt.ts +611 -0
  900. package/src/task/agents.ts +167 -0
  901. package/src/task/commands.ts +132 -0
  902. package/src/task/discovery.ts +122 -0
  903. package/src/task/executor.ts +2133 -0
  904. package/src/task/index.ts +1419 -0
  905. package/src/task/name-generator.ts +1577 -0
  906. package/src/task/omp-command.ts +26 -0
  907. package/src/task/output-manager.ts +88 -0
  908. package/src/task/parallel.ts +116 -0
  909. package/src/task/render.ts +1381 -0
  910. package/src/task/repair-args.ts +129 -0
  911. package/src/task/subprocess-tool-registry.ts +88 -0
  912. package/src/task/types.ts +336 -0
  913. package/src/task/worktree.ts +514 -0
  914. package/src/telemetry-export.ts +144 -0
  915. package/src/thinking.ts +167 -0
  916. package/src/tiny/compiled-runtime.ts +179 -0
  917. package/src/tiny/device.ts +111 -0
  918. package/src/tiny/dtype.ts +101 -0
  919. package/src/tiny/models.ts +242 -0
  920. package/src/tiny/text.ts +165 -0
  921. package/src/tiny/title-client.ts +543 -0
  922. package/src/tiny/title-protocol.ts +56 -0
  923. package/src/tiny/worker.ts +568 -0
  924. package/src/tool-discovery/mode.ts +24 -0
  925. package/src/tool-discovery/tool-index.ts +256 -0
  926. package/src/tools/approval.ts +189 -0
  927. package/src/tools/archive-reader.ts +721 -0
  928. package/src/tools/ask.ts +928 -0
  929. package/src/tools/ast-edit.ts +642 -0
  930. package/src/tools/ast-grep.ts +452 -0
  931. package/src/tools/auto-generated-guard.ts +322 -0
  932. package/src/tools/bash-command-fixup.ts +37 -0
  933. package/src/tools/bash-interactive.ts +408 -0
  934. package/src/tools/bash-interceptor.ts +67 -0
  935. package/src/tools/bash-pty-selection.ts +14 -0
  936. package/src/tools/bash-skill-urls.ts +248 -0
  937. package/src/tools/bash.ts +1386 -0
  938. package/src/tools/browser/attach.ts +175 -0
  939. package/src/tools/browser/launch.ts +660 -0
  940. package/src/tools/browser/readable.ts +112 -0
  941. package/src/tools/browser/registry.ts +197 -0
  942. package/src/tools/browser/render.ts +216 -0
  943. package/src/tools/browser/tab-protocol.ts +105 -0
  944. package/src/tools/browser/tab-supervisor.ts +628 -0
  945. package/src/tools/browser/tab-worker-entry.ts +21 -0
  946. package/src/tools/browser/tab-worker.ts +1226 -0
  947. package/src/tools/browser.ts +343 -0
  948. package/src/tools/checkpoint.ts +136 -0
  949. package/src/tools/conflict-detect.ts +718 -0
  950. package/src/tools/context.ts +39 -0
  951. package/src/tools/debug.ts +1067 -0
  952. package/src/tools/eval-backends.ts +27 -0
  953. package/src/tools/eval-render.ts +752 -0
  954. package/src/tools/eval.ts +577 -0
  955. package/src/tools/fetch.ts +1926 -0
  956. package/src/tools/file-recorder.ts +35 -0
  957. package/src/tools/find.ts +609 -0
  958. package/src/tools/fs-cache-invalidation.ts +28 -0
  959. package/src/tools/gh-cache-invalidation.ts +255 -0
  960. package/src/tools/gh-format.ts +12 -0
  961. package/src/tools/gh-renderer.ts +481 -0
  962. package/src/tools/gh.ts +3720 -0
  963. package/src/tools/github-cache.ts +637 -0
  964. package/src/tools/grouped-file-output.ts +210 -0
  965. package/src/tools/image-gen.ts +1517 -0
  966. package/src/tools/index.ts +599 -0
  967. package/src/tools/inspect-image-renderer.ts +132 -0
  968. package/src/tools/inspect-image.ts +174 -0
  969. package/src/tools/irc.ts +723 -0
  970. package/src/tools/job.ts +557 -0
  971. package/src/tools/json-tree.ts +243 -0
  972. package/src/tools/jtd-to-json-schema.ts +219 -0
  973. package/src/tools/jtd-to-typescript.ts +136 -0
  974. package/src/tools/jtd-utils.ts +102 -0
  975. package/src/tools/list-limit.ts +40 -0
  976. package/src/tools/match-line-format.ts +20 -0
  977. package/src/tools/memory-edit.ts +59 -0
  978. package/src/tools/memory-recall.ts +100 -0
  979. package/src/tools/memory-reflect.ts +88 -0
  980. package/src/tools/memory-render.ts +202 -0
  981. package/src/tools/memory-retain.ts +91 -0
  982. package/src/tools/output-meta.ts +754 -0
  983. package/src/tools/output-schema-validator.ts +132 -0
  984. package/src/tools/path-utils.ts +1054 -0
  985. package/src/tools/plan-mode-guard.ts +108 -0
  986. package/src/tools/puppeteer/00_stealth_tampering.txt +63 -0
  987. package/src/tools/puppeteer/01_stealth_activity.txt +20 -0
  988. package/src/tools/puppeteer/02_stealth_hairline.txt +11 -0
  989. package/src/tools/puppeteer/03_stealth_botd.txt +384 -0
  990. package/src/tools/puppeteer/04_stealth_iframe.txt +81 -0
  991. package/src/tools/puppeteer/05_stealth_webgl.txt +75 -0
  992. package/src/tools/puppeteer/06_stealth_screen.txt +72 -0
  993. package/src/tools/puppeteer/07_stealth_fonts.txt +97 -0
  994. package/src/tools/puppeteer/08_stealth_audio.txt +51 -0
  995. package/src/tools/puppeteer/09_stealth_locale.txt +46 -0
  996. package/src/tools/puppeteer/10_stealth_plugins.txt +206 -0
  997. package/src/tools/puppeteer/11_stealth_hardware.txt +8 -0
  998. package/src/tools/puppeteer/12_stealth_codecs.txt +40 -0
  999. package/src/tools/puppeteer/13_stealth_worker.txt +74 -0
  1000. package/src/tools/read.ts +2929 -0
  1001. package/src/tools/render-mermaid.ts +69 -0
  1002. package/src/tools/render-utils.ts +838 -0
  1003. package/src/tools/renderers.ts +77 -0
  1004. package/src/tools/report-tool-issue.ts +534 -0
  1005. package/src/tools/resolve.ts +276 -0
  1006. package/src/tools/review.ts +253 -0
  1007. package/src/tools/search-tool-bm25.ts +351 -0
  1008. package/src/tools/search.ts +1580 -0
  1009. package/src/tools/sqlite-reader.ts +828 -0
  1010. package/src/tools/ssh.ts +349 -0
  1011. package/src/tools/todo.ts +982 -0
  1012. package/src/tools/tool-errors.ts +62 -0
  1013. package/src/tools/tool-result.ts +94 -0
  1014. package/src/tools/tool-timeouts.ts +30 -0
  1015. package/src/tools/tts.ts +133 -0
  1016. package/src/tools/write.ts +1217 -0
  1017. package/src/tools/yield.ts +269 -0
  1018. package/src/tui/code-cell.ts +216 -0
  1019. package/src/tui/file-list.ts +55 -0
  1020. package/src/tui/hyperlink.ts +175 -0
  1021. package/src/tui/index.ts +12 -0
  1022. package/src/tui/output-block.ts +240 -0
  1023. package/src/tui/status-line.ts +54 -0
  1024. package/src/tui/tree-list.ts +84 -0
  1025. package/src/tui/types.ts +15 -0
  1026. package/src/tui/utils.ts +103 -0
  1027. package/src/utils/block-context.ts +312 -0
  1028. package/src/utils/changelog.ts +132 -0
  1029. package/src/utils/clipboard.ts +193 -0
  1030. package/src/utils/command-args.ts +76 -0
  1031. package/src/utils/commit-message-generator.ts +151 -0
  1032. package/src/utils/edit-mode.ts +41 -0
  1033. package/src/utils/enhanced-paste.ts +230 -0
  1034. package/src/utils/event-bus.ts +33 -0
  1035. package/src/utils/external-editor.ts +65 -0
  1036. package/src/utils/file-display-mode.ts +45 -0
  1037. package/src/utils/file-mentions.ts +281 -0
  1038. package/src/utils/git.ts +1833 -0
  1039. package/src/utils/image-loading.ts +132 -0
  1040. package/src/utils/image-resize.ts +309 -0
  1041. package/src/utils/jj.ts +248 -0
  1042. package/src/utils/lang-from-path.ts +239 -0
  1043. package/src/utils/markit.ts +89 -0
  1044. package/src/utils/open.ts +55 -0
  1045. package/src/utils/session-color.ts +68 -0
  1046. package/src/utils/shell-snapshot.ts +187 -0
  1047. package/src/utils/sixel.ts +69 -0
  1048. package/src/utils/title-generator.ts +373 -0
  1049. package/src/utils/tool-choice.ts +33 -0
  1050. package/src/utils/tools-manager.ts +363 -0
  1051. package/src/web/kagi.ts +305 -0
  1052. package/src/web/parallel.ts +353 -0
  1053. package/src/web/scrapers/artifacthub.ts +207 -0
  1054. package/src/web/scrapers/arxiv.ts +83 -0
  1055. package/src/web/scrapers/aur.ts +162 -0
  1056. package/src/web/scrapers/biorxiv.ts +133 -0
  1057. package/src/web/scrapers/bluesky.ts +262 -0
  1058. package/src/web/scrapers/brew.ts +172 -0
  1059. package/src/web/scrapers/cheatsh.ts +68 -0
  1060. package/src/web/scrapers/chocolatey.ts +196 -0
  1061. package/src/web/scrapers/choosealicense.ts +95 -0
  1062. package/src/web/scrapers/cisa-kev.ts +87 -0
  1063. package/src/web/scrapers/clojars.ts +154 -0
  1064. package/src/web/scrapers/coingecko.ts +177 -0
  1065. package/src/web/scrapers/crates-io.ts +97 -0
  1066. package/src/web/scrapers/crossref.ts +136 -0
  1067. package/src/web/scrapers/devto.ts +147 -0
  1068. package/src/web/scrapers/discogs.ts +306 -0
  1069. package/src/web/scrapers/discourse.ts +197 -0
  1070. package/src/web/scrapers/dockerhub.ts +138 -0
  1071. package/src/web/scrapers/docs-rs.ts +653 -0
  1072. package/src/web/scrapers/fdroid.ts +134 -0
  1073. package/src/web/scrapers/firefox-addons.ts +191 -0
  1074. package/src/web/scrapers/flathub.ts +223 -0
  1075. package/src/web/scrapers/github-gist.ts +58 -0
  1076. package/src/web/scrapers/github.ts +704 -0
  1077. package/src/web/scrapers/gitlab.ts +401 -0
  1078. package/src/web/scrapers/go-pkg.ts +266 -0
  1079. package/src/web/scrapers/hackage.ts +140 -0
  1080. package/src/web/scrapers/hackernews.ts +189 -0
  1081. package/src/web/scrapers/hex.ts +105 -0
  1082. package/src/web/scrapers/huggingface.ts +321 -0
  1083. package/src/web/scrapers/iacr.ts +89 -0
  1084. package/src/web/scrapers/index.ts +252 -0
  1085. package/src/web/scrapers/jetbrains-marketplace.ts +159 -0
  1086. package/src/web/scrapers/lemmy.ts +203 -0
  1087. package/src/web/scrapers/lobsters.ts +175 -0
  1088. package/src/web/scrapers/mastodon.ts +292 -0
  1089. package/src/web/scrapers/maven.ts +138 -0
  1090. package/src/web/scrapers/mdn.ts +173 -0
  1091. package/src/web/scrapers/metacpan.ts +222 -0
  1092. package/src/web/scrapers/musicbrainz.ts +250 -0
  1093. package/src/web/scrapers/npm.ts +98 -0
  1094. package/src/web/scrapers/nuget.ts +183 -0
  1095. package/src/web/scrapers/nvd.ts +222 -0
  1096. package/src/web/scrapers/ollama.ts +239 -0
  1097. package/src/web/scrapers/open-vsx.ts +106 -0
  1098. package/src/web/scrapers/opencorporates.ts +292 -0
  1099. package/src/web/scrapers/openlibrary.ts +336 -0
  1100. package/src/web/scrapers/orcid.ts +286 -0
  1101. package/src/web/scrapers/osv.ts +176 -0
  1102. package/src/web/scrapers/packagist.ts +160 -0
  1103. package/src/web/scrapers/pub-dev.ts +143 -0
  1104. package/src/web/scrapers/pubmed.ts +211 -0
  1105. package/src/web/scrapers/pypi.ts +112 -0
  1106. package/src/web/scrapers/rawg.ts +110 -0
  1107. package/src/web/scrapers/readthedocs.ts +120 -0
  1108. package/src/web/scrapers/reddit.ts +95 -0
  1109. package/src/web/scrapers/repology.ts +251 -0
  1110. package/src/web/scrapers/rfc.ts +201 -0
  1111. package/src/web/scrapers/rubygems.ts +103 -0
  1112. package/src/web/scrapers/searchcode.ts +189 -0
  1113. package/src/web/scrapers/sec-edgar.ts +261 -0
  1114. package/src/web/scrapers/semantic-scholar.ts +171 -0
  1115. package/src/web/scrapers/snapcraft.ts +187 -0
  1116. package/src/web/scrapers/sourcegraph.ts +336 -0
  1117. package/src/web/scrapers/spdx.ts +108 -0
  1118. package/src/web/scrapers/spotify.ts +198 -0
  1119. package/src/web/scrapers/stackoverflow.ts +120 -0
  1120. package/src/web/scrapers/terraform.ts +277 -0
  1121. package/src/web/scrapers/tldr.ts +47 -0
  1122. package/src/web/scrapers/twitter.ts +94 -0
  1123. package/src/web/scrapers/types.ts +397 -0
  1124. package/src/web/scrapers/utils.ts +109 -0
  1125. package/src/web/scrapers/vimeo.ts +133 -0
  1126. package/src/web/scrapers/vscode-marketplace.ts +187 -0
  1127. package/src/web/scrapers/w3c.ts +156 -0
  1128. package/src/web/scrapers/wikidata.ts +344 -0
  1129. package/src/web/scrapers/wikipedia.ts +84 -0
  1130. package/src/web/scrapers/youtube.ts +325 -0
  1131. package/src/web/search/index.ts +292 -0
  1132. package/src/web/search/provider.ts +157 -0
  1133. package/src/web/search/providers/anthropic.ts +318 -0
  1134. package/src/web/search/providers/base.ts +89 -0
  1135. package/src/web/search/providers/brave.ts +152 -0
  1136. package/src/web/search/providers/codex.ts +591 -0
  1137. package/src/web/search/providers/exa.ts +400 -0
  1138. package/src/web/search/providers/gemini.ts +460 -0
  1139. package/src/web/search/providers/jina.ts +111 -0
  1140. package/src/web/search/providers/kagi.ts +86 -0
  1141. package/src/web/search/providers/kimi.ts +196 -0
  1142. package/src/web/search/providers/parallel.ts +225 -0
  1143. package/src/web/search/providers/perplexity.ts +730 -0
  1144. package/src/web/search/providers/searxng.ts +313 -0
  1145. package/src/web/search/providers/synthetic.ts +114 -0
  1146. package/src/web/search/providers/tavily.ts +176 -0
  1147. package/src/web/search/providers/utils.ts +128 -0
  1148. package/src/web/search/providers/zai.ts +333 -0
  1149. package/src/web/search/render.ts +262 -0
  1150. package/src/web/search/types.ts +482 -0
  1151. package/src/web/search/utils.ts +17 -0
  1152. package/src/workspace-tree.ts +286 -0
@@ -0,0 +1,3676 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import type { AgentMessage } from "@oh-my-pi/pi-agent-core";
5
+ import type {
6
+ ImageContent,
7
+ Message,
8
+ MessageAttribution,
9
+ ProviderPayload,
10
+ ServiceTier,
11
+ TextContent,
12
+ Usage,
13
+ } from "@oh-my-pi/pi-ai";
14
+ import { getTerminalId } from './stubs/tui/index.ts';
15
+ import {
16
+ getBlobsDir,
17
+ getAgentDir as getDefaultAgentDir,
18
+ getProjectDir,
19
+ getSessionsDir,
20
+ getTerminalSessionsDir,
21
+ hasFsCode,
22
+ isEnoent,
23
+ logger,
24
+ parseJsonlLenient,
25
+ pathIsWithin,
26
+ resolveEquivalentPath,
27
+ Snowflake,
28
+ toError,
29
+ } from "@oh-my-pi/pi-utils";
30
+ import { getPreservedSnapcompactArchive, snapcompactImages } from "@oh-my-pi/snapcompact";
31
+ import { ArtifactManager } from "./artifacts";
32
+ import {
33
+ type BlobPutOptions,
34
+ type BlobPutResult,
35
+ BlobStore,
36
+ externalizeImageData,
37
+ externalizeImageDataSync,
38
+ externalizeImageDataUrl,
39
+ externalizeImageDataUrlSync,
40
+ isBlobRef,
41
+ isImageDataUrl,
42
+ resolveImageData,
43
+ resolveImageDataUrl,
44
+ } from "./blob-store";
45
+ import {
46
+ type BashExecutionMessage,
47
+ type CustomMessage,
48
+ createBranchSummaryMessage,
49
+ createCompactionSummaryMessage,
50
+ createCustomMessage,
51
+ type FileMentionMessage,
52
+ type HookMessage,
53
+ type PythonExecutionMessage,
54
+ sanitizeRehydratedOpenAIResponsesAssistantMessage,
55
+ stripInternalDetailsFields,
56
+ } from "./messages";
57
+ import type { SessionStorage, SessionStorageWriter } from "./session-storage";
58
+ import { FileSessionStorage, MemorySessionStorage } from "./session-storage";
59
+
60
+ export const CURRENT_SESSION_VERSION = 3;
61
+
62
+ export interface SessionHeader {
63
+ type: "session";
64
+ version?: number; // v1 sessions don't have this
65
+ id: string;
66
+ title?: string; // Auto-generated title from first message
67
+ titleSource?: "auto" | "user";
68
+ timestamp: string;
69
+ cwd: string;
70
+ parentSession?: string;
71
+ }
72
+
73
+ export interface NewSessionOptions {
74
+ parentSession?: string;
75
+ /** Skip flushing the current session and delete it instead of saving. */
76
+ drop?: boolean;
77
+ }
78
+
79
+ export interface SessionEntryBase {
80
+ type: string;
81
+ id: string;
82
+ parentId: string | null;
83
+ timestamp: string;
84
+ }
85
+
86
+ export interface SessionMessageEntry extends SessionEntryBase {
87
+ type: "message";
88
+ message: AgentMessage;
89
+ }
90
+
91
+ export interface ThinkingLevelChangeEntry extends SessionEntryBase {
92
+ type: "thinking_level_change";
93
+ thinkingLevel?: string | null;
94
+ }
95
+
96
+ export interface ModelChangeEntry extends SessionEntryBase {
97
+ type: "model_change";
98
+ /** Model in "provider/modelId" format */
99
+ model: string;
100
+ /** Role: "default", "smol", "slow", etc. Undefined treated as "default" */
101
+ role?: string;
102
+ }
103
+
104
+ export interface ServiceTierChangeEntry extends SessionEntryBase {
105
+ type: "service_tier_change";
106
+ serviceTier: ServiceTier | null;
107
+ }
108
+
109
+ export interface CompactionEntry<T = unknown> extends SessionEntryBase {
110
+ type: "compaction";
111
+ summary: string;
112
+ shortSummary?: string;
113
+ firstKeptEntryId: string;
114
+ tokensBefore: number;
115
+ /** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */
116
+ details?: T;
117
+ /** Hook-provided data to persist across compaction */
118
+ preserveData?: Record<string, unknown>;
119
+ /** True if generated by an extension, undefined/false if pi-generated (backward compatible) */
120
+ fromExtension?: boolean;
121
+ }
122
+
123
+ export interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {
124
+ type: "branch_summary";
125
+ fromId: string;
126
+ summary: string;
127
+ /** Extension-specific data (not sent to LLM) */
128
+ details?: T;
129
+ /** True if generated by an extension, false if pi-generated */
130
+ fromExtension?: boolean;
131
+ }
132
+
133
+ /**
134
+ * Custom entry for extensions to store extension-specific data in the session.
135
+ * Use customType to identify your extension's entries.
136
+ *
137
+ * Purpose: Persist extension state across session reloads. On reload, extensions can
138
+ * scan entries for their customType and reconstruct internal state.
139
+ *
140
+ * Does NOT participate in LLM context (ignored by buildSessionContext).
141
+ * For injecting content into context, see CustomMessageEntry.
142
+ */
143
+ export interface CustomEntry<T = unknown> extends SessionEntryBase {
144
+ type: "custom";
145
+ customType: string;
146
+ data?: T;
147
+ }
148
+
149
+ /** Label entry for user-defined bookmarks/markers on entries. */
150
+ export interface LabelEntry extends SessionEntryBase {
151
+ type: "label";
152
+ targetId: string;
153
+ label: string | undefined;
154
+ }
155
+
156
+ /** TTSR injection entry - tracks which time-traveling rules have been injected this session. */
157
+ export interface TtsrInjectionEntry extends SessionEntryBase {
158
+ type: "ttsr_injection";
159
+ /** Names of rules that were injected */
160
+ injectedRules: string[];
161
+ }
162
+
163
+ /** Persisted MCP discovery selection state for a session branch. */
164
+ export interface MCPToolSelectionEntry extends SessionEntryBase {
165
+ type: "mcp_tool_selection";
166
+ /** MCP tool names selected for visibility in discovery mode. */
167
+ selectedToolNames: string[];
168
+ }
169
+
170
+ /** Session init entry - captures initial context for subagent sessions (debugging/replay). */
171
+ export interface SessionInitEntry extends SessionEntryBase {
172
+ type: "session_init";
173
+ /** Full system prompt sent to the model */
174
+ systemPrompt: string;
175
+ /** Initial task/user message */
176
+ task: string;
177
+ /** Tools available to the agent */
178
+ tools: string[];
179
+ /** Output schema if structured output was requested */
180
+ outputSchema?: unknown;
181
+ }
182
+
183
+ /** Mode change entry - tracks agent mode transitions (e.g. plan mode). */
184
+ export interface ModeChangeEntry extends SessionEntryBase {
185
+ type: "mode_change";
186
+ /** Current mode name, or "none" when exiting a mode */
187
+ mode: string;
188
+ /** Optional mode-specific data (e.g. plan file path) */
189
+ data?: Record<string, unknown>;
190
+ }
191
+
192
+ /**
193
+ * Custom message entry for extensions to inject messages into LLM context.
194
+ * Use customType to identify your extension's entries.
195
+ *
196
+ * Unlike CustomEntry, this DOES participate in LLM context.
197
+ * The content participates in LLM context through convertToLlm().
198
+ * Use details for extension-specific metadata (not sent to LLM).
199
+ *
200
+ * display controls TUI rendering:
201
+ * - false: hidden entirely
202
+ * - true: rendered with distinct styling (different from user messages)
203
+ */
204
+ export interface CustomMessageEntry<T = unknown> extends SessionEntryBase {
205
+ type: "custom_message";
206
+ customType: string;
207
+ content: string | (TextContent | ImageContent)[];
208
+ details?: T;
209
+ display: boolean;
210
+ /** Who initiated this message for billing/attribution semantics. */
211
+ attribution?: MessageAttribution;
212
+ }
213
+
214
+ /** Session entry - has id/parentId for tree structure (returned by "read" methods in SessionManager) */
215
+ export type SessionEntry =
216
+ | SessionMessageEntry
217
+ | ThinkingLevelChangeEntry
218
+ | ModelChangeEntry
219
+ | ServiceTierChangeEntry
220
+ | CompactionEntry
221
+ | BranchSummaryEntry
222
+ | CustomEntry
223
+ | CustomMessageEntry
224
+ | LabelEntry
225
+ | TtsrInjectionEntry
226
+ | MCPToolSelectionEntry
227
+ | SessionInitEntry
228
+ | ModeChangeEntry;
229
+
230
+ /** Raw file entry (includes header) */
231
+ export type FileEntry = SessionHeader | SessionEntry;
232
+
233
+ /** Tree node for getTree() - defensive copy of session structure */
234
+ export interface SessionTreeNode {
235
+ entry: SessionEntry;
236
+ children: SessionTreeNode[];
237
+ /** Resolved label for this entry, if any */
238
+ label?: string;
239
+ }
240
+
241
+ export interface SessionContext {
242
+ messages: AgentMessage[];
243
+ thinkingLevel?: string;
244
+ serviceTier?: ServiceTier;
245
+ /** Model roles: { default: "provider/modelId", small: "provider/modelId", ... } */
246
+ models: Record<string, string>;
247
+ /** Names of TTSR rules that have been injected this session */
248
+ injectedTtsrRules: string[];
249
+ /** MCP tool names selected through discovery for this session branch. */
250
+ selectedMCPToolNames: string[];
251
+ /** Whether this branch contains an explicit persisted MCP selection entry. */
252
+ hasPersistedMCPToolSelection: boolean;
253
+ /** Active mode (e.g. "plan") or "none" if no special mode is active */
254
+ mode: string;
255
+ /** Mode-specific data from the last mode_change entry */
256
+ modeData?: Record<string, unknown>;
257
+ }
258
+
259
+ export const EPHEMERAL_MODEL_CHANGE_ROLE = "fallback";
260
+
261
+ /** Lists session model strings to try when restoring, in fallback order. */
262
+ export function getRestorableSessionModels(
263
+ models: Readonly<Record<string, string>>,
264
+ lastModelChangeRole: string | undefined,
265
+ ): string[] {
266
+ const defaultModel = models.default;
267
+ if (
268
+ !lastModelChangeRole ||
269
+ lastModelChangeRole === "default" ||
270
+ lastModelChangeRole === EPHEMERAL_MODEL_CHANGE_ROLE
271
+ ) {
272
+ return defaultModel ? [defaultModel] : [];
273
+ }
274
+
275
+ const roleModel = models[lastModelChangeRole];
276
+ if (!roleModel) return defaultModel ? [defaultModel] : [];
277
+ if (!defaultModel || roleModel === defaultModel) return [roleModel];
278
+ return [roleModel, defaultModel];
279
+ }
280
+
281
+ /**
282
+ * Coarse lifecycle status of a session, derived from its last persisted message.
283
+ *
284
+ * - `complete` — the last assistant turn ended with no unanswered tool calls, i.e.
285
+ * the agent yielded control back to the user.
286
+ * - `interrupted` — work was cut off mid-flight: a trailing assistant turn with
287
+ * pending tool calls, a trailing tool result the agent never continued from, or
288
+ * a length-truncated turn.
289
+ * - `aborted` — the last assistant turn was cancelled by the user.
290
+ * - `error` — the last assistant turn ended in an error.
291
+ * - `pending` — a trailing user message with no assistant reply persisted after it.
292
+ * - `unknown` — status could not be determined (empty/header-only session, or the
293
+ * final message was larger than the tail window that was read).
294
+ */
295
+ export type SessionStatus = "complete" | "interrupted" | "aborted" | "error" | "pending" | "unknown";
296
+
297
+ export interface SessionInfo {
298
+ path: string;
299
+ id: string;
300
+ /** Working directory where the session was started. Empty string for old sessions. */
301
+ cwd: string;
302
+ title?: string;
303
+ /** Path to the parent session (if this session was forked). */
304
+ parentSessionPath?: string;
305
+ created: Date;
306
+ modified: Date;
307
+ messageCount: number;
308
+ /** File size in bytes on disk; used for compact list rendering. */
309
+ size: number;
310
+ firstMessage: string;
311
+ allMessagesText: string;
312
+ /**
313
+ * Coarse lifecycle status from the session's last persisted message. Optional:
314
+ * synthesized {@link SessionInfo}s (cross-project stubs, tests) leave it unset.
315
+ */
316
+ status?: SessionStatus;
317
+ }
318
+
319
+ export type ReadonlySessionManager = Pick<
320
+ SessionManager,
321
+ | "getCwd"
322
+ | "getSessionDir"
323
+ | "getSessionId"
324
+ | "getSessionFile"
325
+ | "getSessionName"
326
+ | "getArtifactsDir"
327
+ | "getArtifactManager"
328
+ | "allocateArtifactPath"
329
+ | "saveArtifact"
330
+ | "getArtifactPath"
331
+ | "getLeafId"
332
+ | "getLeafEntry"
333
+ | "getEntry"
334
+ | "getLabel"
335
+ | "getBranch"
336
+ | "getHeader"
337
+ | "getEntries"
338
+ | "getTree"
339
+ | "getUsageStatistics"
340
+ | "putBlob"
341
+ | "putBlobSync"
342
+ >;
343
+
344
+ function createSessionId(): string {
345
+ return Bun.randomUUIDv7();
346
+ }
347
+
348
+ /** Generate a unique short ID (8 hex chars, collision-checked) */
349
+ function generateId(byId: { has(id: string): boolean }): string {
350
+ for (let i = 0; i < 100; i++) {
351
+ const id = crypto.randomUUID().slice(-8);
352
+ if (!byId.has(id)) return id;
353
+ }
354
+ return Snowflake.next(); // fallback to full snowflake id
355
+ }
356
+
357
+ /** Migrate v1 → v2: add id/parentId tree structure. Mutates in place. */
358
+ function migrateV1ToV2(entries: FileEntry[]): void {
359
+ const ids = new Set<string>();
360
+ let prevId: string | null = null;
361
+
362
+ for (const entry of entries) {
363
+ if (entry.type === "session") {
364
+ entry.version = 2;
365
+ continue;
366
+ }
367
+
368
+ entry.id = generateId(ids);
369
+ entry.parentId = prevId;
370
+ prevId = entry.id;
371
+
372
+ // Convert firstKeptEntryIndex to firstKeptEntryId for compaction
373
+ if (entry.type === "compaction") {
374
+ const comp = entry as CompactionEntry & { firstKeptEntryIndex?: number };
375
+ if (typeof comp.firstKeptEntryIndex === "number") {
376
+ const targetEntry = entries[comp.firstKeptEntryIndex];
377
+ if (targetEntry && targetEntry.type !== "session") {
378
+ comp.firstKeptEntryId = targetEntry.id;
379
+ }
380
+ delete comp.firstKeptEntryIndex;
381
+ }
382
+ }
383
+ }
384
+ }
385
+
386
+ /** Migrate v2 → v3: rename hookMessage role to custom. Mutates in place. */
387
+ function migrateV2ToV3(entries: FileEntry[]): void {
388
+ for (const entry of entries) {
389
+ if (entry.type === "session") {
390
+ entry.version = 3;
391
+ continue;
392
+ }
393
+
394
+ if (entry.type === "message") {
395
+ const msg = entry.message as { role?: string };
396
+ if (msg.role === "hookMessage") {
397
+ (entry.message as { role: string }).role = "custom";
398
+ }
399
+ }
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Run all necessary migrations to bring entries to current version.
405
+ * Mutates entries in place. Returns true if any migration was applied.
406
+ */
407
+ function migrateToCurrentVersion(entries: FileEntry[]): boolean {
408
+ const header = entries.find(e => e.type === "session") as SessionHeader | undefined;
409
+ const version = header?.version ?? 1;
410
+
411
+ if (version >= CURRENT_SESSION_VERSION) return false;
412
+
413
+ if (version < 2) migrateV1ToV2(entries);
414
+ if (version < 3) migrateV2ToV3(entries);
415
+
416
+ return true;
417
+ }
418
+
419
+ /** Exported for testing */
420
+ export function migrateSessionEntries(entries: FileEntry[]): void {
421
+ migrateToCurrentVersion(entries);
422
+ }
423
+
424
+ const migratedSessionRoots = new Set<string>();
425
+
426
+ /**
427
+ * Merge or rename a legacy session directory into its canonical target.
428
+ * Best effort: callers decide whether migration failures should surface.
429
+ */
430
+ function migrateSessionDirPath(oldPath: string, newPath: string): void {
431
+ const existing = fs.statSync(newPath, { throwIfNoEntry: false });
432
+ if (existing?.isDirectory()) {
433
+ for (const file of fs.readdirSync(oldPath)) {
434
+ const src = path.join(oldPath, file);
435
+ const dst = path.join(newPath, file);
436
+ if (!fs.existsSync(dst)) {
437
+ fs.renameSync(src, dst);
438
+ }
439
+ }
440
+ fs.rmSync(oldPath, { recursive: true, force: true });
441
+ return;
442
+ }
443
+ if (existing) {
444
+ fs.rmSync(newPath, { recursive: true, force: true });
445
+ }
446
+ fs.renameSync(oldPath, newPath);
447
+ }
448
+
449
+ function encodeLegacyAbsoluteSessionDirName(cwd: string): string {
450
+ const resolvedCwd = path.resolve(cwd);
451
+ return `--${resolvedCwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
452
+ }
453
+
454
+ function encodeRelativeSessionDirName(prefix: string, root: string, cwd: string): string {
455
+ const relative = path.relative(root, cwd).replace(/[/\\:]/g, "-");
456
+ return relative ? (prefix.endsWith("-") ? `${prefix}${relative}` : `${prefix}-${relative}`) : prefix;
457
+ }
458
+
459
+ function getDefaultSessionDirName(cwd: string): { encodedDirName: string; resolvedCwd: string } {
460
+ const resolvedCwd = path.resolve(cwd);
461
+ const canonicalCwd = resolveEquivalentPath(resolvedCwd);
462
+ const home = resolveEquivalentPath(os.homedir());
463
+ const tempRoot = resolveEquivalentPath(os.tmpdir());
464
+ const encodedDirName = pathIsWithin(home, canonicalCwd)
465
+ ? encodeRelativeSessionDirName("-", home, canonicalCwd)
466
+ : pathIsWithin(tempRoot, canonicalCwd)
467
+ ? encodeRelativeSessionDirName("-tmp", tempRoot, canonicalCwd)
468
+ : encodeLegacyAbsoluteSessionDirName(canonicalCwd);
469
+ return { encodedDirName, resolvedCwd };
470
+ }
471
+
472
+ /**
473
+ * Migrate old `--<home-encoded>-*--` session dirs to the new `-*` format.
474
+ * Runs once per sessions root on first access, best-effort.
475
+ */
476
+ function migrateHomeSessionDirs(sessionsRoot: string): void {
477
+ if (migratedSessionRoots.has(sessionsRoot)) return;
478
+ migratedSessionRoots.add(sessionsRoot);
479
+
480
+ const home = os.homedir();
481
+ const homeEncoded = home.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-");
482
+ const oldPrefix = `--${homeEncoded}-`;
483
+ const oldExact = `--${homeEncoded}--`;
484
+
485
+ let entries: string[];
486
+ try {
487
+ entries = fs.readdirSync(sessionsRoot);
488
+ } catch {
489
+ return;
490
+ }
491
+
492
+ for (const entry of entries) {
493
+ let remainder: string;
494
+ if (entry === oldExact) {
495
+ remainder = "";
496
+ } else if (entry.startsWith(oldPrefix) && entry.endsWith("--")) {
497
+ remainder = entry.slice(oldPrefix.length, -2);
498
+ } else {
499
+ continue;
500
+ }
501
+
502
+ const newName = remainder ? `-${remainder}` : "-";
503
+ const oldPath = path.join(sessionsRoot, entry);
504
+ const newPath = path.join(sessionsRoot, newName);
505
+
506
+ try {
507
+ migrateSessionDirPath(oldPath, newPath);
508
+ } catch {
509
+ // Best effort
510
+ }
511
+ }
512
+ }
513
+
514
+ function migrateLegacyAbsoluteSessionDir(cwd: string, sessionDir: string, sessionsRoot: string): void {
515
+ const legacyDir = path.join(sessionsRoot, encodeLegacyAbsoluteSessionDirName(cwd));
516
+ if (legacyDir === sessionDir || !fs.existsSync(legacyDir)) return;
517
+
518
+ try {
519
+ migrateSessionDirPath(legacyDir, sessionDir);
520
+ } catch {
521
+ // Best effort
522
+ }
523
+ }
524
+
525
+ function resolveManagedSessionRoot(sessionDir: string, cwd: string): string | undefined {
526
+ const currentDirName = path.basename(sessionDir);
527
+ const { encodedDirName } = getDefaultSessionDirName(cwd);
528
+ if (currentDirName !== encodedDirName && currentDirName !== encodeLegacyAbsoluteSessionDirName(cwd)) {
529
+ return undefined;
530
+ }
531
+ return path.dirname(sessionDir);
532
+ }
533
+
534
+ /** Exported for compaction.test.ts */
535
+ export function parseSessionEntries(content: string): FileEntry[] {
536
+ return parseJsonlLenient<FileEntry>(content);
537
+ }
538
+
539
+ export function getLatestCompactionEntry(entries: SessionEntry[]): CompactionEntry | null {
540
+ for (let i = entries.length - 1; i >= 0; i--) {
541
+ if (entries[i].type === "compaction") {
542
+ return entries[i] as CompactionEntry;
543
+ }
544
+ }
545
+ return null;
546
+ }
547
+
548
+ export interface BuildSessionContextOptions {
549
+ /**
550
+ * Build the full-history display transcript instead of the LLM context:
551
+ * every path entry in chronological order, with each compaction emitted
552
+ * inline as a `compactionSummary` message at the position it fired rather
553
+ * than replacing the history before it. Display-only — never send the
554
+ * result to a provider.
555
+ */
556
+ transcript?: boolean;
557
+ }
558
+
559
+ /**
560
+ * Build the session context from entries using tree traversal.
561
+ * If leafId is provided, walks from that entry to root.
562
+ * Handles compaction and branch summaries along the path.
563
+ */
564
+ export function buildSessionContext(
565
+ entries: SessionEntry[],
566
+ leafId?: string | null,
567
+ byId?: Map<string, SessionEntry>,
568
+ options?: BuildSessionContextOptions,
569
+ ): SessionContext {
570
+ // Build uuid index if not available
571
+ if (!byId) {
572
+ byId = new Map<string, SessionEntry>();
573
+ for (const entry of entries) {
574
+ byId.set(entry.id, entry);
575
+ }
576
+ }
577
+
578
+ // Find leaf
579
+ let leaf: SessionEntry | undefined;
580
+ if (leafId === null) {
581
+ // Explicitly null - return no messages (navigated to before first entry)
582
+ return {
583
+ messages: [],
584
+ thinkingLevel: "off",
585
+ serviceTier: undefined,
586
+ models: {},
587
+ injectedTtsrRules: [],
588
+ selectedMCPToolNames: [],
589
+ hasPersistedMCPToolSelection: false,
590
+ mode: "none",
591
+ };
592
+ }
593
+ if (leafId) {
594
+ leaf = byId.get(leafId);
595
+ }
596
+ if (!leaf) {
597
+ // Fallback to last entry (when leafId is undefined)
598
+ leaf = entries[entries.length - 1];
599
+ }
600
+
601
+ if (!leaf) {
602
+ return {
603
+ messages: [],
604
+ thinkingLevel: "off",
605
+ serviceTier: undefined,
606
+ models: {},
607
+ injectedTtsrRules: [],
608
+ selectedMCPToolNames: [],
609
+ hasPersistedMCPToolSelection: false,
610
+ mode: "none",
611
+ };
612
+ }
613
+
614
+ // Walk from leaf to root, collecting path
615
+ const path: SessionEntry[] = [];
616
+ let current: SessionEntry | undefined = leaf;
617
+ while (current) {
618
+ path.unshift(current);
619
+ current = current.parentId ? byId.get(current.parentId) : undefined;
620
+ }
621
+
622
+ // Extract settings and find compaction
623
+ let thinkingLevel: string | undefined = "off";
624
+ let serviceTier: ServiceTier | undefined;
625
+ const models: Record<string, string> = {};
626
+ let compaction: CompactionEntry | null = null;
627
+ const injectedTtsrRulesSet = new Set<string>();
628
+ let selectedMCPToolNames: string[] = [];
629
+ let hasPersistedMCPToolSelection = false;
630
+ let mode = "none";
631
+ let modeData: Record<string, unknown> | undefined;
632
+ // Track whether an explicit `model_change` with role="default" has been
633
+ // seen on this path. Once a user (or the agent itself) records an
634
+ // explicit default, later assistant-message inference must NOT overwrite
635
+ // it: temporary fallbacks (retry fallback, context promotion) and
636
+ // server-side model downgrades both produce assistant messages tagged
637
+ // with the wrong model id, which previously clobbered the user's pick on
638
+ // resume (issue #849).
639
+ let hasExplicitDefaultModel = false;
640
+
641
+ for (const entry of path) {
642
+ if (entry.type === "thinking_level_change") {
643
+ thinkingLevel = entry.thinkingLevel ?? "off";
644
+ } else if (entry.type === "model_change") {
645
+ // New format: { model: "provider/id", role?: string }
646
+ if (entry.model) {
647
+ const role = entry.role ?? "default";
648
+ models[role] = entry.model;
649
+ if (role === "default") {
650
+ hasExplicitDefaultModel = true;
651
+ }
652
+ }
653
+ } else if (entry.type === "service_tier_change") {
654
+ serviceTier = entry.serviceTier ?? undefined;
655
+ } else if (entry.type === "message" && entry.message.role === "assistant") {
656
+ // Legacy fallback: infer default model from assistant messages only
657
+ // when no explicit `model_change` (role=default) entry has been
658
+ // recorded yet. Newer sessions always record an explicit default
659
+ // model_change at the start of the conversation, so this branch is
660
+ // only used to keep pre-model_change sessions working.
661
+ if (!hasExplicitDefaultModel) {
662
+ models.default = `${entry.message.provider}/${entry.message.model}`;
663
+ }
664
+ } else if (entry.type === "compaction") {
665
+ compaction = entry;
666
+ } else if (entry.type === "ttsr_injection") {
667
+ // Collect injected TTSR rule names
668
+ for (const ruleName of entry.injectedRules) {
669
+ injectedTtsrRulesSet.add(ruleName);
670
+ }
671
+ } else if (entry.type === "mcp_tool_selection") {
672
+ selectedMCPToolNames = [...entry.selectedToolNames];
673
+ hasPersistedMCPToolSelection = true;
674
+ } else if (entry.type === "mode_change") {
675
+ mode = entry.mode;
676
+ modeData = entry.data;
677
+ }
678
+ }
679
+
680
+ const injectedTtsrRules = Array.from(injectedTtsrRulesSet);
681
+
682
+ // Build messages and collect corresponding entries
683
+ // When there's a compaction, we need to:
684
+ // 1. Emit summary first (entry = compaction)
685
+ // 2. Emit kept messages (from firstKeptEntryId up to compaction)
686
+ // 3. Emit messages after compaction
687
+ const messages: AgentMessage[] = [];
688
+
689
+ const appendMessage = (entry: SessionEntry) => {
690
+ if (entry.type === "message") {
691
+ messages.push(entry.message);
692
+ } else if (entry.type === "custom_message") {
693
+ messages.push(
694
+ createCustomMessage(
695
+ entry.customType,
696
+ entry.content,
697
+ entry.display,
698
+ entry.details,
699
+ entry.timestamp,
700
+ entry.attribution,
701
+ ),
702
+ );
703
+ } else if (entry.type === "branch_summary" && entry.summary) {
704
+ messages.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));
705
+ }
706
+ };
707
+
708
+ if (options?.transcript) {
709
+ // Display transcript: every entry in chronological order. Compactions do
710
+ // not erase prior history here — each renders inline (as a divider in the
711
+ // TUI) at the point it fired, with any snapcompact frames re-attached so
712
+ // the component can report them.
713
+ for (const entry of path) {
714
+ if (entry.type === "compaction") {
715
+ const snapcompactArchive = getPreservedSnapcompactArchive(entry.preserveData);
716
+ messages.push(
717
+ createCompactionSummaryMessage(
718
+ entry.summary,
719
+ entry.tokensBefore,
720
+ entry.timestamp,
721
+ entry.shortSummary,
722
+ undefined,
723
+ snapcompactArchive ? snapcompactImages(snapcompactArchive) : undefined,
724
+ ),
725
+ );
726
+ } else {
727
+ appendMessage(entry);
728
+ }
729
+ }
730
+ } else if (compaction) {
731
+ const providerPayload: ProviderPayload | undefined = (() => {
732
+ const candidate = compaction.preserveData?.openaiRemoteCompaction;
733
+ if (!candidate || typeof candidate !== "object") return undefined;
734
+ const remote = candidate as { provider?: unknown; replacementHistory?: unknown };
735
+ if (typeof remote.provider !== "string" || remote.provider.length === 0) return undefined;
736
+ if (!Array.isArray(remote.replacementHistory)) return undefined;
737
+ return {
738
+ type: "openaiResponsesHistory",
739
+ provider: remote.provider,
740
+ items: remote.replacementHistory as Array<Record<string, unknown>>,
741
+ };
742
+ })();
743
+ const remoteReplacementHistory = providerPayload?.items;
744
+
745
+ // Emit summary first; re-attach any archived snapcompact frames so the
746
+ // model can keep reading the archived history after every context rebuild.
747
+ const snapcompactArchive = getPreservedSnapcompactArchive(compaction.preserveData);
748
+ messages.push(
749
+ createCompactionSummaryMessage(
750
+ compaction.summary,
751
+ compaction.tokensBefore,
752
+ compaction.timestamp,
753
+ compaction.shortSummary,
754
+ providerPayload,
755
+ snapcompactArchive ? snapcompactImages(snapcompactArchive) : undefined,
756
+ ),
757
+ );
758
+
759
+ // Find compaction index in path
760
+ const compactionIdx = path.findIndex(e => e.type === "compaction" && e.id === compaction.id);
761
+
762
+ if (!remoteReplacementHistory) {
763
+ // Emit kept messages (before compaction, starting from firstKeptEntryId)
764
+ let foundFirstKept = false;
765
+ for (let i = 0; i < compactionIdx; i++) {
766
+ const entry = path[i];
767
+ if (entry.id === compaction.firstKeptEntryId) {
768
+ foundFirstKept = true;
769
+ }
770
+ if (foundFirstKept) {
771
+ appendMessage(entry);
772
+ }
773
+ }
774
+ }
775
+
776
+ // Emit messages after compaction
777
+ for (let i = compactionIdx + 1; i < path.length; i++) {
778
+ const entry = path[i];
779
+ appendMessage(entry);
780
+ }
781
+ } else {
782
+ // No compaction - emit all messages, handle branch summaries and custom messages
783
+ for (const entry of path) {
784
+ appendMessage(entry);
785
+ }
786
+ }
787
+
788
+ // Strip dangling tool_use blocks — a tool_use with no matching tool_result on the
789
+ // resolved leaf→root path — from ANY assistant turn, not just the trailing one.
790
+ // This happens whenever the leaf (or a branch point) lands such that an assistant
791
+ // turn's tool results are off the selected path: its result children live on a
792
+ // sibling branch, or it is the leaf itself (results are children below it). Left
793
+ // in place, `transformMessages` fabricates one synthetic "aborted"/"No result
794
+ // provided" result per dangling call, which render as phantom failed calls and
795
+ // re-inject the failed batch into the model's
796
+ // context — the rewind/restore loop.
797
+ //
798
+ // Stripping is necessary but not sufficient: a *modified* assistant turn that still
799
+ // carries signed `thinking`/`redacted_thinking` is rejected by Anthropic — "thinking
800
+ // blocks in the latest assistant message cannot be modified", and signed thinking
801
+ // replayed out of its original turn shape can also fail signature validation (this
802
+ // bites the handoff/branch-summary request). So when we rewrite a turn we also
803
+ // neutralize its protected reasoning: drop `redactedThinking` (encrypted, no
804
+ // plaintext to keep) and clear `thinking` signatures so the provider encoder
805
+ // downgrades them to plain text (verified accepted by the live API), preserving the
806
+ // visible reasoning while removing the immutability/invalid-signature hazard. Drop a
807
+ // turn left with no content. (Live turns never qualify: their results are persisted
808
+ // on the same path before any context rebuild.)
809
+ const pairedToolResultIds = new Set<string>();
810
+ for (const message of messages) {
811
+ if (message.role === "toolResult") pairedToolResultIds.add(message.toolCallId);
812
+ }
813
+ for (let i = messages.length - 1; i >= 0; i--) {
814
+ const message = messages[i];
815
+ if (message.role !== "assistant") continue;
816
+ const hasDangling = message.content.some(
817
+ block => block.type === "toolCall" && !pairedToolResultIds.has(block.id),
818
+ );
819
+ if (!hasDangling) continue;
820
+ const normalized = message.content
821
+ .filter(
822
+ block =>
823
+ !(block.type === "toolCall" && !pairedToolResultIds.has(block.id)) && block.type !== "redactedThinking",
824
+ )
825
+ .map(block =>
826
+ block.type === "thinking" && block.thinkingSignature ? { ...block, thinkingSignature: undefined } : block,
827
+ );
828
+ if (normalized.length === 0) {
829
+ messages.splice(i, 1);
830
+ } else {
831
+ messages[i] = { ...message, content: normalized };
832
+ }
833
+ }
834
+
835
+ return {
836
+ messages,
837
+ thinkingLevel,
838
+ serviceTier,
839
+ models,
840
+ injectedTtsrRules,
841
+ selectedMCPToolNames,
842
+ hasPersistedMCPToolSelection,
843
+ mode,
844
+ modeData,
845
+ };
846
+ }
847
+
848
+ /**
849
+ * Compute the default session directory for a cwd.
850
+ * Classifies cwd by canonical location so symlink/alias paths resolve to the
851
+ * same home-relative or temp-root directory names as their real targets.
852
+ */
853
+ function computeDefaultSessionDir(
854
+ cwd: string,
855
+ storage: SessionStorage,
856
+ sessionsRoot: string = getSessionsDir(),
857
+ ): string {
858
+ const { encodedDirName, resolvedCwd } = getDefaultSessionDirName(cwd);
859
+ migrateHomeSessionDirs(sessionsRoot);
860
+ const sessionDir = path.join(sessionsRoot, encodedDirName);
861
+ migrateLegacyAbsoluteSessionDir(resolvedCwd, sessionDir, sessionsRoot);
862
+ storage.ensureDirSync(sessionDir);
863
+ return sessionDir;
864
+ }
865
+
866
+ // =============================================================================
867
+ // Terminal breadcrumbs: maps terminal (TTY) -> last session file for --continue
868
+ // =============================================================================
869
+
870
+ /**
871
+ * Write a breadcrumb linking the current terminal to a session file.
872
+ * The breadcrumb contains the cwd and session path so --continue can
873
+ * find "this terminal's last session" even when running concurrent instances.
874
+ */
875
+ function writeTerminalBreadcrumb(cwd: string, sessionFile: string): void {
876
+ const terminalId = getTerminalId();
877
+ if (!terminalId) return;
878
+
879
+ const breadcrumbDir = getTerminalSessionsDir();
880
+ const breadcrumbFile = path.join(breadcrumbDir, terminalId);
881
+ const content = `${cwd}\n${sessionFile}\n`;
882
+ // Best-effort — don't break session creation if breadcrumb fails
883
+ Bun.write(breadcrumbFile, content).catch(() => {});
884
+ }
885
+
886
+ interface TerminalBreadcrumb {
887
+ cwd: string;
888
+ sessionFile: string;
889
+ }
890
+
891
+ /**
892
+ * Read the raw terminal breadcrumb for the current terminal.
893
+ * Returns the recorded cwd + session file (verified to exist) regardless of
894
+ * whether the recorded cwd still matches the current one. Callers decide how
895
+ * to interpret a cwd mismatch (e.g. a moved/renamed worktree).
896
+ */
897
+ async function readTerminalBreadcrumbEntry(): Promise<TerminalBreadcrumb | null> {
898
+ const terminalId = getTerminalId();
899
+ if (!terminalId) return null;
900
+
901
+ try {
902
+ const breadcrumbFile = path.join(getTerminalSessionsDir(), terminalId);
903
+ const content = await Bun.file(breadcrumbFile).text();
904
+ const lines = content.trim().split("\n");
905
+ if (lines.length < 2) return null;
906
+
907
+ const breadcrumbCwd = lines[0];
908
+ const sessionFile = lines[1];
909
+
910
+ // Verify the session file still exists
911
+ const stat = fs.statSync(sessionFile, { throwIfNoEntry: false });
912
+ if (stat?.isFile()) return { cwd: breadcrumbCwd, sessionFile };
913
+ } catch (err) {
914
+ if (!isEnoent(err)) logger.debug("Terminal breadcrumb read failed", { err });
915
+ // Breadcrumb doesn't exist or is corrupt — fall through
916
+ }
917
+ return null;
918
+ }
919
+
920
+ /** Exported for testing */
921
+ export async function loadEntriesFromFile(
922
+ filePath: string,
923
+ storage: SessionStorage = new FileSessionStorage(),
924
+ ): Promise<FileEntry[]> {
925
+ let content: string;
926
+ try {
927
+ content = await storage.readText(filePath);
928
+ } catch (err) {
929
+ if (isEnoent(err)) return [];
930
+ throw err;
931
+ }
932
+ const entries = parseJsonlLenient<FileEntry>(content);
933
+
934
+ // Validate session header
935
+ if (entries.length === 0) return entries;
936
+ const header = entries[0] as SessionHeader;
937
+ if (header.type !== "session" || typeof header.id !== "string") {
938
+ return [];
939
+ }
940
+
941
+ return entries;
942
+ }
943
+
944
+ /**
945
+ * Resolve blob references in loaded entries, restoring both session image blocks and persisted
946
+ * provider image URLs back to the inline data expected by downstream transports. Mutates entries in place.
947
+ */
948
+ function hasImageUrl(value: unknown): value is { image_url: string } {
949
+ return typeof value === "object" && value !== null && "image_url" in value && typeof value.image_url === "string";
950
+ }
951
+
952
+ async function resolvePersistedImageUrlRefs(value: unknown, blobStore: BlobStore): Promise<void> {
953
+ if (Array.isArray(value)) {
954
+ await Promise.all(value.map(item => resolvePersistedImageUrlRefs(item, blobStore)));
955
+ return;
956
+ }
957
+
958
+ if (typeof value !== "object" || value === null) return;
959
+
960
+ if (hasImageUrl(value) && isBlobRef(value.image_url)) {
961
+ value.image_url = await resolveImageDataUrl(blobStore, value.image_url);
962
+ }
963
+
964
+ await Promise.all(Object.values(value).map(item => resolvePersistedImageUrlRefs(item, blobStore)));
965
+ }
966
+
967
+ async function resolveBlobRefsInEntries(entries: FileEntry[], blobStore: BlobStore): Promise<void> {
968
+ const promises: Promise<void>[] = [];
969
+
970
+ for (const entry of entries) {
971
+ if (entry.type === "session") continue;
972
+
973
+ let contentArray: unknown[] | undefined;
974
+ if (entry.type === "message" && "content" in entry.message && Array.isArray(entry.message.content)) {
975
+ contentArray = entry.message.content;
976
+ } else if (entry.type === "custom_message" && Array.isArray(entry.content)) {
977
+ contentArray = entry.content;
978
+ }
979
+
980
+ if (contentArray) {
981
+ for (const block of contentArray) {
982
+ if (isImageBlock(block) && isBlobRef(block.data)) {
983
+ promises.push(
984
+ resolveImageData(blobStore, block.data).then(resolved => {
985
+ block.data = resolved;
986
+ }),
987
+ );
988
+ }
989
+ }
990
+ }
991
+
992
+ promises.push(resolvePersistedImageUrlRefs(entry, blobStore));
993
+ }
994
+
995
+ await Promise.all(promises);
996
+ }
997
+
998
+ /**
999
+ * Read-only message view of a session file: load entries, migrate to the
1000
+ * current version, resolve blob refs, and build the context along the
1001
+ * persisted leaf path (last entry). Does NOT create a writer or take the
1002
+ * session lock — safe to call against a file another session is writing.
1003
+ */
1004
+ export async function loadSessionMessagesReadOnly(filePath: string): Promise<AgentMessage[]> {
1005
+ const entries = await loadEntriesFromFile(filePath);
1006
+ if (entries.length === 0) return [];
1007
+ migrateToCurrentVersion(entries);
1008
+ await resolveBlobRefsInEntries(entries, new BlobStore(getBlobsDir()));
1009
+ const sessionEntries = entries.filter((e): e is SessionEntry => e.type !== "session");
1010
+ return buildSessionContext(sessionEntries).messages;
1011
+ }
1012
+
1013
+ /**
1014
+ * Lightweight metadata for a session file, used in session picker UI.
1015
+ * Uses lazy getters to defer string formatting until actually displayed.
1016
+ */
1017
+ function sanitizeSessionName(value: string | undefined): string | undefined {
1018
+ if (!value) return undefined;
1019
+ const firstLine = value.split(/\r?\n/)[0] ?? "";
1020
+ const stripped = firstLine.replace(/[\x00-\x1F\x7F]/g, "");
1021
+ const trimmed = stripped.trim();
1022
+ return trimmed.length > 0 ? trimmed : undefined;
1023
+ }
1024
+
1025
+ class RecentSessionInfo {
1026
+ #fullName: string | undefined;
1027
+ #timeAgo: string | undefined;
1028
+ readonly #headerTimestamp: string | undefined;
1029
+
1030
+ constructor(
1031
+ readonly path: string,
1032
+ readonly mtime: number,
1033
+ header: Record<string, unknown>,
1034
+ firstPrompt?: string,
1035
+ ) {
1036
+ // Prefer an explicit title, then the first user prompt. The raw UUID `id` is
1037
+ // intentionally not used as a fallback: showing it as a "name" is unfriendly and
1038
+ // indistinguishable from neighboring sessions in the UI. The friendly fallback is
1039
+ // derived lazily in `fullName` from the session timestamp.
1040
+ const trystr = (v: unknown) => (typeof v === "string" ? v : undefined);
1041
+ this.#fullName = sanitizeSessionName(trystr(header.title)) ?? sanitizeSessionName(firstPrompt);
1042
+ this.#headerTimestamp = trystr(header.timestamp);
1043
+ }
1044
+
1045
+ /** Display name. Falls back to a timestamp-based label, never the raw UUID. */
1046
+ get fullName(): string {
1047
+ if (this.#fullName) return this.#fullName;
1048
+ const ts = this.#headerTimestamp ? Date.parse(this.#headerTimestamp) : Number.NaN;
1049
+ const date = new Date(Number.isFinite(ts) ? ts : this.mtime);
1050
+ const time = date.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" });
1051
+ this.#fullName = `Untitled · ${time}`;
1052
+ return this.#fullName;
1053
+ }
1054
+
1055
+ /**
1056
+ * Display name without an arbitrary length cap. The renderer is responsible for
1057
+ * width-aware truncation so adjacent fields (e.g. the relative time) stay visible.
1058
+ */
1059
+ get name(): string {
1060
+ return this.fullName;
1061
+ }
1062
+
1063
+ /** Human-readable relative time (e.g., "2 hours ago") */
1064
+ get timeAgo(): string {
1065
+ if (this.#timeAgo) return this.#timeAgo;
1066
+ this.#timeAgo = formatTimeAgo(new Date(this.mtime));
1067
+ return this.#timeAgo;
1068
+ }
1069
+ }
1070
+
1071
+ /**
1072
+ * Extracts the text content from a user message entry.
1073
+ * Returns undefined if the entry is not a user message or has no text.
1074
+ */
1075
+ function extractFirstUserPrompt(entries: Array<Record<string, unknown>>): string | undefined {
1076
+ for (const entry of entries) {
1077
+ if (entry.type !== "message") continue;
1078
+ const message = entry.message as Record<string, unknown> | undefined;
1079
+ if (message?.role !== "user") continue;
1080
+ const content = message.content;
1081
+ if (typeof content === "string") return content;
1082
+ if (Array.isArray(content)) {
1083
+ for (const block of content) {
1084
+ if (typeof block === "object" && block !== null && "text" in block) {
1085
+ const text = (block as { text: unknown }).text;
1086
+ if (typeof text === "string") return text;
1087
+ }
1088
+ }
1089
+ }
1090
+ }
1091
+ return undefined;
1092
+ }
1093
+
1094
+ /**
1095
+ * Promote orphaned `<basename>.jsonl.<snowflake>.bak` backups created by
1096
+ * `#replaceSessionFileAfterEperm` back to their primary path when the primary
1097
+ * is missing. This runs once per session-dir scan, before the main `*.jsonl`
1098
+ * glob, so a crash between the two renames in the EPERM-rewrite path does not
1099
+ * leave the user's last good state stranded outside the loader's view.
1100
+ *
1101
+ * Exported for testing.
1102
+ */
1103
+ export async function recoverOrphanedBackups(sessionDir: string, storage: SessionStorage): Promise<void> {
1104
+ let backups: string[];
1105
+ try {
1106
+ backups = storage.listFilesSync(sessionDir, "*.bak");
1107
+ } catch {
1108
+ return;
1109
+ }
1110
+ if (backups.length === 0) return;
1111
+ // For each primary path, pick the newest backup (highest mtime) as the recovery source.
1112
+ const candidates = new Map<string, { backup: string; mtimeMs: number }>();
1113
+ for (const backup of backups) {
1114
+ const name = path.basename(backup);
1115
+ // Expect "<primary>.<snowflake>.bak" where <primary> ends in ".jsonl".
1116
+ if (!name.endsWith(".bak")) continue;
1117
+ const trimmed = name.slice(0, -".bak".length);
1118
+ const dotIdx = trimmed.lastIndexOf(".");
1119
+ if (dotIdx <= 0) continue;
1120
+ const primaryName = trimmed.slice(0, dotIdx);
1121
+ if (!primaryName.endsWith(".jsonl")) continue;
1122
+ const primaryPath = path.join(sessionDir, primaryName);
1123
+ let mtimeMs = 0;
1124
+ try {
1125
+ mtimeMs = storage.statSync(backup).mtimeMs;
1126
+ } catch {
1127
+ continue;
1128
+ }
1129
+ const existing = candidates.get(primaryPath);
1130
+ if (!existing || mtimeMs > existing.mtimeMs) {
1131
+ candidates.set(primaryPath, { backup, mtimeMs });
1132
+ }
1133
+ }
1134
+ for (const [primaryPath, { backup }] of candidates) {
1135
+ if (storage.existsSync(primaryPath)) continue;
1136
+ try {
1137
+ await storage.rename(backup, primaryPath);
1138
+ logger.warn("Recovered orphaned session backup", {
1139
+ sessionFile: primaryPath,
1140
+ backupPath: backup,
1141
+ });
1142
+ } catch (err) {
1143
+ logger.warn("Failed to recover orphaned session backup", {
1144
+ sessionFile: primaryPath,
1145
+ backupPath: backup,
1146
+ error: toError(err).message,
1147
+ });
1148
+ }
1149
+ }
1150
+ }
1151
+
1152
+ /**
1153
+ * Reads all session files from the directory and returns them sorted by mtime (newest first).
1154
+ * Uses low-level file I/O to efficiently read only the first 4KB of each file
1155
+ * to extract the JSON header and first user message without loading entire session logs into memory.
1156
+ */
1157
+ async function getSortedSessions(sessionDir: string, storage: SessionStorage): Promise<RecentSessionInfo[]> {
1158
+ await recoverOrphanedBackups(sessionDir, storage);
1159
+ try {
1160
+ const files: string[] = storage.listFilesSync(sessionDir, "*.jsonl");
1161
+ const sessions: RecentSessionInfo[] = [];
1162
+ await Promise.all(
1163
+ files.map(async (path: string) => {
1164
+ try {
1165
+ const [content] = await storage.readTextSlices(path, 4096, 0);
1166
+ const entries = parseJsonlLenient<Record<string, unknown>>(content);
1167
+ if (entries.length === 0) return;
1168
+ const header = entries[0] as Record<string, unknown>;
1169
+ if (header.type !== "session" || typeof header.id !== "string") return;
1170
+ const mtime = storage.statSync(path).mtimeMs;
1171
+ const firstPrompt = header.title ? undefined : extractFirstUserPrompt(entries);
1172
+ sessions.push(new RecentSessionInfo(path, mtime, header, firstPrompt));
1173
+ } catch {}
1174
+ }),
1175
+ );
1176
+ return sessions.sort((a, b) => b.mtime - a.mtime);
1177
+ } catch {
1178
+ return [];
1179
+ }
1180
+ }
1181
+
1182
+ /** Exported for testing */
1183
+ export async function findMostRecentSession(
1184
+ sessionDir: string,
1185
+ storage: SessionStorage = new FileSessionStorage(),
1186
+ ): Promise<string | null> {
1187
+ const sessions = await getSortedSessions(sessionDir, storage);
1188
+ return sessions[0]?.path || null;
1189
+ }
1190
+
1191
+ /** Format a time difference as a human-readable string */
1192
+ function formatTimeAgo(date: Date): string {
1193
+ const now = Date.now();
1194
+ const diffMs = now - date.getTime();
1195
+ const diffMins = Math.floor(diffMs / 60000);
1196
+ const diffHours = Math.floor(diffMs / 3600000);
1197
+ const diffDays = Math.floor(diffMs / 86400000);
1198
+
1199
+ if (diffMins < 1) return "just now";
1200
+ if (diffMins < 60) return `${diffMins}m ago`;
1201
+ if (diffHours < 24) return `${diffHours}h ago`;
1202
+ if (diffDays < 7) return `${diffDays}d ago`;
1203
+ return date.toLocaleDateString();
1204
+ }
1205
+
1206
+ const MAX_PERSIST_CHARS = 500_000;
1207
+ const TRUNCATION_NOTICE = "\n\n[Session persistence truncated large content]";
1208
+ /** Minimum base64 length to externalize to blob store (skip tiny inline images) */
1209
+ const BLOB_EXTERNALIZE_THRESHOLD = 1024;
1210
+ const TEXT_CONTENT_KEY = "content";
1211
+
1212
+ /**
1213
+ * Recursively truncate large strings in an object for session persistence.
1214
+ * - Truncates any oversized string fields (key-agnostic)
1215
+ * - Replaces oversized image blocks with text notices
1216
+ * - Updates lineCount when content is truncated
1217
+ * - Returns original object if no changes needed (structural sharing)
1218
+ */
1219
+ function truncateString(value: string, maxLength: number): string {
1220
+ if (value.length <= maxLength) return value;
1221
+ let truncated = value.slice(0, maxLength);
1222
+ if (truncated.length > 0) {
1223
+ const last = truncated.charCodeAt(truncated.length - 1);
1224
+ if (last >= 0xd800 && last <= 0xdbff) {
1225
+ truncated = truncated.slice(0, -1);
1226
+ }
1227
+ }
1228
+ return truncated;
1229
+ }
1230
+
1231
+ function isImageBlock(value: unknown): value is { type: "image"; data: string; mimeType?: string } {
1232
+ return (
1233
+ typeof value === "object" &&
1234
+ value !== null &&
1235
+ "type" in value &&
1236
+ (value as { type?: string }).type === "image" &&
1237
+ "data" in value &&
1238
+ typeof (value as { data?: string }).data === "string"
1239
+ );
1240
+ }
1241
+
1242
+ async function truncateForPersistence(obj: FileEntry, blobStore: BlobStore, key?: string): Promise<FileEntry>;
1243
+ async function truncateForPersistence(obj: string, blobStore: BlobStore, key?: string): Promise<string>;
1244
+ async function truncateForPersistence(obj: unknown[], blobStore: BlobStore, key?: string): Promise<unknown[]>;
1245
+ async function truncateForPersistence(obj: object, blobStore: BlobStore, key?: string): Promise<object>;
1246
+ async function truncateForPersistence(
1247
+ obj: null | undefined,
1248
+ blobStore: BlobStore,
1249
+ key?: string,
1250
+ ): Promise<null | undefined>;
1251
+ async function truncateForPersistence(obj: unknown, blobStore: BlobStore, key?: string): Promise<unknown> {
1252
+ if (obj === null || obj === undefined) return obj;
1253
+
1254
+ if (typeof obj === "string") {
1255
+ if (key === "image_url" && isImageDataUrl(obj)) {
1256
+ return externalizeImageDataUrl(blobStore, obj);
1257
+ }
1258
+
1259
+ if (obj.length > MAX_PERSIST_CHARS) {
1260
+ // Cryptographic signatures must be preserved exactly or cleared entirely — never truncated.
1261
+ // Truncation would produce an invalid signature that the API rejects.
1262
+ if (key === "thinkingSignature" || key === "thoughtSignature" || key === "textSignature") {
1263
+ return "";
1264
+ }
1265
+
1266
+ const limit = Math.max(0, MAX_PERSIST_CHARS - TRUNCATION_NOTICE.length);
1267
+ return `${truncateString(obj, limit)}${TRUNCATION_NOTICE}`;
1268
+ }
1269
+
1270
+ return obj;
1271
+ }
1272
+
1273
+ if (Array.isArray(obj)) {
1274
+ let changed = false;
1275
+ const result = await Promise.all(
1276
+ obj.map(async item => {
1277
+ // Special handling: compress oversized images while preserving shape
1278
+ if (key === TEXT_CONTENT_KEY && isImageBlock(item)) {
1279
+ if (!isBlobRef(item.data) && item.data.length >= BLOB_EXTERNALIZE_THRESHOLD) {
1280
+ changed = true;
1281
+ const blobRef = await externalizeImageData(blobStore, item.data, item.mimeType);
1282
+ return { ...item, data: blobRef };
1283
+ }
1284
+ }
1285
+
1286
+ const newItem = await truncateForPersistence(item, blobStore, key);
1287
+ if (newItem !== item) changed = true;
1288
+ return newItem;
1289
+ }),
1290
+ );
1291
+ return changed ? result : obj;
1292
+ }
1293
+
1294
+ if (typeof obj === "object") {
1295
+ let changed = false;
1296
+ const entries: Array<readonly [string, unknown]> = await Promise.all(
1297
+ Object.entries(obj).flatMap(([childKey, value]) => {
1298
+ // Strip transient/redundant properties that shouldn't be persisted.
1299
+ // - partialJson: streaming accumulator for tool call JSON parsing
1300
+ // - jsonlEvents: raw subprocess streaming events (already saved to artifact files)
1301
+ if (childKey === "partialJson" || childKey === "jsonlEvents") {
1302
+ changed = true;
1303
+ return [];
1304
+ }
1305
+
1306
+ return [
1307
+ (async () => {
1308
+ const newValue = await truncateForPersistence(value, blobStore, childKey);
1309
+ if (newValue !== value) changed = true;
1310
+ return [childKey, newValue] as const;
1311
+ })(),
1312
+ ];
1313
+ }),
1314
+ );
1315
+
1316
+ if (!changed) return obj;
1317
+
1318
+ const contentEntry = entries.find(([childKey]) => childKey === "content");
1319
+ const lineCountEntry = entries.find(([childKey]) => childKey === "lineCount");
1320
+ if (
1321
+ contentEntry &&
1322
+ typeof contentEntry[1] === "string" &&
1323
+ lineCountEntry &&
1324
+ typeof lineCountEntry[1] === "number"
1325
+ ) {
1326
+ const content = contentEntry[1];
1327
+ const updatedEntries = entries.map(([childKey, value]) =>
1328
+ childKey === "lineCount" ? ([childKey, content.split("\n").length] as const) : ([childKey, value] as const),
1329
+ );
1330
+ return Object.fromEntries(updatedEntries);
1331
+ }
1332
+ return Object.fromEntries(entries);
1333
+ }
1334
+
1335
+ return obj;
1336
+ }
1337
+
1338
+ async function prepareEntryForPersistence(entry: FileEntry, blobStore: BlobStore): Promise<FileEntry> {
1339
+ return truncateForPersistence(entry, blobStore);
1340
+ }
1341
+
1342
+ /**
1343
+ * Synchronous variant of {@link truncateForPersistence}.
1344
+ *
1345
+ * The async version's overhead — `Promise.all` over `Object.entries`/`Array.prototype.map`,
1346
+ * one microtask hop per nested node — is pure waste for entries without image blobs
1347
+ * (the vast majority). The fast path runs in one synchronous tick so an OOM/SIGKILL
1348
+ * landing right after `_persist` returns cannot lose the entry. Image externalization
1349
+ * still happens, but via the synchronous blob-store path (`fs.writeFileSync`), so the
1350
+ * blob bytes are in the kernel page cache before the JSONL line referencing them is
1351
+ * written.
1352
+ */
1353
+ function truncateForPersistenceSync(obj: unknown, blobStore: BlobStore, key?: string): unknown {
1354
+ if (obj === null || obj === undefined) return obj;
1355
+
1356
+ if (typeof obj === "string") {
1357
+ if (key === "image_url" && isImageDataUrl(obj)) {
1358
+ return externalizeImageDataUrlSync(blobStore, obj);
1359
+ }
1360
+ if (obj.length > MAX_PERSIST_CHARS) {
1361
+ if (key === "thinkingSignature" || key === "thoughtSignature" || key === "textSignature") {
1362
+ return "";
1363
+ }
1364
+ const limit = Math.max(0, MAX_PERSIST_CHARS - TRUNCATION_NOTICE.length);
1365
+ return `${truncateString(obj, limit)}${TRUNCATION_NOTICE}`;
1366
+ }
1367
+ return obj;
1368
+ }
1369
+
1370
+ if (Array.isArray(obj)) {
1371
+ let changed = false;
1372
+ const result: unknown[] = new Array(obj.length);
1373
+ for (let i = 0; i < obj.length; i++) {
1374
+ const item = obj[i];
1375
+ if (
1376
+ key === TEXT_CONTENT_KEY &&
1377
+ isImageBlock(item) &&
1378
+ !isBlobRef(item.data) &&
1379
+ item.data.length >= BLOB_EXTERNALIZE_THRESHOLD
1380
+ ) {
1381
+ changed = true;
1382
+ result[i] = { ...item, data: externalizeImageDataSync(blobStore, item.data, item.mimeType) };
1383
+ continue;
1384
+ }
1385
+ const newItem = truncateForPersistenceSync(item, blobStore, key);
1386
+ if (newItem !== item) changed = true;
1387
+ result[i] = newItem;
1388
+ }
1389
+ return changed ? result : obj;
1390
+ }
1391
+
1392
+ if (typeof obj === "object") {
1393
+ let changed = false;
1394
+ const entries: Array<readonly [string, unknown]> = [];
1395
+ for (const [childKey, value] of Object.entries(obj)) {
1396
+ if (childKey === "partialJson" || childKey === "jsonlEvents") {
1397
+ changed = true;
1398
+ continue;
1399
+ }
1400
+ const newValue = truncateForPersistenceSync(value, blobStore, childKey);
1401
+ if (newValue !== value) changed = true;
1402
+ entries.push([childKey, newValue]);
1403
+ }
1404
+ if (!changed) return obj;
1405
+
1406
+ const contentEntry = entries.find(([childKey]) => childKey === "content");
1407
+ const lineCountEntry = entries.find(([childKey]) => childKey === "lineCount");
1408
+ if (
1409
+ contentEntry &&
1410
+ typeof contentEntry[1] === "string" &&
1411
+ lineCountEntry &&
1412
+ typeof lineCountEntry[1] === "number"
1413
+ ) {
1414
+ const content = contentEntry[1];
1415
+ const updatedEntries = entries.map(([childKey, value]) =>
1416
+ childKey === "lineCount" ? ([childKey, content.split("\n").length] as const) : ([childKey, value] as const),
1417
+ );
1418
+ return Object.fromEntries(updatedEntries);
1419
+ }
1420
+ return Object.fromEntries(entries);
1421
+ }
1422
+
1423
+ return obj;
1424
+ }
1425
+
1426
+ function prepareEntryForPersistenceSync(entry: FileEntry, blobStore: BlobStore): FileEntry {
1427
+ return truncateForPersistenceSync(entry, blobStore) as FileEntry;
1428
+ }
1429
+
1430
+ class NdjsonFileWriter {
1431
+ #writer: SessionStorageWriter;
1432
+ #closed = false;
1433
+ #closing = false;
1434
+ #error: Error | undefined;
1435
+ #pendingWrites: Promise<void> = Promise.resolve();
1436
+ #onError: ((err: Error) => void) | undefined;
1437
+
1438
+ constructor(storage: SessionStorage, path: string, options?: { flags?: "a" | "w"; onError?: (err: Error) => void }) {
1439
+ this.#onError = options?.onError;
1440
+ this.#writer = storage.openWriter(path, {
1441
+ flags: options?.flags ?? "a",
1442
+ onError: (err: Error) => this.#recordError(err),
1443
+ });
1444
+ }
1445
+
1446
+ #recordError(err: unknown): Error {
1447
+ const writeErr = toError(err);
1448
+ if (!this.#error) this.#error = writeErr;
1449
+ this.#onError?.(writeErr);
1450
+ return writeErr;
1451
+ }
1452
+
1453
+ #enqueue(task: () => Promise<void>): Promise<void> {
1454
+ const run = async () => {
1455
+ if (this.#error) throw this.#error;
1456
+ await task();
1457
+ };
1458
+ const next = this.#pendingWrites.then(run);
1459
+ void next.catch((err: unknown) => {
1460
+ if (!this.#error) this.#error = toError(err);
1461
+ });
1462
+ this.#pendingWrites = next;
1463
+ return next;
1464
+ }
1465
+
1466
+ async #writeLine(line: string): Promise<void> {
1467
+ if (this.#error) throw this.#error;
1468
+ try {
1469
+ await this.#writer.writeLine(line);
1470
+ } catch (err) {
1471
+ throw this.#recordError(err);
1472
+ }
1473
+ }
1474
+
1475
+ /** Queue a write. Returns a promise so callers can await if needed. */
1476
+ write(entry: FileEntry): Promise<void> {
1477
+ if (this.#closed || this.#closing) throw new Error("Writer closed");
1478
+ if (this.#error) throw this.#error;
1479
+ const line = `${JSON.stringify(entry)}\n`;
1480
+ return this.#enqueue(() => this.#writeLine(line));
1481
+ }
1482
+
1483
+ /**
1484
+ * Synchronously serialize and append the entry. Returns once `fs.writeSync` has handed
1485
+ * the bytes to the kernel page cache — durable across OOM/SIGKILL even before fsync.
1486
+ *
1487
+ * Callers MUST NOT mix this with pending async `write()` calls on the same writer:
1488
+ * the async path is queued through `#pendingWrites`, but this method bypasses the
1489
+ * queue. Use only when no concurrent async write is in flight (the session-manager
1490
+ * persist path enforces this via `#flushed`/`#needsFullRewriteOnNextPersist`).
1491
+ */
1492
+ writeSync(entry: FileEntry): void {
1493
+ if (this.#closed || this.#closing) throw new Error("Writer closed");
1494
+ if (this.#error) throw this.#error;
1495
+ const line = `${JSON.stringify(entry)}\n`;
1496
+ try {
1497
+ this.#writer.writeLineSync(line);
1498
+ } catch (err) {
1499
+ throw this.#recordError(err);
1500
+ }
1501
+ }
1502
+
1503
+ /** Flush all buffered data to disk. Waits for all queued writes. */
1504
+ async flush(): Promise<void> {
1505
+ if (this.#closed) return;
1506
+ if (this.#error) throw this.#error;
1507
+
1508
+ await this.#enqueue(async () => {});
1509
+
1510
+ if (this.#error) throw this.#error;
1511
+
1512
+ try {
1513
+ await this.#writer.flush();
1514
+ } catch (err) {
1515
+ throw this.#recordError(err);
1516
+ }
1517
+ }
1518
+
1519
+ /** Sync data to persistent storage. */
1520
+ async fsync(): Promise<void> {
1521
+ if (this.#closed) return;
1522
+ if (this.#error) throw this.#error;
1523
+ try {
1524
+ await this.#writer.fsync();
1525
+ } catch (err) {
1526
+ throw this.#recordError(err);
1527
+ }
1528
+ }
1529
+
1530
+ /** Close the writer, flushing all data. */
1531
+ async close(): Promise<void> {
1532
+ if (this.#closed || this.#closing) return;
1533
+ this.#closing = true;
1534
+
1535
+ let closeError: Error | undefined;
1536
+ try {
1537
+ await this.flush();
1538
+ } catch (err) {
1539
+ closeError = toError(err);
1540
+ }
1541
+
1542
+ try {
1543
+ await this.#pendingWrites;
1544
+ } catch (err) {
1545
+ if (!closeError) closeError = toError(err);
1546
+ }
1547
+
1548
+ try {
1549
+ await this.#writer.close();
1550
+ } catch (err) {
1551
+ const endErr = this.#recordError(err);
1552
+ if (!closeError) closeError = endErr;
1553
+ }
1554
+
1555
+ this.#closed = true;
1556
+
1557
+ if (!closeError && this.#error) closeError = this.#error;
1558
+ if (closeError) throw closeError;
1559
+ }
1560
+
1561
+ /** Check if there's a stored error. */
1562
+ getError(): Error | undefined {
1563
+ return this.#error;
1564
+ }
1565
+
1566
+ /** True while the writer accepts new writes (not closing or closed). */
1567
+ isOpen(): boolean {
1568
+ return !this.#closed && !this.#closing;
1569
+ }
1570
+ }
1571
+
1572
+ /** Get recent sessions for display in welcome screen (which reserves WELCOME_SESSION_SLOTS rows) */
1573
+ export async function getRecentSessions(
1574
+ sessionDir: string,
1575
+ limit = 4,
1576
+ storage: SessionStorage = new FileSessionStorage(),
1577
+ ): Promise<RecentSessionInfo[]> {
1578
+ const sessions = await getSortedSessions(sessionDir, storage);
1579
+ return sessions.slice(0, limit);
1580
+ }
1581
+
1582
+ /**
1583
+ * Manages conversation sessions as append-only trees stored in JSONL files.
1584
+ *
1585
+ * Each session entry has an id and parentId forming a tree structure. The "leaf"
1586
+ * pointer tracks the current position. Appending creates a child of the current leaf.
1587
+ * Branching moves the leaf to an earlier entry, allowing new branches without
1588
+ * modifying history.
1589
+ *
1590
+ * Use buildSessionContext() to get the resolved message list for the LLM, which
1591
+ * handles compaction summaries and follows the path from root to current leaf.
1592
+ */
1593
+ export interface UsageStatistics {
1594
+ input: number;
1595
+ output: number;
1596
+ cacheRead: number;
1597
+ cacheWrite: number;
1598
+ premiumRequests: number;
1599
+ cost: number;
1600
+ }
1601
+
1602
+ function getTaskToolUsage(details: unknown): Usage | undefined {
1603
+ if (!details || typeof details !== "object") return undefined;
1604
+ const record = details as Record<string, unknown>;
1605
+ const usage = record.usage;
1606
+ if (!usage || typeof usage !== "object") return undefined;
1607
+ return usage as Usage;
1608
+ }
1609
+
1610
+ function extractTextFromContent(content: Message["content"]): string {
1611
+ if (typeof content === "string") return content;
1612
+ return content
1613
+ .filter((block): block is TextContent => block.type === "text")
1614
+ .map(block => block.text)
1615
+ .join(" ");
1616
+ }
1617
+
1618
+ const SESSION_LIST_PREFIX_BYTES = 4096;
1619
+ /**
1620
+ * Tail window read to derive {@link SessionStatus}. Large enough to capture a
1621
+ * typical final assistant turn (thinking + text); when the final message exceeds
1622
+ * it the status falls back to `unknown` rather than misreporting.
1623
+ */
1624
+ const SESSION_LIST_SUFFIX_BYTES = 32_768;
1625
+ const SESSION_LIST_PARALLEL_THRESHOLD = 64;
1626
+ const SESSION_LIST_MAX_WORKERS = 16;
1627
+
1628
+ /**
1629
+ * Derive a {@link SessionStatus} from a tail window of a session file. Entries are
1630
+ * newline-terminated on write, so within the window only the first line can be a
1631
+ * partial fragment — it simply fails to parse and is skipped. We walk backwards to
1632
+ * the last `message` entry and classify by its role / stop reason.
1633
+ */
1634
+ function deriveSessionStatus(suffix: string): SessionStatus {
1635
+ if (!suffix) return "unknown";
1636
+ const lines = suffix.split("\n");
1637
+ for (let i = lines.length - 1; i >= 0; i--) {
1638
+ const line = lines[i];
1639
+ // Every persisted entry is `JSON.stringify(obj)` → starts with `{`. This
1640
+ // cheaply rejects blank lines and the leading partial fragment without
1641
+ // attempting to parse a multi-KB tail of a truncated line.
1642
+ if (line.charCodeAt(0) !== 123) continue;
1643
+ let entry: { type?: string; message?: TailMessage };
1644
+ try {
1645
+ entry = JSON.parse(line);
1646
+ } catch {
1647
+ continue;
1648
+ }
1649
+ if (entry.type === "message" && entry.message) {
1650
+ return statusFromTailMessage(entry.message);
1651
+ }
1652
+ }
1653
+ return "unknown";
1654
+ }
1655
+
1656
+ interface TailMessage {
1657
+ role?: string;
1658
+ stopReason?: string;
1659
+ content?: unknown;
1660
+ }
1661
+
1662
+ function isToolCallBlock(block: unknown): boolean {
1663
+ return typeof block === "object" && block !== null && (block as { type?: unknown }).type === "toolCall";
1664
+ }
1665
+
1666
+ function statusFromTailMessage(message: TailMessage): SessionStatus {
1667
+ switch (message.role) {
1668
+ case "assistant": {
1669
+ switch (message.stopReason) {
1670
+ case "error":
1671
+ return "error";
1672
+ case "aborted":
1673
+ return "aborted";
1674
+ case "length":
1675
+ return "interrupted";
1676
+ }
1677
+ // A turn that ends without unanswered tool calls means the agent yielded
1678
+ // control back to the user — complete. Trailing tool calls (no tool
1679
+ // results after) mean the loop was cut off before running them.
1680
+ const content = message.content;
1681
+ if (Array.isArray(content) && content.some(isToolCallBlock)) return "interrupted";
1682
+ return "complete";
1683
+ }
1684
+ case "toolResult":
1685
+ // Tools ran but the agent never produced the following assistant turn.
1686
+ return "interrupted";
1687
+ case "user":
1688
+ // User message with no assistant reply persisted after it.
1689
+ return "pending";
1690
+ default:
1691
+ return "unknown";
1692
+ }
1693
+ }
1694
+
1695
+ function decodeJsonStringFragment(value: string): string {
1696
+ const safeValue = value.endsWith("\\") ? value.slice(0, -1) : value;
1697
+ try {
1698
+ return JSON.parse(`"${safeValue}"`) as string;
1699
+ } catch {
1700
+ return safeValue
1701
+ .replace(/\\n/g, "\n")
1702
+ .replace(/\\r/g, "\r")
1703
+ .replace(/\\t/g, "\t")
1704
+ .replace(/\\"/g, '"')
1705
+ .replace(/\\\\/g, "\\");
1706
+ }
1707
+ }
1708
+
1709
+ function extractStringProperty(source: string, name: string, startIndex = 0): string | undefined {
1710
+ const propertyIndex = source.indexOf(`"${name}"`, startIndex);
1711
+ if (propertyIndex === -1) return undefined;
1712
+
1713
+ const colonIndex = source.indexOf(":", propertyIndex + name.length + 2);
1714
+ if (colonIndex === -1) return undefined;
1715
+
1716
+ let valueIndex = colonIndex + 1;
1717
+ while (valueIndex < source.length) {
1718
+ const char = source.charCodeAt(valueIndex);
1719
+ if (char !== 32 && char !== 9 && char !== 10 && char !== 13) break;
1720
+ valueIndex++;
1721
+ }
1722
+ if (source.charCodeAt(valueIndex) !== 34) return undefined;
1723
+
1724
+ const valueStart = valueIndex + 1;
1725
+ let escaped = false;
1726
+ for (let i = valueStart; i < source.length; i++) {
1727
+ const char = source.charCodeAt(i);
1728
+ if (escaped) {
1729
+ escaped = false;
1730
+ continue;
1731
+ }
1732
+ if (char === 92) {
1733
+ escaped = true;
1734
+ continue;
1735
+ }
1736
+ if (char === 34) {
1737
+ return decodeJsonStringFragment(source.slice(valueStart, i));
1738
+ }
1739
+ }
1740
+
1741
+ return decodeJsonStringFragment(source.slice(valueStart));
1742
+ }
1743
+
1744
+ function countMessageMarkers(content: string): number {
1745
+ let count = 0;
1746
+ let index = 0;
1747
+ while (index < content.length) {
1748
+ const typeIndex = content.indexOf('"type"', index);
1749
+ if (typeIndex === -1) break;
1750
+ const colonIndex = content.indexOf(":", typeIndex + 6);
1751
+ if (colonIndex === -1) break;
1752
+ const type = extractStringProperty(content, "type", typeIndex);
1753
+ if (type === "message") count++;
1754
+ index = colonIndex + 1;
1755
+ }
1756
+ return count;
1757
+ }
1758
+
1759
+ function extractFirstUserMessageFromPrefix(content: string): string | undefined {
1760
+ const roleIndex = content.indexOf('"role"');
1761
+ if (roleIndex === -1) return undefined;
1762
+
1763
+ let index = roleIndex;
1764
+ while (index !== -1) {
1765
+ const role = extractStringProperty(content, "role", index);
1766
+ if (role === "user") {
1767
+ return extractStringProperty(content, "content", index) ?? extractStringProperty(content, "text", index);
1768
+ }
1769
+ index = content.indexOf('"role"', index + 6);
1770
+ }
1771
+
1772
+ return undefined;
1773
+ }
1774
+
1775
+ interface SessionListHeader {
1776
+ type: "session";
1777
+ id: string;
1778
+ cwd?: string;
1779
+ title?: string;
1780
+ parentSession?: string;
1781
+ timestamp?: string;
1782
+ }
1783
+
1784
+ function parseSessionListHeader(
1785
+ content: string,
1786
+ entries: Array<Record<string, unknown>>,
1787
+ ): SessionListHeader | undefined {
1788
+ const parsedHeader = entries[0];
1789
+ if (parsedHeader?.type === "session" && typeof parsedHeader.id === "string") {
1790
+ return {
1791
+ type: "session",
1792
+ id: parsedHeader.id,
1793
+ cwd: typeof parsedHeader.cwd === "string" ? parsedHeader.cwd : undefined,
1794
+ title: typeof parsedHeader.title === "string" ? parsedHeader.title : undefined,
1795
+ parentSession: typeof parsedHeader.parentSession === "string" ? parsedHeader.parentSession : undefined,
1796
+ timestamp: typeof parsedHeader.timestamp === "string" ? parsedHeader.timestamp : undefined,
1797
+ };
1798
+ }
1799
+
1800
+ const firstLineEnd = content.indexOf("\n");
1801
+ const firstLine = firstLineEnd === -1 ? content : content.slice(0, firstLineEnd);
1802
+ if (extractStringProperty(firstLine, "type") !== "session") return undefined;
1803
+
1804
+ const id = extractStringProperty(firstLine, "id");
1805
+ if (!id) return undefined;
1806
+
1807
+ return {
1808
+ type: "session",
1809
+ id,
1810
+ cwd: extractStringProperty(firstLine, "cwd"),
1811
+ title: extractStringProperty(firstLine, "title"),
1812
+ parentSession: extractStringProperty(firstLine, "parentSession"),
1813
+ timestamp: extractStringProperty(firstLine, "timestamp"),
1814
+ };
1815
+ }
1816
+
1817
+ function getSessionListWorkerCount(fileCount: number): number {
1818
+ if (fileCount <= SESSION_LIST_PARALLEL_THRESHOLD) return 1;
1819
+ return Math.min(
1820
+ SESSION_LIST_MAX_WORKERS,
1821
+ os.availableParallelism(),
1822
+ Math.ceil(fileCount / SESSION_LIST_PARALLEL_THRESHOLD),
1823
+ );
1824
+ }
1825
+
1826
+ async function collectSessionFromFile(file: string, storage: SessionStorage): Promise<SessionInfo | undefined> {
1827
+ try {
1828
+ const stat = storage.statSync(file);
1829
+ const [content, suffix] = await storage.readTextSlices(
1830
+ file,
1831
+ SESSION_LIST_PREFIX_BYTES,
1832
+ SESSION_LIST_SUFFIX_BYTES,
1833
+ );
1834
+ const { size, mtime } = stat;
1835
+ const entries = parseJsonlLenient<Record<string, unknown>>(content);
1836
+ const header = parseSessionListHeader(content, entries);
1837
+ if (!header) return undefined;
1838
+
1839
+ let parsedMessageCount = 0;
1840
+ let firstMessage = "";
1841
+ const allMessages: string[] = [];
1842
+ let shortSummary: string | undefined;
1843
+
1844
+ for (let i = 1; i < entries.length; i++) {
1845
+ const entry = entries[i] as { type?: string; message?: Message; shortSummary?: string };
1846
+
1847
+ if (entry.type === "compaction" && typeof entry.shortSummary === "string") {
1848
+ shortSummary = entry.shortSummary;
1849
+ }
1850
+
1851
+ if (entry.type === "message" && entry.message) {
1852
+ parsedMessageCount++;
1853
+
1854
+ if (entry.message.role === "user" || entry.message.role === "assistant") {
1855
+ const textContent = extractTextFromContent(entry.message.content);
1856
+
1857
+ if (textContent) {
1858
+ allMessages.push(textContent);
1859
+
1860
+ if (!firstMessage && entry.message.role === "user") {
1861
+ firstMessage = textContent;
1862
+ }
1863
+ }
1864
+ }
1865
+ }
1866
+ }
1867
+
1868
+ firstMessage ||= extractFirstUserMessageFromPrefix(content) ?? "";
1869
+ const messageCount = Math.max(parsedMessageCount, countMessageMarkers(content));
1870
+ return {
1871
+ path: file,
1872
+ id: header.id,
1873
+ cwd: header.cwd ?? "",
1874
+ title: header.title ?? shortSummary,
1875
+ parentSessionPath: header.parentSession,
1876
+ created: new Date(header.timestamp ?? ""),
1877
+ modified: mtime,
1878
+ messageCount,
1879
+ size,
1880
+ firstMessage: firstMessage || "(no messages)",
1881
+ allMessagesText: allMessages.length > 0 ? allMessages.join(" ") : firstMessage,
1882
+ status: deriveSessionStatus(suffix),
1883
+ };
1884
+ } catch {
1885
+ return undefined;
1886
+ }
1887
+ }
1888
+
1889
+ async function collectSessionsFromFileStride(
1890
+ files: string[],
1891
+ storage: SessionStorage,
1892
+ startIndex: number,
1893
+ stride: number,
1894
+ ): Promise<SessionInfo[]> {
1895
+ const sessions: SessionInfo[] = [];
1896
+
1897
+ for (let i = startIndex; i < files.length; i += stride) {
1898
+ const session = await collectSessionFromFile(files[i], storage);
1899
+ if (session) sessions.push(session);
1900
+ }
1901
+
1902
+ return sessions;
1903
+ }
1904
+
1905
+ async function collectSessionsFromFiles(files: string[], storage: SessionStorage): Promise<SessionInfo[]> {
1906
+ const workerCount = getSessionListWorkerCount(files.length);
1907
+ const sessions =
1908
+ workerCount === 1
1909
+ ? await collectSessionsFromFileStride(files, storage, 0, 1)
1910
+ : (
1911
+ await Promise.all(
1912
+ Array.from({ length: workerCount }, (_, workerIndex) =>
1913
+ collectSessionsFromFileStride(files, storage, workerIndex, workerCount),
1914
+ ),
1915
+ )
1916
+ ).flat();
1917
+
1918
+ sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
1919
+ return sessions;
1920
+ }
1921
+
1922
+ export interface ResolvedSessionMatch {
1923
+ session: SessionInfo;
1924
+ scope: "local" | "global";
1925
+ }
1926
+
1927
+ function sessionMatchesResumeArg(session: SessionInfo, sessionArg: string): boolean {
1928
+ const normalizedArg = sessionArg.toLowerCase();
1929
+ const normalizedId = session.id.toLowerCase();
1930
+ if (normalizedId.startsWith(normalizedArg)) {
1931
+ return true;
1932
+ }
1933
+
1934
+ const fileName = path.basename(session.path, ".jsonl").toLowerCase();
1935
+ if (fileName.startsWith(normalizedArg)) {
1936
+ return true;
1937
+ }
1938
+
1939
+ const separator = fileName.lastIndexOf("_");
1940
+ if (separator < 0) {
1941
+ return false;
1942
+ }
1943
+
1944
+ const fileSessionId = fileName.slice(separator + 1);
1945
+ return fileSessionId.startsWith(normalizedArg);
1946
+ }
1947
+
1948
+ export async function resolveResumableSession(
1949
+ sessionArg: string,
1950
+ cwd: string,
1951
+ sessionDir?: string,
1952
+ storage: SessionStorage = new FileSessionStorage(),
1953
+ ): Promise<ResolvedSessionMatch | undefined> {
1954
+ const localSessionDir = sessionDir ?? SessionManager.getDefaultSessionDir(cwd, undefined, storage);
1955
+ const localSessions = await SessionManager.list(cwd, localSessionDir, storage);
1956
+ const localMatch = localSessions.find(session => sessionMatchesResumeArg(session, sessionArg));
1957
+ if (localMatch) {
1958
+ return { session: localMatch, scope: "local" };
1959
+ }
1960
+
1961
+ if (sessionDir) {
1962
+ return undefined;
1963
+ }
1964
+
1965
+ const globalSessions = await SessionManager.listAll(storage);
1966
+ const globalMatch = globalSessions.find(session => sessionMatchesResumeArg(session, sessionArg));
1967
+ if (!globalMatch) {
1968
+ return undefined;
1969
+ }
1970
+
1971
+ return { session: globalMatch, scope: "global" };
1972
+ }
1973
+ interface SessionManagerStateSnapshot {
1974
+ cwd: string;
1975
+ sessionDir: string;
1976
+ sessionId: string;
1977
+ sessionName: string | undefined;
1978
+ titleSource: "auto" | "user" | undefined;
1979
+ sessionFile: string | undefined;
1980
+ flushed: boolean;
1981
+ needsFullRewriteOnNextPersist: boolean;
1982
+ fileEntries: FileEntry[];
1983
+ }
1984
+
1985
+ export class SessionManager {
1986
+ #sessionId: string = "";
1987
+ #sessionName: string | undefined;
1988
+ #titleSource: "auto" | "user" | undefined;
1989
+ #sessionFile: string | undefined;
1990
+ #flushed: boolean = false;
1991
+ #needsFullRewriteOnNextPersist: boolean = false;
1992
+ #ensuredOnDisk: boolean = false;
1993
+ #fileEntries: FileEntry[] = [];
1994
+ #byId: Map<string, SessionEntry> = new Map();
1995
+ #labelsById: Map<string, string> = new Map();
1996
+ #leafId: string | null = null;
1997
+ #usageStatistics = {
1998
+ input: 0,
1999
+ output: 0,
2000
+ cacheRead: 0,
2001
+ cacheWrite: 0,
2002
+ premiumRequests: 0,
2003
+ cost: 0,
2004
+ } satisfies UsageStatistics;
2005
+ /** Per-turn output-token budget set by a `+Nk` directive (total null when none this turn). */
2006
+ #turnBudget: { total: number | null; hard: boolean } = { total: null, hard: false };
2007
+ /** Cumulative `output` snapshot captured when the current turn budget window opened. */
2008
+ #turnBaselineOutput = 0;
2009
+ /** Output tokens consumed by eval-spawned subagents in the current turn window. */
2010
+ #turnEvalOutput = 0;
2011
+ #persistWriter: NdjsonFileWriter | undefined;
2012
+ #persistWriterPath: string | undefined;
2013
+ #persistChain: Promise<void> = Promise.resolve();
2014
+ #persistError: Error | undefined;
2015
+ #persistErrorReported = false;
2016
+ #artifactManager: ArtifactManager | null = null;
2017
+ #artifactManagerSessionFile: string | null = null;
2018
+ // When set, take precedence over the lazily-derived per-session manager.
2019
+ // Subagents adopt the parent's manager so artifact IDs are unique across the
2020
+ // whole agent tree and all files land in the parent's artifacts dir.
2021
+ #adoptedArtifactManager: ArtifactManager | null = null;
2022
+ // In-memory artifact fallback for non-persistent sessions (persist=false).
2023
+ // Keyed by sequential numeric ID string; mirrors the file-based ArtifactManager ID scheme.
2024
+ #inMemoryArtifacts: Map<string, string> | null = null;
2025
+ #inMemoryArtifactCounter = 0;
2026
+ readonly #blobStore: BlobStore;
2027
+ #suppressBreadcrumb = false;
2028
+ #sessionNameChangedCallbacks = new Set<() => void>();
2029
+
2030
+ private constructor(
2031
+ private cwd: string,
2032
+ private sessionDir: string,
2033
+ private readonly persist: boolean,
2034
+ private readonly storage: SessionStorage,
2035
+ ) {
2036
+ this.#blobStore = new BlobStore(getBlobsDir());
2037
+ if (persist && sessionDir) {
2038
+ this.storage.ensureDirSync(sessionDir);
2039
+ }
2040
+ // Note: call _initSession() or _initSessionFile() after construction
2041
+ }
2042
+
2043
+ #maybeWriteBreadcrumb(cwd: string, sessionFile: string): void {
2044
+ if (this.#suppressBreadcrumb) return;
2045
+ writeTerminalBreadcrumb(cwd, sessionFile);
2046
+ }
2047
+
2048
+ /** Puts a binary blob into the blob store and returns the blob reference */
2049
+ async putBlob(data: Buffer, options?: BlobPutOptions): Promise<BlobPutResult> {
2050
+ return this.#blobStore.put(data, options);
2051
+ }
2052
+
2053
+ /** Synchronous variant of {@link putBlob} for rebuild-only render paths. */
2054
+ putBlobSync(data: Buffer, options?: BlobPutOptions): BlobPutResult {
2055
+ return this.#blobStore.putSync(data, options);
2056
+ }
2057
+
2058
+ captureState(): SessionManagerStateSnapshot {
2059
+ return {
2060
+ cwd: this.cwd,
2061
+ sessionDir: this.sessionDir,
2062
+ sessionId: this.#sessionId,
2063
+ sessionName: this.#sessionName,
2064
+ titleSource: this.#titleSource,
2065
+ sessionFile: this.#sessionFile,
2066
+ flushed: this.#flushed,
2067
+ needsFullRewriteOnNextPersist: this.#needsFullRewriteOnNextPersist,
2068
+ // Snapshot entry objects by reference: switch/reload replaces the active entry array,
2069
+ // so rollback does not need structured cloning of extension/custom details.
2070
+ fileEntries: [...this.#fileEntries],
2071
+ };
2072
+ }
2073
+
2074
+ restoreState(snapshot: SessionManagerStateSnapshot): void {
2075
+ this.cwd = snapshot.cwd;
2076
+ this.sessionDir = snapshot.sessionDir;
2077
+ this.#sessionId = snapshot.sessionId;
2078
+ this.#sessionName = snapshot.sessionName;
2079
+ this.#titleSource = snapshot.titleSource;
2080
+ this.#sessionFile = snapshot.sessionFile;
2081
+ this.#flushed = snapshot.flushed;
2082
+ this.#needsFullRewriteOnNextPersist = snapshot.needsFullRewriteOnNextPersist;
2083
+ this.#fileEntries = [...snapshot.fileEntries];
2084
+ this.#persistWriter = undefined;
2085
+ this.#persistWriterPath = undefined;
2086
+ this.#persistChain = Promise.resolve();
2087
+ this.#persistError = undefined;
2088
+ this.#persistErrorReported = false;
2089
+ this.#artifactManager = null;
2090
+ this.#artifactManagerSessionFile = null;
2091
+ this.#adoptedArtifactManager = null;
2092
+ this.#buildIndex();
2093
+ if (this.#sessionFile) {
2094
+ this.#maybeWriteBreadcrumb(this.cwd, this.#sessionFile);
2095
+ }
2096
+ }
2097
+
2098
+ /** Initialize with a specific session file (used by factory methods) */
2099
+ async #initSessionFile(sessionFile: string): Promise<void> {
2100
+ await this.setSessionFile(sessionFile);
2101
+ }
2102
+
2103
+ /** Initialize with a new session (used by factory methods) */
2104
+ #initNewSession(): void {
2105
+ this.#newSessionSync();
2106
+ }
2107
+
2108
+ /** Switch to a different session file (used for resume and branching) */
2109
+ async setSessionFile(sessionFile: string): Promise<void> {
2110
+ await this.#closePersistWriter();
2111
+ this.#persistError = undefined;
2112
+ this.#persistErrorReported = false;
2113
+ this.#sessionFile = path.resolve(sessionFile);
2114
+ this.#maybeWriteBreadcrumb(this.cwd, this.#sessionFile);
2115
+ this.#fileEntries = await loadEntriesFromFile(this.#sessionFile, this.storage);
2116
+ if (this.#fileEntries.length > 0) {
2117
+ const header = this.#fileEntries.find(e => e.type === "session") as SessionHeader | undefined;
2118
+ this.#sessionId = header?.id ?? createSessionId();
2119
+ this.#sessionName = header?.title;
2120
+ this.#titleSource = header?.titleSource;
2121
+
2122
+ // Adopt the loaded session's own working directory. Sessions are stored in
2123
+ // a directory keyed by their cwd, so resuming a session from another
2124
+ // project (e.g. global review in the picker) must re-point cwd/sessionDir
2125
+ // at that project. Same-cwd resumes and in-place reloads are a no-op; old
2126
+ // sessions with no recorded cwd keep the current cwd.
2127
+ const headerCwd = header?.cwd ? path.resolve(header.cwd) : undefined;
2128
+ if (headerCwd && headerCwd !== this.cwd) {
2129
+ this.cwd = headerCwd;
2130
+ this.sessionDir = path.resolve(this.#sessionFile, "..");
2131
+ this.#maybeWriteBreadcrumb(this.cwd, this.#sessionFile);
2132
+ }
2133
+
2134
+ this.#needsFullRewriteOnNextPersist = migrateToCurrentVersion(this.#fileEntries);
2135
+
2136
+ await resolveBlobRefsInEntries(this.#fileEntries, this.#blobStore);
2137
+ this.sanitizeLoadedOpenAIResponsesReplayMetadata();
2138
+
2139
+ this.#buildIndex();
2140
+ this.#flushed = true;
2141
+ this.#ensuredOnDisk = true;
2142
+ } else {
2143
+ const explicitPath = this.#sessionFile;
2144
+ this.#newSessionSync();
2145
+ this.#sessionFile = explicitPath; // preserve explicit path from --session flag
2146
+ await this.#rewriteFile();
2147
+ this.#flushed = true;
2148
+ this.#ensuredOnDisk = true;
2149
+ return;
2150
+ }
2151
+ }
2152
+
2153
+ /** Start a new session. Closes any existing writer first. */
2154
+ async newSession(options?: NewSessionOptions): Promise<string | undefined> {
2155
+ await this.#closePersistWriter();
2156
+ return this.#newSessionSync(options);
2157
+ }
2158
+
2159
+ /** Delete a session file and its artifacts. Drains the persist writer first to avoid EPERM on Windows. ENOENT is treated as success. */
2160
+ async dropSession(sessionPath: string): Promise<void> {
2161
+ await this.#closePersistWriter();
2162
+ try {
2163
+ await this.storage.deleteSessionWithArtifacts(sessionPath);
2164
+ } catch (err) {
2165
+ if (isEnoent(err)) return;
2166
+ throw err;
2167
+ }
2168
+ }
2169
+
2170
+ /**
2171
+ * Fork the current session, creating a new session file with the same entries.
2172
+ * Returns both the old and new session file paths for artifact copying.
2173
+ * @returns { oldSessionFile, newSessionFile } or undefined if not persisting
2174
+ */
2175
+ async fork(): Promise<{ oldSessionFile: string; newSessionFile: string } | undefined> {
2176
+ if (!this.persist || !this.#sessionFile) {
2177
+ return undefined;
2178
+ }
2179
+
2180
+ const oldSessionFile = this.#sessionFile;
2181
+ const oldSessionId = this.#sessionId;
2182
+
2183
+ // Close the current writer
2184
+ await this.#closePersistWriter();
2185
+ this.#persistChain = Promise.resolve();
2186
+ this.#persistError = undefined;
2187
+ this.#persistErrorReported = false;
2188
+
2189
+ // Create new session ID and header
2190
+ this.#sessionId = createSessionId();
2191
+ const timestamp = new Date().toISOString();
2192
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
2193
+ this.#sessionFile = path.join(this.getSessionDir(), `${fileTimestamp}_${this.#sessionId}.jsonl`);
2194
+
2195
+ // Update the header with new ID but keep all entries
2196
+ const oldHeader = this.#fileEntries.find(e => e.type === "session") as SessionHeader | undefined;
2197
+ const newHeader: SessionHeader = {
2198
+ type: "session",
2199
+ version: CURRENT_SESSION_VERSION,
2200
+ id: this.#sessionId,
2201
+ title: oldHeader?.title ?? this.#sessionName,
2202
+ titleSource: oldHeader?.titleSource ?? this.#titleSource,
2203
+ timestamp,
2204
+ cwd: this.cwd,
2205
+ parentSession: oldSessionId,
2206
+ };
2207
+ this.#sessionName = newHeader.title;
2208
+ this.#titleSource = newHeader.titleSource;
2209
+
2210
+ // Replace the header in fileEntries
2211
+ const entries = this.#fileEntries.filter((e): e is SessionEntry => e.type !== "session");
2212
+ this.#fileEntries = [newHeader, ...entries];
2213
+
2214
+ // Write the new session file
2215
+ this.#flushed = false;
2216
+ await this.#rewriteFile();
2217
+
2218
+ return { oldSessionFile, newSessionFile: this.#sessionFile };
2219
+ }
2220
+
2221
+ /**
2222
+ * Move the session to a new working directory.
2223
+ * Moves session files and artifacts on disk, updates all internal references,
2224
+ * and rewrites the session header with the new cwd. When provided,
2225
+ * `targetSessionDir` is used instead of deriving the default directory for
2226
+ * the new cwd (for `--continue --session-dir` / `--resume --session-dir`).
2227
+ */
2228
+ async moveTo(newCwd: string, targetSessionDir?: string): Promise<void> {
2229
+ const resolvedCwd = path.resolve(newCwd);
2230
+ if (resolvedCwd === this.cwd && (!targetSessionDir || path.resolve(targetSessionDir) === this.sessionDir)) return;
2231
+
2232
+ const managedSessionsRoot = resolveManagedSessionRoot(this.sessionDir, this.cwd);
2233
+ const newSessionDir = targetSessionDir
2234
+ ? path.resolve(targetSessionDir)
2235
+ : managedSessionsRoot
2236
+ ? computeDefaultSessionDir(resolvedCwd, this.storage, managedSessionsRoot)
2237
+ : computeDefaultSessionDir(resolvedCwd, this.storage);
2238
+ let hadSessionFile = false;
2239
+
2240
+ if (this.persist && this.#sessionFile) {
2241
+ this.storage.ensureDirSync(newSessionDir);
2242
+ // Close the persist writer before moving files
2243
+ await this.#closePersistWriter();
2244
+ this.#persistChain = Promise.resolve();
2245
+ this.#persistError = undefined;
2246
+ this.#persistErrorReported = false;
2247
+
2248
+ const oldSessionFile = this.#sessionFile;
2249
+ const newSessionFile = path.join(newSessionDir, path.basename(oldSessionFile));
2250
+ const oldArtifactDir = oldSessionFile.slice(0, -6); // strip .jsonl
2251
+ const newArtifactDir = newSessionFile.slice(0, -6);
2252
+ const sameSessionFile = path.resolve(oldSessionFile) === path.resolve(newSessionFile);
2253
+ const sameArtifactDir = path.resolve(oldArtifactDir) === path.resolve(newArtifactDir);
2254
+ hadSessionFile = this.storage.existsSync(oldSessionFile);
2255
+ let movedSessionFile = false;
2256
+ let movedArtifactDir = false;
2257
+
2258
+ try {
2259
+ // Guard: session file may not exist yet (no assistant messages persisted)
2260
+ if (hadSessionFile && !sameSessionFile) {
2261
+ await fs.promises.rename(oldSessionFile, newSessionFile);
2262
+ movedSessionFile = true;
2263
+ }
2264
+
2265
+ if (!sameArtifactDir) {
2266
+ try {
2267
+ const stat = await fs.promises.stat(oldArtifactDir);
2268
+ if (stat.isDirectory()) {
2269
+ await fs.promises.rename(oldArtifactDir, newArtifactDir);
2270
+ movedArtifactDir = true;
2271
+ }
2272
+ } catch (err) {
2273
+ if (!isEnoent(err)) throw err;
2274
+ }
2275
+ }
2276
+ } catch (err) {
2277
+ if (movedArtifactDir) {
2278
+ try {
2279
+ await fs.promises.rename(newArtifactDir, oldArtifactDir);
2280
+ } catch (rollbackErr) {
2281
+ throw new Error(
2282
+ `Failed to move artifacts and rollback: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`,
2283
+ );
2284
+ }
2285
+ }
2286
+ if (movedSessionFile) {
2287
+ try {
2288
+ await fs.promises.rename(newSessionFile, oldSessionFile);
2289
+ } catch (rollbackErr) {
2290
+ throw new Error(
2291
+ `Failed to move session file and rollback: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`,
2292
+ );
2293
+ }
2294
+ }
2295
+ throw err;
2296
+ }
2297
+ this.#sessionFile = newSessionFile;
2298
+ }
2299
+
2300
+ // Update cwd and sessionDir after the move succeeds.
2301
+ this.cwd = resolvedCwd;
2302
+ this.sessionDir = newSessionDir;
2303
+
2304
+ // Update the session header in fileEntries
2305
+ const header = this.#fileEntries.find(e => e.type === "session") as SessionHeader | undefined;
2306
+ if (header) {
2307
+ header.cwd = resolvedCwd;
2308
+ }
2309
+
2310
+ // Rewrite the session file at its new location with updated header.
2311
+ // hadSessionFile: file existed before move → must rewrite to update cwd
2312
+ // hasAssistant: assistant messages in memory but file missing → recreate from memory
2313
+ // Neither true → fresh session, never written → preserve lazy-persist
2314
+ const hasAssistant = this.#fileEntries.some(e => e.type === "message" && e.message.role === "assistant");
2315
+ if (this.persist && this.#sessionFile && (hadSessionFile || hasAssistant)) {
2316
+ await this.#rewriteFile();
2317
+ }
2318
+
2319
+ // Update terminal breadcrumb
2320
+ if (this.#sessionFile) {
2321
+ this.#maybeWriteBreadcrumb(resolvedCwd, this.#sessionFile);
2322
+ }
2323
+ }
2324
+
2325
+ /** Sync version for initial creation (no existing writer to close) */
2326
+ #newSessionSync(options?: NewSessionOptions): string | undefined {
2327
+ this.#persistChain = Promise.resolve();
2328
+ this.#persistError = undefined;
2329
+ this.#persistErrorReported = false;
2330
+ this.#sessionId = createSessionId();
2331
+ this.#sessionName = undefined;
2332
+ this.#titleSource = undefined;
2333
+ const timestamp = new Date().toISOString();
2334
+ const header: SessionHeader = {
2335
+ type: "session",
2336
+ version: CURRENT_SESSION_VERSION,
2337
+ id: this.#sessionId,
2338
+ timestamp,
2339
+ cwd: this.cwd,
2340
+ parentSession: options?.parentSession,
2341
+ };
2342
+ this.#fileEntries = [header];
2343
+ this.#byId.clear();
2344
+ this.#labelsById.clear();
2345
+ this.#leafId = null;
2346
+ this.#flushed = false;
2347
+ this.#needsFullRewriteOnNextPersist = false;
2348
+ this.#ensuredOnDisk = false;
2349
+ this.#usageStatistics = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, premiumRequests: 0, cost: 0 };
2350
+ this.#inMemoryArtifacts = null;
2351
+ this.#inMemoryArtifactCounter = 0;
2352
+
2353
+ if (this.persist) {
2354
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
2355
+ this.#sessionFile = path.join(this.getSessionDir(), `${fileTimestamp}_${this.#sessionId}.jsonl`);
2356
+ this.#maybeWriteBreadcrumb(this.cwd, this.#sessionFile);
2357
+ }
2358
+ return this.#sessionFile;
2359
+ }
2360
+
2361
+ #buildIndex(): void {
2362
+ this.#byId.clear();
2363
+ this.#labelsById.clear();
2364
+ this.#leafId = null;
2365
+ this.#usageStatistics = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, premiumRequests: 0, cost: 0 };
2366
+ for (const entry of this.#fileEntries) {
2367
+ if (entry.type === "session") continue;
2368
+ this.#byId.set(entry.id, entry);
2369
+ this.#leafId = entry.id;
2370
+ if (entry.type === "label") {
2371
+ if (entry.label) {
2372
+ this.#labelsById.set(entry.targetId, entry.label);
2373
+ } else {
2374
+ this.#labelsById.delete(entry.targetId);
2375
+ }
2376
+ }
2377
+ if (entry.type === "message" && entry.message.role === "assistant") {
2378
+ const usage = entry.message.usage;
2379
+ this.#usageStatistics.input += usage.input;
2380
+ this.#usageStatistics.output += usage.output;
2381
+ this.#usageStatistics.cacheRead += usage.cacheRead;
2382
+ this.#usageStatistics.cacheWrite += usage.cacheWrite;
2383
+ this.#usageStatistics.premiumRequests += usage.premiumRequests ?? 0;
2384
+ this.#usageStatistics.cost += usage.cost.total;
2385
+ }
2386
+
2387
+ if (entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolName === "task") {
2388
+ const usage = getTaskToolUsage(entry.message.details);
2389
+ if (usage) {
2390
+ this.#usageStatistics.input += usage.input;
2391
+ this.#usageStatistics.output += usage.output;
2392
+ this.#usageStatistics.cacheRead += usage.cacheRead;
2393
+ this.#usageStatistics.cacheWrite += usage.cacheWrite;
2394
+ this.#usageStatistics.premiumRequests += usage.premiumRequests ?? 0;
2395
+ this.#usageStatistics.cost += usage.cost.total;
2396
+ }
2397
+ }
2398
+ }
2399
+ }
2400
+
2401
+ #recordPersistError(err: unknown): Error {
2402
+ const normalized = toError(err);
2403
+ if (!this.#persistError) this.#persistError = normalized;
2404
+ if (!this.#persistErrorReported) {
2405
+ this.#persistErrorReported = true;
2406
+ logger.error("Session persistence error.", {
2407
+ sessionFile: this.#sessionFile,
2408
+ error: normalized.message,
2409
+ stack: normalized.stack,
2410
+ });
2411
+ }
2412
+ return normalized;
2413
+ }
2414
+
2415
+ #queuePersistTask(task: () => Promise<void>, options?: { ignoreError?: boolean }): Promise<void> {
2416
+ const next = this.#persistChain.then(async () => {
2417
+ if (this.#persistError && !options?.ignoreError) throw this.#persistError;
2418
+ await task();
2419
+ });
2420
+ this.#persistChain = next.catch(err => {
2421
+ this.#recordPersistError(err);
2422
+ });
2423
+ return next;
2424
+ }
2425
+
2426
+ #ensurePersistWriter(): NdjsonFileWriter | undefined {
2427
+ if (!this.persist || !this.#sessionFile) return undefined;
2428
+ if (this.#persistError) throw this.#persistError;
2429
+ if (this.#persistWriter && this.#persistWriterPath === this.#sessionFile) {
2430
+ if (this.#persistWriter.isOpen()) return this.#persistWriter;
2431
+ // Cached writer for the current file is mid-close (queued
2432
+ // `#closePersistWriterInternal` has flipped `#closing` but not yet
2433
+ // cleared `#persistWriter`). Returning it would make `writeSync`
2434
+ // throw "Writer closed". Defer to the caller — `_persist` routes
2435
+ // the entry through the async rewrite path so it still lands on disk.
2436
+ return undefined;
2437
+ }
2438
+ // Note: caller must await _closePersistWriter() before calling this if switching files
2439
+ this.#persistWriter = new NdjsonFileWriter(this.storage, this.#sessionFile, {
2440
+ onError: err => {
2441
+ this.#recordPersistError(err);
2442
+ },
2443
+ });
2444
+ this.#persistWriterPath = this.#sessionFile;
2445
+ return this.#persistWriter;
2446
+ }
2447
+
2448
+ async #closePersistWriterInternal(): Promise<void> {
2449
+ if (this.#persistWriter) {
2450
+ await this.#persistWriter.close();
2451
+ this.#persistWriter = undefined;
2452
+ }
2453
+ this.#persistWriterPath = undefined;
2454
+ }
2455
+
2456
+ async #closePersistWriter(): Promise<void> {
2457
+ await this.#queuePersistTask(
2458
+ async () => {
2459
+ await this.#closePersistWriterInternal();
2460
+ },
2461
+ { ignoreError: true },
2462
+ );
2463
+ }
2464
+ // Windows can reject overwrite-style rename with EPERM even after our own writer is closed.
2465
+ // Move the old session file aside first so a failed retry can roll back to the last good file.
2466
+ // The backup uses a plain `<basename>.<snowflake>.bak` name (no leading dot) so that if the
2467
+ // process crashes between the two renames, `recoverOrphanedBackups` can find it via the
2468
+ // shared `*.bak` glob on both real and in-memory storage backends and promote it back to
2469
+ // the primary on the next session-dir scan.
2470
+
2471
+ async #replaceSessionFileAfterEperm(tempPath: string, targetPath: string, renameError: unknown): Promise<void> {
2472
+ const dir = path.resolve(targetPath, "..");
2473
+ const backupPath = path.join(dir, `${path.basename(targetPath)}.${Snowflake.next()}.bak`);
2474
+ try {
2475
+ await this.storage.rename(targetPath, backupPath);
2476
+ } catch (err) {
2477
+ if (isEnoent(err)) {
2478
+ await this.storage.rename(tempPath, targetPath);
2479
+ return;
2480
+ }
2481
+ throw toError(renameError);
2482
+ }
2483
+
2484
+ try {
2485
+ await this.storage.rename(tempPath, targetPath);
2486
+ } catch (err) {
2487
+ const replaceError = toError(err);
2488
+ const originalError = toError(renameError);
2489
+ try {
2490
+ await this.storage.rename(backupPath, targetPath);
2491
+ } catch (rollbackErr) {
2492
+ const rollbackError = toError(rollbackErr);
2493
+ throw new Error(
2494
+ `Failed to replace session file after EPERM (original: ${originalError.message}; retry: ${replaceError.message}); rollback from ${backupPath} also failed: ${rollbackError.message}`,
2495
+ { cause: originalError },
2496
+ );
2497
+ }
2498
+ throw replaceError;
2499
+ }
2500
+
2501
+ try {
2502
+ await this.storage.unlink(backupPath);
2503
+ } catch (err) {
2504
+ if (!isEnoent(err)) {
2505
+ logger.warn("Failed to remove session rewrite backup", {
2506
+ sessionFile: targetPath,
2507
+ backupPath,
2508
+ error: toError(err).message,
2509
+ });
2510
+ }
2511
+ }
2512
+ }
2513
+
2514
+ async #replaceSessionFile(tempPath: string, targetPath: string): Promise<void> {
2515
+ try {
2516
+ await this.storage.rename(tempPath, targetPath);
2517
+ } catch (err) {
2518
+ if (!hasFsCode(err, "EPERM")) throw toError(err);
2519
+ await this.#replaceSessionFileAfterEperm(tempPath, targetPath, err);
2520
+ }
2521
+ }
2522
+ async #writeEntriesAtomically(entries: FileEntry[]): Promise<void> {
2523
+ if (!this.#sessionFile) return;
2524
+ const dir = path.resolve(this.#sessionFile, "..");
2525
+ const tempPath = path.join(dir, `.${path.basename(this.#sessionFile)}.${Snowflake.next()}.tmp`);
2526
+ const writer = new NdjsonFileWriter(this.storage, tempPath, { flags: "w" });
2527
+ try {
2528
+ for (const entry of entries) {
2529
+ await writer.write(entry);
2530
+ }
2531
+ await writer.flush();
2532
+ await writer.fsync();
2533
+ await writer.close();
2534
+ await this.#replaceSessionFile(tempPath, this.#sessionFile);
2535
+ } catch (err) {
2536
+ try {
2537
+ await writer.close();
2538
+ } catch {
2539
+ // Ignore cleanup errors
2540
+ }
2541
+ try {
2542
+ await this.storage.unlink(tempPath);
2543
+ } catch {
2544
+ // Ignore cleanup errors
2545
+ }
2546
+ throw toError(err);
2547
+ }
2548
+ }
2549
+
2550
+ async #rewriteFile(): Promise<void> {
2551
+ if (!this.persist || !this.#sessionFile) return;
2552
+ await this.#queuePersistTask(async () => {
2553
+ await this.#closePersistWriterInternal();
2554
+ const entries = await Promise.all(
2555
+ this.#fileEntries.map(entry => prepareEntryForPersistence(entry, this.#blobStore)),
2556
+ );
2557
+ await this.#writeEntriesAtomically(entries);
2558
+ this.#needsFullRewriteOnNextPersist = false;
2559
+ this.#flushed = true;
2560
+ });
2561
+ }
2562
+
2563
+ isPersisted(): boolean {
2564
+ return this.persist;
2565
+ }
2566
+
2567
+ /**
2568
+ * Force-persist all current entries to disk, even when no assistant message exists yet.
2569
+ * Used by ACP mode where session/new must create a discoverable session immediately.
2570
+ */
2571
+ async ensureOnDisk(): Promise<void> {
2572
+ if (!this.persist || !this.#sessionFile) return;
2573
+ if (this.#flushed && !this.#needsFullRewriteOnNextPersist) return;
2574
+ await this.#rewriteFile();
2575
+ this.#ensuredOnDisk = true;
2576
+ }
2577
+
2578
+ /** Flush pending writes to disk. Call before switching sessions or on shutdown. */
2579
+ async flush(): Promise<void> {
2580
+ await this.#queuePersistTask(async () => {
2581
+ if (this.#persistWriter) {
2582
+ await this.#persistWriter.flush();
2583
+ await this.#persistWriter.fsync();
2584
+ }
2585
+ });
2586
+ if (this.#persistError) throw this.#persistError;
2587
+ }
2588
+
2589
+ /** Close the persistent writer after flushing all pending data. */
2590
+ async close(): Promise<void> {
2591
+ if (!this.#persistWriter) return;
2592
+ await this.#queuePersistTask(async () => {
2593
+ await this.#closePersistWriterInternal();
2594
+ this.#flushed = true;
2595
+ });
2596
+ if (this.#persistError) throw this.#persistError;
2597
+ }
2598
+
2599
+ getCwd(): string {
2600
+ return this.cwd;
2601
+ }
2602
+
2603
+ /** Get usage statistics across all assistant messages in the session. */
2604
+ getUsageStatistics(): UsageStatistics {
2605
+ return this.#usageStatistics;
2606
+ }
2607
+
2608
+ /**
2609
+ * Open a new per-turn budget window: snapshot the cumulative output baseline,
2610
+ * reset the eval-subagent counter, and set the (optional) ceiling. Called once
2611
+ * per real user message; `total` is null when no `+Nk` directive was present.
2612
+ */
2613
+ beginTurnBudget(total: number | null, hard: boolean): void {
2614
+ this.#turnBudget = { total, hard };
2615
+ this.#turnBaselineOutput = this.#usageStatistics.output;
2616
+ this.#turnEvalOutput = 0;
2617
+ }
2618
+
2619
+ /** Record output tokens consumed by an eval-spawned subagent in the current turn. */
2620
+ recordEvalSubagentOutput(output: number): void {
2621
+ if (Number.isFinite(output) && output > 0) this.#turnEvalOutput += output;
2622
+ }
2623
+
2624
+ /**
2625
+ * Current turn budget for the eval `budget` helper: the ceiling (null = none),
2626
+ * output tokens spent this turn (main loop + eval-spawned subagents, no
2627
+ * double-count), and whether the ceiling is hard.
2628
+ */
2629
+ getTurnBudget(): { total: number | null; spent: number; hard: boolean } {
2630
+ const mainDelta = Math.max(0, this.#usageStatistics.output - this.#turnBaselineOutput);
2631
+ return { total: this.#turnBudget.total, spent: mainDelta + this.#turnEvalOutput, hard: this.#turnBudget.hard };
2632
+ }
2633
+
2634
+ getSessionDir(): string {
2635
+ return this.sessionDir;
2636
+ }
2637
+
2638
+ getSessionId(): string {
2639
+ return this.#sessionId;
2640
+ }
2641
+
2642
+ getSessionFile(): string | undefined {
2643
+ return this.#sessionFile;
2644
+ }
2645
+
2646
+ /**
2647
+ * Returns the session artifacts directory path (session file path without .jsonl).
2648
+ * Returns null when the session is not persisted to a file.
2649
+ * When this session has adopted an external ArtifactManager (subagent case),
2650
+ * returns that manager's directory so reads/writes land in the shared parent
2651
+ * dir instead of a private (non-existent) subdir.
2652
+ */
2653
+ getArtifactsDir(): string | null {
2654
+ if (this.#adoptedArtifactManager) return this.#adoptedArtifactManager.dir;
2655
+ const sessionFile = this.#sessionFile;
2656
+ return sessionFile ? sessionFile.slice(0, -6) : null;
2657
+ }
2658
+
2659
+ /**
2660
+ * Adopt an externally-owned ArtifactManager. Used by subagents to share
2661
+ * the parent session's artifact directory and ID counter.
2662
+ */
2663
+ adoptArtifactManager(manager: ArtifactManager): void {
2664
+ this.#adoptedArtifactManager = manager;
2665
+ }
2666
+
2667
+ /**
2668
+ * Returns the ArtifactManager this session writes through. Lazily creates
2669
+ * one bound to the current session file unless an external manager was
2670
+ * adopted via `adoptArtifactManager`. Returns null only for non-persistent
2671
+ * sessions with no adopted manager.
2672
+ */
2673
+ getArtifactManager(): ArtifactManager | null {
2674
+ return this.#getOrCreateArtifactManager();
2675
+ }
2676
+
2677
+ /**
2678
+ * Returns an artifact manager bound to the current session file.
2679
+ * Recreates the manager when the active session file changes.
2680
+ */
2681
+ #getOrCreateArtifactManager(): ArtifactManager | null {
2682
+ if (this.#adoptedArtifactManager) return this.#adoptedArtifactManager;
2683
+ const sessionFile = this.#sessionFile;
2684
+ if (!sessionFile) {
2685
+ this.#artifactManager = null;
2686
+ this.#artifactManagerSessionFile = null;
2687
+ return null;
2688
+ }
2689
+
2690
+ if (this.#artifactManager && this.#artifactManagerSessionFile === sessionFile) {
2691
+ return this.#artifactManager;
2692
+ }
2693
+
2694
+ const manager = new ArtifactManager(sessionFile.slice(0, -6));
2695
+ this.#artifactManager = manager;
2696
+ this.#artifactManagerSessionFile = sessionFile;
2697
+ return manager;
2698
+ }
2699
+
2700
+ /**
2701
+ * Allocate a new artifact path and ID for the current session.
2702
+ * Returns an empty object when the session is not persisted.
2703
+ */
2704
+ async allocateArtifactPath(toolType: string): Promise<{ id?: string; path?: string }> {
2705
+ const manager = this.#getOrCreateArtifactManager();
2706
+ if (!manager) return {};
2707
+ return manager.allocatePath(toolType);
2708
+ }
2709
+
2710
+ /**
2711
+ * Save artifact content under the current session and return artifact ID.
2712
+ * Returns an artifact ID for all sessions (file-backed for persistent, in-memory fallback otherwise).
2713
+ */
2714
+ async saveArtifact(content: string, toolType: string): Promise<string | undefined> {
2715
+ const manager = this.#getOrCreateArtifactManager();
2716
+ if (manager) return manager.save(content, toolType);
2717
+ // Non-persistent session: store in memory so spill truncation can proceed.
2718
+ if (!this.#inMemoryArtifacts) this.#inMemoryArtifacts = new Map();
2719
+ const id = String(this.#inMemoryArtifactCounter++);
2720
+ this.#inMemoryArtifacts.set(id, content);
2721
+ return id;
2722
+ }
2723
+
2724
+ /**
2725
+ * Resolve an artifact ID to an on-disk path for the current session.
2726
+ * Returns null when missing or when the session is not persisted.
2727
+ */
2728
+ async getArtifactPath(id: string): Promise<string | null> {
2729
+ const manager = this.#getOrCreateArtifactManager();
2730
+ if (!manager) return null;
2731
+ return manager.getPath(id);
2732
+ }
2733
+
2734
+ /**
2735
+ * Path to the unsent-input draft sidecar for the current session. Lives inside
2736
+ * the artifacts directory so it is removed together with the session on
2737
+ * `dropSession`. Returns null when the session has no on-disk identity.
2738
+ */
2739
+ #getDraftPath(): string | null {
2740
+ const dir = this.getArtifactsDir();
2741
+ return dir ? path.join(dir, "draft.txt") : null;
2742
+ }
2743
+
2744
+ /**
2745
+ * Persist (or clear) the current editor draft so the next resume of this
2746
+ * session can restore it. Empty text deletes any stale draft. No-op when the
2747
+ * session is not persisted.
2748
+ */
2749
+ async saveDraft(text: string): Promise<void> {
2750
+ const draftPath = this.#getDraftPath();
2751
+ if (!draftPath || !this.persist) return;
2752
+ if (text.length === 0) {
2753
+ try {
2754
+ await this.storage.unlink(draftPath);
2755
+ } catch (err) {
2756
+ if (!isEnoent(err)) throw err;
2757
+ }
2758
+ return;
2759
+ }
2760
+ // Force the session header onto disk so resume can find the file we are
2761
+ // attaching this draft to. Without this, a session whose first message
2762
+ // never produced an assistant reply would persist a draft next to a
2763
+ // session file that does not exist on disk.
2764
+ await this.ensureOnDisk();
2765
+ await this.storage.writeText(draftPath, text);
2766
+ }
2767
+
2768
+ /**
2769
+ * Read and remove the saved draft. Returns the previously-saved text, or
2770
+ * null when no draft is pending. Single-shot: a successful read removes the
2771
+ * sidecar so a subsequent resume does not re-restore the same text.
2772
+ */
2773
+ async consumeDraft(): Promise<string | null> {
2774
+ const draftPath = this.#getDraftPath();
2775
+ if (!draftPath) return null;
2776
+ let text: string;
2777
+ try {
2778
+ text = await this.storage.readText(draftPath);
2779
+ } catch (err) {
2780
+ if (isEnoent(err)) return null;
2781
+ throw err;
2782
+ }
2783
+ try {
2784
+ await this.storage.unlink(draftPath);
2785
+ } catch (err) {
2786
+ if (!isEnoent(err)) throw err;
2787
+ }
2788
+ return text;
2789
+ }
2790
+
2791
+ /** The source that set the session name: "user" (manual /rename or RPC) or "auto" (generated title). */
2792
+ get titleSource(): "auto" | "user" | undefined {
2793
+ return this.#titleSource;
2794
+ }
2795
+
2796
+ getSessionName(): string | undefined {
2797
+ return this.#sessionName;
2798
+ }
2799
+
2800
+ onSessionNameChanged(cb: () => void): () => void {
2801
+ this.#sessionNameChangedCallbacks.add(cb);
2802
+ return () => {
2803
+ this.#sessionNameChangedCallbacks.delete(cb);
2804
+ };
2805
+ }
2806
+
2807
+ #fireSessionNameChanged(): void {
2808
+ for (const cb of [...this.#sessionNameChangedCallbacks]) {
2809
+ try {
2810
+ cb();
2811
+ } catch (err) {
2812
+ logger.warn("SessionManager: session name change hook failed", { error: String(err) });
2813
+ }
2814
+ }
2815
+ }
2816
+
2817
+ /** Strip C0/C1 control characters (includes ESC, so removes ANSI sequences) and collapse whitespace. */
2818
+ static #sanitizeName(name: string): string {
2819
+ return name
2820
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, " ")
2821
+ .replace(/ +/g, " ")
2822
+ .trim();
2823
+ }
2824
+
2825
+ /**
2826
+ * Set the session display name.
2827
+ * @param source - "user" for explicit renames (/rename command, RPC); "auto" for generated titles.
2828
+ * Auto-generated titles are silently ignored when the user has already set a name.
2829
+ */
2830
+ async setSessionName(name: string, source: "auto" | "user" = "auto"): Promise<boolean> {
2831
+ // User-set names take permanent precedence over auto-generated ones.
2832
+ if (this.#titleSource === "user" && source === "auto") return false;
2833
+
2834
+ const sanitized = SessionManager.#sanitizeName(name);
2835
+ if (!sanitized) return false;
2836
+
2837
+ this.#sessionName = sanitized;
2838
+ this.#titleSource = source;
2839
+
2840
+ // Update the in-memory header (so first flush includes title)
2841
+ const header = this.#fileEntries.find(e => e.type === "session") as SessionHeader | undefined;
2842
+ if (header) {
2843
+ header.title = sanitized;
2844
+ header.titleSource = source;
2845
+ }
2846
+
2847
+ // Update the session file header with the title (if already flushed)
2848
+ const sessionFile = this.#sessionFile;
2849
+ if (this.persist && sessionFile && this.storage.existsSync(sessionFile)) {
2850
+ await this.#rewriteFile();
2851
+ }
2852
+ this.#fireSessionNameChanged();
2853
+ return true;
2854
+ }
2855
+
2856
+ _persist(entry: SessionEntry): void {
2857
+ if (!this.persist || !this.#sessionFile) return;
2858
+ if (this.#persistError) throw this.#persistError;
2859
+
2860
+ // Normally we wait for the first assistant message before persisting to avoid
2861
+ // creating files for sessions that never produce output. Once ensureOnDisk() has
2862
+ // been called, the session is already on disk and every entry must be flushed.
2863
+ if (!this.#ensuredOnDisk) {
2864
+ const hasAssistant = this.#fileEntries.some(e => e.type === "message" && e.message.role === "assistant");
2865
+ if (!hasAssistant) {
2866
+ // Mark as not flushed so when assistant arrives, all entries get written.
2867
+ this.#flushed = false;
2868
+ return;
2869
+ }
2870
+ }
2871
+
2872
+ if (this.#needsFullRewriteOnNextPersist || !this.#flushed) {
2873
+ // Cold path: rewrite the whole file atomically. Async — the writer is
2874
+ // closed/reopened and every entry is re-prepared. Errors flow through
2875
+ // `#persistChain` → `#recordPersistError`; we swallow the rejection
2876
+ // here to avoid an unhandled rejection when the persist dir races with
2877
+ // test-level tempDir cleanup.
2878
+ this.#rewriteFile().catch(() => {});
2879
+ return;
2880
+ }
2881
+
2882
+ // Hot path: synchronously truncate + append. `fs.writeSync` returns once the
2883
+ // bytes are in the kernel page cache, so the entry survives an OOM/SIGKILL
2884
+ // landing immediately after this call. Image externalization (rare) runs via
2885
+ // the synchronous blob-store path so blob bytes are durable before the JSONL
2886
+ // line referencing them is written.
2887
+ try {
2888
+ const writer = this.#ensurePersistWriter();
2889
+ if (!writer) {
2890
+ // `#ensurePersistWriter` returns undefined here only when the cached
2891
+ // writer is mid-close (the `!persist`/`!sessionFile` cases are
2892
+ // rejected above). Route through `#rewriteFile` so the entry — which
2893
+ // is already in `#fileEntries` — persists once the close drains.
2894
+ this.#rewriteFile().catch(() => {});
2895
+ return;
2896
+ }
2897
+ const persistedEntry = prepareEntryForPersistenceSync(entry, this.#blobStore);
2898
+ writer.writeSync(persistedEntry);
2899
+ } catch (err) {
2900
+ this.#recordPersistError(err);
2901
+ }
2902
+ }
2903
+
2904
+ #appendEntry(entry: SessionEntry): void {
2905
+ this.#fileEntries.push(entry);
2906
+ this.#byId.set(entry.id, entry);
2907
+ this.#leafId = entry.id;
2908
+ this._persist(entry);
2909
+ if (entry.type === "message" && entry.message.role === "assistant") {
2910
+ const usage = entry.message.usage;
2911
+ this.#usageStatistics.input += usage.input;
2912
+ this.#usageStatistics.output += usage.output;
2913
+ this.#usageStatistics.cacheRead += usage.cacheRead;
2914
+ this.#usageStatistics.cacheWrite += usage.cacheWrite;
2915
+ this.#usageStatistics.premiumRequests += usage.premiumRequests ?? 0;
2916
+ this.#usageStatistics.cost += usage.cost.total;
2917
+ }
2918
+
2919
+ if (entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolName === "task") {
2920
+ const usage = getTaskToolUsage(entry.message.details);
2921
+ if (usage) {
2922
+ this.#usageStatistics.input += usage.input;
2923
+ this.#usageStatistics.output += usage.output;
2924
+ this.#usageStatistics.cacheRead += usage.cacheRead;
2925
+ this.#usageStatistics.cacheWrite += usage.cacheWrite;
2926
+ this.#usageStatistics.premiumRequests += usage.premiumRequests ?? 0;
2927
+ this.#usageStatistics.cost += usage.cost.total;
2928
+ }
2929
+ }
2930
+ }
2931
+
2932
+ /** Append a message as child of current leaf, then advance leaf. Returns entry id.
2933
+ * Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly.
2934
+ * Reason: we want these to be top-level entries in the session, not message session entries,
2935
+ * so it is easier to find them.
2936
+ * These need to be appended via appendCompaction() and appendBranchSummary() methods.
2937
+ */
2938
+ appendMessage(
2939
+ message:
2940
+ | Message
2941
+ | CustomMessage
2942
+ | HookMessage
2943
+ | BashExecutionMessage
2944
+ | PythonExecutionMessage
2945
+ | FileMentionMessage,
2946
+ ): string {
2947
+ const entry: SessionMessageEntry = {
2948
+ type: "message",
2949
+ id: generateId(this.#byId),
2950
+ parentId: this.#leafId,
2951
+ timestamp: new Date().toISOString(),
2952
+ message,
2953
+ };
2954
+ this.#appendEntry(entry);
2955
+ return entry.id;
2956
+ }
2957
+
2958
+ /** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */
2959
+ appendThinkingLevelChange(thinkingLevel?: string): string {
2960
+ const entry: ThinkingLevelChangeEntry = {
2961
+ type: "thinking_level_change",
2962
+ id: generateId(this.#byId),
2963
+ parentId: this.#leafId,
2964
+ timestamp: new Date().toISOString(),
2965
+ thinkingLevel: thinkingLevel ?? null,
2966
+ };
2967
+ this.#appendEntry(entry);
2968
+ return entry.id;
2969
+ }
2970
+
2971
+ appendServiceTierChange(serviceTier: ServiceTier | null): string {
2972
+ const entry: ServiceTierChangeEntry = {
2973
+ type: "service_tier_change",
2974
+ id: generateId(this.#byId),
2975
+ parentId: this.#leafId,
2976
+ timestamp: new Date().toISOString(),
2977
+ serviceTier,
2978
+ };
2979
+ this.#appendEntry(entry);
2980
+ return entry.id;
2981
+ }
2982
+
2983
+ /** Append a mode change as child of current leaf, then advance leaf. Returns entry id. */
2984
+ appendModeChange(mode: string, data?: Record<string, unknown>): string {
2985
+ const entry: ModeChangeEntry = {
2986
+ type: "mode_change",
2987
+ id: generateId(this.#byId),
2988
+ parentId: this.#leafId,
2989
+ timestamp: new Date().toISOString(),
2990
+ mode,
2991
+ data,
2992
+ };
2993
+ this.#appendEntry(entry);
2994
+ return entry.id;
2995
+ }
2996
+
2997
+ /**
2998
+ * Append a model change as child of current leaf, then advance leaf. Returns entry id.
2999
+ * @param model Model in "provider/modelId" format
3000
+ * @param role Optional role (default: "default")
3001
+ */
3002
+ appendModelChange(model: string, role?: string): string {
3003
+ const entry: ModelChangeEntry = {
3004
+ type: "model_change",
3005
+ id: generateId(this.#byId),
3006
+ parentId: this.#leafId,
3007
+ timestamp: new Date().toISOString(),
3008
+ model,
3009
+ role,
3010
+ };
3011
+ this.#appendEntry(entry);
3012
+ return entry.id;
3013
+ }
3014
+
3015
+ /** Append session init metadata (for subagent debugging/replay). Returns entry id. */
3016
+ appendSessionInit(init: { systemPrompt: string; task: string; tools: string[]; outputSchema?: unknown }): string {
3017
+ const entry: SessionInitEntry = {
3018
+ type: "session_init",
3019
+ id: generateId(this.#byId),
3020
+ parentId: this.#leafId,
3021
+ timestamp: new Date().toISOString(),
3022
+ ...init,
3023
+ };
3024
+ this.#appendEntry(entry);
3025
+ return entry.id;
3026
+ }
3027
+
3028
+ /** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */
3029
+ appendCompaction<T = unknown>(
3030
+ summary: string,
3031
+ shortSummary: string | undefined,
3032
+ firstKeptEntryId: string,
3033
+ tokensBefore: number,
3034
+ details?: T,
3035
+ fromExtension?: boolean,
3036
+ preserveData?: Record<string, unknown>,
3037
+ ): string {
3038
+ const entry: CompactionEntry<T> = {
3039
+ type: "compaction",
3040
+ id: generateId(this.#byId),
3041
+ parentId: this.#leafId,
3042
+ timestamp: new Date().toISOString(),
3043
+ summary,
3044
+ shortSummary,
3045
+ firstKeptEntryId,
3046
+ tokensBefore,
3047
+ details,
3048
+ fromExtension,
3049
+ preserveData,
3050
+ };
3051
+ this.#appendEntry(entry);
3052
+ return entry.id;
3053
+ }
3054
+
3055
+ /** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */
3056
+ appendCustomEntry(customType: string, data?: unknown): string {
3057
+ const entry: CustomEntry = {
3058
+ type: "custom",
3059
+ customType,
3060
+ data,
3061
+ id: generateId(this.#byId),
3062
+ parentId: this.#leafId,
3063
+ timestamp: new Date().toISOString(),
3064
+ };
3065
+ this.#appendEntry(entry);
3066
+ return entry.id;
3067
+ }
3068
+
3069
+ /**
3070
+ * Rewrite the session file after in-place entry updates.
3071
+ * Use sparingly (e.g., pruning old tool outputs).
3072
+ */
3073
+ async rewriteEntries(): Promise<void> {
3074
+ if (!this.persist || !this.#sessionFile) return;
3075
+ await this.#rewriteFile();
3076
+ }
3077
+
3078
+ /**
3079
+ * Append a custom message entry (for extensions) that participates in LLM context.
3080
+ * @param customType Hook identifier for filtering on reload
3081
+ * @param content Message content (string or TextContent/ImageContent array)
3082
+ * @param display Whether to show in TUI (true = styled display, false = hidden)
3083
+ * @param details Optional extension-specific metadata (not sent to LLM)
3084
+ * @param attribution Who initiated this message for billing/attribution semantics
3085
+ * @returns Entry id
3086
+ */
3087
+ appendCustomMessageEntry<T = unknown>(
3088
+ customType: string,
3089
+ content: string | (TextContent | ImageContent)[],
3090
+ display: boolean,
3091
+ details?: T,
3092
+ attribution: MessageAttribution = "agent",
3093
+ ): string {
3094
+ const entry: CustomMessageEntry<T> = {
3095
+ type: "custom_message",
3096
+ customType,
3097
+ content,
3098
+ display,
3099
+ // Drop AgentSession-internal transient fields (allowlist in
3100
+ // `INTERNAL_DETAILS_FIELDS`) before disk persistence. Single
3101
+ // chokepoint covers every CustomMessage write path.
3102
+ details: stripInternalDetailsFields(details),
3103
+ attribution,
3104
+ id: generateId(this.#byId),
3105
+ parentId: this.#leafId,
3106
+ timestamp: new Date().toISOString(),
3107
+ };
3108
+ this.#appendEntry(entry);
3109
+ return entry.id;
3110
+ }
3111
+
3112
+ // =========================================================================
3113
+ // TTSR (Time Traveling Stream Rules)
3114
+ // =========================================================================
3115
+
3116
+ /**
3117
+ * Append an MCP tool selection entry recording the discovery-selected MCP tools.
3118
+ * @param selectedToolNames MCP tool names selected for this branch
3119
+ * @returns Entry id
3120
+ */
3121
+ appendMCPToolSelection(selectedToolNames: string[]): string {
3122
+ const entry: MCPToolSelectionEntry = {
3123
+ type: "mcp_tool_selection",
3124
+ id: generateId(this.#byId),
3125
+ parentId: this.#leafId,
3126
+ timestamp: new Date().toISOString(),
3127
+ selectedToolNames: [...selectedToolNames],
3128
+ };
3129
+ this.#appendEntry(entry);
3130
+ return entry.id;
3131
+ }
3132
+
3133
+ /**
3134
+ * Append a TTSR injection entry recording which rules were injected.
3135
+ * @param ruleNames Names of rules that were injected
3136
+ * @returns Entry id
3137
+ */
3138
+ appendTtsrInjection(ruleNames: string[]): string {
3139
+ const entry: TtsrInjectionEntry = {
3140
+ type: "ttsr_injection",
3141
+ id: generateId(this.#byId),
3142
+ parentId: this.#leafId,
3143
+ timestamp: new Date().toISOString(),
3144
+ injectedRules: ruleNames,
3145
+ };
3146
+ this.#appendEntry(entry);
3147
+ return entry.id;
3148
+ }
3149
+
3150
+ /**
3151
+ * Get all unique TTSR rule names that have been injected in the current branch.
3152
+ * Scans from root to current leaf for ttsr_injection entries.
3153
+ */
3154
+ getInjectedTtsrRules(): string[] {
3155
+ const path = this.getBranch();
3156
+ const ruleNames = new Set<string>();
3157
+ for (const entry of path) {
3158
+ if (entry.type === "ttsr_injection") {
3159
+ for (const name of entry.injectedRules) {
3160
+ ruleNames.add(name);
3161
+ }
3162
+ }
3163
+ }
3164
+ return Array.from(ruleNames);
3165
+ }
3166
+
3167
+ // =========================================================================
3168
+ // Tree Traversal
3169
+ // =========================================================================
3170
+
3171
+ getLeafId(): string | null {
3172
+ return this.#leafId;
3173
+ }
3174
+
3175
+ getLeafEntry(): SessionEntry | undefined {
3176
+ return this.#leafId ? this.#byId.get(this.#leafId) : undefined;
3177
+ }
3178
+
3179
+ /**
3180
+ * Get the most recent model role from the current session path.
3181
+ * Returns undefined if no model change has been recorded.
3182
+ */
3183
+ getLastModelChangeRole(): string | undefined {
3184
+ let current = this.getLeafEntry();
3185
+ while (current) {
3186
+ if (current.type === "model_change") {
3187
+ return current.role ?? "default";
3188
+ }
3189
+ current = current.parentId ? this.#byId.get(current.parentId) : undefined;
3190
+ }
3191
+ return undefined;
3192
+ }
3193
+
3194
+ getEntry(id: string): SessionEntry | undefined {
3195
+ return this.#byId.get(id);
3196
+ }
3197
+
3198
+ /**
3199
+ * Get all direct children of an entry.
3200
+ */
3201
+ getChildren(parentId: string): SessionEntry[] {
3202
+ const children: SessionEntry[] = [];
3203
+ for (const entry of this.#byId.values()) {
3204
+ if (entry.parentId === parentId) {
3205
+ children.push(entry);
3206
+ }
3207
+ }
3208
+ return children;
3209
+ }
3210
+
3211
+ /**
3212
+ * Get the label for an entry, if any.
3213
+ */
3214
+ getLabel(id: string): string | undefined {
3215
+ return this.#labelsById.get(id);
3216
+ }
3217
+
3218
+ /**
3219
+ * Set or clear a label on an entry.
3220
+ * Labels are user-defined markers for bookmarking/navigation.
3221
+ * Pass undefined or empty string to clear the label.
3222
+ */
3223
+ appendLabelChange(targetId: string, label: string | undefined): string {
3224
+ if (!this.#byId.has(targetId)) {
3225
+ throw new Error(`Entry ${targetId} not found`);
3226
+ }
3227
+ const entry: LabelEntry = {
3228
+ type: "label",
3229
+ id: generateId(this.#byId),
3230
+ parentId: this.#leafId,
3231
+ timestamp: new Date().toISOString(),
3232
+ targetId,
3233
+ label,
3234
+ };
3235
+ this.#appendEntry(entry);
3236
+ if (label) {
3237
+ this.#labelsById.set(targetId, label);
3238
+ } else {
3239
+ this.#labelsById.delete(targetId);
3240
+ }
3241
+ return entry.id;
3242
+ }
3243
+
3244
+ /**
3245
+ * Walk from entry to root, returning all entries in path order.
3246
+ * Includes all entry types (messages, compaction, model changes, etc.).
3247
+ * Use buildSessionContext() to get the resolved messages for the LLM.
3248
+ */
3249
+ getBranch(fromId?: string): SessionEntry[] {
3250
+ const path: SessionEntry[] = [];
3251
+ const startId = fromId ?? this.#leafId;
3252
+ let current = startId ? this.#byId.get(startId) : undefined;
3253
+ while (current) {
3254
+ path.unshift(current);
3255
+ current = current.parentId ? this.#byId.get(current.parentId) : undefined;
3256
+ }
3257
+ return path;
3258
+ }
3259
+
3260
+ /**
3261
+ * Build the session context (what gets sent to the LLM), or — with
3262
+ * `{ transcript: true }` — the full-history display transcript.
3263
+ * Uses tree traversal from current leaf.
3264
+ */
3265
+ buildSessionContext(options?: BuildSessionContextOptions): SessionContext {
3266
+ return buildSessionContext(this.getEntries(), this.#leafId, this.#byId, options);
3267
+ }
3268
+
3269
+ /** Strip stale OpenAI Responses assistant replay metadata from loaded in-memory entries. */
3270
+ sanitizeLoadedOpenAIResponsesReplayMetadata(): boolean {
3271
+ let didSanitize = false;
3272
+ for (const entry of this.#fileEntries) {
3273
+ if (entry.type !== "message" || entry.message.role !== "assistant") {
3274
+ continue;
3275
+ }
3276
+
3277
+ const sanitizedMessage = sanitizeRehydratedOpenAIResponsesAssistantMessage(entry.message);
3278
+ if (sanitizedMessage === entry.message) {
3279
+ continue;
3280
+ }
3281
+
3282
+ entry.message = sanitizedMessage;
3283
+ didSanitize = true;
3284
+ }
3285
+
3286
+ return didSanitize;
3287
+ }
3288
+
3289
+ /**
3290
+ * Get session header.
3291
+ */
3292
+ getHeader(): SessionHeader | null {
3293
+ const h = this.#fileEntries.find(e => e.type === "session");
3294
+ return h ? (h as SessionHeader) : null;
3295
+ }
3296
+
3297
+ /**
3298
+ * Get all session entries (excludes header). Returns a shallow copy.
3299
+ * The session is append-only: use appendXXX() to add entries, branch() to
3300
+ * change the leaf pointer. Entries cannot be modified or deleted.
3301
+ */
3302
+ getEntries(): SessionEntry[] {
3303
+ return this.#fileEntries.filter((e): e is SessionEntry => e.type !== "session");
3304
+ }
3305
+
3306
+ /**
3307
+ * Get the session as a tree structure. Returns a shallow defensive copy of all entries.
3308
+ * A well-formed session has exactly one root (first entry with parentId === null).
3309
+ * Orphaned entries (broken parent chain) are also returned as roots.
3310
+ */
3311
+ getTree(): SessionTreeNode[] {
3312
+ const entries = this.getEntries();
3313
+ const nodeMap = new Map<string, SessionTreeNode>();
3314
+ const roots: SessionTreeNode[] = [];
3315
+
3316
+ // Create nodes with resolved labels
3317
+ for (const entry of entries) {
3318
+ const label = this.#labelsById.get(entry.id);
3319
+ nodeMap.set(entry.id, { entry, children: [], label });
3320
+ }
3321
+
3322
+ // Build tree
3323
+ for (const entry of entries) {
3324
+ const node = nodeMap.get(entry.id)!;
3325
+ if (entry.parentId === null || entry.parentId === entry.id) {
3326
+ roots.push(node);
3327
+ } else {
3328
+ const parent = nodeMap.get(entry.parentId);
3329
+ if (parent) {
3330
+ parent.children.push(node);
3331
+ } else {
3332
+ // Orphan - treat as root
3333
+ roots.push(node);
3334
+ }
3335
+ }
3336
+ }
3337
+
3338
+ // Sort children by timestamp (oldest first, newest at bottom)
3339
+ // Use iterative approach to avoid stack overflow on deep trees
3340
+ const stack: SessionTreeNode[] = [...roots];
3341
+ while (stack.length > 0) {
3342
+ const node = stack.pop()!;
3343
+ node.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());
3344
+ stack.push(...node.children);
3345
+ }
3346
+
3347
+ return roots;
3348
+ }
3349
+
3350
+ // =========================================================================
3351
+ // Branching
3352
+ // =========================================================================
3353
+
3354
+ /**
3355
+ * Start a new branch from an earlier entry.
3356
+ * Moves the leaf pointer to the specified entry. The next appendXXX() call
3357
+ * will create a child of that entry, forming a new branch. Existing entries
3358
+ * are not modified or deleted.
3359
+ */
3360
+ branch(branchFromId: string): void {
3361
+ if (!this.#byId.has(branchFromId)) {
3362
+ throw new Error(`Entry ${branchFromId} not found`);
3363
+ }
3364
+ this.#leafId = branchFromId;
3365
+ }
3366
+
3367
+ /**
3368
+ * Reset the leaf pointer to null (before any entries).
3369
+ * The next appendXXX() call will create a new root entry (parentId = null).
3370
+ * Use this when navigating to re-edit the first user message.
3371
+ */
3372
+ resetLeaf(): void {
3373
+ this.#leafId = null;
3374
+ }
3375
+
3376
+ /**
3377
+ * Start a new branch with a summary of the abandoned path.
3378
+ * Same as branch(), but also appends a branch_summary entry that captures
3379
+ * context from the abandoned conversation path.
3380
+ */
3381
+ branchWithSummary(branchFromId: string | null, summary: string, details?: unknown, fromExtension?: boolean): string {
3382
+ if (branchFromId !== null && !this.#byId.has(branchFromId)) {
3383
+ throw new Error(`Entry ${branchFromId} not found`);
3384
+ }
3385
+ this.#leafId = branchFromId;
3386
+ const entry: BranchSummaryEntry = {
3387
+ type: "branch_summary",
3388
+ id: generateId(this.#byId),
3389
+ parentId: branchFromId,
3390
+ timestamp: new Date().toISOString(),
3391
+ fromId: branchFromId ?? "root",
3392
+ summary,
3393
+ details,
3394
+ fromExtension,
3395
+ };
3396
+ this.#appendEntry(entry);
3397
+ return entry.id;
3398
+ }
3399
+
3400
+ /**
3401
+ * Create a new session file containing only the path from root to the specified leaf.
3402
+ * Useful for extracting a single conversation path from a branched session.
3403
+ * Returns the new session file path, or undefined if not persisting.
3404
+ */
3405
+ createBranchedSession(leafId: string): string | undefined {
3406
+ const previousSessionFile = this.#sessionFile;
3407
+ const branchPath = this.getBranch(leafId);
3408
+ if (branchPath.length === 0) {
3409
+ throw new Error(`Entry ${leafId} not found`);
3410
+ }
3411
+
3412
+ // Filter out LabelEntry from path - we'll recreate them from the resolved map
3413
+ const pathWithoutLabels = branchPath.filter(e => e.type !== "label");
3414
+
3415
+ const newSessionId = createSessionId();
3416
+ const timestamp = new Date().toISOString();
3417
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
3418
+ const newSessionFile = path.join(this.getSessionDir(), `${fileTimestamp}_${newSessionId}.jsonl`);
3419
+
3420
+ const header: SessionHeader = {
3421
+ type: "session",
3422
+ version: CURRENT_SESSION_VERSION,
3423
+ id: newSessionId,
3424
+ timestamp,
3425
+ cwd: this.cwd,
3426
+ parentSession: this.persist ? previousSessionFile : undefined,
3427
+ };
3428
+
3429
+ // Collect labels for entries in the path
3430
+ const pathEntryIds = new Set(pathWithoutLabels.map(e => e.id));
3431
+ const labelsToWrite: Array<{ targetId: string; label: string }> = [];
3432
+ for (const [targetId, label] of this.#labelsById) {
3433
+ if (pathEntryIds.has(targetId)) {
3434
+ labelsToWrite.push({ targetId, label });
3435
+ }
3436
+ }
3437
+
3438
+ if (this.persist) {
3439
+ const lines: string[] = [];
3440
+ lines.push(JSON.stringify(header));
3441
+ for (const entry of pathWithoutLabels) {
3442
+ lines.push(JSON.stringify(entry));
3443
+ }
3444
+ // Write fresh label entries at the end
3445
+ const lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
3446
+ let parentId = lastEntryId;
3447
+ const labelEntries: LabelEntry[] = [];
3448
+ for (const { targetId, label } of labelsToWrite) {
3449
+ const labelEntry: LabelEntry = {
3450
+ type: "label",
3451
+ id: generateId(new Set(pathEntryIds)),
3452
+ parentId,
3453
+ timestamp: new Date().toISOString(),
3454
+ targetId,
3455
+ label,
3456
+ };
3457
+ lines.push(JSON.stringify(labelEntry));
3458
+ pathEntryIds.add(labelEntry.id);
3459
+ labelEntries.push(labelEntry);
3460
+ parentId = labelEntry.id;
3461
+ }
3462
+ this.storage.writeTextSync(newSessionFile, `${lines.join("\n")}\n`);
3463
+ this.#fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
3464
+ this.#sessionId = newSessionId;
3465
+ this.#sessionFile = newSessionFile;
3466
+ this.#flushed = true;
3467
+ this.#buildIndex();
3468
+ return newSessionFile;
3469
+ }
3470
+
3471
+ // In-memory mode: replace current session with the path + labels
3472
+ const labelEntries: LabelEntry[] = [];
3473
+ let parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
3474
+ for (const { targetId, label } of labelsToWrite) {
3475
+ const labelEntry: LabelEntry = {
3476
+ type: "label",
3477
+ id: generateId(new Set([...pathEntryIds, ...labelEntries.map(e => e.id)])),
3478
+ parentId,
3479
+ timestamp: new Date().toISOString(),
3480
+ targetId,
3481
+ label,
3482
+ };
3483
+ labelEntries.push(labelEntry);
3484
+ parentId = labelEntry.id;
3485
+ }
3486
+ this.#fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
3487
+ this.#sessionId = newSessionId;
3488
+ this.#buildIndex();
3489
+ return undefined;
3490
+ }
3491
+
3492
+ /**
3493
+ * Resolve the canonical default session directory for a cwd.
3494
+ */
3495
+ static getDefaultSessionDir(
3496
+ cwd: string,
3497
+ agentDir?: string,
3498
+ storage: SessionStorage = new FileSessionStorage(),
3499
+ ): string {
3500
+ return computeDefaultSessionDir(cwd, storage, getSessionsDir(agentDir));
3501
+ }
3502
+
3503
+ /**
3504
+ * Create a new session.
3505
+ * @param cwd Working directory (stored in session header)
3506
+ * @param sessionDir Optional session directory. If omitted, uses default (~/.omp/agent/sessions/<encoded-cwd>/).
3507
+ */
3508
+ static create(cwd: string, sessionDir?: string, storage: SessionStorage = new FileSessionStorage()): SessionManager {
3509
+ const dir = sessionDir ?? SessionManager.getDefaultSessionDir(cwd, undefined, storage);
3510
+ const manager = new SessionManager(cwd, dir, true, storage);
3511
+ manager.#initNewSession();
3512
+ return manager;
3513
+ }
3514
+
3515
+ /**
3516
+ * Fork a session into the current project directory.
3517
+ * Copies history from another session file while creating a new session file in the current sessionDir.
3518
+ */
3519
+ static async forkFrom(
3520
+ sourcePath: string,
3521
+ cwd: string,
3522
+ sessionDir?: string,
3523
+ storage: SessionStorage = new FileSessionStorage(),
3524
+ options?: { suppressBreadcrumb?: boolean },
3525
+ ): Promise<SessionManager> {
3526
+ const dir = sessionDir ?? SessionManager.getDefaultSessionDir(cwd, undefined, storage);
3527
+ const manager = new SessionManager(cwd, dir, true, storage);
3528
+ manager.#suppressBreadcrumb = options?.suppressBreadcrumb === true;
3529
+ const forkEntries = structuredClone(await loadEntriesFromFile(sourcePath, storage)) as FileEntry[];
3530
+ migrateToCurrentVersion(forkEntries);
3531
+ await resolveBlobRefsInEntries(forkEntries, manager.#blobStore);
3532
+ const sourceHeader = forkEntries.find(e => e.type === "session") as SessionHeader | undefined;
3533
+ const historyEntries = forkEntries.filter(entry => entry.type !== "session") as SessionEntry[];
3534
+ manager.#newSessionSync({ parentSession: sourceHeader?.id });
3535
+ const newHeader = manager.#fileEntries[0] as SessionHeader;
3536
+ newHeader.title = sourceHeader?.title;
3537
+ newHeader.titleSource = sourceHeader?.titleSource;
3538
+ manager.#fileEntries = [newHeader, ...historyEntries];
3539
+ manager.#sessionName = newHeader.title;
3540
+ manager.#titleSource = newHeader.titleSource;
3541
+ manager.sanitizeLoadedOpenAIResponsesReplayMetadata();
3542
+ manager.#buildIndex();
3543
+ await manager.#rewriteFile();
3544
+ return manager;
3545
+ }
3546
+
3547
+ /**
3548
+ * Open a specific session file.
3549
+ * @param path Path to session file
3550
+ * @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent.
3551
+ */
3552
+ static async open(
3553
+ filePath: string,
3554
+ sessionDir?: string,
3555
+ storage: SessionStorage = new FileSessionStorage(),
3556
+ ): Promise<SessionManager> {
3557
+ // Extract cwd from session header if possible, otherwise use getProjectDir()
3558
+ const entries = await loadEntriesFromFile(filePath, storage);
3559
+ const header = entries.find(e => e.type === "session") as SessionHeader | undefined;
3560
+ const cwd = header?.cwd ?? getProjectDir();
3561
+ // If no sessionDir provided, derive from file's parent directory
3562
+ const dir = sessionDir ?? path.resolve(filePath, "..");
3563
+ const manager = new SessionManager(cwd, dir, true, storage);
3564
+ await manager.#initSessionFile(filePath);
3565
+ return manager;
3566
+ }
3567
+
3568
+ /**
3569
+ * Continue the most recent session, or create new if none.
3570
+ * @param cwd Working directory
3571
+ * @param sessionDir Optional session directory. If omitted, uses default (~/.omp/agent/sessions/<encoded-cwd>/).
3572
+ */
3573
+ static async continueRecent(
3574
+ cwd: string,
3575
+ sessionDir?: string,
3576
+ storage: SessionStorage = new FileSessionStorage(),
3577
+ ): Promise<SessionManager> {
3578
+ const dir = sessionDir ?? SessionManager.getDefaultSessionDir(cwd, undefined, storage);
3579
+ // Prefer terminal-scoped breadcrumb (handles concurrent sessions correctly)
3580
+ const breadcrumb = await readTerminalBreadcrumbEntry();
3581
+ const breadcrumbCwd = breadcrumb ? path.resolve(breadcrumb.cwd) : undefined;
3582
+ const resolvedCwd = path.resolve(cwd);
3583
+ let mostRecent: string | null | undefined;
3584
+ if (breadcrumb && breadcrumbCwd !== resolvedCwd) {
3585
+ // The terminal's last session was started in a different cwd. If that cwd no
3586
+ // longer exists (e.g. `git worktree move`/dir rename) and the new location has
3587
+ // no sessions of its own, re-root the session here instead of silently starting
3588
+ // fresh — otherwise the relocated session would be unreachable via --continue.
3589
+ // When an explicit sessionDir is reused across the move, the stale breadcrumb
3590
+ // file itself may be the most recent entry there; don't count it as a
3591
+ // current-directory session. If that shared dir also contains an older session
3592
+ // that already belongs to the current cwd, prefer that local session instead
3593
+ // of re-rooting the stale breadcrumb over it.
3594
+ const resolvedBreadcrumbCwd = path.resolve(breadcrumb.cwd);
3595
+ mostRecent = await findMostRecentSession(dir, storage);
3596
+ const sourceCwdGone = !fs.existsSync(resolvedBreadcrumbCwd);
3597
+ const breadcrumbSessionFile = path.resolve(breadcrumb.sessionFile);
3598
+ const mostRecentIsBreadcrumb =
3599
+ mostRecent !== null && mostRecent !== undefined && path.resolve(mostRecent) === breadcrumbSessionFile;
3600
+ let hasCurrentCwdSession = false;
3601
+ if (sourceCwdGone && mostRecentIsBreadcrumb) {
3602
+ const currentCwdSession = (await SessionManager.list(cwd, dir, storage)).find(
3603
+ session =>
3604
+ path.resolve(session.path) !== breadcrumbSessionFile &&
3605
+ session.cwd &&
3606
+ path.resolve(session.cwd) === resolvedCwd,
3607
+ );
3608
+ if (currentCwdSession) {
3609
+ mostRecent = currentCwdSession.path;
3610
+ hasCurrentCwdSession = true;
3611
+ }
3612
+ }
3613
+ const relocated = sourceCwdGone && (mostRecent === null || (mostRecentIsBreadcrumb && !hasCurrentCwdSession));
3614
+ if (relocated) {
3615
+ logger.info("Re-rooting moved session", { from: resolvedBreadcrumbCwd, to: resolvedCwd });
3616
+ const manager = await SessionManager.open(breadcrumb.sessionFile, undefined, storage);
3617
+ await manager.moveTo(cwd, sessionDir);
3618
+ return manager;
3619
+ }
3620
+ }
3621
+ const terminalSession = breadcrumb && breadcrumbCwd === resolvedCwd ? breadcrumb.sessionFile : null;
3622
+ if (mostRecent === undefined) mostRecent = terminalSession ?? (await findMostRecentSession(dir, storage));
3623
+ const manager = new SessionManager(cwd, dir, true, storage);
3624
+ if (mostRecent) {
3625
+ await manager.#initSessionFile(mostRecent);
3626
+ } else {
3627
+ manager.#initNewSession();
3628
+ }
3629
+ return manager;
3630
+ }
3631
+
3632
+ /** Create an in-memory session (no file persistence) */
3633
+ static inMemory(
3634
+ cwd: string = getProjectDir(),
3635
+ storage: SessionStorage = new MemorySessionStorage(),
3636
+ ): SessionManager {
3637
+ const manager = new SessionManager(cwd, "", false, storage);
3638
+ manager.#initNewSession();
3639
+ return manager;
3640
+ }
3641
+
3642
+ /**
3643
+ * List all sessions.
3644
+ * @param cwd Working directory (used to compute default session directory)
3645
+ * @param sessionDir Optional session directory. If omitted, uses default (~/.omp/agent/sessions/<encoded-cwd>/).
3646
+ */
3647
+ static async list(
3648
+ cwd: string,
3649
+ sessionDir?: string,
3650
+ storage: SessionStorage = new FileSessionStorage(),
3651
+ ): Promise<SessionInfo[]> {
3652
+ const dir = sessionDir ?? SessionManager.getDefaultSessionDir(cwd, undefined, storage);
3653
+ try {
3654
+ await recoverOrphanedBackups(dir, storage);
3655
+ const files = storage.listFilesSync(dir, "*.jsonl");
3656
+ return await collectSessionsFromFiles(files, storage);
3657
+ } catch {
3658
+ return [];
3659
+ }
3660
+ }
3661
+
3662
+ /**
3663
+ * List all sessions across all project directories.
3664
+ */
3665
+ static async listAll(storage: SessionStorage = new FileSessionStorage()): Promise<SessionInfo[]> {
3666
+ const sessionsRoot = path.join(getDefaultAgentDir(), "sessions");
3667
+ try {
3668
+ const files = await Array.fromAsync(new Bun.Glob("*/*.jsonl").scan(sessionsRoot), name =>
3669
+ path.join(sessionsRoot, name),
3670
+ );
3671
+ return await collectSessionsFromFiles(files, storage);
3672
+ } catch {
3673
+ return [];
3674
+ }
3675
+ }
3676
+ }