@f5-sales-demo/xcsh 19.51.2

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 (899) hide show
  1. package/CHANGELOG.md +7073 -0
  2. package/README.md +14 -0
  3. package/examples/README.md +21 -0
  4. package/examples/custom-tools/README.md +109 -0
  5. package/examples/custom-tools/hello/index.ts +20 -0
  6. package/examples/custom-tools/todo/index.ts +206 -0
  7. package/examples/extensions/README.md +143 -0
  8. package/examples/extensions/api-demo.ts +89 -0
  9. package/examples/extensions/chalk-logger.ts +25 -0
  10. package/examples/extensions/hello.ts +32 -0
  11. package/examples/extensions/pirate.ts +43 -0
  12. package/examples/extensions/plan-mode.ts +551 -0
  13. package/examples/extensions/reload-runtime.ts +37 -0
  14. package/examples/extensions/todo.ts +296 -0
  15. package/examples/extensions/tools.ts +145 -0
  16. package/examples/extensions/with-deps/index.ts +36 -0
  17. package/examples/extensions/with-deps/package-lock.json +31 -0
  18. package/examples/extensions/with-deps/package.json +16 -0
  19. package/examples/hooks/README.md +56 -0
  20. package/examples/hooks/auto-commit-on-exit.ts +48 -0
  21. package/examples/hooks/confirm-destructive.ts +58 -0
  22. package/examples/hooks/custom-compaction.ts +115 -0
  23. package/examples/hooks/dirty-repo-guard.ts +51 -0
  24. package/examples/hooks/file-trigger.ts +40 -0
  25. package/examples/hooks/git-checkpoint.ts +52 -0
  26. package/examples/hooks/handoff.ts +149 -0
  27. package/examples/hooks/permission-gate.ts +33 -0
  28. package/examples/hooks/protected-paths.ts +29 -0
  29. package/examples/hooks/qna.ts +118 -0
  30. package/examples/hooks/status-line.ts +39 -0
  31. package/examples/sdk/01-minimal.ts +21 -0
  32. package/examples/sdk/02-custom-model.ts +49 -0
  33. package/examples/sdk/03-custom-prompt.ts +43 -0
  34. package/examples/sdk/04-skills.ts +43 -0
  35. package/examples/sdk/06-extensions.ts +80 -0
  36. package/examples/sdk/06-hooks.ts +61 -0
  37. package/examples/sdk/07-context-files.ts +35 -0
  38. package/examples/sdk/08-prompt-templates.ts +41 -0
  39. package/examples/sdk/08-slash-commands.ts +46 -0
  40. package/examples/sdk/09-api-keys-and-oauth.ts +54 -0
  41. package/examples/sdk/11-sessions.ts +47 -0
  42. package/examples/sdk/README.md +172 -0
  43. package/package.json +539 -0
  44. package/scripts/build-info/resolvers.ts +51 -0
  45. package/scripts/capture-ax-fixture.ts +84 -0
  46. package/scripts/capture-login-fixture.ts +30 -0
  47. package/scripts/check-workflow-field-coverage.ts +101 -0
  48. package/scripts/extension-uat-harness.ts +340 -0
  49. package/scripts/format-prompts.ts +68 -0
  50. package/scripts/generate-api-spec-index.ts +580 -0
  51. package/scripts/generate-branding-index.ts +81 -0
  52. package/scripts/generate-build-info.ts +106 -0
  53. package/scripts/generate-console-catalog.ts +88 -0
  54. package/scripts/generate-console-field-metadata.ts +74 -0
  55. package/scripts/generate-docs-index.ts +40 -0
  56. package/scripts/generate-template.ts +32 -0
  57. package/scripts/generate-terraform-index.ts +81 -0
  58. package/scripts/mermaid-gallery.ts +132 -0
  59. package/scripts/uat-matrix-modalities.ts +451 -0
  60. package/scripts/uat-matrix-report.ts +175 -0
  61. package/scripts/uat-matrix.ts +353 -0
  62. package/src/async/index.ts +2 -0
  63. package/src/async/job-manager.ts +416 -0
  64. package/src/async/support.ts +5 -0
  65. package/src/autoresearch/apply-contract-to-state.ts +1 -0
  66. package/src/autoresearch/command-resume.md +17 -0
  67. package/src/autoresearch/contract.ts +205 -0
  68. package/src/autoresearch/dashboard.ts +374 -0
  69. package/src/autoresearch/git.ts +191 -0
  70. package/src/autoresearch/helpers.ts +328 -0
  71. package/src/autoresearch/index.ts +402 -0
  72. package/src/autoresearch/prompt.md +236 -0
  73. package/src/autoresearch/resume-message.md +16 -0
  74. package/src/autoresearch/state.ts +303 -0
  75. package/src/autoresearch/tools/init-experiment.ts +400 -0
  76. package/src/autoresearch/tools/log-experiment.ts +793 -0
  77. package/src/autoresearch/tools/run-experiment.ts +679 -0
  78. package/src/autoresearch/types.ts +114 -0
  79. package/src/browser/acquire.ts +249 -0
  80. package/src/browser/actions.ts +126 -0
  81. package/src/browser/auth.ts +176 -0
  82. package/src/browser/ax.ts +134 -0
  83. package/src/browser/cdp-core.ts +45 -0
  84. package/src/browser/cdp-page-actions.ts +51 -0
  85. package/src/browser/chrome-locate.ts +66 -0
  86. package/src/browser/dom-context.ts +89 -0
  87. package/src/browser/dt-context.ts +100 -0
  88. package/src/browser/extension-bridge.ts +182 -0
  89. package/src/browser/extension-page-actions.ts +397 -0
  90. package/src/browser/extension-provider.ts +373 -0
  91. package/src/browser/index.ts +17 -0
  92. package/src/browser/input-commit.ts +74 -0
  93. package/src/browser/native-messaging.ts +20 -0
  94. package/src/browser/page-actions.ts +18 -0
  95. package/src/browser/provider.ts +155 -0
  96. package/src/browser/resolver.ts +126 -0
  97. package/src/browser/selector.ts +40 -0
  98. package/src/bun-imports.d.ts +22 -0
  99. package/src/capability/context-file.ts +43 -0
  100. package/src/capability/extension-module.ts +34 -0
  101. package/src/capability/extension.ts +47 -0
  102. package/src/capability/fs.ts +107 -0
  103. package/src/capability/hook.ts +40 -0
  104. package/src/capability/index.ts +438 -0
  105. package/src/capability/instruction.ts +37 -0
  106. package/src/capability/mcp.ts +74 -0
  107. package/src/capability/prompt.ts +35 -0
  108. package/src/capability/rule.ts +224 -0
  109. package/src/capability/settings.ts +34 -0
  110. package/src/capability/skill.ts +50 -0
  111. package/src/capability/slash-command.ts +40 -0
  112. package/src/capability/ssh.ts +41 -0
  113. package/src/capability/system-prompt.ts +34 -0
  114. package/src/capability/tool.ts +38 -0
  115. package/src/capability/types.ts +168 -0
  116. package/src/cli/agents-cli.ts +138 -0
  117. package/src/cli/args.ts +286 -0
  118. package/src/cli/chrome-cli.ts +88 -0
  119. package/src/cli/classify-install-target.ts +50 -0
  120. package/src/cli/commands/init-xdg.ts +27 -0
  121. package/src/cli/config-cli.ts +418 -0
  122. package/src/cli/file-processor.ts +121 -0
  123. package/src/cli/grep-cli.ts +160 -0
  124. package/src/cli/grievances-cli.ts +78 -0
  125. package/src/cli/initial-message.ts +58 -0
  126. package/src/cli/jupyter-cli.ts +106 -0
  127. package/src/cli/list-models.ts +128 -0
  128. package/src/cli/plugin-cli.ts +964 -0
  129. package/src/cli/read-cli.ts +68 -0
  130. package/src/cli/session-picker.ts +52 -0
  131. package/src/cli/setup-cli.ts +479 -0
  132. package/src/cli/shell-cli.ts +174 -0
  133. package/src/cli/ssh-cli.ts +179 -0
  134. package/src/cli/stats-cli.ts +182 -0
  135. package/src/cli/update-cli.ts +446 -0
  136. package/src/cli/web-search-cli.ts +203 -0
  137. package/src/cli.ts +123 -0
  138. package/src/commands/agents.ts +57 -0
  139. package/src/commands/chrome-host.ts +71 -0
  140. package/src/commands/chrome.ts +28 -0
  141. package/src/commands/commit.ts +36 -0
  142. package/src/commands/config.ts +51 -0
  143. package/src/commands/grep.ts +48 -0
  144. package/src/commands/grievances.ts +20 -0
  145. package/src/commands/jupyter.ts +32 -0
  146. package/src/commands/launch.ts +144 -0
  147. package/src/commands/plugin.ts +78 -0
  148. package/src/commands/read.ts +33 -0
  149. package/src/commands/setup.ts +42 -0
  150. package/src/commands/shell.ts +29 -0
  151. package/src/commands/ssh.ts +60 -0
  152. package/src/commands/stats.ts +29 -0
  153. package/src/commands/update.ts +21 -0
  154. package/src/commands/web-search.ts +46 -0
  155. package/src/commit/agentic/agent.ts +314 -0
  156. package/src/commit/agentic/fallback.ts +96 -0
  157. package/src/commit/agentic/index.ts +354 -0
  158. package/src/commit/agentic/prompts/analyze-file.md +22 -0
  159. package/src/commit/agentic/prompts/session-user.md +25 -0
  160. package/src/commit/agentic/prompts/split-confirm.md +1 -0
  161. package/src/commit/agentic/prompts/system.md +38 -0
  162. package/src/commit/agentic/state.ts +60 -0
  163. package/src/commit/agentic/tools/analyze-file.ts +127 -0
  164. package/src/commit/agentic/tools/git-file-diff.ts +191 -0
  165. package/src/commit/agentic/tools/git-hunk.ts +50 -0
  166. package/src/commit/agentic/tools/git-overview.ts +81 -0
  167. package/src/commit/agentic/tools/index.ts +54 -0
  168. package/src/commit/agentic/tools/propose-changelog.ts +139 -0
  169. package/src/commit/agentic/tools/propose-commit.ts +122 -0
  170. package/src/commit/agentic/tools/recent-commits.ts +81 -0
  171. package/src/commit/agentic/tools/schemas.ts +31 -0
  172. package/src/commit/agentic/tools/split-commit.ts +251 -0
  173. package/src/commit/agentic/topo-sort.ts +44 -0
  174. package/src/commit/agentic/trivial.ts +51 -0
  175. package/src/commit/agentic/validation.ts +183 -0
  176. package/src/commit/analysis/conventional.ts +122 -0
  177. package/src/commit/analysis/index.ts +4 -0
  178. package/src/commit/analysis/scope.ts +242 -0
  179. package/src/commit/analysis/summary.ts +105 -0
  180. package/src/commit/analysis/validation.ts +66 -0
  181. package/src/commit/changelog/detect.ts +40 -0
  182. package/src/commit/changelog/generate.ts +101 -0
  183. package/src/commit/changelog/index.ts +234 -0
  184. package/src/commit/changelog/parse.ts +44 -0
  185. package/src/commit/cli.ts +85 -0
  186. package/src/commit/git/diff.ts +148 -0
  187. package/src/commit/index.ts +5 -0
  188. package/src/commit/map-reduce/index.ts +69 -0
  189. package/src/commit/map-reduce/map-phase.ts +193 -0
  190. package/src/commit/map-reduce/reduce-phase.ts +108 -0
  191. package/src/commit/map-reduce/utils.ts +9 -0
  192. package/src/commit/message.ts +11 -0
  193. package/src/commit/model-selection.ts +66 -0
  194. package/src/commit/pipeline.ts +242 -0
  195. package/src/commit/prompts/analysis-system.md +148 -0
  196. package/src/commit/prompts/analysis-user.md +38 -0
  197. package/src/commit/prompts/changelog-system.md +50 -0
  198. package/src/commit/prompts/changelog-user.md +18 -0
  199. package/src/commit/prompts/file-observer-system.md +24 -0
  200. package/src/commit/prompts/file-observer-user.md +8 -0
  201. package/src/commit/prompts/reduce-system.md +50 -0
  202. package/src/commit/prompts/reduce-user.md +17 -0
  203. package/src/commit/prompts/summary-retry.md +3 -0
  204. package/src/commit/prompts/summary-system.md +38 -0
  205. package/src/commit/prompts/summary-user.md +13 -0
  206. package/src/commit/prompts/types-description.md +2 -0
  207. package/src/commit/types.ts +118 -0
  208. package/src/commit/utils/exclusions.ts +42 -0
  209. package/src/commit/utils.ts +44 -0
  210. package/src/config/auto-config.ts +698 -0
  211. package/src/config/context-schema.json +115 -0
  212. package/src/config/file-lock.ts +121 -0
  213. package/src/config/keybindings.ts +493 -0
  214. package/src/config/mcp-schema.json +230 -0
  215. package/src/config/model-equivalence.ts +675 -0
  216. package/src/config/model-registry.ts +2265 -0
  217. package/src/config/model-resolver.ts +1289 -0
  218. package/src/config/prompt-templates.ts +271 -0
  219. package/src/config/resolve-config-value.ts +110 -0
  220. package/src/config/settings-schema.ts +2155 -0
  221. package/src/config/settings.ts +730 -0
  222. package/src/config.ts +418 -0
  223. package/src/cursor.ts +323 -0
  224. package/src/dap/client.ts +674 -0
  225. package/src/dap/config.ts +150 -0
  226. package/src/dap/defaults.json +211 -0
  227. package/src/dap/index.ts +4 -0
  228. package/src/dap/session.ts +1255 -0
  229. package/src/dap/types.ts +600 -0
  230. package/src/debug/index.ts +440 -0
  231. package/src/debug/log-formatting.ts +58 -0
  232. package/src/debug/log-viewer.ts +908 -0
  233. package/src/debug/profiler.ts +158 -0
  234. package/src/debug/report-bundle.ts +365 -0
  235. package/src/debug/system-info.ts +107 -0
  236. package/src/discovery/agents-md.ts +67 -0
  237. package/src/discovery/agents.ts +219 -0
  238. package/src/discovery/builtin.ts +851 -0
  239. package/src/discovery/claude-plugins.ts +297 -0
  240. package/src/discovery/claude.ts +543 -0
  241. package/src/discovery/cline.ts +83 -0
  242. package/src/discovery/codex.ts +535 -0
  243. package/src/discovery/cursor.ts +220 -0
  244. package/src/discovery/gemini.ts +396 -0
  245. package/src/discovery/github.ts +118 -0
  246. package/src/discovery/helpers.ts +934 -0
  247. package/src/discovery/index.ts +79 -0
  248. package/src/discovery/language.ts +46 -0
  249. package/src/discovery/mcp-json.ts +171 -0
  250. package/src/discovery/opencode.ts +393 -0
  251. package/src/discovery/plugin-dir-roots.ts +28 -0
  252. package/src/discovery/ssh.ts +153 -0
  253. package/src/discovery/substitute-plugin-root.ts +29 -0
  254. package/src/discovery/vscode.ts +105 -0
  255. package/src/discovery/windsurf.ts +147 -0
  256. package/src/edit/diff.ts +818 -0
  257. package/src/edit/index.ts +481 -0
  258. package/src/edit/line-hash.ts +67 -0
  259. package/src/edit/modes/chunk.ts +762 -0
  260. package/src/edit/modes/hashline.ts +1366 -0
  261. package/src/edit/modes/patch.ts +1791 -0
  262. package/src/edit/modes/replace.ts +1115 -0
  263. package/src/edit/normalize.ts +375 -0
  264. package/src/edit/renderer.ts +627 -0
  265. package/src/exa/factory.ts +61 -0
  266. package/src/exa/index.ts +27 -0
  267. package/src/exa/mcp-client.ts +293 -0
  268. package/src/exa/render.ts +232 -0
  269. package/src/exa/researcher.ts +47 -0
  270. package/src/exa/search.ts +86 -0
  271. package/src/exa/types.ts +166 -0
  272. package/src/exa/websets.ts +247 -0
  273. package/src/exec/bash-executor.ts +332 -0
  274. package/src/exec/exec.ts +53 -0
  275. package/src/exec/idle-timeout-watchdog.ts +126 -0
  276. package/src/exec/non-interactive-env.ts +48 -0
  277. package/src/export/custom-share.ts +65 -0
  278. package/src/export/html/index.ts +161 -0
  279. package/src/export/html/template.css +1001 -0
  280. package/src/export/html/template.generated.ts +2 -0
  281. package/src/export/html/template.html +46 -0
  282. package/src/export/html/template.js +1950 -0
  283. package/src/export/html/template.macro.ts +24 -0
  284. package/src/export/html/vendor/highlight.min.js +1213 -0
  285. package/src/export/html/vendor/marked.min.js +6 -0
  286. package/src/export/ttsr.ts +434 -0
  287. package/src/extensibility/custom-commands/bundled/ci-green/index.ts +25 -0
  288. package/src/extensibility/custom-commands/bundled/review/index.ts +456 -0
  289. package/src/extensibility/custom-commands/index.ts +2 -0
  290. package/src/extensibility/custom-commands/loader.ts +236 -0
  291. package/src/extensibility/custom-commands/types.ts +111 -0
  292. package/src/extensibility/custom-tools/index.ts +7 -0
  293. package/src/extensibility/custom-tools/loader.ts +238 -0
  294. package/src/extensibility/custom-tools/types.ts +251 -0
  295. package/src/extensibility/custom-tools/wrapper.ts +47 -0
  296. package/src/extensibility/extensions/index.ts +15 -0
  297. package/src/extensibility/extensions/loader.ts +572 -0
  298. package/src/extensibility/extensions/runner.ts +848 -0
  299. package/src/extensibility/extensions/types.ts +1394 -0
  300. package/src/extensibility/extensions/wrapper.ts +191 -0
  301. package/src/extensibility/hooks/index.ts +5 -0
  302. package/src/extensibility/hooks/loader.ts +255 -0
  303. package/src/extensibility/hooks/runner.ts +425 -0
  304. package/src/extensibility/hooks/tool-wrapper.ts +108 -0
  305. package/src/extensibility/hooks/types.ts +826 -0
  306. package/src/extensibility/plugins/doctor.ts +66 -0
  307. package/src/extensibility/plugins/git-url.ts +281 -0
  308. package/src/extensibility/plugins/index.ts +9 -0
  309. package/src/extensibility/plugins/installer.ts +192 -0
  310. package/src/extensibility/plugins/loader.ts +267 -0
  311. package/src/extensibility/plugins/manager.ts +731 -0
  312. package/src/extensibility/plugins/marketplace/cache.ts +136 -0
  313. package/src/extensibility/plugins/marketplace/fetcher.ts +318 -0
  314. package/src/extensibility/plugins/marketplace/index.ts +6 -0
  315. package/src/extensibility/plugins/marketplace/manager.ts +781 -0
  316. package/src/extensibility/plugins/marketplace/prerequisites.ts +255 -0
  317. package/src/extensibility/plugins/marketplace/registry.ts +196 -0
  318. package/src/extensibility/plugins/marketplace/source-resolver.ts +147 -0
  319. package/src/extensibility/plugins/marketplace/types.ts +201 -0
  320. package/src/extensibility/plugins/parser.ts +105 -0
  321. package/src/extensibility/plugins/types.ts +194 -0
  322. package/src/extensibility/skills.ts +269 -0
  323. package/src/extensibility/slash-commands.ts +246 -0
  324. package/src/extensibility/tool-proxy.ts +25 -0
  325. package/src/extensibility/utils.ts +38 -0
  326. package/src/index.ts +61 -0
  327. package/src/internal-urls/agent-protocol.ts +136 -0
  328. package/src/internal-urls/api-catalog-resolve.ts +495 -0
  329. package/src/internal-urls/api-catalog-types.ts +94 -0
  330. package/src/internal-urls/api-spec-resolve.ts +1036 -0
  331. package/src/internal-urls/api-spec-types.ts +239 -0
  332. package/src/internal-urls/artifact-protocol.ts +97 -0
  333. package/src/internal-urls/branding-index.generated.ts +88 -0
  334. package/src/internal-urls/build-info-runtime.ts +302 -0
  335. package/src/internal-urls/build-info.generated.ts +33 -0
  336. package/src/internal-urls/computer-profile.ts +692 -0
  337. package/src/internal-urls/console-catalog-types.ts +21 -0
  338. package/src/internal-urls/console-catalog.generated.ts +532 -0
  339. package/src/internal-urls/console-field-metadata-types.ts +59 -0
  340. package/src/internal-urls/console-field-metadata.generated.ts +4841 -0
  341. package/src/internal-urls/console-resolve.ts +178 -0
  342. package/src/internal-urls/docs-index.generated.ts +698 -0
  343. package/src/internal-urls/extension-api.md +147 -0
  344. package/src/internal-urls/index.ts +46 -0
  345. package/src/internal-urls/jobs-protocol.ts +119 -0
  346. package/src/internal-urls/json-query.ts +126 -0
  347. package/src/internal-urls/local-protocol.ts +206 -0
  348. package/src/internal-urls/mcp-protocol.ts +156 -0
  349. package/src/internal-urls/memory-protocol.ts +133 -0
  350. package/src/internal-urls/parse.ts +72 -0
  351. package/src/internal-urls/profile-collectors.ts +106 -0
  352. package/src/internal-urls/router.ts +55 -0
  353. package/src/internal-urls/rule-protocol.ts +55 -0
  354. package/src/internal-urls/skill-protocol.ts +111 -0
  355. package/src/internal-urls/terraform-index.generated.ts +1852 -0
  356. package/src/internal-urls/terraform-resolve.ts +184 -0
  357. package/src/internal-urls/terraform-types.ts +45 -0
  358. package/src/internal-urls/types.ts +52 -0
  359. package/src/internal-urls/user-profile.ts +363 -0
  360. package/src/internal-urls/xcsh-protocol.ts +644 -0
  361. package/src/ipy/cancellation.ts +28 -0
  362. package/src/ipy/executor.ts +1155 -0
  363. package/src/ipy/gateway-coordinator.ts +424 -0
  364. package/src/ipy/kernel.ts +1091 -0
  365. package/src/ipy/modules.ts +144 -0
  366. package/src/ipy/prelude.py +849 -0
  367. package/src/ipy/prelude.ts +3 -0
  368. package/src/ipy/runtime.ts +221 -0
  369. package/src/locales/ar.json +512 -0
  370. package/src/locales/de.json +512 -0
  371. package/src/locales/en.json +549 -0
  372. package/src/locales/es.json +512 -0
  373. package/src/locales/fr.json +512 -0
  374. package/src/locales/hi.json +512 -0
  375. package/src/locales/index.ts +29 -0
  376. package/src/locales/it.json +512 -0
  377. package/src/locales/ja.json +512 -0
  378. package/src/locales/ko.json +512 -0
  379. package/src/locales/pt-br.json +512 -0
  380. package/src/locales/th.json +512 -0
  381. package/src/locales/zh-cn.json +512 -0
  382. package/src/locales/zh-tw.json +512 -0
  383. package/src/lsp/client.ts +941 -0
  384. package/src/lsp/clients/biome-client.ts +202 -0
  385. package/src/lsp/clients/index.ts +50 -0
  386. package/src/lsp/clients/lsp-linter-client.ts +93 -0
  387. package/src/lsp/clients/swiftlint-client.ts +120 -0
  388. package/src/lsp/config.ts +418 -0
  389. package/src/lsp/defaults.json +999 -0
  390. package/src/lsp/edits.ts +109 -0
  391. package/src/lsp/index.ts +1746 -0
  392. package/src/lsp/lspmux.ts +233 -0
  393. package/src/lsp/render.ts +692 -0
  394. package/src/lsp/startup-events.ts +13 -0
  395. package/src/lsp/types.ts +444 -0
  396. package/src/lsp/utils.ts +691 -0
  397. package/src/main.ts +944 -0
  398. package/src/mcp/client.ts +482 -0
  399. package/src/mcp/config-writer.ts +225 -0
  400. package/src/mcp/config.ts +365 -0
  401. package/src/mcp/discoverable-tool-metadata.ts +202 -0
  402. package/src/mcp/index.ts +29 -0
  403. package/src/mcp/json-rpc.ts +84 -0
  404. package/src/mcp/loader.ts +124 -0
  405. package/src/mcp/manager.ts +1152 -0
  406. package/src/mcp/oauth-discovery.ts +349 -0
  407. package/src/mcp/oauth-flow.ts +387 -0
  408. package/src/mcp/render.ts +157 -0
  409. package/src/mcp/smithery-auth.ts +104 -0
  410. package/src/mcp/smithery-connect.ts +145 -0
  411. package/src/mcp/smithery-registry.ts +477 -0
  412. package/src/mcp/tool-bridge.ts +417 -0
  413. package/src/mcp/tool-cache.ts +117 -0
  414. package/src/mcp/transports/http.ts +475 -0
  415. package/src/mcp/transports/index.ts +6 -0
  416. package/src/mcp/transports/stdio.ts +325 -0
  417. package/src/mcp/types.ts +423 -0
  418. package/src/memories/index.ts +1115 -0
  419. package/src/memories/storage.ts +577 -0
  420. package/src/modes/acp/acp-agent.ts +1361 -0
  421. package/src/modes/acp/acp-event-mapper.ts +538 -0
  422. package/src/modes/acp/acp-mode.ts +15 -0
  423. package/src/modes/acp/index.ts +2 -0
  424. package/src/modes/components/agent-dashboard.ts +1124 -0
  425. package/src/modes/components/assistant-message.ts +213 -0
  426. package/src/modes/components/bash-execution.ts +345 -0
  427. package/src/modes/components/bordered-loader.ts +41 -0
  428. package/src/modes/components/branch-summary-message.ts +45 -0
  429. package/src/modes/components/btw-panel.ts +103 -0
  430. package/src/modes/components/compaction-summary-message.ts +51 -0
  431. package/src/modes/components/context-add-wizard.ts +534 -0
  432. package/src/modes/components/countdown-timer.ts +75 -0
  433. package/src/modes/components/custom-editor.ts +238 -0
  434. package/src/modes/components/custom-message.ts +91 -0
  435. package/src/modes/components/diff.ts +210 -0
  436. package/src/modes/components/dynamic-border.ts +25 -0
  437. package/src/modes/components/extensions/extension-dashboard.ts +326 -0
  438. package/src/modes/components/extensions/extension-list.ts +492 -0
  439. package/src/modes/components/extensions/index.ts +9 -0
  440. package/src/modes/components/extensions/inspector-panel.ts +317 -0
  441. package/src/modes/components/extensions/state-manager.ts +587 -0
  442. package/src/modes/components/extensions/types.ts +191 -0
  443. package/src/modes/components/footer.ts +262 -0
  444. package/src/modes/components/gutter-block.ts +315 -0
  445. package/src/modes/components/history-search.ts +158 -0
  446. package/src/modes/components/hook-editor.ts +151 -0
  447. package/src/modes/components/hook-input.ts +81 -0
  448. package/src/modes/components/hook-message.ts +100 -0
  449. package/src/modes/components/hook-selector.ts +192 -0
  450. package/src/modes/components/index.ts +36 -0
  451. package/src/modes/components/keybinding-hints.ts +65 -0
  452. package/src/modes/components/login-dialog.ts +164 -0
  453. package/src/modes/components/mcp-add-wizard.ts +1314 -0
  454. package/src/modes/components/model-selector.ts +946 -0
  455. package/src/modes/components/oauth-selector.ts +211 -0
  456. package/src/modes/components/plugin-selector.ts +95 -0
  457. package/src/modes/components/plugin-settings.ts +477 -0
  458. package/src/modes/components/plugins/index.ts +5 -0
  459. package/src/modes/components/plugins/plugin-dashboard.ts +523 -0
  460. package/src/modes/components/plugins/plugin-inspector-pane.ts +84 -0
  461. package/src/modes/components/plugins/plugin-list-pane.ts +109 -0
  462. package/src/modes/components/plugins/state-manager.ts +229 -0
  463. package/src/modes/components/plugins/types.ts +51 -0
  464. package/src/modes/components/plugins/utils.ts +6 -0
  465. package/src/modes/components/python-execution.ts +244 -0
  466. package/src/modes/components/queue-mode-selector.ts +56 -0
  467. package/src/modes/components/read-tool-group.ts +137 -0
  468. package/src/modes/components/session-observer-overlay.ts +483 -0
  469. package/src/modes/components/session-selector.ts +343 -0
  470. package/src/modes/components/settings-defs.ts +568 -0
  471. package/src/modes/components/settings-selector.ts +641 -0
  472. package/src/modes/components/show-images-selector.ts +45 -0
  473. package/src/modes/components/skill-message.ts +90 -0
  474. package/src/modes/components/status-line/context-gradient.ts +64 -0
  475. package/src/modes/components/status-line/git-utils.ts +42 -0
  476. package/src/modes/components/status-line/hex-ansi.ts +29 -0
  477. package/src/modes/components/status-line/index.ts +4 -0
  478. package/src/modes/components/status-line/presets.ts +174 -0
  479. package/src/modes/components/status-line/segments.ts +494 -0
  480. package/src/modes/components/status-line/separators.ts +55 -0
  481. package/src/modes/components/status-line/token-rate.ts +66 -0
  482. package/src/modes/components/status-line/types.ts +96 -0
  483. package/src/modes/components/status-line-segment-editor.ts +361 -0
  484. package/src/modes/components/status-line.ts +729 -0
  485. package/src/modes/components/theme-selector.ts +63 -0
  486. package/src/modes/components/thinking-selector.ts +52 -0
  487. package/src/modes/components/todo-reminder.ts +54 -0
  488. package/src/modes/components/tool-execution.ts +781 -0
  489. package/src/modes/components/tree-selector.ts +908 -0
  490. package/src/modes/components/ttsr-notification.ts +80 -0
  491. package/src/modes/components/user-message-selector.ts +141 -0
  492. package/src/modes/components/user-message.ts +100 -0
  493. package/src/modes/components/visual-truncate.ts +63 -0
  494. package/src/modes/components/welcome-checks.ts +313 -0
  495. package/src/modes/components/welcome.ts +270 -0
  496. package/src/modes/controllers/btw-controller.ts +193 -0
  497. package/src/modes/controllers/chord-routing.ts +37 -0
  498. package/src/modes/controllers/command-controller.ts +1293 -0
  499. package/src/modes/controllers/context-command-controller.ts +61 -0
  500. package/src/modes/controllers/event-controller.ts +743 -0
  501. package/src/modes/controllers/extension-ui-controller.ts +983 -0
  502. package/src/modes/controllers/input-controller.ts +877 -0
  503. package/src/modes/controllers/mcp-command-controller.ts +1940 -0
  504. package/src/modes/controllers/selector-controller.ts +1292 -0
  505. package/src/modes/controllers/ssh-command-controller.ts +421 -0
  506. package/src/modes/index.ts +34 -0
  507. package/src/modes/interactive-mode.ts +1781 -0
  508. package/src/modes/oauth-manual-input.ts +42 -0
  509. package/src/modes/print-mode.ts +196 -0
  510. package/src/modes/prompt-action-autocomplete.ts +231 -0
  511. package/src/modes/rpc/host-tools.ts +186 -0
  512. package/src/modes/rpc/rpc-client.ts +762 -0
  513. package/src/modes/rpc/rpc-mode.ts +877 -0
  514. package/src/modes/rpc/rpc-types.ts +322 -0
  515. package/src/modes/session-observer-registry.ts +146 -0
  516. package/src/modes/shared.ts +30 -0
  517. package/src/modes/theme/defaults/index.ts +7 -0
  518. package/src/modes/theme/defaults/xcsh-dark.json +113 -0
  519. package/src/modes/theme/defaults/xcsh-light.json +115 -0
  520. package/src/modes/theme/mermaid-cache.ts +151 -0
  521. package/src/modes/theme/mermaid-palette.ts +39 -0
  522. package/src/modes/theme/theme-schema.json +553 -0
  523. package/src/modes/theme/theme.ts +2563 -0
  524. package/src/modes/types.ts +273 -0
  525. package/src/modes/utils/hotkeys-markdown.ts +60 -0
  526. package/src/modes/utils/keybinding-matchers.ts +30 -0
  527. package/src/modes/utils/read-group-outcome-aggregator.ts +55 -0
  528. package/src/modes/utils/sanitize-error-message.ts +60 -0
  529. package/src/modes/utils/tools-markdown.ts +28 -0
  530. package/src/modes/utils/ui-helpers.ts +734 -0
  531. package/src/plan-mode/approved-plan.ts +55 -0
  532. package/src/plan-mode/state.ts +6 -0
  533. package/src/priority.json +37 -0
  534. package/src/prompts/agents/designer.md +67 -0
  535. package/src/prompts/agents/explore.md +61 -0
  536. package/src/prompts/agents/frontmatter.md +10 -0
  537. package/src/prompts/agents/init.md +36 -0
  538. package/src/prompts/agents/librarian.md +121 -0
  539. package/src/prompts/agents/plan.md +49 -0
  540. package/src/prompts/agents/reviewer.md +127 -0
  541. package/src/prompts/agents/task.md +16 -0
  542. package/src/prompts/ci-green-request.md +35 -0
  543. package/src/prompts/compaction/branch-summary-context.md +5 -0
  544. package/src/prompts/compaction/branch-summary-preamble.md +2 -0
  545. package/src/prompts/compaction/branch-summary.md +30 -0
  546. package/src/prompts/compaction/compaction-short-summary.md +9 -0
  547. package/src/prompts/compaction/compaction-summary-context.md +5 -0
  548. package/src/prompts/compaction/compaction-summary.md +38 -0
  549. package/src/prompts/compaction/compaction-turn-prefix.md +17 -0
  550. package/src/prompts/compaction/compaction-update-summary.md +45 -0
  551. package/src/prompts/memories/consolidation.md +30 -0
  552. package/src/prompts/memories/read-path.md +11 -0
  553. package/src/prompts/memories/stage_one_input.md +6 -0
  554. package/src/prompts/memories/stage_one_system.md +21 -0
  555. package/src/prompts/review-request.md +70 -0
  556. package/src/prompts/system/agent-creation-architect.md +65 -0
  557. package/src/prompts/system/agent-creation-user.md +6 -0
  558. package/src/prompts/system/auto-handoff-threshold-focus.md +1 -0
  559. package/src/prompts/system/btw-user.md +8 -0
  560. package/src/prompts/system/commit-message-system.md +2 -0
  561. package/src/prompts/system/custom-system-prompt.md +82 -0
  562. package/src/prompts/system/eager-todo.md +13 -0
  563. package/src/prompts/system/file-operations.md +10 -0
  564. package/src/prompts/system/handoff-document.md +48 -0
  565. package/src/prompts/system/plan-mode-active.md +114 -0
  566. package/src/prompts/system/plan-mode-approved.md +23 -0
  567. package/src/prompts/system/plan-mode-reference.md +14 -0
  568. package/src/prompts/system/plan-mode-subagent.md +34 -0
  569. package/src/prompts/system/plan-mode-tool-decision-reminder.md +9 -0
  570. package/src/prompts/system/subagent-submit-reminder.md +7 -0
  571. package/src/prompts/system/subagent-system-prompt.md +36 -0
  572. package/src/prompts/system/subagent-user-prompt.md +12 -0
  573. package/src/prompts/system/summarization-system.md +3 -0
  574. package/src/prompts/system/system-prompt.md +698 -0
  575. package/src/prompts/system/title-system.md +2 -0
  576. package/src/prompts/system/ttsr-interrupt.md +7 -0
  577. package/src/prompts/system/web-search.md +28 -0
  578. package/src/prompts/tools/ask.md +28 -0
  579. package/src/prompts/tools/ast-edit.md +48 -0
  580. package/src/prompts/tools/ast-grep.md +54 -0
  581. package/src/prompts/tools/async-result.md +5 -0
  582. package/src/prompts/tools/bash.md +67 -0
  583. package/src/prompts/tools/browser.md +26 -0
  584. package/src/prompts/tools/calculator.md +10 -0
  585. package/src/prompts/tools/cancel-job.md +5 -0
  586. package/src/prompts/tools/catalog-workflow-runner.md +13 -0
  587. package/src/prompts/tools/checkpoint.md +16 -0
  588. package/src/prompts/tools/chunk-edit.md +279 -0
  589. package/src/prompts/tools/debug.md +43 -0
  590. package/src/prompts/tools/display-image.md +23 -0
  591. package/src/prompts/tools/exit-plan-mode.md +41 -0
  592. package/src/prompts/tools/find.md +26 -0
  593. package/src/prompts/tools/gemini-image.md +7 -0
  594. package/src/prompts/tools/grep.md +29 -0
  595. package/src/prompts/tools/hashline.md +131 -0
  596. package/src/prompts/tools/inspect-image-system.md +20 -0
  597. package/src/prompts/tools/inspect-image.md +32 -0
  598. package/src/prompts/tools/lsp.md +33 -0
  599. package/src/prompts/tools/patch.md +77 -0
  600. package/src/prompts/tools/poll.md +5 -0
  601. package/src/prompts/tools/python.md +60 -0
  602. package/src/prompts/tools/read-chunk.md +35 -0
  603. package/src/prompts/tools/read.md +63 -0
  604. package/src/prompts/tools/render-mermaid.md +9 -0
  605. package/src/prompts/tools/replace.md +36 -0
  606. package/src/prompts/tools/resolve.md +8 -0
  607. package/src/prompts/tools/rewind.md +13 -0
  608. package/src/prompts/tools/search-tool-bm25.md +34 -0
  609. package/src/prompts/tools/ssh.md +44 -0
  610. package/src/prompts/tools/task-summary.md +28 -0
  611. package/src/prompts/tools/task.md +131 -0
  612. package/src/prompts/tools/todo-write.md +89 -0
  613. package/src/prompts/tools/vim.md +98 -0
  614. package/src/prompts/tools/web-search.md +10 -0
  615. package/src/prompts/tools/write.md +14 -0
  616. package/src/prompts/tools/xcsh-api.md +283 -0
  617. package/src/resource-management/index.ts +42 -0
  618. package/src/sdk.ts +2123 -0
  619. package/src/secrets/index.ts +146 -0
  620. package/src/secrets/obfuscator.ts +290 -0
  621. package/src/secrets/regex.ts +21 -0
  622. package/src/services/context-env.ts +102 -0
  623. package/src/services/xcsh-api-client.ts +230 -0
  624. package/src/services/xcsh-context-command.ts +803 -0
  625. package/src/services/xcsh-context-display.ts +49 -0
  626. package/src/services/xcsh-context-indicators.ts +17 -0
  627. package/src/services/xcsh-context-segment.ts +39 -0
  628. package/src/services/xcsh-context.ts +1410 -0
  629. package/src/services/xcsh-env.ts +107 -0
  630. package/src/services/xcsh-knowledge.ts +177 -0
  631. package/src/services/xcsh-table.ts +164 -0
  632. package/src/session/agent-session.ts +6690 -0
  633. package/src/session/agent-storage.ts +451 -0
  634. package/src/session/artifacts.ts +132 -0
  635. package/src/session/auth-storage.ts +17 -0
  636. package/src/session/blob-store.ts +135 -0
  637. package/src/session/compaction/branch-summarization.ts +322 -0
  638. package/src/session/compaction/compaction.ts +1388 -0
  639. package/src/session/compaction/index.ts +7 -0
  640. package/src/session/compaction/pruning.ts +91 -0
  641. package/src/session/compaction/utils.ts +184 -0
  642. package/src/session/history-storage.ts +253 -0
  643. package/src/session/messages.ts +597 -0
  644. package/src/session/session-dump-format.ts +203 -0
  645. package/src/session/session-manager.ts +2816 -0
  646. package/src/session/session-storage.ts +370 -0
  647. package/src/session/streaming-output.ts +770 -0
  648. package/src/session/tool-choice-queue.ts +213 -0
  649. package/src/slash-commands/builtin-registry.ts +1614 -0
  650. package/src/slash-commands/export-command.ts +178 -0
  651. package/src/slash-commands/marketplace-install-parser.ts +99 -0
  652. package/src/slash-commands/resource-commands.ts +250 -0
  653. package/src/ssh/config-writer.ts +183 -0
  654. package/src/ssh/connection-manager.ts +445 -0
  655. package/src/ssh/ssh-executor.ts +131 -0
  656. package/src/ssh/sshfs-mount.ts +137 -0
  657. package/src/ssh/utils.ts +8 -0
  658. package/src/stt/downloader.ts +71 -0
  659. package/src/stt/index.ts +3 -0
  660. package/src/stt/recorder.ts +351 -0
  661. package/src/stt/setup.ts +52 -0
  662. package/src/stt/stt-controller.ts +160 -0
  663. package/src/stt/transcribe.py +70 -0
  664. package/src/stt/transcriber.ts +91 -0
  665. package/src/system-prompt.ts +688 -0
  666. package/src/task/agents.ts +166 -0
  667. package/src/task/commands.ts +131 -0
  668. package/src/task/discovery.ts +126 -0
  669. package/src/task/executor.ts +1324 -0
  670. package/src/task/index.ts +1197 -0
  671. package/src/task/isolation-backend.ts +72 -0
  672. package/src/task/name-generator.ts +1577 -0
  673. package/src/task/output-manager.ts +107 -0
  674. package/src/task/parallel.ts +116 -0
  675. package/src/task/render.ts +1035 -0
  676. package/src/task/subprocess-tool-registry.ts +88 -0
  677. package/src/task/template.ts +33 -0
  678. package/src/task/types.ts +230 -0
  679. package/src/task/worktree.ts +580 -0
  680. package/src/task/xcsh-command.ts +26 -0
  681. package/src/thinking.ts +87 -0
  682. package/src/tools/action-renderer.ts +198 -0
  683. package/src/tools/archive-reader.ts +315 -0
  684. package/src/tools/ask.ts +791 -0
  685. package/src/tools/ast-edit.ts +492 -0
  686. package/src/tools/ast-grep.ts +453 -0
  687. package/src/tools/auto-generated-guard.ts +305 -0
  688. package/src/tools/bash-interactive.ts +383 -0
  689. package/src/tools/bash-interceptor.ts +67 -0
  690. package/src/tools/bash-normalize.ts +107 -0
  691. package/src/tools/bash-skill-urls.ts +246 -0
  692. package/src/tools/bash.ts +878 -0
  693. package/src/tools/browser-renderer.ts +129 -0
  694. package/src/tools/browser.ts +1366 -0
  695. package/src/tools/calculator.ts +543 -0
  696. package/src/tools/cancel-job.ts +100 -0
  697. package/src/tools/catalog-workflow-runner.ts +718 -0
  698. package/src/tools/checkpoint.ts +133 -0
  699. package/src/tools/context.ts +39 -0
  700. package/src/tools/debug.ts +1004 -0
  701. package/src/tools/display-image-renderer.ts +96 -0
  702. package/src/tools/display-image.ts +109 -0
  703. package/src/tools/exit-plan-mode.ts +101 -0
  704. package/src/tools/fetch.ts +1462 -0
  705. package/src/tools/find.ts +437 -0
  706. package/src/tools/fs-cache-invalidation.ts +33 -0
  707. package/src/tools/gemini-image.ts +1004 -0
  708. package/src/tools/grep.ts +705 -0
  709. package/src/tools/index.ts +442 -0
  710. package/src/tools/inspect-image-renderer.ts +101 -0
  711. package/src/tools/inspect-image.ts +176 -0
  712. package/src/tools/json-tree.ts +266 -0
  713. package/src/tools/jtd-to-json-schema.ts +199 -0
  714. package/src/tools/jtd-to-typescript.ts +136 -0
  715. package/src/tools/jtd-utils.ts +102 -0
  716. package/src/tools/list-limit.ts +40 -0
  717. package/src/tools/mermaid-renderer.ts +127 -0
  718. package/src/tools/notebook.ts +288 -0
  719. package/src/tools/output-meta.ts +588 -0
  720. package/src/tools/path-utils.ts +560 -0
  721. package/src/tools/plan-mode-guard.ts +41 -0
  722. package/src/tools/poll-tool.ts +177 -0
  723. package/src/tools/puppeteer/00_stealth_tampering.txt +63 -0
  724. package/src/tools/puppeteer/01_stealth_activity.txt +20 -0
  725. package/src/tools/puppeteer/02_stealth_hairline.txt +11 -0
  726. package/src/tools/puppeteer/03_stealth_botd.txt +384 -0
  727. package/src/tools/puppeteer/04_stealth_iframe.txt +81 -0
  728. package/src/tools/puppeteer/05_stealth_webgl.txt +75 -0
  729. package/src/tools/puppeteer/06_stealth_screen.txt +72 -0
  730. package/src/tools/puppeteer/07_stealth_fonts.txt +97 -0
  731. package/src/tools/puppeteer/08_stealth_audio.txt +51 -0
  732. package/src/tools/puppeteer/09_stealth_locale.txt +46 -0
  733. package/src/tools/puppeteer/10_stealth_plugins.txt +206 -0
  734. package/src/tools/puppeteer/11_stealth_hardware.txt +8 -0
  735. package/src/tools/puppeteer/12_stealth_codecs.txt +40 -0
  736. package/src/tools/puppeteer/13_stealth_worker.txt +74 -0
  737. package/src/tools/python.ts +1184 -0
  738. package/src/tools/read.ts +1591 -0
  739. package/src/tools/render-mermaid.ts +93 -0
  740. package/src/tools/render-utils.ts +677 -0
  741. package/src/tools/renderers.ts +82 -0
  742. package/src/tools/report-tool-issue.ts +80 -0
  743. package/src/tools/resolve.ts +196 -0
  744. package/src/tools/review.ts +238 -0
  745. package/src/tools/search-tool-bm25.ts +288 -0
  746. package/src/tools/sqlite-reader.ts +623 -0
  747. package/src/tools/ssh.ts +322 -0
  748. package/src/tools/submit-result.ts +229 -0
  749. package/src/tools/todo-render.ts +33 -0
  750. package/src/tools/todo-write.ts +440 -0
  751. package/src/tools/tool-errors.ts +62 -0
  752. package/src/tools/tool-result.ts +93 -0
  753. package/src/tools/tool-timeouts.ts +30 -0
  754. package/src/tools/vim.ts +981 -0
  755. package/src/tools/write.ts +671 -0
  756. package/src/tools/xcsh-api-renderer.ts +402 -0
  757. package/src/tools/xcsh-api.ts +887 -0
  758. package/src/tui/code-cell.ts +101 -0
  759. package/src/tui/file-list.ts +47 -0
  760. package/src/tui/index.ts +11 -0
  761. package/src/tui/output-block.ts +175 -0
  762. package/src/tui/status-line.ts +39 -0
  763. package/src/tui/tree-list.ts +84 -0
  764. package/src/tui/types.ts +15 -0
  765. package/src/tui/utils.ts +103 -0
  766. package/src/utils/changelog.ts +98 -0
  767. package/src/utils/clipboard.ts +80 -0
  768. package/src/utils/command-args.ts +76 -0
  769. package/src/utils/commit-message-generator.ts +137 -0
  770. package/src/utils/edit-mode.ts +50 -0
  771. package/src/utils/event-bus.ts +33 -0
  772. package/src/utils/external-editor.ts +65 -0
  773. package/src/utils/file-display-mode.ts +37 -0
  774. package/src/utils/file-mentions.ts +376 -0
  775. package/src/utils/fuzzy.ts +108 -0
  776. package/src/utils/git.ts +1495 -0
  777. package/src/utils/gitstatus.ts +140 -0
  778. package/src/utils/image-convert.ts +27 -0
  779. package/src/utils/image-loading.ts +98 -0
  780. package/src/utils/image-passthrough.ts +118 -0
  781. package/src/utils/image-resize.ts +272 -0
  782. package/src/utils/image-viewer.ts +17 -0
  783. package/src/utils/lang-from-path.ts +239 -0
  784. package/src/utils/markit.ts +81 -0
  785. package/src/utils/open.ts +20 -0
  786. package/src/utils/session-color.ts +55 -0
  787. package/src/utils/shell-snapshot.ts +188 -0
  788. package/src/utils/title-generator.ts +193 -0
  789. package/src/utils/tool-choice.ts +28 -0
  790. package/src/utils/tools-manager.ts +356 -0
  791. package/src/vim/buffer.ts +309 -0
  792. package/src/vim/commands.ts +382 -0
  793. package/src/vim/engine.ts +2426 -0
  794. package/src/vim/parser.ts +151 -0
  795. package/src/vim/render.ts +252 -0
  796. package/src/vim/types.ts +197 -0
  797. package/src/web/kagi.ts +174 -0
  798. package/src/web/parallel.ts +346 -0
  799. package/src/web/scrapers/artifacthub.ts +207 -0
  800. package/src/web/scrapers/arxiv.ts +83 -0
  801. package/src/web/scrapers/aur.ts +162 -0
  802. package/src/web/scrapers/biorxiv.ts +133 -0
  803. package/src/web/scrapers/bluesky.ts +262 -0
  804. package/src/web/scrapers/brew.ts +172 -0
  805. package/src/web/scrapers/cheatsh.ts +68 -0
  806. package/src/web/scrapers/chocolatey.ts +196 -0
  807. package/src/web/scrapers/choosealicense.ts +95 -0
  808. package/src/web/scrapers/cisa-kev.ts +87 -0
  809. package/src/web/scrapers/clojars.ts +154 -0
  810. package/src/web/scrapers/coingecko.ts +177 -0
  811. package/src/web/scrapers/crates-io.ts +110 -0
  812. package/src/web/scrapers/crossref.ts +136 -0
  813. package/src/web/scrapers/devto.ts +147 -0
  814. package/src/web/scrapers/discogs.ts +306 -0
  815. package/src/web/scrapers/discourse.ts +197 -0
  816. package/src/web/scrapers/dockerhub.ts +138 -0
  817. package/src/web/scrapers/docs-rs.ts +653 -0
  818. package/src/web/scrapers/fdroid.ts +134 -0
  819. package/src/web/scrapers/firefox-addons.ts +191 -0
  820. package/src/web/scrapers/flathub.ts +223 -0
  821. package/src/web/scrapers/github-gist.ts +58 -0
  822. package/src/web/scrapers/github.ts +452 -0
  823. package/src/web/scrapers/gitlab.ts +401 -0
  824. package/src/web/scrapers/go-pkg.ts +266 -0
  825. package/src/web/scrapers/hackage.ts +140 -0
  826. package/src/web/scrapers/hackernews.ts +189 -0
  827. package/src/web/scrapers/hex.ts +105 -0
  828. package/src/web/scrapers/huggingface.ts +321 -0
  829. package/src/web/scrapers/iacr.ts +89 -0
  830. package/src/web/scrapers/index.ts +252 -0
  831. package/src/web/scrapers/jetbrains-marketplace.ts +159 -0
  832. package/src/web/scrapers/lemmy.ts +203 -0
  833. package/src/web/scrapers/lobsters.ts +175 -0
  834. package/src/web/scrapers/mastodon.ts +292 -0
  835. package/src/web/scrapers/maven.ts +138 -0
  836. package/src/web/scrapers/mdn.ts +169 -0
  837. package/src/web/scrapers/metacpan.ts +222 -0
  838. package/src/web/scrapers/musicbrainz.ts +250 -0
  839. package/src/web/scrapers/npm.ts +98 -0
  840. package/src/web/scrapers/nuget.ts +183 -0
  841. package/src/web/scrapers/nvd.ts +222 -0
  842. package/src/web/scrapers/ollama.ts +239 -0
  843. package/src/web/scrapers/open-vsx.ts +106 -0
  844. package/src/web/scrapers/opencorporates.ts +292 -0
  845. package/src/web/scrapers/openlibrary.ts +336 -0
  846. package/src/web/scrapers/orcid.ts +286 -0
  847. package/src/web/scrapers/osv.ts +176 -0
  848. package/src/web/scrapers/packagist.ts +160 -0
  849. package/src/web/scrapers/pub-dev.ts +143 -0
  850. package/src/web/scrapers/pubmed.ts +211 -0
  851. package/src/web/scrapers/pypi.ts +112 -0
  852. package/src/web/scrapers/rawg.ts +110 -0
  853. package/src/web/scrapers/readthedocs.ts +120 -0
  854. package/src/web/scrapers/reddit.ts +95 -0
  855. package/src/web/scrapers/repology.ts +251 -0
  856. package/src/web/scrapers/rfc.ts +201 -0
  857. package/src/web/scrapers/rubygems.ts +103 -0
  858. package/src/web/scrapers/searchcode.ts +190 -0
  859. package/src/web/scrapers/sec-edgar.ts +261 -0
  860. package/src/web/scrapers/semantic-scholar.ts +171 -0
  861. package/src/web/scrapers/snapcraft.ts +187 -0
  862. package/src/web/scrapers/sourcegraph.ts +336 -0
  863. package/src/web/scrapers/spdx.ts +108 -0
  864. package/src/web/scrapers/spotify.ts +198 -0
  865. package/src/web/scrapers/stackoverflow.ts +120 -0
  866. package/src/web/scrapers/terraform.ts +277 -0
  867. package/src/web/scrapers/tldr.ts +47 -0
  868. package/src/web/scrapers/twitter.ts +93 -0
  869. package/src/web/scrapers/types.ts +267 -0
  870. package/src/web/scrapers/utils.ts +109 -0
  871. package/src/web/scrapers/vimeo.ts +133 -0
  872. package/src/web/scrapers/vscode-marketplace.ts +187 -0
  873. package/src/web/scrapers/w3c.ts +156 -0
  874. package/src/web/scrapers/wikidata.ts +344 -0
  875. package/src/web/scrapers/wikipedia.ts +84 -0
  876. package/src/web/scrapers/youtube.ts +313 -0
  877. package/src/web/search/errors.ts +120 -0
  878. package/src/web/search/index.ts +346 -0
  879. package/src/web/search/params.ts +129 -0
  880. package/src/web/search/provider.ts +97 -0
  881. package/src/web/search/providers/anthropic.ts +339 -0
  882. package/src/web/search/providers/base.ts +35 -0
  883. package/src/web/search/providers/brave.ts +150 -0
  884. package/src/web/search/providers/codex.ts +402 -0
  885. package/src/web/search/providers/exa.ts +264 -0
  886. package/src/web/search/providers/firecrawl.ts +115 -0
  887. package/src/web/search/providers/gemini.ts +566 -0
  888. package/src/web/search/providers/jina.ts +99 -0
  889. package/src/web/search/providers/kagi.ts +70 -0
  890. package/src/web/search/providers/kimi.ts +157 -0
  891. package/src/web/search/providers/parallel.ts +63 -0
  892. package/src/web/search/providers/perplexity.ts +546 -0
  893. package/src/web/search/providers/synthetic.ts +113 -0
  894. package/src/web/search/providers/tavily.ts +162 -0
  895. package/src/web/search/providers/utils.ts +36 -0
  896. package/src/web/search/providers/zai.ts +311 -0
  897. package/src/web/search/render.ts +348 -0
  898. package/src/web/search/types.ts +438 -0
  899. package/src/web/search/utils.ts +17 -0
@@ -0,0 +1,2816 @@
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 "@f5xc-salesdemos/pi-agent-core";
5
+ import type {
6
+ ImageContent,
7
+ Message,
8
+ MessageAttribution,
9
+ ProviderPayload,
10
+ ServiceTier,
11
+ TextContent,
12
+ Usage,
13
+ } from "@f5xc-salesdemos/pi-ai";
14
+ import { getTerminalId } from "@f5xc-salesdemos/pi-tui";
15
+ import {
16
+ getBlobsDir,
17
+ getAgentDir as getDefaultAgentDir,
18
+ getProjectDir,
19
+ getSessionsDir,
20
+ getTerminalSessionsDir,
21
+ isEnoent,
22
+ logger,
23
+ parseJsonlLenient,
24
+ pathIsWithin,
25
+ resolveEquivalentPath,
26
+ Snowflake,
27
+ toError,
28
+ } from "@f5xc-salesdemos/pi-utils";
29
+ import { ArtifactManager } from "./artifacts";
30
+ import {
31
+ type BlobPutResult,
32
+ BlobStore,
33
+ externalizeImageData,
34
+ externalizeImageDataUrl,
35
+ isBlobRef,
36
+ isImageDataUrl,
37
+ resolveImageData,
38
+ resolveImageDataUrl,
39
+ } from "./blob-store";
40
+ import {
41
+ type BashExecutionMessage,
42
+ type CustomMessage,
43
+ createBranchSummaryMessage,
44
+ createCompactionSummaryMessage,
45
+ createCustomMessage,
46
+ type FileMentionMessage,
47
+ type HookMessage,
48
+ type PythonExecutionMessage,
49
+ sanitizeRehydratedOpenAIResponsesAssistantMessage,
50
+ } from "./messages";
51
+ import type { SessionStorage, SessionStorageWriter } from "./session-storage";
52
+ import { FileSessionStorage, MemorySessionStorage } from "./session-storage";
53
+
54
+ export const CURRENT_SESSION_VERSION = 3;
55
+
56
+ export interface SessionHeader {
57
+ type: "session";
58
+ version?: number; // v1 sessions don't have this
59
+ id: string;
60
+ title?: string; // Auto-generated title from first message
61
+ titleSource?: "auto" | "user";
62
+ timestamp: string;
63
+ cwd: string;
64
+ parentSession?: string;
65
+ }
66
+
67
+ export interface NewSessionOptions {
68
+ parentSession?: string;
69
+ }
70
+
71
+ export interface SessionEntryBase {
72
+ type: string;
73
+ id: string;
74
+ parentId: string | null;
75
+ timestamp: string;
76
+ }
77
+
78
+ export interface SessionMessageEntry extends SessionEntryBase {
79
+ type: "message";
80
+ message: AgentMessage;
81
+ }
82
+
83
+ export interface ThinkingLevelChangeEntry extends SessionEntryBase {
84
+ type: "thinking_level_change";
85
+ thinkingLevel?: string | null;
86
+ }
87
+
88
+ export interface ModelChangeEntry extends SessionEntryBase {
89
+ type: "model_change";
90
+ /** Model in "provider/modelId" format */
91
+ model: string;
92
+ /** Role: "default", "smol", "slow", etc. Undefined treated as "default" */
93
+ role?: string;
94
+ }
95
+
96
+ export interface ContextChangeEntry extends SessionEntryBase {
97
+ type: "context_change";
98
+ /** Context name from ContextStatus.activeContextName. */
99
+ contextName: string;
100
+ /** Tenant derived from the active context's apiUrl. */
101
+ tenant: string;
102
+ /** Effective namespace (XCSH_NAMESPACE env override applied, falls back to context.defaultNamespace). */
103
+ namespace: string;
104
+ }
105
+
106
+ export interface ServiceTierChangeEntry extends SessionEntryBase {
107
+ type: "service_tier_change";
108
+ serviceTier: ServiceTier | null;
109
+ }
110
+
111
+ export interface CompactionEntry<T = unknown> extends SessionEntryBase {
112
+ type: "compaction";
113
+ summary: string;
114
+ shortSummary?: string;
115
+ firstKeptEntryId: string;
116
+ tokensBefore: number;
117
+ /** Extension-specific data (e.g., ArtifactIndex, version markers for structured compaction) */
118
+ details?: T;
119
+ /** Hook-provided data to persist across compaction */
120
+ preserveData?: Record<string, unknown>;
121
+ /** True if generated by an extension, undefined/false if pi-generated (backward compatible) */
122
+ fromExtension?: boolean;
123
+ }
124
+
125
+ export interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {
126
+ type: "branch_summary";
127
+ fromId: string;
128
+ summary: string;
129
+ /** Extension-specific data (not sent to LLM) */
130
+ details?: T;
131
+ /** True if generated by an extension, false if pi-generated */
132
+ fromExtension?: boolean;
133
+ }
134
+
135
+ /**
136
+ * Custom entry for extensions to store extension-specific data in the session.
137
+ * Use customType to identify your extension's entries.
138
+ *
139
+ * Purpose: Persist extension state across session reloads. On reload, extensions can
140
+ * scan entries for their customType and reconstruct internal state.
141
+ *
142
+ * Does NOT participate in LLM context (ignored by buildSessionContext).
143
+ * For injecting content into context, see CustomMessageEntry.
144
+ */
145
+ export interface CustomEntry<T = unknown> extends SessionEntryBase {
146
+ type: "custom";
147
+ customType: string;
148
+ data?: T;
149
+ }
150
+
151
+ /** Label entry for user-defined bookmarks/markers on entries. */
152
+ export interface LabelEntry extends SessionEntryBase {
153
+ type: "label";
154
+ targetId: string;
155
+ label: string | undefined;
156
+ }
157
+
158
+ /** TTSR injection entry - tracks which time-traveling rules have been injected this session. */
159
+ export interface TtsrInjectionEntry extends SessionEntryBase {
160
+ type: "ttsr_injection";
161
+ /** Names of rules that were injected */
162
+ injectedRules: string[];
163
+ }
164
+
165
+ /** Persisted MCP discovery selection state for a session branch. */
166
+ export interface MCPToolSelectionEntry extends SessionEntryBase {
167
+ type: "mcp_tool_selection";
168
+ /** MCP tool names selected for visibility in discovery mode. */
169
+ selectedToolNames: string[];
170
+ }
171
+
172
+ /** Session init entry - captures initial context for subagent sessions (debugging/replay). */
173
+ export interface SessionInitEntry extends SessionEntryBase {
174
+ type: "session_init";
175
+ /** Full system prompt sent to the model */
176
+ systemPrompt: string;
177
+ /** Initial task/user message */
178
+ task: string;
179
+ /** Tools available to the agent */
180
+ tools: string[];
181
+ /** Output schema if structured output was requested */
182
+ outputSchema?: unknown;
183
+ }
184
+
185
+ /** Mode change entry - tracks agent mode transitions (e.g. plan mode). */
186
+ export interface ModeChangeEntry extends SessionEntryBase {
187
+ type: "mode_change";
188
+ /** Current mode name, or "none" when exiting a mode */
189
+ mode: string;
190
+ /** Optional mode-specific data (e.g. plan file path) */
191
+ data?: Record<string, unknown>;
192
+ }
193
+
194
+ /**
195
+ * Custom message entry for extensions to inject messages into LLM context.
196
+ * Use customType to identify your extension's entries.
197
+ *
198
+ * Unlike CustomEntry, this DOES participate in LLM context.
199
+ * The content participates in LLM context through convertToLlm().
200
+ * Use details for extension-specific metadata (not sent to LLM).
201
+ *
202
+ * display controls TUI rendering:
203
+ * - false: hidden entirely
204
+ * - true: rendered with distinct styling (different from user messages)
205
+ */
206
+ export interface CustomMessageEntry<T = unknown> extends SessionEntryBase {
207
+ type: "custom_message";
208
+ customType: string;
209
+ content: string | (TextContent | ImageContent)[];
210
+ details?: T;
211
+ display: boolean;
212
+ /** Who initiated this message for billing/attribution semantics. */
213
+ attribution?: MessageAttribution;
214
+ }
215
+
216
+ /** Session entry - has id/parentId for tree structure (returned by "read" methods in SessionManager) */
217
+ export type SessionEntry =
218
+ | SessionMessageEntry
219
+ | ThinkingLevelChangeEntry
220
+ | ModelChangeEntry
221
+ | ContextChangeEntry
222
+ | ServiceTierChangeEntry
223
+ | CompactionEntry
224
+ | BranchSummaryEntry
225
+ | CustomEntry
226
+ | CustomMessageEntry
227
+ | LabelEntry
228
+ | TtsrInjectionEntry
229
+ | MCPToolSelectionEntry
230
+ | SessionInitEntry
231
+ | ModeChangeEntry;
232
+
233
+ /** Raw file entry (includes header) */
234
+ export type FileEntry = SessionHeader | SessionEntry;
235
+
236
+ /** Tree node for getTree() - defensive copy of session structure */
237
+ export interface SessionTreeNode {
238
+ entry: SessionEntry;
239
+ children: SessionTreeNode[];
240
+ /** Resolved label for this entry, if any */
241
+ label?: string;
242
+ }
243
+
244
+ export interface SessionContext {
245
+ messages: AgentMessage[];
246
+ thinkingLevel?: string;
247
+ serviceTier?: ServiceTier;
248
+ /** Model roles: { default: "provider/modelId", small: "provider/modelId", ... } */
249
+ models: Record<string, string>;
250
+ /** Active context name from the last context_change entry, or undefined if none. */
251
+ activeContextName?: string;
252
+ /** Active context tenant from the last context_change entry, or undefined if none. */
253
+ activeContextTenant?: string;
254
+ /** Names of TTSR rules that have been injected this session */
255
+ injectedTtsrRules: string[];
256
+ /** MCP tool names selected through discovery for this session branch. */
257
+ selectedMCPToolNames: string[];
258
+ /** Whether this branch contains an explicit persisted MCP selection entry. */
259
+ hasPersistedMCPToolSelection: boolean;
260
+ /** Active mode (e.g. "plan") or "none" if no special mode is active */
261
+ mode: string;
262
+ /** Mode-specific data from the last mode_change entry */
263
+ modeData?: Record<string, unknown>;
264
+ }
265
+
266
+ export interface SessionInfo {
267
+ path: string;
268
+ id: string;
269
+ /** Working directory where the session was started. Empty string for old sessions. */
270
+ cwd: string;
271
+ title?: string;
272
+ /** Path to the parent session (if this session was forked). */
273
+ parentSessionPath?: string;
274
+ created: Date;
275
+ modified: Date;
276
+ messageCount: number;
277
+ firstMessage: string;
278
+ allMessagesText: string;
279
+ }
280
+
281
+ export type ReadonlySessionManager = Pick<
282
+ SessionManager,
283
+ | "getCwd"
284
+ | "getSessionDir"
285
+ | "getSessionId"
286
+ | "getSessionFile"
287
+ | "getSessionName"
288
+ | "getArtifactsDir"
289
+ | "allocateArtifactPath"
290
+ | "saveArtifact"
291
+ | "getArtifactPath"
292
+ | "getLeafId"
293
+ | "getLeafEntry"
294
+ | "getEntry"
295
+ | "getLabel"
296
+ | "getBranch"
297
+ | "getHeader"
298
+ | "getEntries"
299
+ | "getTree"
300
+ | "getUsageStatistics"
301
+ | "putBlob"
302
+ >;
303
+
304
+ /** Generate a unique short ID (8 hex chars, collision-checked) */
305
+ function generateId(byId: { has(id: string): boolean }): string {
306
+ for (let i = 0; i < 100; i++) {
307
+ const id = crypto.randomUUID().slice(-8);
308
+ if (!byId.has(id)) return id;
309
+ }
310
+ return Snowflake.next(); // fallback to full snowflake id
311
+ }
312
+
313
+ /** Migrate v1 → v2: add id/parentId tree structure. Mutates in place. */
314
+ function migrateV1ToV2(entries: FileEntry[]): void {
315
+ const ids = new Set<string>();
316
+ let prevId: string | null = null;
317
+
318
+ for (const entry of entries) {
319
+ if (entry.type === "session") {
320
+ entry.version = 2;
321
+ continue;
322
+ }
323
+
324
+ entry.id = generateId(ids);
325
+ entry.parentId = prevId;
326
+ prevId = entry.id;
327
+
328
+ // Convert firstKeptEntryIndex to firstKeptEntryId for compaction
329
+ if (entry.type === "compaction") {
330
+ const comp = entry as CompactionEntry & { firstKeptEntryIndex?: number };
331
+ if (typeof comp.firstKeptEntryIndex === "number") {
332
+ const targetEntry = entries[comp.firstKeptEntryIndex];
333
+ if (targetEntry && targetEntry.type !== "session") {
334
+ comp.firstKeptEntryId = targetEntry.id;
335
+ }
336
+ delete comp.firstKeptEntryIndex;
337
+ }
338
+ }
339
+ }
340
+ }
341
+
342
+ /** Migrate v2 → v3: rename hookMessage role to custom. Mutates in place. */
343
+ function migrateV2ToV3(entries: FileEntry[]): void {
344
+ for (const entry of entries) {
345
+ if (entry.type === "session") {
346
+ entry.version = 3;
347
+ continue;
348
+ }
349
+
350
+ if (entry.type === "message") {
351
+ const msg = entry.message as { role?: string };
352
+ if (msg.role === "hookMessage") {
353
+ (entry.message as { role: string }).role = "custom";
354
+ }
355
+ }
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Run all necessary migrations to bring entries to current version.
361
+ * Mutates entries in place. Returns true if any migration was applied.
362
+ */
363
+ function migrateToCurrentVersion(entries: FileEntry[]): boolean {
364
+ const header = entries.find(e => e.type === "session") as SessionHeader | undefined;
365
+ const version = header?.version ?? 1;
366
+
367
+ if (version >= CURRENT_SESSION_VERSION) return false;
368
+
369
+ if (version < 2) migrateV1ToV2(entries);
370
+ if (version < 3) migrateV2ToV3(entries);
371
+
372
+ return true;
373
+ }
374
+
375
+ /** Exported for testing */
376
+ export function migrateSessionEntries(entries: FileEntry[]): void {
377
+ migrateToCurrentVersion(entries);
378
+ }
379
+
380
+ const migratedSessionRoots = new Set<string>();
381
+
382
+ /**
383
+ * Merge or rename a legacy session directory into its canonical target.
384
+ * Best effort: callers decide whether migration failures should surface.
385
+ */
386
+ function migrateSessionDirPath(oldPath: string, newPath: string): void {
387
+ const existing = fs.statSync(newPath, { throwIfNoEntry: false });
388
+ if (existing?.isDirectory()) {
389
+ for (const file of fs.readdirSync(oldPath)) {
390
+ const src = path.join(oldPath, file);
391
+ const dst = path.join(newPath, file);
392
+ if (!fs.existsSync(dst)) {
393
+ fs.renameSync(src, dst);
394
+ }
395
+ }
396
+ fs.rmSync(oldPath, { recursive: true, force: true });
397
+ return;
398
+ }
399
+ if (existing) {
400
+ fs.rmSync(newPath, { recursive: true, force: true });
401
+ }
402
+ fs.renameSync(oldPath, newPath);
403
+ }
404
+
405
+ function encodeLegacyAbsoluteSessionDirName(cwd: string): string {
406
+ const resolvedCwd = path.resolve(cwd);
407
+ return `--${resolvedCwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
408
+ }
409
+
410
+ function encodeRelativeSessionDirName(prefix: string, root: string, cwd: string): string {
411
+ const relative = path.relative(root, cwd).replace(/[/\\:]/g, "-");
412
+ return relative ? (prefix.endsWith("-") ? `${prefix}${relative}` : `${prefix}-${relative}`) : prefix;
413
+ }
414
+
415
+ function getDefaultSessionDirName(cwd: string): { encodedDirName: string; resolvedCwd: string } {
416
+ const resolvedCwd = path.resolve(cwd);
417
+ const canonicalCwd = resolveEquivalentPath(resolvedCwd);
418
+ const home = resolveEquivalentPath(os.homedir());
419
+ const tempRoot = resolveEquivalentPath(os.tmpdir());
420
+ const encodedDirName = pathIsWithin(home, canonicalCwd)
421
+ ? encodeRelativeSessionDirName("-", home, canonicalCwd)
422
+ : pathIsWithin(tempRoot, canonicalCwd)
423
+ ? encodeRelativeSessionDirName("-tmp", tempRoot, canonicalCwd)
424
+ : encodeLegacyAbsoluteSessionDirName(canonicalCwd);
425
+ return { encodedDirName, resolvedCwd };
426
+ }
427
+
428
+ /**
429
+ * Migrate old `--<home-encoded>-*--` session dirs to the new `-*` format.
430
+ * Runs once per sessions root on first access, best-effort.
431
+ */
432
+ function migrateHomeSessionDirs(sessionsRoot: string): void {
433
+ if (migratedSessionRoots.has(sessionsRoot)) return;
434
+ migratedSessionRoots.add(sessionsRoot);
435
+
436
+ const home = os.homedir();
437
+ const homeEncoded = home.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-");
438
+ const oldPrefix = `--${homeEncoded}-`;
439
+ const oldExact = `--${homeEncoded}--`;
440
+
441
+ let entries: string[];
442
+ try {
443
+ entries = fs.readdirSync(sessionsRoot);
444
+ } catch {
445
+ return;
446
+ }
447
+
448
+ for (const entry of entries) {
449
+ let remainder: string;
450
+ if (entry === oldExact) {
451
+ remainder = "";
452
+ } else if (entry.startsWith(oldPrefix) && entry.endsWith("--")) {
453
+ remainder = entry.slice(oldPrefix.length, -2);
454
+ } else {
455
+ continue;
456
+ }
457
+
458
+ const newName = remainder ? `-${remainder}` : "-";
459
+ const oldPath = path.join(sessionsRoot, entry);
460
+ const newPath = path.join(sessionsRoot, newName);
461
+
462
+ try {
463
+ migrateSessionDirPath(oldPath, newPath);
464
+ } catch {
465
+ // Best effort
466
+ }
467
+ }
468
+ }
469
+
470
+ function migrateLegacyAbsoluteSessionDir(cwd: string, sessionDir: string, sessionsRoot: string): void {
471
+ const legacyDir = path.join(sessionsRoot, encodeLegacyAbsoluteSessionDirName(cwd));
472
+ if (legacyDir === sessionDir || !fs.existsSync(legacyDir)) return;
473
+
474
+ try {
475
+ migrateSessionDirPath(legacyDir, sessionDir);
476
+ } catch {
477
+ // Best effort
478
+ }
479
+ }
480
+
481
+ function resolveManagedSessionRoot(sessionDir: string, cwd: string): string | undefined {
482
+ const currentDirName = path.basename(sessionDir);
483
+ const { encodedDirName } = getDefaultSessionDirName(cwd);
484
+ if (currentDirName !== encodedDirName && currentDirName !== encodeLegacyAbsoluteSessionDirName(cwd)) {
485
+ return undefined;
486
+ }
487
+ return path.dirname(sessionDir);
488
+ }
489
+
490
+ /** Exported for compaction.test.ts */
491
+ export function parseSessionEntries(content: string): FileEntry[] {
492
+ return parseJsonlLenient<FileEntry>(content);
493
+ }
494
+
495
+ export function getLatestCompactionEntry(entries: SessionEntry[]): CompactionEntry | null {
496
+ for (let i = entries.length - 1; i >= 0; i--) {
497
+ if (entries[i].type === "compaction") {
498
+ return entries[i] as CompactionEntry;
499
+ }
500
+ }
501
+ return null;
502
+ }
503
+
504
+ /**
505
+ * Build the session context from entries using tree traversal.
506
+ * If leafId is provided, walks from that entry to root.
507
+ * Handles compaction and branch summaries along the path.
508
+ */
509
+ export function buildSessionContext(
510
+ entries: SessionEntry[],
511
+ leafId?: string | null,
512
+ byId?: Map<string, SessionEntry>,
513
+ ): SessionContext {
514
+ // Build uuid index if not available
515
+ if (!byId) {
516
+ byId = new Map<string, SessionEntry>();
517
+ for (const entry of entries) {
518
+ byId.set(entry.id, entry);
519
+ }
520
+ }
521
+
522
+ // Find leaf
523
+ let leaf: SessionEntry | undefined;
524
+ if (leafId === null) {
525
+ // Explicitly null - return no messages (navigated to before first entry)
526
+ return {
527
+ messages: [],
528
+ thinkingLevel: "off",
529
+ serviceTier: undefined,
530
+ models: {},
531
+ injectedTtsrRules: [],
532
+ selectedMCPToolNames: [],
533
+ hasPersistedMCPToolSelection: false,
534
+ mode: "none",
535
+ };
536
+ }
537
+ if (leafId) {
538
+ leaf = byId.get(leafId);
539
+ }
540
+ if (!leaf) {
541
+ // Fallback to last entry (when leafId is undefined)
542
+ leaf = entries[entries.length - 1];
543
+ }
544
+
545
+ if (!leaf) {
546
+ return {
547
+ messages: [],
548
+ thinkingLevel: "off",
549
+ serviceTier: undefined,
550
+ models: {},
551
+ injectedTtsrRules: [],
552
+ selectedMCPToolNames: [],
553
+ hasPersistedMCPToolSelection: false,
554
+ mode: "none",
555
+ };
556
+ }
557
+
558
+ // Walk from leaf to root, collecting path
559
+ const path: SessionEntry[] = [];
560
+ let current: SessionEntry | undefined = leaf;
561
+ while (current) {
562
+ path.unshift(current);
563
+ current = current.parentId ? byId.get(current.parentId) : undefined;
564
+ }
565
+
566
+ // Extract settings and find compaction
567
+ let thinkingLevel: string | undefined = "off";
568
+ let serviceTier: ServiceTier | undefined;
569
+ const models: Record<string, string> = {};
570
+ let activeContextName: string | undefined;
571
+ let activeContextTenant: string | undefined;
572
+ let compaction: CompactionEntry | null = null;
573
+ const injectedTtsrRulesSet = new Set<string>();
574
+ let selectedMCPToolNames: string[] = [];
575
+ let hasPersistedMCPToolSelection = false;
576
+ let mode = "none";
577
+ let modeData: Record<string, unknown> | undefined;
578
+
579
+ for (const entry of path) {
580
+ if (entry.type === "thinking_level_change") {
581
+ thinkingLevel = entry.thinkingLevel ?? "off";
582
+ } else if (entry.type === "model_change") {
583
+ // New format: { model: "provider/id", role?: string }
584
+ if (entry.model) {
585
+ const role = entry.role ?? "default";
586
+ models[role] = entry.model;
587
+ }
588
+ } else if (entry.type === "context_change") {
589
+ activeContextName = entry.contextName;
590
+ activeContextTenant = entry.tenant;
591
+ } else if (entry.type === "service_tier_change") {
592
+ serviceTier = entry.serviceTier ?? undefined;
593
+ } else if (entry.type === "message" && entry.message.role === "assistant") {
594
+ // Infer default model from assistant messages
595
+ models.default = `${entry.message.provider}/${entry.message.model}`;
596
+ } else if (entry.type === "compaction") {
597
+ compaction = entry;
598
+ } else if (entry.type === "ttsr_injection") {
599
+ // Collect injected TTSR rule names
600
+ for (const ruleName of entry.injectedRules) {
601
+ injectedTtsrRulesSet.add(ruleName);
602
+ }
603
+ } else if (entry.type === "mcp_tool_selection") {
604
+ selectedMCPToolNames = [...entry.selectedToolNames];
605
+ hasPersistedMCPToolSelection = true;
606
+ } else if (entry.type === "mode_change") {
607
+ mode = entry.mode;
608
+ modeData = entry.data;
609
+ }
610
+ }
611
+
612
+ const injectedTtsrRules = Array.from(injectedTtsrRulesSet);
613
+
614
+ // Build messages and collect corresponding entries
615
+ // When there's a compaction, we need to:
616
+ // 1. Emit summary first (entry = compaction)
617
+ // 2. Emit kept messages (from firstKeptEntryId up to compaction)
618
+ // 3. Emit messages after compaction
619
+ const messages: AgentMessage[] = [];
620
+
621
+ const appendMessage = (entry: SessionEntry) => {
622
+ if (entry.type === "message") {
623
+ messages.push(entry.message);
624
+ } else if (entry.type === "custom_message") {
625
+ messages.push(
626
+ createCustomMessage(
627
+ entry.customType,
628
+ entry.content,
629
+ entry.display,
630
+ entry.details,
631
+ entry.timestamp,
632
+ entry.attribution,
633
+ ),
634
+ );
635
+ } else if (entry.type === "branch_summary" && entry.summary) {
636
+ messages.push(createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp));
637
+ }
638
+ };
639
+
640
+ if (compaction) {
641
+ const providerPayload: ProviderPayload | undefined = (() => {
642
+ const candidate = compaction.preserveData?.openaiRemoteCompaction;
643
+ if (!candidate || typeof candidate !== "object") return undefined;
644
+ const remote = candidate as { provider?: unknown; replacementHistory?: unknown };
645
+ if (typeof remote.provider !== "string" || remote.provider.length === 0) return undefined;
646
+ if (!Array.isArray(remote.replacementHistory)) return undefined;
647
+ return {
648
+ type: "openaiResponsesHistory",
649
+ provider: remote.provider,
650
+ items: remote.replacementHistory as Array<Record<string, unknown>>,
651
+ };
652
+ })();
653
+ const remoteReplacementHistory = providerPayload?.items;
654
+
655
+ // Emit summary first
656
+ messages.push(
657
+ createCompactionSummaryMessage(
658
+ compaction.summary,
659
+ compaction.tokensBefore,
660
+ compaction.timestamp,
661
+ compaction.shortSummary,
662
+ providerPayload,
663
+ ),
664
+ );
665
+
666
+ // Find compaction index in path
667
+ const compactionIdx = path.findIndex(e => e.type === "compaction" && e.id === compaction.id);
668
+
669
+ if (!remoteReplacementHistory) {
670
+ // Emit kept messages (before compaction, starting from firstKeptEntryId)
671
+ let foundFirstKept = false;
672
+ for (let i = 0; i < compactionIdx; i++) {
673
+ const entry = path[i];
674
+ if (entry.id === compaction.firstKeptEntryId) {
675
+ foundFirstKept = true;
676
+ }
677
+ if (foundFirstKept) {
678
+ appendMessage(entry);
679
+ }
680
+ }
681
+ }
682
+
683
+ // Emit messages after compaction
684
+ for (let i = compactionIdx + 1; i < path.length; i++) {
685
+ const entry = path[i];
686
+ appendMessage(entry);
687
+ }
688
+ } else {
689
+ // No compaction - emit all messages, handle branch summaries and custom messages
690
+ for (const entry of path) {
691
+ appendMessage(entry);
692
+ }
693
+ }
694
+
695
+ return {
696
+ messages,
697
+ thinkingLevel,
698
+ serviceTier,
699
+ models,
700
+ activeContextName,
701
+ activeContextTenant,
702
+ injectedTtsrRules,
703
+ selectedMCPToolNames,
704
+ hasPersistedMCPToolSelection,
705
+ mode,
706
+ modeData,
707
+ };
708
+ }
709
+
710
+ /**
711
+ * Compute the default session directory for a cwd.
712
+ * Classifies cwd by canonical location so symlink/alias paths resolve to the
713
+ * same home-relative or temp-root directory names as their real targets.
714
+ */
715
+ function computeDefaultSessionDir(
716
+ cwd: string,
717
+ storage: SessionStorage,
718
+ sessionsRoot: string = getSessionsDir(),
719
+ ): string {
720
+ const { encodedDirName, resolvedCwd } = getDefaultSessionDirName(cwd);
721
+ migrateHomeSessionDirs(sessionsRoot);
722
+ const sessionDir = path.join(sessionsRoot, encodedDirName);
723
+ migrateLegacyAbsoluteSessionDir(resolvedCwd, sessionDir, sessionsRoot);
724
+ storage.ensureDirSync(sessionDir);
725
+ return sessionDir;
726
+ }
727
+
728
+ // =============================================================================
729
+ // Terminal breadcrumbs: maps terminal (TTY) -> last session file for --continue
730
+ // =============================================================================
731
+
732
+ /**
733
+ * Write a breadcrumb linking the current terminal to a session file.
734
+ * The breadcrumb contains the cwd and session path so --continue can
735
+ * find "this terminal's last session" even when running concurrent instances.
736
+ */
737
+ function writeTerminalBreadcrumb(cwd: string, sessionFile: string): void {
738
+ const terminalId = getTerminalId();
739
+ if (!terminalId) return;
740
+
741
+ const breadcrumbDir = getTerminalSessionsDir();
742
+ const breadcrumbFile = path.join(breadcrumbDir, terminalId);
743
+ const content = `${cwd}\n${sessionFile}\n`;
744
+ // Best-effort — don't break session creation if breadcrumb fails
745
+ Bun.write(breadcrumbFile, content).catch(() => {});
746
+ }
747
+
748
+ /**
749
+ * Read the terminal breadcrumb for the current terminal, scoped to a cwd.
750
+ * Returns the session file path if it exists and matches the cwd, null otherwise.
751
+ */
752
+ async function readTerminalBreadcrumb(cwd: string): Promise<string | null> {
753
+ const terminalId = getTerminalId();
754
+ if (!terminalId) return null;
755
+
756
+ try {
757
+ const breadcrumbFile = path.join(getTerminalSessionsDir(), terminalId);
758
+ const content = await Bun.file(breadcrumbFile).text();
759
+ const lines = content.trim().split("\n");
760
+ if (lines.length < 2) return null;
761
+
762
+ const breadcrumbCwd = lines[0];
763
+ const sessionFile = lines[1];
764
+
765
+ // Only return if cwd matches (user might have cd'd)
766
+ if (path.resolve(breadcrumbCwd) !== path.resolve(cwd)) return null;
767
+
768
+ // Verify the session file still exists
769
+ const stat = fs.statSync(sessionFile, { throwIfNoEntry: false });
770
+ if (stat?.isFile()) return sessionFile;
771
+ } catch (err) {
772
+ if (!isEnoent(err)) logger.debug("Terminal breadcrumb read failed", { err });
773
+ // Breadcrumb doesn't exist or is corrupt — fall through
774
+ }
775
+ return null;
776
+ }
777
+
778
+ /** Exported for testing */
779
+ export async function loadEntriesFromFile(
780
+ filePath: string,
781
+ storage: SessionStorage = new FileSessionStorage(),
782
+ ): Promise<FileEntry[]> {
783
+ let content: string;
784
+ try {
785
+ content = await storage.readText(filePath);
786
+ } catch (err) {
787
+ if (isEnoent(err)) return [];
788
+ throw err;
789
+ }
790
+ const entries = parseJsonlLenient<FileEntry>(content);
791
+
792
+ // Validate session header
793
+ if (entries.length === 0) return entries;
794
+ const header = entries[0] as SessionHeader;
795
+ if (header.type !== "session" || typeof header.id !== "string") {
796
+ return [];
797
+ }
798
+
799
+ return entries;
800
+ }
801
+
802
+ /**
803
+ * Resolve blob references in loaded entries, restoring both session image blocks and persisted
804
+ * provider image URLs back to the inline data expected by downstream transports. Mutates entries in place.
805
+ */
806
+ function hasImageUrl(value: unknown): value is { image_url: string } {
807
+ return typeof value === "object" && value !== null && "image_url" in value && typeof value.image_url === "string";
808
+ }
809
+
810
+ async function resolvePersistedImageUrlRefs(value: unknown, blobStore: BlobStore): Promise<void> {
811
+ if (Array.isArray(value)) {
812
+ await Promise.all(value.map(item => resolvePersistedImageUrlRefs(item, blobStore)));
813
+ return;
814
+ }
815
+
816
+ if (typeof value !== "object" || value === null) return;
817
+
818
+ if (hasImageUrl(value) && isBlobRef(value.image_url)) {
819
+ value.image_url = await resolveImageDataUrl(blobStore, value.image_url);
820
+ }
821
+
822
+ await Promise.all(Object.values(value).map(item => resolvePersistedImageUrlRefs(item, blobStore)));
823
+ }
824
+
825
+ async function resolveBlobRefsInEntries(entries: FileEntry[], blobStore: BlobStore): Promise<void> {
826
+ const promises: Promise<void>[] = [];
827
+
828
+ for (const entry of entries) {
829
+ if (entry.type === "session") continue;
830
+
831
+ let contentArray: unknown[] | undefined;
832
+ if (entry.type === "message" && "content" in entry.message && Array.isArray(entry.message.content)) {
833
+ contentArray = entry.message.content;
834
+ } else if (entry.type === "custom_message" && Array.isArray(entry.content)) {
835
+ contentArray = entry.content;
836
+ }
837
+
838
+ if (contentArray) {
839
+ for (const block of contentArray) {
840
+ if (isImageBlock(block) && isBlobRef(block.data)) {
841
+ promises.push(
842
+ resolveImageData(blobStore, block.data).then(resolved => {
843
+ block.data = resolved;
844
+ }),
845
+ );
846
+ }
847
+ }
848
+ }
849
+
850
+ promises.push(resolvePersistedImageUrlRefs(entry, blobStore));
851
+ }
852
+
853
+ await Promise.all(promises);
854
+ }
855
+
856
+ /**
857
+ * Lightweight metadata for a session file, used in session picker UI.
858
+ * Uses lazy getters to defer string formatting until actually displayed.
859
+ */
860
+ function sanitizeSessionName(value: string | undefined): string | undefined {
861
+ if (!value) return undefined;
862
+ const firstLine = value.split(/\r?\n/)[0] ?? "";
863
+ const stripped = firstLine.replace(/[\x00-\x1F\x7F]/g, "");
864
+ const trimmed = stripped.trim();
865
+ return trimmed.length > 0 ? trimmed : undefined;
866
+ }
867
+
868
+ class RecentSessionInfo {
869
+ #fullName: string | undefined;
870
+ #name: string | undefined;
871
+ #timeAgo: string | undefined;
872
+
873
+ constructor(
874
+ readonly path: string,
875
+ readonly mtime: number,
876
+ header: Record<string, unknown>,
877
+ firstPrompt?: string,
878
+ ) {
879
+ // Extract title from session header, falling back to first user prompt, then id
880
+ const trystr = (v: unknown) => (typeof v === "string" ? v : undefined);
881
+ this.#fullName =
882
+ sanitizeSessionName(trystr(header.title)) ??
883
+ sanitizeSessionName(firstPrompt) ??
884
+ sanitizeSessionName(trystr(header.id));
885
+ }
886
+
887
+ /** Full session name from header, or filename without extension as fallback */
888
+ get fullName(): string {
889
+ if (this.#fullName) return this.#fullName;
890
+ this.#fullName = this.path.split("/").pop()?.replace(".jsonl", "") ?? "Unknown";
891
+ return this.#fullName;
892
+ }
893
+
894
+ /** Truncated name for display (max 40 chars) */
895
+ get name(): string {
896
+ if (this.#name) return this.#name;
897
+ const fullName = this.fullName;
898
+ this.#name = fullName.length <= 40 ? fullName : `${fullName.slice(0, 39)}…`;
899
+ return this.#name;
900
+ }
901
+
902
+ /** Human-readable relative time (e.g., "2 hours ago") */
903
+ get timeAgo(): string {
904
+ if (this.#timeAgo) return this.#timeAgo;
905
+ this.#timeAgo = formatTimeAgo(new Date(this.mtime));
906
+ return this.#timeAgo;
907
+ }
908
+ }
909
+
910
+ /**
911
+ * Extracts the text content from a user message entry.
912
+ * Returns undefined if the entry is not a user message or has no text.
913
+ */
914
+ function extractFirstUserPrompt(entries: Array<Record<string, unknown>>): string | undefined {
915
+ for (const entry of entries) {
916
+ if (entry.type !== "message") continue;
917
+ const message = entry.message as Record<string, unknown> | undefined;
918
+ if (message?.role !== "user") continue;
919
+ const content = message.content;
920
+ if (typeof content === "string") return content;
921
+ if (Array.isArray(content)) {
922
+ for (const block of content) {
923
+ if (typeof block === "object" && block !== null && "text" in block) {
924
+ const text = (block as { text: unknown }).text;
925
+ if (typeof text === "string") return text;
926
+ }
927
+ }
928
+ }
929
+ }
930
+ return undefined;
931
+ }
932
+
933
+ /**
934
+ * Reads all session files from the directory and returns them sorted by mtime (newest first).
935
+ * Uses low-level file I/O to efficiently read only the first 4KB of each file
936
+ * to extract the JSON header and first user message without loading entire session logs into memory.
937
+ */
938
+ async function getSortedSessions(sessionDir: string, storage: SessionStorage): Promise<RecentSessionInfo[]> {
939
+ try {
940
+ const files: string[] = storage.listFilesSync(sessionDir, "*.jsonl");
941
+ const sessions: RecentSessionInfo[] = [];
942
+ await Promise.all(
943
+ files.map(async (path: string) => {
944
+ try {
945
+ const content = await storage.readTextPrefix(path, 4096);
946
+ const entries = parseJsonlLenient<Record<string, unknown>>(content);
947
+ if (entries.length === 0) return;
948
+ const header = entries[0] as Record<string, unknown>;
949
+ if (header.type !== "session" || typeof header.id !== "string") return;
950
+ const mtime = storage.statSync(path).mtimeMs;
951
+ const firstPrompt = header.title ? undefined : extractFirstUserPrompt(entries);
952
+ sessions.push(new RecentSessionInfo(path, mtime, header, firstPrompt));
953
+ } catch {}
954
+ }),
955
+ );
956
+ return sessions.sort((a, b) => b.mtime - a.mtime);
957
+ } catch {
958
+ return [];
959
+ }
960
+ }
961
+
962
+ /** Exported for testing */
963
+ export async function findMostRecentSession(
964
+ sessionDir: string,
965
+ storage: SessionStorage = new FileSessionStorage(),
966
+ ): Promise<string | null> {
967
+ const sessions = await getSortedSessions(sessionDir, storage);
968
+ return sessions[0]?.path || null;
969
+ }
970
+
971
+ /** Format a time difference as a human-readable string */
972
+ function formatTimeAgo(date: Date): string {
973
+ const now = Date.now();
974
+ const diffMs = now - date.getTime();
975
+ const diffMins = Math.floor(diffMs / 60000);
976
+ const diffHours = Math.floor(diffMs / 3600000);
977
+ const diffDays = Math.floor(diffMs / 86400000);
978
+
979
+ if (diffMins < 1) return "just now";
980
+ if (diffMins < 60) return `${diffMins}m ago`;
981
+ if (diffHours < 24) return `${diffHours}h ago`;
982
+ if (diffDays < 7) return `${diffDays}d ago`;
983
+ return date.toLocaleDateString();
984
+ }
985
+
986
+ const MAX_PERSIST_CHARS = 500_000;
987
+ const TRUNCATION_NOTICE = "\n\n[Session persistence truncated large content]";
988
+ /** Minimum base64 length to externalize to blob store (skip tiny inline images) */
989
+ const BLOB_EXTERNALIZE_THRESHOLD = 1024;
990
+ const TEXT_CONTENT_KEY = "content";
991
+
992
+ /**
993
+ * Recursively truncate large strings in an object for session persistence.
994
+ * - Truncates any oversized string fields (key-agnostic)
995
+ * - Replaces oversized image blocks with text notices
996
+ * - Updates lineCount when content is truncated
997
+ * - Returns original object if no changes needed (structural sharing)
998
+ */
999
+ function truncateString(value: string, maxLength: number): string {
1000
+ if (value.length <= maxLength) return value;
1001
+ let truncated = value.slice(0, maxLength);
1002
+ if (truncated.length > 0) {
1003
+ const last = truncated.charCodeAt(truncated.length - 1);
1004
+ if (last >= 0xd800 && last <= 0xdbff) {
1005
+ truncated = truncated.slice(0, -1);
1006
+ }
1007
+ }
1008
+ return truncated;
1009
+ }
1010
+
1011
+ function isImageBlock(value: unknown): value is { type: "image"; data: string; mimeType?: string } {
1012
+ return (
1013
+ typeof value === "object" &&
1014
+ value !== null &&
1015
+ "type" in value &&
1016
+ (value as { type?: string }).type === "image" &&
1017
+ "data" in value &&
1018
+ typeof (value as { data?: string }).data === "string"
1019
+ );
1020
+ }
1021
+
1022
+ async function truncateForPersistence(obj: FileEntry, blobStore: BlobStore, key?: string): Promise<FileEntry>;
1023
+ async function truncateForPersistence(obj: string, blobStore: BlobStore, key?: string): Promise<string>;
1024
+ async function truncateForPersistence(obj: unknown[], blobStore: BlobStore, key?: string): Promise<unknown[]>;
1025
+ async function truncateForPersistence(obj: object, blobStore: BlobStore, key?: string): Promise<object>;
1026
+ async function truncateForPersistence(
1027
+ obj: null | undefined,
1028
+ blobStore: BlobStore,
1029
+ key?: string,
1030
+ ): Promise<null | undefined>;
1031
+ async function truncateForPersistence(obj: unknown, blobStore: BlobStore, key?: string): Promise<unknown> {
1032
+ if (obj === null || obj === undefined) return obj;
1033
+
1034
+ if (typeof obj === "string") {
1035
+ if (key === "image_url" && isImageDataUrl(obj)) {
1036
+ return externalizeImageDataUrl(blobStore, obj);
1037
+ }
1038
+
1039
+ if (obj.length > MAX_PERSIST_CHARS) {
1040
+ // Cryptographic signatures must be preserved exactly or cleared entirely — never truncated.
1041
+ // Truncation would produce an invalid signature that the API rejects.
1042
+ if (key === "thinkingSignature" || key === "thoughtSignature" || key === "textSignature") {
1043
+ return "";
1044
+ }
1045
+
1046
+ const limit = Math.max(0, MAX_PERSIST_CHARS - TRUNCATION_NOTICE.length);
1047
+ return `${truncateString(obj, limit)}${TRUNCATION_NOTICE}`;
1048
+ }
1049
+
1050
+ return obj;
1051
+ }
1052
+
1053
+ if (Array.isArray(obj)) {
1054
+ let changed = false;
1055
+ const result = await Promise.all(
1056
+ obj.map(async item => {
1057
+ // Special handling: compress oversized images while preserving shape
1058
+ if (key === TEXT_CONTENT_KEY && isImageBlock(item)) {
1059
+ if (!isBlobRef(item.data) && item.data.length >= BLOB_EXTERNALIZE_THRESHOLD) {
1060
+ changed = true;
1061
+ const blobRef = await externalizeImageData(blobStore, item.data);
1062
+ return { ...item, data: blobRef };
1063
+ }
1064
+ }
1065
+
1066
+ const newItem = await truncateForPersistence(item, blobStore, key);
1067
+ if (newItem !== item) changed = true;
1068
+ return newItem;
1069
+ }),
1070
+ );
1071
+ return changed ? result : obj;
1072
+ }
1073
+
1074
+ if (typeof obj === "object") {
1075
+ let changed = false;
1076
+ const entries: Array<readonly [string, unknown]> = await Promise.all(
1077
+ Object.entries(obj).flatMap(([childKey, value]) => {
1078
+ // Strip transient/redundant properties that shouldn't be persisted.
1079
+ // - partialJson: streaming accumulator for tool call JSON parsing
1080
+ // - jsonlEvents: raw subprocess streaming events (already saved to artifact files)
1081
+ if (childKey === "partialJson" || childKey === "jsonlEvents") {
1082
+ changed = true;
1083
+ return [];
1084
+ }
1085
+
1086
+ return [
1087
+ (async () => {
1088
+ const newValue = await truncateForPersistence(value, blobStore, childKey);
1089
+ if (newValue !== value) changed = true;
1090
+ return [childKey, newValue] as const;
1091
+ })(),
1092
+ ];
1093
+ }),
1094
+ );
1095
+
1096
+ if (!changed) return obj;
1097
+
1098
+ const contentEntry = entries.find(([childKey]) => childKey === "content");
1099
+ const lineCountEntry = entries.find(([childKey]) => childKey === "lineCount");
1100
+ if (
1101
+ contentEntry &&
1102
+ typeof contentEntry[1] === "string" &&
1103
+ lineCountEntry &&
1104
+ typeof lineCountEntry[1] === "number"
1105
+ ) {
1106
+ const content = contentEntry[1];
1107
+ const updatedEntries = entries.map(([childKey, value]) =>
1108
+ childKey === "lineCount" ? ([childKey, content.split("\n").length] as const) : ([childKey, value] as const),
1109
+ );
1110
+ return Object.fromEntries(updatedEntries);
1111
+ }
1112
+ return Object.fromEntries(entries);
1113
+ }
1114
+
1115
+ return obj;
1116
+ }
1117
+
1118
+ async function prepareEntryForPersistence(entry: FileEntry, blobStore: BlobStore): Promise<FileEntry> {
1119
+ return truncateForPersistence(entry, blobStore);
1120
+ }
1121
+
1122
+ class NdjsonFileWriter {
1123
+ #writer: SessionStorageWriter;
1124
+ #closed = false;
1125
+ #closing = false;
1126
+ #error: Error | undefined;
1127
+ #pendingWrites: Promise<void> = Promise.resolve();
1128
+ #onError: ((err: Error) => void) | undefined;
1129
+
1130
+ constructor(storage: SessionStorage, path: string, options?: { flags?: "a" | "w"; onError?: (err: Error) => void }) {
1131
+ this.#onError = options?.onError;
1132
+ this.#writer = storage.openWriter(path, {
1133
+ flags: options?.flags ?? "a",
1134
+ onError: (err: Error) => this.#recordError(err),
1135
+ });
1136
+ }
1137
+
1138
+ #recordError(err: unknown): Error {
1139
+ const writeErr = toError(err);
1140
+ if (!this.#error) this.#error = writeErr;
1141
+ this.#onError?.(writeErr);
1142
+ return writeErr;
1143
+ }
1144
+
1145
+ #enqueue(task: () => Promise<void>): Promise<void> {
1146
+ const run = async () => {
1147
+ if (this.#error) throw this.#error;
1148
+ await task();
1149
+ };
1150
+ const next = this.#pendingWrites.then(run);
1151
+ void next.catch((err: unknown) => {
1152
+ if (!this.#error) this.#error = toError(err);
1153
+ });
1154
+ this.#pendingWrites = next;
1155
+ return next;
1156
+ }
1157
+
1158
+ async #writeLine(line: string): Promise<void> {
1159
+ if (this.#error) throw this.#error;
1160
+ try {
1161
+ await this.#writer.writeLine(line);
1162
+ } catch (err) {
1163
+ throw this.#recordError(err);
1164
+ }
1165
+ }
1166
+
1167
+ /** Queue a write. Returns a promise so callers can await if needed. */
1168
+ write(entry: FileEntry): Promise<void> {
1169
+ if (this.#closed || this.#closing) throw new Error("Writer closed");
1170
+ if (this.#error) throw this.#error;
1171
+ const line = `${JSON.stringify(entry)}\n`;
1172
+ return this.#enqueue(() => this.#writeLine(line));
1173
+ }
1174
+
1175
+ /** Flush all buffered data to disk. Waits for all queued writes. */
1176
+ async flush(): Promise<void> {
1177
+ if (this.#closed) return;
1178
+ if (this.#error) throw this.#error;
1179
+
1180
+ await this.#enqueue(async () => {});
1181
+
1182
+ if (this.#error) throw this.#error;
1183
+
1184
+ try {
1185
+ await this.#writer.flush();
1186
+ } catch (err) {
1187
+ throw this.#recordError(err);
1188
+ }
1189
+ }
1190
+
1191
+ /** Sync data to persistent storage. */
1192
+ async fsync(): Promise<void> {
1193
+ if (this.#closed) return;
1194
+ if (this.#error) throw this.#error;
1195
+ try {
1196
+ await this.#writer.fsync();
1197
+ } catch (err) {
1198
+ throw this.#recordError(err);
1199
+ }
1200
+ }
1201
+
1202
+ /** Close the writer, flushing all data. */
1203
+ async close(): Promise<void> {
1204
+ if (this.#closed || this.#closing) return;
1205
+ this.#closing = true;
1206
+
1207
+ let closeError: Error | undefined;
1208
+ try {
1209
+ await this.flush();
1210
+ } catch (err) {
1211
+ closeError = toError(err);
1212
+ }
1213
+
1214
+ try {
1215
+ await this.#pendingWrites;
1216
+ } catch (err) {
1217
+ if (!closeError) closeError = toError(err);
1218
+ }
1219
+
1220
+ try {
1221
+ await this.#writer.close();
1222
+ } catch (err) {
1223
+ const endErr = this.#recordError(err);
1224
+ if (!closeError) closeError = endErr;
1225
+ }
1226
+
1227
+ this.#closed = true;
1228
+
1229
+ if (!closeError && this.#error) closeError = this.#error;
1230
+ if (closeError) throw closeError;
1231
+ }
1232
+
1233
+ /** Check if there's a stored error. */
1234
+ getError(): Error | undefined {
1235
+ return this.#error;
1236
+ }
1237
+ }
1238
+
1239
+ /** Get recent sessions for display in welcome screen */
1240
+ export async function getRecentSessions(
1241
+ sessionDir: string,
1242
+ limit = 3,
1243
+ storage: SessionStorage = new FileSessionStorage(),
1244
+ ): Promise<RecentSessionInfo[]> {
1245
+ const sessions = await getSortedSessions(sessionDir, storage);
1246
+ return sessions.slice(0, limit);
1247
+ }
1248
+
1249
+ /**
1250
+ * Manages conversation sessions as append-only trees stored in JSONL files.
1251
+ *
1252
+ * Each session entry has an id and parentId forming a tree structure. The "leaf"
1253
+ * pointer tracks the current position. Appending creates a child of the current leaf.
1254
+ * Branching moves the leaf to an earlier entry, allowing new branches without
1255
+ * modifying history.
1256
+ *
1257
+ * Use buildSessionContext() to get the resolved message list for the LLM, which
1258
+ * handles compaction summaries and follows the path from root to current leaf.
1259
+ */
1260
+ export interface UsageStatistics {
1261
+ input: number;
1262
+ output: number;
1263
+ cacheRead: number;
1264
+ cacheWrite: number;
1265
+ premiumRequests: number;
1266
+ cost: number;
1267
+ }
1268
+
1269
+ function getTaskToolUsage(details: unknown): Usage | undefined {
1270
+ if (!details || typeof details !== "object") return undefined;
1271
+ const record = details as Record<string, unknown>;
1272
+ const usage = record.usage;
1273
+ if (!usage || typeof usage !== "object") return undefined;
1274
+ return usage as Usage;
1275
+ }
1276
+
1277
+ function extractTextFromContent(content: Message["content"]): string {
1278
+ if (typeof content === "string") return content;
1279
+ return content
1280
+ .filter((block): block is TextContent => block.type === "text")
1281
+ .map(block => block.text)
1282
+ .join(" ");
1283
+ }
1284
+
1285
+ async function collectSessionsFromFiles(files: string[], storage: SessionStorage): Promise<SessionInfo[]> {
1286
+ const sessions: SessionInfo[] = [];
1287
+
1288
+ // Collect session info for all files in parallel
1289
+ await Promise.all(
1290
+ files.map(async file => {
1291
+ try {
1292
+ const content = await storage.readText(file);
1293
+ const entries = parseJsonlLenient<Record<string, unknown>>(content);
1294
+ if (entries.length === 0) return;
1295
+
1296
+ // Check first entry for valid session header
1297
+ type SessionHeaderShape = {
1298
+ type: string;
1299
+ id: string;
1300
+ cwd?: string;
1301
+ title?: string;
1302
+ titleSource?: "auto" | "user";
1303
+ timestamp: string;
1304
+ };
1305
+ const header = entries[0] as SessionHeaderShape;
1306
+ if (header.type !== "session" || !header.id) return;
1307
+
1308
+ let messageCount = 0;
1309
+ let firstMessage = "";
1310
+ const allMessages: string[] = [];
1311
+ let shortSummary: string | undefined;
1312
+
1313
+ for (let i = 1; i < entries.length; i++) {
1314
+ const entry = entries[i] as { type?: string; message?: Message; shortSummary?: string };
1315
+
1316
+ if (entry.type === "compaction" && typeof entry.shortSummary === "string") {
1317
+ shortSummary = entry.shortSummary;
1318
+ }
1319
+
1320
+ if (entry.type === "message" && entry.message) {
1321
+ messageCount++;
1322
+
1323
+ if (entry.message.role === "user" || entry.message.role === "assistant") {
1324
+ const textContent = extractTextFromContent(entry.message.content);
1325
+
1326
+ if (textContent) {
1327
+ allMessages.push(textContent);
1328
+
1329
+ if (!firstMessage && entry.message.role === "user") {
1330
+ firstMessage = textContent;
1331
+ }
1332
+ }
1333
+ }
1334
+ }
1335
+ }
1336
+
1337
+ const stats = storage.statSync(file);
1338
+ sessions.push({
1339
+ path: file,
1340
+ id: header.id,
1341
+ cwd: typeof header.cwd === "string" ? header.cwd : "",
1342
+ title: header.title ?? shortSummary,
1343
+ parentSessionPath: (header as SessionHeader).parentSession,
1344
+ created: new Date(header.timestamp),
1345
+ modified: stats.mtime,
1346
+ messageCount,
1347
+ firstMessage: firstMessage || "(no messages)",
1348
+ allMessagesText: allMessages.join(" "),
1349
+ });
1350
+ } catch {}
1351
+ }),
1352
+ );
1353
+
1354
+ sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
1355
+ return sessions;
1356
+ }
1357
+
1358
+ export interface ResolvedSessionMatch {
1359
+ session: SessionInfo;
1360
+ scope: "local" | "global";
1361
+ }
1362
+
1363
+ function sessionMatchesResumeArg(session: SessionInfo, sessionArg: string): boolean {
1364
+ const normalizedArg = sessionArg.toLowerCase();
1365
+ const normalizedId = session.id.toLowerCase();
1366
+ if (normalizedId.startsWith(normalizedArg)) {
1367
+ return true;
1368
+ }
1369
+
1370
+ const fileName = path.basename(session.path, ".jsonl").toLowerCase();
1371
+ if (fileName.startsWith(normalizedArg)) {
1372
+ return true;
1373
+ }
1374
+
1375
+ const separator = fileName.lastIndexOf("_");
1376
+ if (separator < 0) {
1377
+ return false;
1378
+ }
1379
+
1380
+ const fileSessionId = fileName.slice(separator + 1);
1381
+ return fileSessionId.startsWith(normalizedArg);
1382
+ }
1383
+
1384
+ export async function resolveResumableSession(
1385
+ sessionArg: string,
1386
+ cwd: string,
1387
+ sessionDir?: string,
1388
+ storage: SessionStorage = new FileSessionStorage(),
1389
+ ): Promise<ResolvedSessionMatch | undefined> {
1390
+ const localSessionDir = sessionDir ?? SessionManager.getDefaultSessionDir(cwd, undefined, storage);
1391
+ const localSessions = await SessionManager.list(cwd, localSessionDir, storage);
1392
+ const localMatch = localSessions.find(session => sessionMatchesResumeArg(session, sessionArg));
1393
+ if (localMatch) {
1394
+ return { session: localMatch, scope: "local" };
1395
+ }
1396
+
1397
+ if (sessionDir) {
1398
+ return undefined;
1399
+ }
1400
+
1401
+ const globalSessions = await SessionManager.listAll(storage);
1402
+ const globalMatch = globalSessions.find(session => sessionMatchesResumeArg(session, sessionArg));
1403
+ if (!globalMatch) {
1404
+ return undefined;
1405
+ }
1406
+
1407
+ return { session: globalMatch, scope: "global" };
1408
+ }
1409
+ interface SessionManagerStateSnapshot {
1410
+ sessionId: string;
1411
+ sessionName: string | undefined;
1412
+ titleSource: "auto" | "user" | undefined;
1413
+ sessionFile: string | undefined;
1414
+ flushed: boolean;
1415
+ needsFullRewriteOnNextPersist: boolean;
1416
+ fileEntries: FileEntry[];
1417
+ }
1418
+
1419
+ export class SessionManager {
1420
+ #sessionId: string = "";
1421
+ #sessionName: string | undefined;
1422
+ #titleSource: "auto" | "user" | undefined;
1423
+ #sessionFile: string | undefined;
1424
+ #flushed: boolean = false;
1425
+ #needsFullRewriteOnNextPersist: boolean = false;
1426
+ #ensuredOnDisk: boolean = false;
1427
+ #fileEntries: FileEntry[] = [];
1428
+ #byId: Map<string, SessionEntry> = new Map();
1429
+ #labelsById: Map<string, string> = new Map();
1430
+ #leafId: string | null = null;
1431
+ #usageStatistics = {
1432
+ input: 0,
1433
+ output: 0,
1434
+ cacheRead: 0,
1435
+ cacheWrite: 0,
1436
+ premiumRequests: 0,
1437
+ cost: 0,
1438
+ } satisfies UsageStatistics;
1439
+ #persistWriter: NdjsonFileWriter | undefined;
1440
+ #persistWriterPath: string | undefined;
1441
+ #persistChain: Promise<void> = Promise.resolve();
1442
+ #persistError: Error | undefined;
1443
+ #persistErrorReported = false;
1444
+ #artifactManager: ArtifactManager | null = null;
1445
+ #artifactManagerSessionFile: string | null = null;
1446
+ // In-memory artifact fallback for non-persistent sessions (persist=false).
1447
+ // Keyed by sequential numeric ID string; mirrors the file-based ArtifactManager ID scheme.
1448
+ #inMemoryArtifacts: Map<string, string> | null = null;
1449
+ #inMemoryArtifactCounter = 0;
1450
+ readonly #blobStore: BlobStore;
1451
+
1452
+ private constructor(
1453
+ private cwd: string,
1454
+ private sessionDir: string,
1455
+ private readonly persist: boolean,
1456
+ private readonly storage: SessionStorage,
1457
+ ) {
1458
+ this.#blobStore = new BlobStore(getBlobsDir());
1459
+ if (persist && sessionDir) {
1460
+ this.storage.ensureDirSync(sessionDir);
1461
+ }
1462
+ // Note: call _initSession() or _initSessionFile() after construction
1463
+ }
1464
+
1465
+ /** Puts a binary blob into the blob store and returns the blob reference */
1466
+ async putBlob(data: Buffer): Promise<BlobPutResult> {
1467
+ return this.#blobStore.put(data);
1468
+ }
1469
+
1470
+ captureState(): SessionManagerStateSnapshot {
1471
+ return {
1472
+ sessionId: this.#sessionId,
1473
+ sessionName: this.#sessionName,
1474
+ titleSource: this.#titleSource,
1475
+ sessionFile: this.#sessionFile,
1476
+ flushed: this.#flushed,
1477
+ needsFullRewriteOnNextPersist: this.#needsFullRewriteOnNextPersist,
1478
+ // Snapshot entry objects by reference: switch/reload replaces the active entry array,
1479
+ // so rollback does not need structured cloning of extension/custom details.
1480
+ fileEntries: [...this.#fileEntries],
1481
+ };
1482
+ }
1483
+
1484
+ restoreState(snapshot: SessionManagerStateSnapshot): void {
1485
+ this.#sessionId = snapshot.sessionId;
1486
+ this.#sessionName = snapshot.sessionName;
1487
+ this.#titleSource = snapshot.titleSource;
1488
+ this.#sessionFile = snapshot.sessionFile;
1489
+ this.#flushed = snapshot.flushed;
1490
+ this.#needsFullRewriteOnNextPersist = snapshot.needsFullRewriteOnNextPersist;
1491
+ this.#fileEntries = [...snapshot.fileEntries];
1492
+ this.#persistWriter = undefined;
1493
+ this.#persistWriterPath = undefined;
1494
+ this.#persistChain = Promise.resolve();
1495
+ this.#persistError = undefined;
1496
+ this.#persistErrorReported = false;
1497
+ this.#artifactManager = null;
1498
+ this.#artifactManagerSessionFile = null;
1499
+ this.#buildIndex();
1500
+ if (this.#sessionFile) {
1501
+ writeTerminalBreadcrumb(this.cwd, this.#sessionFile);
1502
+ }
1503
+ }
1504
+
1505
+ /** Initialize with a specific session file (used by factory methods) */
1506
+ async #initSessionFile(sessionFile: string): Promise<void> {
1507
+ await this.setSessionFile(sessionFile);
1508
+ }
1509
+
1510
+ /** Initialize with a new session (used by factory methods) */
1511
+ #initNewSession(): void {
1512
+ this.#newSessionSync();
1513
+ }
1514
+
1515
+ /** Switch to a different session file (used for resume and branching) */
1516
+ async setSessionFile(sessionFile: string): Promise<void> {
1517
+ await this.#closePersistWriter();
1518
+ this.#persistError = undefined;
1519
+ this.#persistErrorReported = false;
1520
+ this.#sessionFile = path.resolve(sessionFile);
1521
+ writeTerminalBreadcrumb(this.cwd, this.#sessionFile);
1522
+ this.#fileEntries = await loadEntriesFromFile(this.#sessionFile, this.storage);
1523
+ if (this.#fileEntries.length > 0) {
1524
+ const header = this.#fileEntries.find(e => e.type === "session") as SessionHeader | undefined;
1525
+ this.#sessionId = header?.id ?? Snowflake.next();
1526
+ this.#sessionName = header?.title;
1527
+ this.#titleSource = header?.titleSource;
1528
+
1529
+ this.#needsFullRewriteOnNextPersist = migrateToCurrentVersion(this.#fileEntries);
1530
+
1531
+ await resolveBlobRefsInEntries(this.#fileEntries, this.#blobStore);
1532
+ this.sanitizeLoadedOpenAIResponsesReplayMetadata();
1533
+
1534
+ this.#buildIndex();
1535
+ this.#flushed = true;
1536
+ this.#ensuredOnDisk = true;
1537
+ } else {
1538
+ const explicitPath = this.#sessionFile;
1539
+ this.#newSessionSync();
1540
+ this.#sessionFile = explicitPath; // preserve explicit path from --session flag
1541
+ await this.#rewriteFile();
1542
+ this.#flushed = true;
1543
+ this.#ensuredOnDisk = true;
1544
+ return;
1545
+ }
1546
+ }
1547
+
1548
+ /** Start a new session. Closes any existing writer first. */
1549
+ async newSession(options?: NewSessionOptions): Promise<string | undefined> {
1550
+ await this.#closePersistWriter();
1551
+ return this.#newSessionSync(options);
1552
+ }
1553
+
1554
+ /**
1555
+ * Fork the current session, creating a new session file with the same entries.
1556
+ * Returns both the old and new session file paths for artifact copying.
1557
+ * @returns { oldSessionFile, newSessionFile } or undefined if not persisting
1558
+ */
1559
+ async fork(): Promise<{ oldSessionFile: string; newSessionFile: string } | undefined> {
1560
+ if (!this.persist || !this.#sessionFile) {
1561
+ return undefined;
1562
+ }
1563
+
1564
+ const oldSessionFile = this.#sessionFile;
1565
+ const oldSessionId = this.#sessionId;
1566
+
1567
+ // Close the current writer
1568
+ await this.#closePersistWriter();
1569
+ this.#persistChain = Promise.resolve();
1570
+ this.#persistError = undefined;
1571
+ this.#persistErrorReported = false;
1572
+
1573
+ // Create new session ID and header
1574
+ this.#sessionId = Snowflake.next();
1575
+ const timestamp = new Date().toISOString();
1576
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
1577
+ this.#sessionFile = path.join(this.getSessionDir(), `${fileTimestamp}_${this.#sessionId}.jsonl`);
1578
+
1579
+ // Update the header with new ID but keep all entries
1580
+ const oldHeader = this.#fileEntries.find(e => e.type === "session") as SessionHeader | undefined;
1581
+ const newHeader: SessionHeader = {
1582
+ type: "session",
1583
+ version: CURRENT_SESSION_VERSION,
1584
+ id: this.#sessionId,
1585
+ title: oldHeader?.title ?? this.#sessionName,
1586
+ titleSource: oldHeader?.titleSource ?? this.#titleSource,
1587
+ timestamp,
1588
+ cwd: this.cwd,
1589
+ parentSession: oldSessionId,
1590
+ };
1591
+ this.#sessionName = newHeader.title;
1592
+ this.#titleSource = newHeader.titleSource;
1593
+
1594
+ // Replace the header in fileEntries
1595
+ const entries = this.#fileEntries.filter((e): e is SessionEntry => e.type !== "session");
1596
+ this.#fileEntries = [newHeader, ...entries];
1597
+
1598
+ // Write the new session file
1599
+ this.#flushed = false;
1600
+ await this.#rewriteFile();
1601
+
1602
+ return { oldSessionFile, newSessionFile: this.#sessionFile };
1603
+ }
1604
+
1605
+ /**
1606
+ * Move the session to a new working directory.
1607
+ * Moves session files and artifacts on disk, updates all internal references,
1608
+ * and rewrites the session header with the new cwd.
1609
+ */
1610
+ async moveTo(newCwd: string): Promise<void> {
1611
+ const resolvedCwd = path.resolve(newCwd);
1612
+ if (resolvedCwd === this.cwd) return;
1613
+
1614
+ const managedSessionsRoot = resolveManagedSessionRoot(this.sessionDir, this.cwd);
1615
+ const newSessionDir = managedSessionsRoot
1616
+ ? computeDefaultSessionDir(resolvedCwd, this.storage, managedSessionsRoot)
1617
+ : computeDefaultSessionDir(resolvedCwd, this.storage);
1618
+ let hadSessionFile = false;
1619
+
1620
+ if (this.persist && this.#sessionFile) {
1621
+ // Close the persist writer before moving files
1622
+ await this.#closePersistWriter();
1623
+ this.#persistChain = Promise.resolve();
1624
+ this.#persistError = undefined;
1625
+ this.#persistErrorReported = false;
1626
+
1627
+ const oldSessionFile = this.#sessionFile;
1628
+ const newSessionFile = path.join(newSessionDir, path.basename(oldSessionFile));
1629
+ const oldArtifactDir = oldSessionFile.slice(0, -6); // strip .jsonl
1630
+ const newArtifactDir = newSessionFile.slice(0, -6);
1631
+ hadSessionFile = this.storage.existsSync(oldSessionFile);
1632
+ let movedSessionFile = false;
1633
+ let movedArtifactDir = false;
1634
+
1635
+ try {
1636
+ // Guard: session file may not exist yet (no assistant messages persisted)
1637
+ if (hadSessionFile) {
1638
+ await fs.promises.rename(oldSessionFile, newSessionFile);
1639
+ movedSessionFile = true;
1640
+ }
1641
+
1642
+ try {
1643
+ const stat = await fs.promises.stat(oldArtifactDir);
1644
+ if (stat.isDirectory()) {
1645
+ await fs.promises.rename(oldArtifactDir, newArtifactDir);
1646
+ movedArtifactDir = true;
1647
+ }
1648
+ } catch (err) {
1649
+ if (!isEnoent(err)) throw err;
1650
+ }
1651
+ } catch (err) {
1652
+ if (movedArtifactDir) {
1653
+ try {
1654
+ await fs.promises.rename(newArtifactDir, oldArtifactDir);
1655
+ } catch (rollbackErr) {
1656
+ throw new Error(
1657
+ `Failed to move artifacts and rollback: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`,
1658
+ );
1659
+ }
1660
+ }
1661
+ if (movedSessionFile) {
1662
+ try {
1663
+ await fs.promises.rename(newSessionFile, oldSessionFile);
1664
+ } catch (rollbackErr) {
1665
+ throw new Error(
1666
+ `Failed to move session file and rollback: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`,
1667
+ );
1668
+ }
1669
+ }
1670
+ throw err;
1671
+ }
1672
+ this.#sessionFile = newSessionFile;
1673
+ }
1674
+
1675
+ // Update cwd and sessionDir after the move succeeds.
1676
+ this.cwd = resolvedCwd;
1677
+ this.sessionDir = newSessionDir;
1678
+
1679
+ // Update the session header in fileEntries
1680
+ const header = this.#fileEntries.find(e => e.type === "session") as SessionHeader | undefined;
1681
+ if (header) {
1682
+ header.cwd = resolvedCwd;
1683
+ }
1684
+
1685
+ // Rewrite the session file at its new location with updated header.
1686
+ // hadSessionFile: file existed before move → must rewrite to update cwd
1687
+ // hasAssistant: assistant messages in memory but file missing → recreate from memory
1688
+ // Neither true → fresh session, never written → preserve lazy-persist
1689
+ const hasAssistant = this.#fileEntries.some(e => e.type === "message" && e.message.role === "assistant");
1690
+ if (this.persist && this.#sessionFile && (hadSessionFile || hasAssistant)) {
1691
+ await this.#rewriteFile();
1692
+ }
1693
+
1694
+ // Update terminal breadcrumb
1695
+ if (this.#sessionFile) {
1696
+ writeTerminalBreadcrumb(resolvedCwd, this.#sessionFile);
1697
+ }
1698
+ }
1699
+
1700
+ /** Sync version for initial creation (no existing writer to close) */
1701
+ #newSessionSync(options?: NewSessionOptions): string | undefined {
1702
+ this.#persistChain = Promise.resolve();
1703
+ this.#persistError = undefined;
1704
+ this.#persistErrorReported = false;
1705
+ this.#sessionId = Snowflake.next();
1706
+ this.#sessionName = undefined;
1707
+ this.#titleSource = undefined;
1708
+ const timestamp = new Date().toISOString();
1709
+ const header: SessionHeader = {
1710
+ type: "session",
1711
+ version: CURRENT_SESSION_VERSION,
1712
+ id: this.#sessionId,
1713
+ timestamp,
1714
+ cwd: this.cwd,
1715
+ parentSession: options?.parentSession,
1716
+ };
1717
+ this.#fileEntries = [header];
1718
+ this.#byId.clear();
1719
+ this.#labelsById.clear();
1720
+ this.#leafId = null;
1721
+ this.#flushed = false;
1722
+ this.#needsFullRewriteOnNextPersist = false;
1723
+ this.#ensuredOnDisk = false;
1724
+ this.#usageStatistics = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, premiumRequests: 0, cost: 0 };
1725
+ this.#inMemoryArtifacts = null;
1726
+ this.#inMemoryArtifactCounter = 0;
1727
+
1728
+ if (this.persist) {
1729
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
1730
+ this.#sessionFile = path.join(this.getSessionDir(), `${fileTimestamp}_${this.#sessionId}.jsonl`);
1731
+ writeTerminalBreadcrumb(this.cwd, this.#sessionFile);
1732
+ }
1733
+ return this.#sessionFile;
1734
+ }
1735
+
1736
+ #buildIndex(): void {
1737
+ this.#byId.clear();
1738
+ this.#labelsById.clear();
1739
+ this.#leafId = null;
1740
+ this.#usageStatistics = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, premiumRequests: 0, cost: 0 };
1741
+ for (const entry of this.#fileEntries) {
1742
+ if (entry.type === "session") continue;
1743
+ this.#byId.set(entry.id, entry);
1744
+ this.#leafId = entry.id;
1745
+ if (entry.type === "label") {
1746
+ if (entry.label) {
1747
+ this.#labelsById.set(entry.targetId, entry.label);
1748
+ } else {
1749
+ this.#labelsById.delete(entry.targetId);
1750
+ }
1751
+ }
1752
+ if (entry.type === "message" && entry.message.role === "assistant") {
1753
+ const usage = entry.message.usage;
1754
+ this.#usageStatistics.input += usage.input;
1755
+ this.#usageStatistics.output += usage.output;
1756
+ this.#usageStatistics.cacheRead += usage.cacheRead;
1757
+ this.#usageStatistics.cacheWrite += usage.cacheWrite;
1758
+ this.#usageStatistics.premiumRequests += usage.premiumRequests ?? 0;
1759
+ this.#usageStatistics.cost += usage.cost.total;
1760
+ }
1761
+
1762
+ if (entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolName === "task") {
1763
+ const usage = getTaskToolUsage(entry.message.details);
1764
+ if (usage) {
1765
+ this.#usageStatistics.input += usage.input;
1766
+ this.#usageStatistics.output += usage.output;
1767
+ this.#usageStatistics.cacheRead += usage.cacheRead;
1768
+ this.#usageStatistics.cacheWrite += usage.cacheWrite;
1769
+ this.#usageStatistics.premiumRequests += usage.premiumRequests ?? 0;
1770
+ this.#usageStatistics.cost += usage.cost.total;
1771
+ }
1772
+ }
1773
+ }
1774
+ }
1775
+
1776
+ #recordPersistError(err: unknown): Error {
1777
+ const normalized = toError(err);
1778
+ if (!this.#persistError) this.#persistError = normalized;
1779
+ if (!this.#persistErrorReported) {
1780
+ this.#persistErrorReported = true;
1781
+ logger.error("Session persistence error.", {
1782
+ sessionFile: this.#sessionFile,
1783
+ error: normalized.message,
1784
+ stack: normalized.stack,
1785
+ });
1786
+ }
1787
+ return normalized;
1788
+ }
1789
+
1790
+ #queuePersistTask(task: () => Promise<void>, options?: { ignoreError?: boolean }): Promise<void> {
1791
+ const next = this.#persistChain.then(async () => {
1792
+ if (this.#persistError && !options?.ignoreError) throw this.#persistError;
1793
+ await task();
1794
+ });
1795
+ this.#persistChain = next.catch(err => {
1796
+ this.#recordPersistError(err);
1797
+ });
1798
+ return next;
1799
+ }
1800
+
1801
+ #ensurePersistWriter(): NdjsonFileWriter | undefined {
1802
+ if (!this.persist || !this.#sessionFile) return undefined;
1803
+ if (this.#persistError) throw this.#persistError;
1804
+ if (this.#persistWriter && this.#persistWriterPath === this.#sessionFile) return this.#persistWriter;
1805
+ // Note: caller must await _closePersistWriter() before calling this if switching files
1806
+ this.#persistWriter = new NdjsonFileWriter(this.storage, this.#sessionFile, {
1807
+ onError: err => {
1808
+ this.#recordPersistError(err);
1809
+ },
1810
+ });
1811
+ this.#persistWriterPath = this.#sessionFile;
1812
+ return this.#persistWriter;
1813
+ }
1814
+
1815
+ async #closePersistWriterInternal(): Promise<void> {
1816
+ if (this.#persistWriter) {
1817
+ await this.#persistWriter.close();
1818
+ this.#persistWriter = undefined;
1819
+ }
1820
+ this.#persistWriterPath = undefined;
1821
+ }
1822
+
1823
+ async #closePersistWriter(): Promise<void> {
1824
+ await this.#queuePersistTask(
1825
+ async () => {
1826
+ await this.#closePersistWriterInternal();
1827
+ },
1828
+ { ignoreError: true },
1829
+ );
1830
+ }
1831
+
1832
+ async #writeEntriesAtomically(entries: FileEntry[]): Promise<void> {
1833
+ if (!this.#sessionFile) return;
1834
+ const dir = path.resolve(this.#sessionFile, "..");
1835
+ const tempPath = path.join(dir, `.${path.basename(this.#sessionFile)}.${Snowflake.next()}.tmp`);
1836
+ const writer = new NdjsonFileWriter(this.storage, tempPath, { flags: "w" });
1837
+ try {
1838
+ for (const entry of entries) {
1839
+ await writer.write(entry);
1840
+ }
1841
+ await writer.flush();
1842
+ await writer.fsync();
1843
+ await writer.close();
1844
+ await this.storage.rename(tempPath, this.#sessionFile);
1845
+ } catch (err) {
1846
+ try {
1847
+ await writer.close();
1848
+ } catch {
1849
+ // Ignore cleanup errors
1850
+ }
1851
+ try {
1852
+ await this.storage.unlink(tempPath);
1853
+ } catch {
1854
+ // Ignore cleanup errors
1855
+ }
1856
+ throw toError(err);
1857
+ }
1858
+ }
1859
+
1860
+ async #rewriteFile(): Promise<void> {
1861
+ if (!this.persist || !this.#sessionFile) return;
1862
+ await this.#queuePersistTask(async () => {
1863
+ await this.#closePersistWriterInternal();
1864
+ const entries = await Promise.all(
1865
+ this.#fileEntries.map(entry => prepareEntryForPersistence(entry, this.#blobStore)),
1866
+ );
1867
+ await this.#writeEntriesAtomically(entries);
1868
+ this.#needsFullRewriteOnNextPersist = false;
1869
+ this.#flushed = true;
1870
+ });
1871
+ }
1872
+
1873
+ isPersisted(): boolean {
1874
+ return this.persist;
1875
+ }
1876
+
1877
+ /**
1878
+ * Force-persist all current entries to disk, even when no assistant message exists yet.
1879
+ * Used by ACP mode where session/new must create a discoverable session immediately.
1880
+ */
1881
+ async ensureOnDisk(): Promise<void> {
1882
+ if (!this.persist || !this.#sessionFile) return;
1883
+ if (this.#flushed && !this.#needsFullRewriteOnNextPersist) return;
1884
+ await this.#rewriteFile();
1885
+ this.#ensuredOnDisk = true;
1886
+ }
1887
+
1888
+ /** Flush pending writes to disk. Call before switching sessions or on shutdown. */
1889
+ async flush(): Promise<void> {
1890
+ await this.#queuePersistTask(async () => {
1891
+ if (this.#persistWriter) {
1892
+ await this.#persistWriter.flush();
1893
+ await this.#persistWriter.fsync();
1894
+ }
1895
+ });
1896
+ if (this.#persistError) throw this.#persistError;
1897
+ }
1898
+
1899
+ /** Close the persistent writer after flushing all pending data. */
1900
+ async close(): Promise<void> {
1901
+ if (!this.#persistWriter) return;
1902
+ await this.#queuePersistTask(async () => {
1903
+ await this.#closePersistWriterInternal();
1904
+ this.#flushed = true;
1905
+ });
1906
+ if (this.#persistError) throw this.#persistError;
1907
+ }
1908
+
1909
+ getCwd(): string {
1910
+ return this.cwd;
1911
+ }
1912
+
1913
+ /** Get usage statistics across all assistant messages in the session. */
1914
+ getUsageStatistics(): UsageStatistics {
1915
+ return this.#usageStatistics;
1916
+ }
1917
+
1918
+ getSessionDir(): string {
1919
+ return this.sessionDir;
1920
+ }
1921
+
1922
+ getSessionId(): string {
1923
+ return this.#sessionId;
1924
+ }
1925
+
1926
+ getSessionFile(): string | undefined {
1927
+ return this.#sessionFile;
1928
+ }
1929
+
1930
+ /**
1931
+ * Returns the session artifacts directory path (session file path without .jsonl).
1932
+ * Returns null when the session is not persisted to a file.
1933
+ */
1934
+ getArtifactsDir(): string | null {
1935
+ const sessionFile = this.#sessionFile;
1936
+ return sessionFile ? sessionFile.slice(0, -6) : null;
1937
+ }
1938
+
1939
+ /**
1940
+ * Returns an artifact manager bound to the current session file.
1941
+ * Recreates the manager when the active session file changes.
1942
+ */
1943
+ #getOrCreateArtifactManager(): ArtifactManager | null {
1944
+ const sessionFile = this.#sessionFile;
1945
+ if (!sessionFile) {
1946
+ this.#artifactManager = null;
1947
+ this.#artifactManagerSessionFile = null;
1948
+ return null;
1949
+ }
1950
+
1951
+ if (this.#artifactManager && this.#artifactManagerSessionFile === sessionFile) {
1952
+ return this.#artifactManager;
1953
+ }
1954
+
1955
+ const manager = new ArtifactManager(sessionFile);
1956
+ this.#artifactManager = manager;
1957
+ this.#artifactManagerSessionFile = sessionFile;
1958
+ return manager;
1959
+ }
1960
+
1961
+ /**
1962
+ * Allocate a new artifact path and ID for the current session.
1963
+ * Returns an empty object when the session is not persisted.
1964
+ */
1965
+ async allocateArtifactPath(toolType: string): Promise<{ id?: string; path?: string }> {
1966
+ const manager = this.#getOrCreateArtifactManager();
1967
+ if (!manager) return {};
1968
+ return manager.allocatePath(toolType);
1969
+ }
1970
+
1971
+ /**
1972
+ * Save artifact content under the current session and return artifact ID.
1973
+ * Returns an artifact ID for all sessions (file-backed for persistent, in-memory fallback otherwise).
1974
+ */
1975
+ async saveArtifact(content: string, toolType: string): Promise<string | undefined> {
1976
+ const manager = this.#getOrCreateArtifactManager();
1977
+ if (manager) return manager.save(content, toolType);
1978
+ // Non-persistent session: store in memory so spill truncation can proceed.
1979
+ if (!this.#inMemoryArtifacts) this.#inMemoryArtifacts = new Map();
1980
+ const id = String(this.#inMemoryArtifactCounter++);
1981
+ this.#inMemoryArtifacts.set(id, content);
1982
+ return id;
1983
+ }
1984
+
1985
+ /**
1986
+ * Resolve an artifact ID to an on-disk path for the current session.
1987
+ * Returns null when missing or when the session is not persisted.
1988
+ */
1989
+ async getArtifactPath(id: string): Promise<string | null> {
1990
+ const manager = this.#getOrCreateArtifactManager();
1991
+ if (!manager) return null;
1992
+ return manager.getPath(id);
1993
+ }
1994
+
1995
+ /** The source that set the session name: "user" (manual /rename or RPC) or "auto" (generated title). */
1996
+ get titleSource(): "auto" | "user" | undefined {
1997
+ return this.#titleSource;
1998
+ }
1999
+
2000
+ getSessionName(): string | undefined {
2001
+ return this.#sessionName;
2002
+ }
2003
+
2004
+ /** Strip C0/C1 control characters (includes ESC, so removes ANSI sequences) and collapse whitespace. */
2005
+ static #sanitizeName(name: string): string {
2006
+ return name
2007
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, " ")
2008
+ .replace(/ +/g, " ")
2009
+ .trim();
2010
+ }
2011
+
2012
+ /**
2013
+ * Set the session display name.
2014
+ * @param source - "user" for explicit renames (/rename command, RPC); "auto" for generated titles.
2015
+ * Auto-generated titles are silently ignored when the user has already set a name.
2016
+ */
2017
+ async setSessionName(name: string, source: "auto" | "user" = "auto"): Promise<boolean> {
2018
+ // User-set names take permanent precedence over auto-generated ones.
2019
+ if (this.#titleSource === "user" && source === "auto") return false;
2020
+
2021
+ const sanitized = SessionManager.#sanitizeName(name);
2022
+ if (!sanitized) return false;
2023
+
2024
+ this.#sessionName = sanitized;
2025
+ this.#titleSource = source;
2026
+
2027
+ // Update the in-memory header (so first flush includes title)
2028
+ const header = this.#fileEntries.find(e => e.type === "session") as SessionHeader | undefined;
2029
+ if (header) {
2030
+ header.title = sanitized;
2031
+ header.titleSource = source;
2032
+ }
2033
+
2034
+ // Update the session file header with the title (if already flushed)
2035
+ const sessionFile = this.#sessionFile;
2036
+ if (this.persist && sessionFile && this.storage.existsSync(sessionFile)) {
2037
+ await this.#rewriteFile();
2038
+ }
2039
+ return true;
2040
+ }
2041
+
2042
+ _persist(entry: SessionEntry): void {
2043
+ if (!this.persist || !this.#sessionFile) return;
2044
+ if (this.#persistError) throw this.#persistError;
2045
+
2046
+ // Normally we wait for the first assistant message before persisting to avoid
2047
+ // creating files for sessions that never produce output. Once ensureOnDisk() has
2048
+ // been called, the session is already on disk and every entry must be flushed.
2049
+ if (!this.#ensuredOnDisk) {
2050
+ const hasAssistant = this.#fileEntries.some(e => e.type === "message" && e.message.role === "assistant");
2051
+ if (!hasAssistant) {
2052
+ // Mark as not flushed so when assistant arrives, all entries get written.
2053
+ this.#flushed = false;
2054
+ return;
2055
+ }
2056
+ }
2057
+
2058
+ if (this.#needsFullRewriteOnNextPersist || !this.#flushed) {
2059
+ // Full flush: rewrite the entire file atomically to avoid
2060
+ // duplicating entries if the file already exists (e.g. from ensureOnDisk).
2061
+ void this.#rewriteFile();
2062
+ } else {
2063
+ void this.#queuePersistTask(async () => {
2064
+ const writer = this.#ensurePersistWriter();
2065
+ if (!writer) return;
2066
+ const persistedEntry = await prepareEntryForPersistence(entry, this.#blobStore);
2067
+ await writer.write(persistedEntry);
2068
+ });
2069
+ }
2070
+ }
2071
+
2072
+ #appendEntry(entry: SessionEntry): void {
2073
+ this.#fileEntries.push(entry);
2074
+ this.#byId.set(entry.id, entry);
2075
+ this.#leafId = entry.id;
2076
+ this._persist(entry);
2077
+ if (entry.type === "message" && entry.message.role === "assistant") {
2078
+ const usage = entry.message.usage;
2079
+ this.#usageStatistics.input += usage.input;
2080
+ this.#usageStatistics.output += usage.output;
2081
+ this.#usageStatistics.cacheRead += usage.cacheRead;
2082
+ this.#usageStatistics.cacheWrite += usage.cacheWrite;
2083
+ this.#usageStatistics.premiumRequests += usage.premiumRequests ?? 0;
2084
+ this.#usageStatistics.cost += usage.cost.total;
2085
+ }
2086
+
2087
+ if (entry.type === "message" && entry.message.role === "toolResult" && entry.message.toolName === "task") {
2088
+ const usage = getTaskToolUsage(entry.message.details);
2089
+ if (usage) {
2090
+ this.#usageStatistics.input += usage.input;
2091
+ this.#usageStatistics.output += usage.output;
2092
+ this.#usageStatistics.cacheRead += usage.cacheRead;
2093
+ this.#usageStatistics.cacheWrite += usage.cacheWrite;
2094
+ this.#usageStatistics.premiumRequests += usage.premiumRequests ?? 0;
2095
+ this.#usageStatistics.cost += usage.cost.total;
2096
+ }
2097
+ }
2098
+ }
2099
+
2100
+ /** Append a message as child of current leaf, then advance leaf. Returns entry id.
2101
+ * Does not allow writing CompactionSummaryMessage and BranchSummaryMessage directly.
2102
+ * Reason: we want these to be top-level entries in the session, not message session entries,
2103
+ * so it is easier to find them.
2104
+ * These need to be appended via appendCompaction() and appendBranchSummary() methods.
2105
+ */
2106
+ appendMessage(
2107
+ message:
2108
+ | Message
2109
+ | CustomMessage
2110
+ | HookMessage
2111
+ | BashExecutionMessage
2112
+ | PythonExecutionMessage
2113
+ | FileMentionMessage,
2114
+ ): string {
2115
+ const entry: SessionMessageEntry = {
2116
+ type: "message",
2117
+ id: generateId(this.#byId),
2118
+ parentId: this.#leafId,
2119
+ timestamp: new Date().toISOString(),
2120
+ message,
2121
+ };
2122
+ this.#appendEntry(entry);
2123
+ return entry.id;
2124
+ }
2125
+
2126
+ /** Append a thinking level change as child of current leaf, then advance leaf. Returns entry id. */
2127
+ appendThinkingLevelChange(thinkingLevel?: string): string {
2128
+ const entry: ThinkingLevelChangeEntry = {
2129
+ type: "thinking_level_change",
2130
+ id: generateId(this.#byId),
2131
+ parentId: this.#leafId,
2132
+ timestamp: new Date().toISOString(),
2133
+ thinkingLevel: thinkingLevel ?? null,
2134
+ };
2135
+ this.#appendEntry(entry);
2136
+ return entry.id;
2137
+ }
2138
+
2139
+ appendServiceTierChange(serviceTier: ServiceTier | null): string {
2140
+ const entry: ServiceTierChangeEntry = {
2141
+ type: "service_tier_change",
2142
+ id: generateId(this.#byId),
2143
+ parentId: this.#leafId,
2144
+ timestamp: new Date().toISOString(),
2145
+ serviceTier,
2146
+ };
2147
+ this.#appendEntry(entry);
2148
+ return entry.id;
2149
+ }
2150
+
2151
+ /** Append a mode change as child of current leaf, then advance leaf. Returns entry id. */
2152
+ appendModeChange(mode: string, data?: Record<string, unknown>): string {
2153
+ const entry: ModeChangeEntry = {
2154
+ type: "mode_change",
2155
+ id: generateId(this.#byId),
2156
+ parentId: this.#leafId,
2157
+ timestamp: new Date().toISOString(),
2158
+ mode,
2159
+ data,
2160
+ };
2161
+ this.#appendEntry(entry);
2162
+ return entry.id;
2163
+ }
2164
+
2165
+ /**
2166
+ * Append a model change as child of current leaf, then advance leaf. Returns entry id.
2167
+ * @param model Model in "provider/modelId" format
2168
+ * @param role Optional role (default: "default")
2169
+ */
2170
+ appendModelChange(model: string, role?: string): string {
2171
+ const entry: ModelChangeEntry = {
2172
+ type: "model_change",
2173
+ id: generateId(this.#byId),
2174
+ parentId: this.#leafId,
2175
+ timestamp: new Date().toISOString(),
2176
+ model,
2177
+ role,
2178
+ };
2179
+ this.#appendEntry(entry);
2180
+ return entry.id;
2181
+ }
2182
+
2183
+ /**
2184
+ * Append a context change as child of current leaf, then advance leaf. Returns entry id.
2185
+ * @param contextName Context name from ContextStatus.activeContextName
2186
+ * @param tenant Tenant derived from the active context's apiUrl
2187
+ * @param namespace Effective namespace (XCSH_NAMESPACE env override applied, falls back to context.defaultNamespace)
2188
+ */
2189
+ appendContextChange(contextName: string, tenant: string, namespace: string): string {
2190
+ const entry: ContextChangeEntry = {
2191
+ type: "context_change",
2192
+ id: generateId(this.#byId),
2193
+ parentId: this.#leafId,
2194
+ timestamp: new Date().toISOString(),
2195
+ contextName,
2196
+ tenant,
2197
+ namespace,
2198
+ };
2199
+ this.#appendEntry(entry);
2200
+ return entry.id;
2201
+ }
2202
+
2203
+ /** Append session init metadata (for subagent debugging/replay). Returns entry id. */
2204
+ appendSessionInit(init: { systemPrompt: string; task: string; tools: string[]; outputSchema?: unknown }): string {
2205
+ const entry: SessionInitEntry = {
2206
+ type: "session_init",
2207
+ id: generateId(this.#byId),
2208
+ parentId: this.#leafId,
2209
+ timestamp: new Date().toISOString(),
2210
+ ...init,
2211
+ };
2212
+ this.#appendEntry(entry);
2213
+ return entry.id;
2214
+ }
2215
+
2216
+ /** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */
2217
+ appendCompaction<T = unknown>(
2218
+ summary: string,
2219
+ shortSummary: string | undefined,
2220
+ firstKeptEntryId: string,
2221
+ tokensBefore: number,
2222
+ details?: T,
2223
+ fromExtension?: boolean,
2224
+ preserveData?: Record<string, unknown>,
2225
+ ): string {
2226
+ const entry: CompactionEntry<T> = {
2227
+ type: "compaction",
2228
+ id: generateId(this.#byId),
2229
+ parentId: this.#leafId,
2230
+ timestamp: new Date().toISOString(),
2231
+ summary,
2232
+ shortSummary,
2233
+ firstKeptEntryId,
2234
+ tokensBefore,
2235
+ details,
2236
+ fromExtension,
2237
+ preserveData,
2238
+ };
2239
+ this.#appendEntry(entry);
2240
+ return entry.id;
2241
+ }
2242
+
2243
+ /** Append a custom entry (for extensions) as child of current leaf, then advance leaf. Returns entry id. */
2244
+ appendCustomEntry(customType: string, data?: unknown): string {
2245
+ const entry: CustomEntry = {
2246
+ type: "custom",
2247
+ customType,
2248
+ data,
2249
+ id: generateId(this.#byId),
2250
+ parentId: this.#leafId,
2251
+ timestamp: new Date().toISOString(),
2252
+ };
2253
+ this.#appendEntry(entry);
2254
+ return entry.id;
2255
+ }
2256
+
2257
+ /**
2258
+ * Rewrite the session file after in-place entry updates.
2259
+ * Use sparingly (e.g., pruning old tool outputs).
2260
+ */
2261
+ async rewriteEntries(): Promise<void> {
2262
+ if (!this.persist || !this.#sessionFile) return;
2263
+ await this.#rewriteFile();
2264
+ }
2265
+
2266
+ /**
2267
+ * Append a custom message entry (for extensions) that participates in LLM context.
2268
+ * @param customType Hook identifier for filtering on reload
2269
+ * @param content Message content (string or TextContent/ImageContent array)
2270
+ * @param display Whether to show in TUI (true = styled display, false = hidden)
2271
+ * @param details Optional extension-specific metadata (not sent to LLM)
2272
+ * @param attribution Who initiated this message for billing/attribution semantics
2273
+ * @returns Entry id
2274
+ */
2275
+ appendCustomMessageEntry<T = unknown>(
2276
+ customType: string,
2277
+ content: string | (TextContent | ImageContent)[],
2278
+ display: boolean,
2279
+ details?: T,
2280
+ attribution: MessageAttribution = "agent",
2281
+ ): string {
2282
+ const entry: CustomMessageEntry<T> = {
2283
+ type: "custom_message",
2284
+ customType,
2285
+ content,
2286
+ display,
2287
+ details,
2288
+ attribution,
2289
+ id: generateId(this.#byId),
2290
+ parentId: this.#leafId,
2291
+ timestamp: new Date().toISOString(),
2292
+ };
2293
+ this.#appendEntry(entry);
2294
+ return entry.id;
2295
+ }
2296
+
2297
+ // =========================================================================
2298
+ // TTSR (Time Traveling Stream Rules)
2299
+ // =========================================================================
2300
+
2301
+ /**
2302
+ * Append an MCP tool selection entry recording the discovery-selected MCP tools.
2303
+ * @param selectedToolNames MCP tool names selected for this branch
2304
+ * @returns Entry id
2305
+ */
2306
+ appendMCPToolSelection(selectedToolNames: string[]): string {
2307
+ const entry: MCPToolSelectionEntry = {
2308
+ type: "mcp_tool_selection",
2309
+ id: generateId(this.#byId),
2310
+ parentId: this.#leafId,
2311
+ timestamp: new Date().toISOString(),
2312
+ selectedToolNames: [...selectedToolNames],
2313
+ };
2314
+ this.#appendEntry(entry);
2315
+ return entry.id;
2316
+ }
2317
+
2318
+ /**
2319
+ * Append a TTSR injection entry recording which rules were injected.
2320
+ * @param ruleNames Names of rules that were injected
2321
+ * @returns Entry id
2322
+ */
2323
+ appendTtsrInjection(ruleNames: string[]): string {
2324
+ const entry: TtsrInjectionEntry = {
2325
+ type: "ttsr_injection",
2326
+ id: generateId(this.#byId),
2327
+ parentId: this.#leafId,
2328
+ timestamp: new Date().toISOString(),
2329
+ injectedRules: ruleNames,
2330
+ };
2331
+ this.#appendEntry(entry);
2332
+ return entry.id;
2333
+ }
2334
+
2335
+ /**
2336
+ * Get all unique TTSR rule names that have been injected in the current branch.
2337
+ * Scans from root to current leaf for ttsr_injection entries.
2338
+ */
2339
+ getInjectedTtsrRules(): string[] {
2340
+ const path = this.getBranch();
2341
+ const ruleNames = new Set<string>();
2342
+ for (const entry of path) {
2343
+ if (entry.type === "ttsr_injection") {
2344
+ for (const name of entry.injectedRules) {
2345
+ ruleNames.add(name);
2346
+ }
2347
+ }
2348
+ }
2349
+ return Array.from(ruleNames);
2350
+ }
2351
+
2352
+ // =========================================================================
2353
+ // Tree Traversal
2354
+ // =========================================================================
2355
+
2356
+ getLeafId(): string | null {
2357
+ return this.#leafId;
2358
+ }
2359
+
2360
+ getLeafEntry(): SessionEntry | undefined {
2361
+ return this.#leafId ? this.#byId.get(this.#leafId) : undefined;
2362
+ }
2363
+
2364
+ /**
2365
+ * Get the most recent model role from the current session path.
2366
+ * Returns undefined if no model change has been recorded.
2367
+ */
2368
+ getLastModelChangeRole(): string | undefined {
2369
+ let current = this.getLeafEntry();
2370
+ while (current) {
2371
+ if (current.type === "model_change") {
2372
+ return current.role ?? "default";
2373
+ }
2374
+ current = current.parentId ? this.#byId.get(current.parentId) : undefined;
2375
+ }
2376
+ return undefined;
2377
+ }
2378
+
2379
+ getEntry(id: string): SessionEntry | undefined {
2380
+ return this.#byId.get(id);
2381
+ }
2382
+
2383
+ /**
2384
+ * Get all direct children of an entry.
2385
+ */
2386
+ getChildren(parentId: string): SessionEntry[] {
2387
+ const children: SessionEntry[] = [];
2388
+ for (const entry of this.#byId.values()) {
2389
+ if (entry.parentId === parentId) {
2390
+ children.push(entry);
2391
+ }
2392
+ }
2393
+ return children;
2394
+ }
2395
+
2396
+ /**
2397
+ * Get the label for an entry, if any.
2398
+ */
2399
+ getLabel(id: string): string | undefined {
2400
+ return this.#labelsById.get(id);
2401
+ }
2402
+
2403
+ /**
2404
+ * Set or clear a label on an entry.
2405
+ * Labels are user-defined markers for bookmarking/navigation.
2406
+ * Pass undefined or empty string to clear the label.
2407
+ */
2408
+ appendLabelChange(targetId: string, label: string | undefined): string {
2409
+ if (!this.#byId.has(targetId)) {
2410
+ throw new Error(`Entry ${targetId} not found`);
2411
+ }
2412
+ const entry: LabelEntry = {
2413
+ type: "label",
2414
+ id: generateId(this.#byId),
2415
+ parentId: this.#leafId,
2416
+ timestamp: new Date().toISOString(),
2417
+ targetId,
2418
+ label,
2419
+ };
2420
+ this.#appendEntry(entry);
2421
+ if (label) {
2422
+ this.#labelsById.set(targetId, label);
2423
+ } else {
2424
+ this.#labelsById.delete(targetId);
2425
+ }
2426
+ return entry.id;
2427
+ }
2428
+
2429
+ /**
2430
+ * Walk from entry to root, returning all entries in path order.
2431
+ * Includes all entry types (messages, compaction, model changes, etc.).
2432
+ * Use buildSessionContext() to get the resolved messages for the LLM.
2433
+ */
2434
+ getBranch(fromId?: string): SessionEntry[] {
2435
+ const path: SessionEntry[] = [];
2436
+ const startId = fromId ?? this.#leafId;
2437
+ let current = startId ? this.#byId.get(startId) : undefined;
2438
+ while (current) {
2439
+ path.unshift(current);
2440
+ current = current.parentId ? this.#byId.get(current.parentId) : undefined;
2441
+ }
2442
+ return path;
2443
+ }
2444
+
2445
+ /**
2446
+ * Build the session context (what gets sent to the LLM).
2447
+ * Uses tree traversal from current leaf.
2448
+ */
2449
+ buildSessionContext(): SessionContext {
2450
+ return buildSessionContext(this.getEntries(), this.#leafId, this.#byId);
2451
+ }
2452
+
2453
+ /** Strip stale OpenAI Responses assistant replay metadata from loaded in-memory entries. */
2454
+ sanitizeLoadedOpenAIResponsesReplayMetadata(): boolean {
2455
+ let didSanitize = false;
2456
+ for (const entry of this.#fileEntries) {
2457
+ if (entry.type !== "message" || entry.message.role !== "assistant") {
2458
+ continue;
2459
+ }
2460
+
2461
+ const sanitizedMessage = sanitizeRehydratedOpenAIResponsesAssistantMessage(entry.message);
2462
+ if (sanitizedMessage === entry.message) {
2463
+ continue;
2464
+ }
2465
+
2466
+ entry.message = sanitizedMessage;
2467
+ didSanitize = true;
2468
+ }
2469
+
2470
+ return didSanitize;
2471
+ }
2472
+
2473
+ /**
2474
+ * Get session header.
2475
+ */
2476
+ getHeader(): SessionHeader | null {
2477
+ const h = this.#fileEntries.find(e => e.type === "session");
2478
+ return h ? (h as SessionHeader) : null;
2479
+ }
2480
+
2481
+ /**
2482
+ * Get all session entries (excludes header). Returns a shallow copy.
2483
+ * The session is append-only: use appendXXX() to add entries, branch() to
2484
+ * change the leaf pointer. Entries cannot be modified or deleted.
2485
+ */
2486
+ getEntries(): SessionEntry[] {
2487
+ return this.#fileEntries.filter((e): e is SessionEntry => e.type !== "session");
2488
+ }
2489
+
2490
+ /**
2491
+ * Get the session as a tree structure. Returns a shallow defensive copy of all entries.
2492
+ * A well-formed session has exactly one root (first entry with parentId === null).
2493
+ * Orphaned entries (broken parent chain) are also returned as roots.
2494
+ */
2495
+ getTree(): SessionTreeNode[] {
2496
+ const entries = this.getEntries();
2497
+ const nodeMap = new Map<string, SessionTreeNode>();
2498
+ const roots: SessionTreeNode[] = [];
2499
+
2500
+ // Create nodes with resolved labels
2501
+ for (const entry of entries) {
2502
+ const label = this.#labelsById.get(entry.id);
2503
+ nodeMap.set(entry.id, { entry, children: [], label });
2504
+ }
2505
+
2506
+ // Build tree
2507
+ for (const entry of entries) {
2508
+ const node = nodeMap.get(entry.id)!;
2509
+ if (entry.parentId === null || entry.parentId === entry.id) {
2510
+ roots.push(node);
2511
+ } else {
2512
+ const parent = nodeMap.get(entry.parentId);
2513
+ if (parent) {
2514
+ parent.children.push(node);
2515
+ } else {
2516
+ // Orphan - treat as root
2517
+ roots.push(node);
2518
+ }
2519
+ }
2520
+ }
2521
+
2522
+ // Sort children by timestamp (oldest first, newest at bottom)
2523
+ // Use iterative approach to avoid stack overflow on deep trees
2524
+ const stack: SessionTreeNode[] = [...roots];
2525
+ while (stack.length > 0) {
2526
+ const node = stack.pop()!;
2527
+ node.children.sort((a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime());
2528
+ stack.push(...node.children);
2529
+ }
2530
+
2531
+ return roots;
2532
+ }
2533
+
2534
+ // =========================================================================
2535
+ // Branching
2536
+ // =========================================================================
2537
+
2538
+ /**
2539
+ * Start a new branch from an earlier entry.
2540
+ * Moves the leaf pointer to the specified entry. The next appendXXX() call
2541
+ * will create a child of that entry, forming a new branch. Existing entries
2542
+ * are not modified or deleted.
2543
+ */
2544
+ branch(branchFromId: string): void {
2545
+ if (!this.#byId.has(branchFromId)) {
2546
+ throw new Error(`Entry ${branchFromId} not found`);
2547
+ }
2548
+ this.#leafId = branchFromId;
2549
+ }
2550
+
2551
+ /**
2552
+ * Reset the leaf pointer to null (before any entries).
2553
+ * The next appendXXX() call will create a new root entry (parentId = null).
2554
+ * Use this when navigating to re-edit the first user message.
2555
+ */
2556
+ resetLeaf(): void {
2557
+ this.#leafId = null;
2558
+ }
2559
+
2560
+ /**
2561
+ * Start a new branch with a summary of the abandoned path.
2562
+ * Same as branch(), but also appends a branch_summary entry that captures
2563
+ * context from the abandoned conversation path.
2564
+ */
2565
+ branchWithSummary(branchFromId: string | null, summary: string, details?: unknown, fromExtension?: boolean): string {
2566
+ if (branchFromId !== null && !this.#byId.has(branchFromId)) {
2567
+ throw new Error(`Entry ${branchFromId} not found`);
2568
+ }
2569
+ this.#leafId = branchFromId;
2570
+ const entry: BranchSummaryEntry = {
2571
+ type: "branch_summary",
2572
+ id: generateId(this.#byId),
2573
+ parentId: branchFromId,
2574
+ timestamp: new Date().toISOString(),
2575
+ fromId: branchFromId ?? "root",
2576
+ summary,
2577
+ details,
2578
+ fromExtension,
2579
+ };
2580
+ this.#appendEntry(entry);
2581
+ return entry.id;
2582
+ }
2583
+
2584
+ /**
2585
+ * Create a new session file containing only the path from root to the specified leaf.
2586
+ * Useful for extracting a single conversation path from a branched session.
2587
+ * Returns the new session file path, or undefined if not persisting.
2588
+ */
2589
+ createBranchedSession(leafId: string): string | undefined {
2590
+ const previousSessionFile = this.#sessionFile;
2591
+ const branchPath = this.getBranch(leafId);
2592
+ if (branchPath.length === 0) {
2593
+ throw new Error(`Entry ${leafId} not found`);
2594
+ }
2595
+
2596
+ // Filter out LabelEntry from path - we'll recreate them from the resolved map
2597
+ const pathWithoutLabels = branchPath.filter(e => e.type !== "label");
2598
+
2599
+ const newSessionId = Snowflake.next();
2600
+ const timestamp = new Date().toISOString();
2601
+ const fileTimestamp = timestamp.replace(/[:.]/g, "-");
2602
+ const newSessionFile = path.join(this.getSessionDir(), `${fileTimestamp}_${newSessionId}.jsonl`);
2603
+
2604
+ const header: SessionHeader = {
2605
+ type: "session",
2606
+ version: CURRENT_SESSION_VERSION,
2607
+ id: newSessionId,
2608
+ timestamp,
2609
+ cwd: this.cwd,
2610
+ parentSession: this.persist ? previousSessionFile : undefined,
2611
+ };
2612
+
2613
+ // Collect labels for entries in the path
2614
+ const pathEntryIds = new Set(pathWithoutLabels.map(e => e.id));
2615
+ const labelsToWrite: Array<{ targetId: string; label: string }> = [];
2616
+ for (const [targetId, label] of this.#labelsById) {
2617
+ if (pathEntryIds.has(targetId)) {
2618
+ labelsToWrite.push({ targetId, label });
2619
+ }
2620
+ }
2621
+
2622
+ if (this.persist) {
2623
+ const lines: string[] = [];
2624
+ lines.push(JSON.stringify(header));
2625
+ for (const entry of pathWithoutLabels) {
2626
+ lines.push(JSON.stringify(entry));
2627
+ }
2628
+ // Write fresh label entries at the end
2629
+ const lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
2630
+ let parentId = lastEntryId;
2631
+ const labelEntries: LabelEntry[] = [];
2632
+ for (const { targetId, label } of labelsToWrite) {
2633
+ const labelEntry: LabelEntry = {
2634
+ type: "label",
2635
+ id: generateId(new Set(pathEntryIds)),
2636
+ parentId,
2637
+ timestamp: new Date().toISOString(),
2638
+ targetId,
2639
+ label,
2640
+ };
2641
+ lines.push(JSON.stringify(labelEntry));
2642
+ pathEntryIds.add(labelEntry.id);
2643
+ labelEntries.push(labelEntry);
2644
+ parentId = labelEntry.id;
2645
+ }
2646
+ this.storage.writeTextSync(newSessionFile, `${lines.join("\n")}\n`);
2647
+ this.#fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
2648
+ this.#sessionId = newSessionId;
2649
+ this.#sessionFile = newSessionFile;
2650
+ this.#flushed = true;
2651
+ this.#buildIndex();
2652
+ return newSessionFile;
2653
+ }
2654
+
2655
+ // In-memory mode: replace current session with the path + labels
2656
+ const labelEntries: LabelEntry[] = [];
2657
+ let parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
2658
+ for (const { targetId, label } of labelsToWrite) {
2659
+ const labelEntry: LabelEntry = {
2660
+ type: "label",
2661
+ id: generateId(new Set([...pathEntryIds, ...labelEntries.map(e => e.id)])),
2662
+ parentId,
2663
+ timestamp: new Date().toISOString(),
2664
+ targetId,
2665
+ label,
2666
+ };
2667
+ labelEntries.push(labelEntry);
2668
+ parentId = labelEntry.id;
2669
+ }
2670
+ this.#fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
2671
+ this.#sessionId = newSessionId;
2672
+ this.#buildIndex();
2673
+ return undefined;
2674
+ }
2675
+
2676
+ /**
2677
+ * Resolve the canonical default session directory for a cwd.
2678
+ */
2679
+ static getDefaultSessionDir(
2680
+ cwd: string,
2681
+ agentDir?: string,
2682
+ storage: SessionStorage = new FileSessionStorage(),
2683
+ ): string {
2684
+ return computeDefaultSessionDir(cwd, storage, getSessionsDir(agentDir));
2685
+ }
2686
+
2687
+ /**
2688
+ * Create a new session.
2689
+ * @param cwd Working directory (stored in session header)
2690
+ * @param sessionDir Optional session directory. If omitted, uses default (~/.xcsh/agent/sessions/<encoded-cwd>/).
2691
+ */
2692
+ static create(cwd: string, sessionDir?: string, storage: SessionStorage = new FileSessionStorage()): SessionManager {
2693
+ const dir = sessionDir ?? SessionManager.getDefaultSessionDir(cwd, undefined, storage);
2694
+ const manager = new SessionManager(cwd, dir, true, storage);
2695
+ manager.#initNewSession();
2696
+ return manager;
2697
+ }
2698
+
2699
+ /**
2700
+ * Fork a session into the current project directory.
2701
+ * Copies history from another session file while creating a new session file in the current sessionDir.
2702
+ */
2703
+ static async forkFrom(
2704
+ sourcePath: string,
2705
+ cwd: string,
2706
+ sessionDir?: string,
2707
+ storage: SessionStorage = new FileSessionStorage(),
2708
+ ): Promise<SessionManager> {
2709
+ const dir = sessionDir ?? SessionManager.getDefaultSessionDir(cwd, undefined, storage);
2710
+ const manager = new SessionManager(cwd, dir, true, storage);
2711
+ const forkEntries = structuredClone(await loadEntriesFromFile(sourcePath, storage)) as FileEntry[];
2712
+ migrateToCurrentVersion(forkEntries);
2713
+ await resolveBlobRefsInEntries(forkEntries, manager.#blobStore);
2714
+ const sourceHeader = forkEntries.find(e => e.type === "session") as SessionHeader | undefined;
2715
+ const historyEntries = forkEntries.filter(entry => entry.type !== "session") as SessionEntry[];
2716
+ manager.#newSessionSync({ parentSession: sourceHeader?.id });
2717
+ const newHeader = manager.#fileEntries[0] as SessionHeader;
2718
+ newHeader.title = sourceHeader?.title;
2719
+ newHeader.titleSource = sourceHeader?.titleSource;
2720
+ manager.#fileEntries = [newHeader, ...historyEntries];
2721
+ manager.#sessionName = newHeader.title;
2722
+ manager.#titleSource = newHeader.titleSource;
2723
+ manager.sanitizeLoadedOpenAIResponsesReplayMetadata();
2724
+ manager.#buildIndex();
2725
+ await manager.#rewriteFile();
2726
+ return manager;
2727
+ }
2728
+
2729
+ /**
2730
+ * Open a specific session file.
2731
+ * @param path Path to session file
2732
+ * @param sessionDir Optional session directory for /new or /branch. If omitted, derives from file's parent.
2733
+ */
2734
+ static async open(
2735
+ filePath: string,
2736
+ sessionDir?: string,
2737
+ storage: SessionStorage = new FileSessionStorage(),
2738
+ ): Promise<SessionManager> {
2739
+ // Extract cwd from session header if possible, otherwise use getProjectDir()
2740
+ const entries = await loadEntriesFromFile(filePath, storage);
2741
+ const header = entries.find(e => e.type === "session") as SessionHeader | undefined;
2742
+ const cwd = header?.cwd ?? getProjectDir();
2743
+ // If no sessionDir provided, derive from file's parent directory
2744
+ const dir = sessionDir ?? path.resolve(filePath, "..");
2745
+ const manager = new SessionManager(cwd, dir, true, storage);
2746
+ await manager.#initSessionFile(filePath);
2747
+ return manager;
2748
+ }
2749
+
2750
+ /**
2751
+ * Continue the most recent session, or create new if none.
2752
+ * @param cwd Working directory
2753
+ * @param sessionDir Optional session directory. If omitted, uses default (~/.xcsh/agent/sessions/<encoded-cwd>/).
2754
+ */
2755
+ static async continueRecent(
2756
+ cwd: string,
2757
+ sessionDir?: string,
2758
+ storage: SessionStorage = new FileSessionStorage(),
2759
+ ): Promise<SessionManager> {
2760
+ const dir = sessionDir ?? SessionManager.getDefaultSessionDir(cwd, undefined, storage);
2761
+ // Prefer terminal-scoped breadcrumb (handles concurrent sessions correctly)
2762
+ const terminalSession = await readTerminalBreadcrumb(cwd);
2763
+ const mostRecent = terminalSession ?? (await findMostRecentSession(dir, storage));
2764
+ const manager = new SessionManager(cwd, dir, true, storage);
2765
+ if (mostRecent) {
2766
+ await manager.#initSessionFile(mostRecent);
2767
+ } else {
2768
+ manager.#initNewSession();
2769
+ }
2770
+ return manager;
2771
+ }
2772
+
2773
+ /** Create an in-memory session (no file persistence) */
2774
+ static inMemory(
2775
+ cwd: string = getProjectDir(),
2776
+ storage: SessionStorage = new MemorySessionStorage(),
2777
+ ): SessionManager {
2778
+ const manager = new SessionManager(cwd, "", false, storage);
2779
+ manager.#initNewSession();
2780
+ return manager;
2781
+ }
2782
+
2783
+ /**
2784
+ * List all sessions.
2785
+ * @param cwd Working directory (used to compute default session directory)
2786
+ * @param sessionDir Optional session directory. If omitted, uses default (~/.xcsh/agent/sessions/<encoded-cwd>/).
2787
+ */
2788
+ static async list(
2789
+ cwd: string,
2790
+ sessionDir?: string,
2791
+ storage: SessionStorage = new FileSessionStorage(),
2792
+ ): Promise<SessionInfo[]> {
2793
+ const dir = sessionDir ?? SessionManager.getDefaultSessionDir(cwd, undefined, storage);
2794
+ try {
2795
+ const files = storage.listFilesSync(dir, "*.jsonl");
2796
+ return await collectSessionsFromFiles(files, storage);
2797
+ } catch {
2798
+ return [];
2799
+ }
2800
+ }
2801
+
2802
+ /**
2803
+ * List all sessions across all project directories.
2804
+ */
2805
+ static async listAll(storage: SessionStorage = new FileSessionStorage()): Promise<SessionInfo[]> {
2806
+ const sessionsRoot = path.join(getDefaultAgentDir(), "sessions");
2807
+ try {
2808
+ const files = Array.from(new Bun.Glob("**/*.jsonl").scanSync(sessionsRoot)).map(name =>
2809
+ path.join(sessionsRoot, name),
2810
+ );
2811
+ return await collectSessionsFromFiles(files, storage);
2812
+ } catch {
2813
+ return [];
2814
+ }
2815
+ }
2816
+ }