shortcutxl 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (423) hide show
  1. package/README.md +59 -0
  2. package/agent-docs/README.md +397 -0
  3. package/agent-docs/docs/compaction.md +390 -0
  4. package/agent-docs/docs/custom-provider.md +580 -0
  5. package/agent-docs/docs/development.md +69 -0
  6. package/agent-docs/docs/extensions.md +1971 -0
  7. package/agent-docs/docs/json.md +79 -0
  8. package/agent-docs/docs/keybindings.md +174 -0
  9. package/agent-docs/docs/models.md +293 -0
  10. package/agent-docs/docs/packages.md +209 -0
  11. package/agent-docs/docs/prompt-templates.md +67 -0
  12. package/agent-docs/docs/providers.md +186 -0
  13. package/agent-docs/docs/rpc.md +1317 -0
  14. package/agent-docs/docs/sdk.md +962 -0
  15. package/agent-docs/docs/session.md +412 -0
  16. package/agent-docs/docs/settings.md +223 -0
  17. package/agent-docs/docs/shell-aliases.md +13 -0
  18. package/agent-docs/docs/skills.md +231 -0
  19. package/agent-docs/docs/terminal-setup.md +70 -0
  20. package/agent-docs/docs/termux.md +127 -0
  21. package/agent-docs/docs/themes.md +295 -0
  22. package/agent-docs/docs/tree.md +219 -0
  23. package/agent-docs/docs/tui.md +887 -0
  24. package/agent-docs/docs/windows.md +17 -0
  25. package/agent-docs/examples/README.md +25 -0
  26. package/agent-docs/examples/extensions/README.md +205 -0
  27. package/agent-docs/examples/extensions/antigravity-image-gen.ts +447 -0
  28. package/agent-docs/examples/extensions/auto-commit-on-exit.ts +49 -0
  29. package/agent-docs/examples/extensions/bash-spawn-hook.ts +30 -0
  30. package/agent-docs/examples/extensions/bookmark.ts +50 -0
  31. package/agent-docs/examples/extensions/built-in-tool-renderer.ts +256 -0
  32. package/agent-docs/examples/extensions/claude-rules.ts +86 -0
  33. package/agent-docs/examples/extensions/commands.ts +75 -0
  34. package/agent-docs/examples/extensions/confirm-destructive.ts +59 -0
  35. package/agent-docs/examples/extensions/custom-compaction.ts +126 -0
  36. package/agent-docs/examples/extensions/custom-footer.ts +63 -0
  37. package/agent-docs/examples/extensions/custom-header.ts +73 -0
  38. package/agent-docs/examples/extensions/custom-provider-anthropic/index.ts +660 -0
  39. package/agent-docs/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
  40. package/agent-docs/examples/extensions/custom-provider-anthropic/package.json +19 -0
  41. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/index.ts +362 -0
  42. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
  43. package/agent-docs/examples/extensions/custom-provider-gitlab-duo/test.ts +88 -0
  44. package/agent-docs/examples/extensions/custom-provider-qwen-cli/index.ts +349 -0
  45. package/agent-docs/examples/extensions/custom-provider-qwen-cli/package.json +16 -0
  46. package/agent-docs/examples/extensions/dirty-repo-guard.ts +56 -0
  47. package/agent-docs/examples/extensions/doom-overlay/README.md +46 -0
  48. package/agent-docs/examples/extensions/doom-overlay/doom/build.sh +152 -0
  49. package/agent-docs/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -0
  50. package/agent-docs/examples/extensions/doom-overlay/doom-component.ts +133 -0
  51. package/agent-docs/examples/extensions/doom-overlay/doom-engine.ts +186 -0
  52. package/agent-docs/examples/extensions/doom-overlay/doom-keys.ts +108 -0
  53. package/agent-docs/examples/extensions/doom-overlay/index.ts +74 -0
  54. package/agent-docs/examples/extensions/doom-overlay/wad-finder.ts +51 -0
  55. package/agent-docs/examples/extensions/dynamic-resources/SKILL.md +8 -0
  56. package/agent-docs/examples/extensions/dynamic-resources/dynamic.json +79 -0
  57. package/agent-docs/examples/extensions/dynamic-resources/dynamic.md +5 -0
  58. package/agent-docs/examples/extensions/dynamic-resources/index.ts +15 -0
  59. package/agent-docs/examples/extensions/dynamic-tools.ts +77 -0
  60. package/agent-docs/examples/extensions/event-bus.ts +43 -0
  61. package/agent-docs/examples/extensions/file-trigger.ts +41 -0
  62. package/agent-docs/examples/extensions/git-checkpoint.ts +53 -0
  63. package/agent-docs/examples/extensions/handoff.ts +155 -0
  64. package/agent-docs/examples/extensions/hello.ts +25 -0
  65. package/agent-docs/examples/extensions/inline-bash.ts +94 -0
  66. package/agent-docs/examples/extensions/input-transform.ts +43 -0
  67. package/agent-docs/examples/extensions/interactive-shell.ts +209 -0
  68. package/agent-docs/examples/extensions/mac-system-theme.ts +47 -0
  69. package/agent-docs/examples/extensions/message-renderer.ts +59 -0
  70. package/agent-docs/examples/extensions/minimal-mode.ts +430 -0
  71. package/agent-docs/examples/extensions/modal-editor.ts +90 -0
  72. package/agent-docs/examples/extensions/model-status.ts +31 -0
  73. package/agent-docs/examples/extensions/notify.ts +55 -0
  74. package/agent-docs/examples/extensions/overlay-qa-tests.ts +936 -0
  75. package/agent-docs/examples/extensions/overlay-test.ts +159 -0
  76. package/agent-docs/examples/extensions/permission-gate.ts +37 -0
  77. package/agent-docs/examples/extensions/pirate.ts +47 -0
  78. package/agent-docs/examples/extensions/plan-mode/README.md +65 -0
  79. package/agent-docs/examples/extensions/plan-mode/index.ts +363 -0
  80. package/agent-docs/examples/extensions/plan-mode/utils.ts +173 -0
  81. package/agent-docs/examples/extensions/preset.ts +418 -0
  82. package/agent-docs/examples/extensions/protected-paths.ts +30 -0
  83. package/agent-docs/examples/extensions/qna.ts +122 -0
  84. package/agent-docs/examples/extensions/question.ts +278 -0
  85. package/agent-docs/examples/extensions/questionnaire.ts +440 -0
  86. package/agent-docs/examples/extensions/rainbow-editor.ts +90 -0
  87. package/agent-docs/examples/extensions/reload-runtime.ts +37 -0
  88. package/agent-docs/examples/extensions/rpc-demo.ts +124 -0
  89. package/agent-docs/examples/extensions/sandbox/index.ts +324 -0
  90. package/agent-docs/examples/extensions/sandbox/package-lock.json +92 -0
  91. package/agent-docs/examples/extensions/sandbox/package.json +19 -0
  92. package/agent-docs/examples/extensions/send-user-message.ts +97 -0
  93. package/agent-docs/examples/extensions/session-name.ts +27 -0
  94. package/agent-docs/examples/extensions/shutdown-command.ts +69 -0
  95. package/agent-docs/examples/extensions/snake.ts +343 -0
  96. package/agent-docs/examples/extensions/space-invaders.ts +566 -0
  97. package/agent-docs/examples/extensions/ssh.ts +233 -0
  98. package/agent-docs/examples/extensions/status-line.ts +40 -0
  99. package/agent-docs/examples/extensions/subagent/README.md +172 -0
  100. package/agent-docs/examples/extensions/subagent/agents/planner.md +37 -0
  101. package/agent-docs/examples/extensions/subagent/agents/reviewer.md +35 -0
  102. package/agent-docs/examples/extensions/subagent/agents/scout.md +50 -0
  103. package/agent-docs/examples/extensions/subagent/agents/worker.md +24 -0
  104. package/agent-docs/examples/extensions/subagent/agents.ts +130 -0
  105. package/agent-docs/examples/extensions/subagent/index.ts +1068 -0
  106. package/agent-docs/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
  107. package/agent-docs/examples/extensions/subagent/prompts/implement.md +10 -0
  108. package/agent-docs/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
  109. package/agent-docs/examples/extensions/summarize.ts +206 -0
  110. package/agent-docs/examples/extensions/system-prompt-header.ts +17 -0
  111. package/agent-docs/examples/extensions/timed-confirm.ts +72 -0
  112. package/agent-docs/examples/extensions/titlebar-spinner.ts +58 -0
  113. package/agent-docs/examples/extensions/todo.ts +314 -0
  114. package/agent-docs/examples/extensions/tool-override.ts +146 -0
  115. package/agent-docs/examples/extensions/tools.ts +145 -0
  116. package/agent-docs/examples/extensions/trigger-compact.ts +40 -0
  117. package/agent-docs/examples/extensions/truncated-tool.ts +194 -0
  118. package/agent-docs/examples/extensions/widget-placement.ts +17 -0
  119. package/agent-docs/examples/extensions/with-deps/index.ts +37 -0
  120. package/agent-docs/examples/extensions/with-deps/package-lock.json +31 -0
  121. package/agent-docs/examples/extensions/with-deps/package.json +22 -0
  122. package/agent-docs/examples/rpc-extension-ui.ts +654 -0
  123. package/agent-docs/examples/sdk/01-minimal.ts +22 -0
  124. package/agent-docs/examples/sdk/02-custom-model.ts +48 -0
  125. package/agent-docs/examples/sdk/03-custom-prompt.ts +55 -0
  126. package/agent-docs/examples/sdk/04-skills.ts +53 -0
  127. package/agent-docs/examples/sdk/05-tools.ts +56 -0
  128. package/agent-docs/examples/sdk/06-extensions.ts +88 -0
  129. package/agent-docs/examples/sdk/07-context-files.ts +40 -0
  130. package/agent-docs/examples/sdk/08-prompt-templates.ts +47 -0
  131. package/agent-docs/examples/sdk/09-api-keys-and-oauth.ts +48 -0
  132. package/agent-docs/examples/sdk/10-settings.ts +54 -0
  133. package/agent-docs/examples/sdk/11-sessions.ts +48 -0
  134. package/agent-docs/examples/sdk/12-full-control.ts +82 -0
  135. package/agent-docs/examples/sdk/README.md +144 -0
  136. package/agent-docs/xll-skill.md +61 -0
  137. package/agent-docs/xll-spec.md +110 -0
  138. package/dist/cli/args.js +290 -0
  139. package/dist/cli/config-selector.js +31 -0
  140. package/dist/cli/file-processor.js +79 -0
  141. package/dist/cli/list-models.js +92 -0
  142. package/dist/cli/package-commands.js +210 -0
  143. package/dist/cli/report-settings-errors.js +11 -0
  144. package/dist/cli/session-picker.js +34 -0
  145. package/dist/cli.js +19 -0
  146. package/dist/config.js +288 -0
  147. package/dist/core/abort.js +15 -0
  148. package/dist/core/agent-loop.js +352 -0
  149. package/dist/core/agent-session.js +2019 -0
  150. package/dist/core/agent.js +410 -0
  151. package/dist/core/auth-storage.js +456 -0
  152. package/dist/core/bash-executor.js +222 -0
  153. package/dist/core/compaction/branch-summarization.js +242 -0
  154. package/dist/core/compaction/compaction.js +610 -0
  155. package/dist/core/compaction/index.js +7 -0
  156. package/dist/core/compaction/utils.js +139 -0
  157. package/dist/core/defaults.js +6 -0
  158. package/dist/core/diagnostics.js +2 -0
  159. package/dist/core/event-bus.js +25 -0
  160. package/dist/core/exec.js +71 -0
  161. package/dist/core/export-html/ansi-to-html.js +256 -0
  162. package/dist/core/export-html/index.js +238 -0
  163. package/dist/core/export-html/session-view-model.js +342 -0
  164. package/dist/core/export-html/template.css +1110 -0
  165. package/dist/core/export-html/template.html +76 -0
  166. package/dist/core/export-html/template.js +1990 -0
  167. package/dist/core/export-html/tool-renderer.js +63 -0
  168. package/dist/core/export-html/vendor/highlight.min.js +7725 -0
  169. package/dist/core/export-html/vendor/marked.min.js +1803 -0
  170. package/dist/core/extensions/index.js +9 -0
  171. package/dist/core/extensions/loader.js +422 -0
  172. package/dist/core/extensions/runner.js +651 -0
  173. package/dist/core/extensions/types.js +35 -0
  174. package/dist/core/extensions/wrapper.js +102 -0
  175. package/dist/core/footer-data-provider.js +162 -0
  176. package/dist/core/index.js +9 -0
  177. package/dist/core/keybindings.js +153 -0
  178. package/dist/core/messages.js +133 -0
  179. package/dist/core/model-registry.js +539 -0
  180. package/dist/core/model-resolver.js +370 -0
  181. package/dist/core/package-manager.js +1485 -0
  182. package/dist/core/prompt-templates.js +253 -0
  183. package/dist/core/resolve-config-value.js +59 -0
  184. package/dist/core/resource-loader.js +700 -0
  185. package/dist/core/sdk.js +197 -0
  186. package/dist/core/session-bash.js +99 -0
  187. package/dist/core/session-compaction.js +165 -0
  188. package/dist/core/session-manager.js +1153 -0
  189. package/dist/core/session-models.js +99 -0
  190. package/dist/core/session-retry.js +155 -0
  191. package/dist/core/settings-manager.js +572 -0
  192. package/dist/core/skills.js +382 -0
  193. package/dist/core/slash-commands.js +31 -0
  194. package/dist/core/system-prompt.js +161 -0
  195. package/dist/core/theme.js +770 -0
  196. package/dist/core/timings.js +26 -0
  197. package/dist/core/tools/bash.js +258 -0
  198. package/dist/core/tools/edit-diff.js +245 -0
  199. package/dist/core/tools/edit.js +148 -0
  200. package/dist/core/tools/find.js +208 -0
  201. package/dist/core/tools/grep.js +246 -0
  202. package/dist/core/tools/index.js +67 -0
  203. package/dist/core/tools/ls.js +123 -0
  204. package/dist/core/tools/path-utils.js +81 -0
  205. package/dist/core/tools/read.js +160 -0
  206. package/dist/core/tools/truncate.js +70 -0
  207. package/dist/core/tools/write.js +82 -0
  208. package/dist/custom/agents/action.js +13 -0
  209. package/dist/custom/agents/document-reader.js +70 -0
  210. package/dist/custom/agents/general.js +26 -0
  211. package/dist/custom/agents/index.js +49 -0
  212. package/dist/custom/agents/installation.js +13 -0
  213. package/dist/custom/agents/types.js +7 -0
  214. package/dist/custom/auth/refresh-timer.js +33 -0
  215. package/dist/custom/auth/shortcut-oauth.js +145 -0
  216. package/dist/custom/constants.js +21 -0
  217. package/dist/custom/context/workbook-summary.js +73 -0
  218. package/dist/custom/credits/shortcut-credits.js +29 -0
  219. package/dist/custom/cron/cron-daemon-entry.js +18 -0
  220. package/dist/custom/cron/daemon-ipc.js +131 -0
  221. package/dist/custom/cron/daemon.js +224 -0
  222. package/dist/custom/cron/jobs.js +226 -0
  223. package/dist/custom/cron/run-log.js +51 -0
  224. package/dist/custom/cron/schedule.js +72 -0
  225. package/dist/custom/cron/status-line.js +98 -0
  226. package/dist/custom/cron/store.js +87 -0
  227. package/dist/custom/cron/types.js +8 -0
  228. package/dist/custom/dev/index.js +59 -0
  229. package/dist/custom/dev/trace-export.js +58 -0
  230. package/dist/custom/ensure-excel.js +63 -0
  231. package/dist/custom/excel-config.js +36 -0
  232. package/dist/custom/preflight.js +422 -0
  233. package/dist/custom/prompts/action.js +100 -0
  234. package/dist/custom/prompts/api.js +66 -0
  235. package/dist/custom/prompts/installation.js +124 -0
  236. package/dist/custom/prompts/shared.js +138 -0
  237. package/dist/custom/providers/llm-usage.js +42 -0
  238. package/dist/custom/providers/message-converter.js +74 -0
  239. package/dist/custom/providers/provider-ids.js +9 -0
  240. package/dist/custom/providers/register-openai-codex-provider.js +27 -0
  241. package/dist/custom/providers/register-shortcut-provider.js +52 -0
  242. package/dist/custom/providers/shortcut-invoke.js +117 -0
  243. package/dist/custom/providers/shortcut-stream.js +252 -0
  244. package/dist/custom/providers/sse-protocol.js +38 -0
  245. package/dist/custom/sync-xll.js +130 -0
  246. package/dist/custom/tools/cron.js +413 -0
  247. package/dist/custom/tools/excel-exec.js +167 -0
  248. package/dist/custom/tools/excel-range.js +50 -0
  249. package/dist/custom/tools/llm-analysis.js +265 -0
  250. package/dist/custom/tools/render-helpers.js +38 -0
  251. package/dist/custom/tools/switch-mode.js +94 -0
  252. package/dist/custom/tools/task/agents.js +6 -0
  253. package/dist/custom/tools/task/index.js +8 -0
  254. package/dist/custom/tools/task/render.js +348 -0
  255. package/dist/custom/tools/task/subprocess.js +320 -0
  256. package/dist/custom/tools/task/task.js +205 -0
  257. package/dist/custom/tools/todo-list.js +195 -0
  258. package/dist/custom/tracing/session-upload.js +93 -0
  259. package/dist/index.js +45 -0
  260. package/dist/main.js +613 -0
  261. package/dist/migrations.js +265 -0
  262. package/dist/modes/index.js +8 -0
  263. package/dist/modes/interactive/components/armin.js +337 -0
  264. package/dist/modes/interactive/components/assistant-message.js +94 -0
  265. package/dist/modes/interactive/components/bash-execution.js +171 -0
  266. package/dist/modes/interactive/components/bordered-loader.js +51 -0
  267. package/dist/modes/interactive/components/branch-summary-message.js +45 -0
  268. package/dist/modes/interactive/components/compaction-summary-message.js +46 -0
  269. package/dist/modes/interactive/components/config-selector.js +488 -0
  270. package/dist/modes/interactive/components/countdown-timer.js +33 -0
  271. package/dist/modes/interactive/components/custom-editor.js +93 -0
  272. package/dist/modes/interactive/components/custom-message.js +81 -0
  273. package/dist/modes/interactive/components/daxnuts.js +140 -0
  274. package/dist/modes/interactive/components/diff.js +133 -0
  275. package/dist/modes/interactive/components/dynamic-border.js +21 -0
  276. package/dist/modes/interactive/components/extension-editor.js +105 -0
  277. package/dist/modes/interactive/components/extension-input.js +61 -0
  278. package/dist/modes/interactive/components/extension-selector.js +78 -0
  279. package/dist/modes/interactive/components/footer.js +309 -0
  280. package/dist/modes/interactive/components/index.js +33 -0
  281. package/dist/modes/interactive/components/keybinding-hints.js +61 -0
  282. package/dist/modes/interactive/components/layout.js +64 -0
  283. package/dist/modes/interactive/components/login-dialog.js +148 -0
  284. package/dist/modes/interactive/components/model-selector.js +237 -0
  285. package/dist/modes/interactive/components/oauth-selector.js +111 -0
  286. package/dist/modes/interactive/components/session-selector-search.js +157 -0
  287. package/dist/modes/interactive/components/session-selector.js +860 -0
  288. package/dist/modes/interactive/components/settings-selector.js +123 -0
  289. package/dist/modes/interactive/components/show-images-selector.js +35 -0
  290. package/dist/modes/interactive/components/skill-invocation-message.js +48 -0
  291. package/dist/modes/interactive/components/theme-selector.js +47 -0
  292. package/dist/modes/interactive/components/thinking-selector.js +47 -0
  293. package/dist/modes/interactive/components/tool-execution.js +789 -0
  294. package/dist/modes/interactive/components/tool-group.js +106 -0
  295. package/dist/modes/interactive/components/tree-selector.js +962 -0
  296. package/dist/modes/interactive/components/user-message-selector.js +115 -0
  297. package/dist/modes/interactive/components/user-message.js +48 -0
  298. package/dist/modes/interactive/components/visual-truncate.js +33 -0
  299. package/dist/modes/interactive/file-attachments.js +135 -0
  300. package/dist/modes/interactive/interactive-mode.js +3775 -0
  301. package/dist/modes/interactive/theme/dark.json +85 -0
  302. package/dist/modes/interactive/theme/light.json +85 -0
  303. package/dist/modes/interactive/theme/theme-schema.json +335 -0
  304. package/dist/modes/interactive/theme/theme.js +177 -0
  305. package/dist/modes/print-mode.js +101 -0
  306. package/dist/modes/rpc/rpc-client.js +387 -0
  307. package/dist/modes/rpc/rpc-mode.js +509 -0
  308. package/dist/modes/rpc/rpc-types.js +8 -0
  309. package/dist/subagent-entry.js +145 -0
  310. package/dist/tool-names.js +34 -0
  311. package/dist/tui/autocomplete.js +596 -0
  312. package/dist/tui/components/box.js +104 -0
  313. package/dist/tui/components/cancellable-loader.js +35 -0
  314. package/dist/tui/components/editor.js +1679 -0
  315. package/dist/tui/components/image.js +69 -0
  316. package/dist/tui/components/input.js +433 -0
  317. package/dist/tui/components/loader.js +49 -0
  318. package/dist/tui/components/markdown.js +629 -0
  319. package/dist/tui/components/select-list.js +152 -0
  320. package/dist/tui/components/settings-list.js +185 -0
  321. package/dist/tui/components/spacer.js +23 -0
  322. package/dist/tui/components/text.js +89 -0
  323. package/dist/tui/components/truncated-text.js +51 -0
  324. package/dist/tui/editor-component.js +2 -0
  325. package/dist/tui/fuzzy.js +107 -0
  326. package/dist/tui/get-east-asian-width/index.js +32 -0
  327. package/dist/tui/get-east-asian-width/lookup.js +404 -0
  328. package/dist/tui/index.js +32 -0
  329. package/dist/tui/keybindings.js +114 -0
  330. package/dist/tui/keys.js +959 -0
  331. package/dist/tui/kill-ring.js +44 -0
  332. package/dist/tui/stdin-buffer.js +317 -0
  333. package/dist/tui/terminal-image.js +288 -0
  334. package/dist/tui/terminal.js +249 -0
  335. package/dist/tui/tui/autocomplete.js +596 -0
  336. package/dist/tui/tui/components/box.js +106 -0
  337. package/dist/tui/tui/components/cancellable-loader.js +35 -0
  338. package/dist/tui/tui/components/editor.js +1679 -0
  339. package/dist/tui/tui/components/image.js +69 -0
  340. package/dist/tui/tui/components/input.js +433 -0
  341. package/dist/tui/tui/components/loader.js +49 -0
  342. package/dist/tui/tui/components/markdown.js +629 -0
  343. package/dist/tui/tui/components/select-list.js +152 -0
  344. package/dist/tui/tui/components/settings-list.js +185 -0
  345. package/dist/tui/tui/components/spacer.js +23 -0
  346. package/dist/tui/tui/components/text.js +91 -0
  347. package/dist/tui/tui/components/truncated-text.js +51 -0
  348. package/dist/tui/tui/editor-component.js +2 -0
  349. package/dist/tui/tui/fuzzy.js +107 -0
  350. package/dist/tui/tui/get-east-asian-width/index.js +32 -0
  351. package/dist/tui/tui/get-east-asian-width/lookup.js +404 -0
  352. package/dist/tui/tui/index.js +32 -0
  353. package/dist/tui/tui/keybindings.js +114 -0
  354. package/dist/tui/tui/keys.js +959 -0
  355. package/dist/tui/tui/kill-ring.js +44 -0
  356. package/dist/tui/tui/stdin-buffer.js +317 -0
  357. package/dist/tui/tui/terminal-image.js +288 -0
  358. package/dist/tui/tui/terminal.js +249 -0
  359. package/dist/tui/tui/tui.js +955 -0
  360. package/dist/tui/tui/undo-stack.js +25 -0
  361. package/dist/tui/tui/utils.js +800 -0
  362. package/dist/tui/tui.js +955 -0
  363. package/dist/tui/undo-stack.js +25 -0
  364. package/dist/tui/utils.js +800 -0
  365. package/dist/utils/changelog.js +87 -0
  366. package/dist/utils/clipboard-image.js +164 -0
  367. package/dist/utils/clipboard-native.js +14 -0
  368. package/dist/utils/clipboard.js +67 -0
  369. package/dist/utils/frontmatter.js +26 -0
  370. package/dist/utils/git.js +166 -0
  371. package/dist/utils/image-convert.js +35 -0
  372. package/dist/utils/image-resize.js +183 -0
  373. package/dist/utils/mime.js +26 -0
  374. package/dist/utils/photon.js +121 -0
  375. package/dist/utils/shell.js +217 -0
  376. package/dist/utils/sleep.js +17 -0
  377. package/dist/utils/tools-manager.js +259 -0
  378. package/package.json +78 -0
  379. package/skills/excel-com-api/SKILL.md +74 -0
  380. package/skills/excel-com-api/excel-type-library.py +27767 -0
  381. package/skills/excel-com-api/office-type-library.py +10867 -0
  382. package/skills/integrations/SKILL.md +138 -0
  383. package/skills/integrations/alphasense.md +457 -0
  384. package/skills/integrations/bloomberg.md +803 -0
  385. package/skills/integrations/calcbench.md +315 -0
  386. package/skills/integrations/capiq.md +848 -0
  387. package/skills/integrations/dynamics-365-finance.md +354 -0
  388. package/skills/integrations/earnings_transcripts.md +387 -0
  389. package/skills/integrations/factset.md +758 -0
  390. package/skills/integrations/ice-fixed-income.md +344 -0
  391. package/skills/integrations/moodys-analytics.md +313 -0
  392. package/skills/integrations/morningstar.md +433 -0
  393. package/skills/integrations/nasdaq-data-link.md +249 -0
  394. package/skills/integrations/pitchbook.md +413 -0
  395. package/skills/integrations/preqin.md +422 -0
  396. package/skills/integrations/quickbooks.md +289 -0
  397. package/skills/integrations/quickfs.md +314 -0
  398. package/skills/integrations/refinitiv.md +473 -0
  399. package/skills/integrations/sage-intacct.md +401 -0
  400. package/skills/integrations/visible-alpha.md +320 -0
  401. package/skills/integrations/xero.md +393 -0
  402. package/skills/integrations/ycharts.md +306 -0
  403. package/skills/pdf-creation/SKILL.md +93 -0
  404. package/skills/pdf-extraction/SKILL.md +32 -0
  405. package/skills/powerpoint-creation/SKILL.md +110 -0
  406. package/skills/sec-edgar/SKILL.md +127 -0
  407. package/skills/sec-edgar/sec_to_pdf.py +109 -0
  408. package/xll/ShortcutXL.xll +0 -0
  409. package/xll/modules/debug_render.py +272 -0
  410. package/xll/modules/gameboy.py +241 -0
  411. package/xll/modules/pong.py +188 -0
  412. package/xll/modules/shortcut_xl/__init__.py +18 -0
  413. package/xll/modules/shortcut_xl/_categorize.py +200 -0
  414. package/xll/modules/shortcut_xl/_com.py +108 -0
  415. package/xll/modules/shortcut_xl/_format.py +252 -0
  416. package/xll/modules/shortcut_xl/_log.py +12 -0
  417. package/xll/modules/shortcut_xl/_managed.py +116 -0
  418. package/xll/modules/shortcut_xl/_registry.py +44 -0
  419. package/xll/modules/shortcut_xl/_threading.py +161 -0
  420. package/xll/modules/shortcut_xl/_tracking.py +283 -0
  421. package/xll/modules/stocks.py +100 -0
  422. package/xll/python3.dll +0 -0
  423. package/xll/python312.dll +0 -0
@@ -0,0 +1,1990 @@
1
+ (function () {
2
+ 'use strict';
3
+
4
+ // ============================================================
5
+ // DATA LOADING
6
+ // ============================================================
7
+
8
+ const base64 = document.getElementById('session-data').textContent;
9
+ const binary = atob(base64);
10
+ const bytes = new Uint8Array(binary.length);
11
+ for (let i = 0; i < binary.length; i++) {
12
+ bytes[i] = binary.charCodeAt(i);
13
+ }
14
+ const data = JSON.parse(new TextDecoder('utf-8').decode(bytes));
15
+ const { header, entries, leafId: defaultLeafId, renderedTools } = data;
16
+
17
+ // ============================================================
18
+ // URL PARAMETER HANDLING
19
+ // ============================================================
20
+
21
+ // Parse URL parameters for deep linking: leafId and targetId
22
+ // Check for injected params (when loaded in iframe via srcdoc) or use window.location
23
+ const injectedParams = document.querySelector('meta[name="pi-url-params"]');
24
+ const searchString = injectedParams
25
+ ? injectedParams.content
26
+ : window.location.search.substring(1);
27
+ const urlParams = new URLSearchParams(searchString);
28
+ const urlLeafId = urlParams.get('leafId');
29
+ const urlTargetId = urlParams.get('targetId');
30
+ // Use URL leafId if provided, otherwise fall back to session default
31
+ const leafId = urlLeafId || defaultLeafId;
32
+
33
+ // ============================================================
34
+ // DATA STRUCTURES
35
+ // ============================================================
36
+
37
+ // Entry lookup by ID
38
+ const byId = new Map();
39
+ for (const entry of entries) {
40
+ byId.set(entry.id, entry);
41
+ }
42
+
43
+ // Tool call lookup (toolCallId -> {name, arguments})
44
+ const toolCallMap = new Map();
45
+ for (const entry of entries) {
46
+ if (entry.type === 'message' && entry.message.role === 'assistant') {
47
+ const content = entry.message.content;
48
+ if (Array.isArray(content)) {
49
+ for (const block of content) {
50
+ if (block.type === 'toolCall') {
51
+ toolCallMap.set(block.id, { name: block.name, arguments: block.arguments });
52
+ }
53
+ }
54
+ }
55
+ }
56
+ }
57
+
58
+ // Turn info lookup: maps the first message entry after a turn_start to { turnIndex, durationMs }
59
+ // This lets us annotate the message inline instead of rendering turn boundaries as separate elements
60
+ const turnInfoByMessageId = new Map();
61
+ {
62
+ // First, build turn_start -> turn_end map for durations
63
+ const turnEndMap = new Map();
64
+ for (const entry of entries) {
65
+ if (entry.type === 'turn_end') {
66
+ let current = byId.get(entry.parentId);
67
+ while (current) {
68
+ if (current.type === 'turn_start') {
69
+ turnEndMap.set(current.id, entry);
70
+ break;
71
+ }
72
+ if (!current.parentId || current.parentId === current.id) break;
73
+ current = byId.get(current.parentId);
74
+ }
75
+ }
76
+ }
77
+ // Then, find the first message child of each turn_start
78
+ for (const entry of entries) {
79
+ if (entry.type === 'turn_start') {
80
+ // Find direct child that is a message
81
+ for (const child of entries) {
82
+ if (child.parentId === entry.id && child.type === 'message') {
83
+ const turnEnd = turnEndMap.get(entry.id);
84
+ const durationMs =
85
+ turnEnd && typeof turnEnd.durationMs === 'number' ? turnEnd.durationMs : undefined;
86
+ turnInfoByMessageId.set(child.id, { turnIndex: entry.turnIndex, durationMs });
87
+ break;
88
+ }
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+ // Label lookup (entryId -> label string)
95
+ // Labels are stored in 'label' entries that reference their target via targetId
96
+ const labelMap = new Map();
97
+ for (const entry of entries) {
98
+ if (entry.type === 'label' && entry.targetId && entry.label) {
99
+ labelMap.set(entry.targetId, entry.label);
100
+ }
101
+ }
102
+
103
+ // ============================================================
104
+ // TREE DATA PREPARATION (no DOM, pure data)
105
+ // ============================================================
106
+
107
+ /**
108
+ * Build tree structure from flat entries.
109
+ * Returns array of root nodes, each with { entry, children, label }.
110
+ */
111
+ function buildTree() {
112
+ const nodeMap = new Map();
113
+ const roots = [];
114
+
115
+ // Create nodes
116
+ for (const entry of entries) {
117
+ nodeMap.set(entry.id, {
118
+ entry,
119
+ children: [],
120
+ label: labelMap.get(entry.id)
121
+ });
122
+ }
123
+
124
+ // Build parent-child relationships
125
+ for (const entry of entries) {
126
+ const node = nodeMap.get(entry.id);
127
+ if (entry.parentId === null || entry.parentId === undefined || entry.parentId === entry.id) {
128
+ roots.push(node);
129
+ } else {
130
+ const parent = nodeMap.get(entry.parentId);
131
+ if (parent) {
132
+ parent.children.push(node);
133
+ } else {
134
+ roots.push(node);
135
+ }
136
+ }
137
+ }
138
+
139
+ // Sort children by timestamp
140
+ function sortChildren(node) {
141
+ node.children.sort(
142
+ (a, b) => new Date(a.entry.timestamp).getTime() - new Date(b.entry.timestamp).getTime()
143
+ );
144
+ node.children.forEach(sortChildren);
145
+ }
146
+ roots.forEach(sortChildren);
147
+
148
+ return roots;
149
+ }
150
+
151
+ /**
152
+ * Build set of entry IDs on path from root to target.
153
+ */
154
+ function buildActivePathIds(targetId) {
155
+ const ids = new Set();
156
+ let current = byId.get(targetId);
157
+ while (current) {
158
+ ids.add(current.id);
159
+ // Stop if no parent or self-referencing (root)
160
+ if (!current.parentId || current.parentId === current.id) {
161
+ break;
162
+ }
163
+ current = byId.get(current.parentId);
164
+ }
165
+ return ids;
166
+ }
167
+
168
+ /**
169
+ * Get array of entries from root to target (the conversation path).
170
+ */
171
+ function getPath(targetId) {
172
+ const path = [];
173
+ let current = byId.get(targetId);
174
+ while (current) {
175
+ path.unshift(current);
176
+ // Stop if no parent or self-referencing (root)
177
+ if (!current.parentId || current.parentId === current.id) {
178
+ break;
179
+ }
180
+ current = byId.get(current.parentId);
181
+ }
182
+ return path;
183
+ }
184
+
185
+ // Tree node lookup for finding leaves
186
+ let treeNodeMap = null;
187
+
188
+ /**
189
+ * Find the newest leaf node reachable from a given node.
190
+ * This allows clicking any node in a branch to show the full branch.
191
+ * Children are sorted by timestamp, so the newest is always last.
192
+ */
193
+ function findNewestLeaf(nodeId) {
194
+ // Build tree node map lazily
195
+ if (!treeNodeMap) {
196
+ treeNodeMap = new Map();
197
+ const tree = buildTree();
198
+ function mapNodes(node) {
199
+ treeNodeMap.set(node.entry.id, node);
200
+ node.children.forEach(mapNodes);
201
+ }
202
+ tree.forEach(mapNodes);
203
+ }
204
+
205
+ const node = treeNodeMap.get(nodeId);
206
+ if (!node) return nodeId;
207
+
208
+ // Follow the newest (last) child at each level
209
+ let current = node;
210
+ while (current.children.length > 0) {
211
+ current = current.children[current.children.length - 1];
212
+ }
213
+ return current.entry.id;
214
+ }
215
+
216
+ /**
217
+ * Flatten tree into list with indentation and connector info.
218
+ * Returns array of { node, indent, showConnector, isLast, gutters, isVirtualRootChild, multipleRoots }.
219
+ * Matches tree-selector.ts logic exactly.
220
+ */
221
+ function flattenTree(roots, activePathIds) {
222
+ const result = [];
223
+ const multipleRoots = roots.length > 1;
224
+
225
+ // Mark which subtrees contain the active leaf
226
+ const containsActive = new Map();
227
+ function markActive(node) {
228
+ let has = activePathIds.has(node.entry.id);
229
+ for (const child of node.children) {
230
+ if (markActive(child)) has = true;
231
+ }
232
+ containsActive.set(node, has);
233
+ return has;
234
+ }
235
+ roots.forEach(markActive);
236
+
237
+ // Stack: [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild]
238
+ const stack = [];
239
+
240
+ // Add roots (prioritize branch containing active leaf)
241
+ const orderedRoots = [...roots].sort(
242
+ (a, b) => Number(containsActive.get(b)) - Number(containsActive.get(a))
243
+ );
244
+ for (let i = orderedRoots.length - 1; i >= 0; i--) {
245
+ const isLast = i === orderedRoots.length - 1;
246
+ stack.push([
247
+ orderedRoots[i],
248
+ multipleRoots ? 1 : 0,
249
+ multipleRoots,
250
+ multipleRoots,
251
+ isLast,
252
+ [],
253
+ multipleRoots
254
+ ]);
255
+ }
256
+
257
+ while (stack.length > 0) {
258
+ const [node, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] =
259
+ stack.pop();
260
+
261
+ result.push({
262
+ node,
263
+ indent,
264
+ showConnector,
265
+ isLast,
266
+ gutters,
267
+ isVirtualRootChild,
268
+ multipleRoots
269
+ });
270
+
271
+ const children = node.children;
272
+ const multipleChildren = children.length > 1;
273
+
274
+ // Order children (active branch first)
275
+ const orderedChildren = [...children].sort(
276
+ (a, b) => Number(containsActive.get(b)) - Number(containsActive.get(a))
277
+ );
278
+
279
+ // Calculate child indent (matches tree-selector.ts)
280
+ let childIndent;
281
+ if (multipleChildren) {
282
+ // Parent branches: children get +1
283
+ childIndent = indent + 1;
284
+ } else if (justBranched && indent > 0) {
285
+ // First generation after a branch: +1 for visual grouping
286
+ childIndent = indent + 1;
287
+ } else {
288
+ // Single-child chain: stay flat
289
+ childIndent = indent;
290
+ }
291
+
292
+ // Build gutters for children
293
+ const connectorDisplayed = showConnector && !isVirtualRootChild;
294
+ const currentDisplayIndent = multipleRoots ? Math.max(0, indent - 1) : indent;
295
+ const connectorPosition = Math.max(0, currentDisplayIndent - 1);
296
+ const childGutters = connectorDisplayed
297
+ ? [...gutters, { position: connectorPosition, show: !isLast }]
298
+ : gutters;
299
+
300
+ // Add children in reverse order for stack
301
+ for (let i = orderedChildren.length - 1; i >= 0; i--) {
302
+ const childIsLast = i === orderedChildren.length - 1;
303
+ stack.push([
304
+ orderedChildren[i],
305
+ childIndent,
306
+ multipleChildren,
307
+ multipleChildren,
308
+ childIsLast,
309
+ childGutters,
310
+ false
311
+ ]);
312
+ }
313
+ }
314
+
315
+ return result;
316
+ }
317
+
318
+ /**
319
+ * Build ASCII prefix string for tree node.
320
+ */
321
+ function buildTreePrefix(flatNode) {
322
+ const { indent, showConnector, isLast, gutters, isVirtualRootChild, multipleRoots } = flatNode;
323
+ const displayIndent = multipleRoots ? Math.max(0, indent - 1) : indent;
324
+ const connector = showConnector && !isVirtualRootChild ? (isLast ? '└─ ' : '├─ ') : '';
325
+ const connectorPosition = connector ? displayIndent - 1 : -1;
326
+
327
+ const totalChars = displayIndent * 3;
328
+ const prefixChars = [];
329
+ for (let i = 0; i < totalChars; i++) {
330
+ const level = Math.floor(i / 3);
331
+ const posInLevel = i % 3;
332
+
333
+ const gutter = gutters.find((g) => g.position === level);
334
+ if (gutter) {
335
+ prefixChars.push(posInLevel === 0 ? (gutter.show ? '│' : ' ') : ' ');
336
+ } else if (connector && level === connectorPosition) {
337
+ if (posInLevel === 0) {
338
+ prefixChars.push(isLast ? '└' : '├');
339
+ } else if (posInLevel === 1) {
340
+ prefixChars.push('─');
341
+ } else {
342
+ prefixChars.push(' ');
343
+ }
344
+ } else {
345
+ prefixChars.push(' ');
346
+ }
347
+ }
348
+ return prefixChars.join('');
349
+ }
350
+
351
+ // ============================================================
352
+ // FILTERING (pure data)
353
+ // ============================================================
354
+
355
+ let filterMode = 'default';
356
+ let searchQuery = '';
357
+
358
+ function hasTextContent(content) {
359
+ if (typeof content === 'string') return content.trim().length > 0;
360
+ if (Array.isArray(content)) {
361
+ for (const c of content) {
362
+ if (c.type === 'text' && c.text && c.text.trim().length > 0) return true;
363
+ }
364
+ }
365
+ return false;
366
+ }
367
+
368
+ function extractContent(content) {
369
+ if (typeof content === 'string') return content;
370
+ if (Array.isArray(content)) {
371
+ return content
372
+ .filter((c) => c.type === 'text' && c.text)
373
+ .map((c) => c.text)
374
+ .join('');
375
+ }
376
+ return '';
377
+ }
378
+
379
+ function getSearchableText(entry, label) {
380
+ const parts = [];
381
+ if (label) parts.push(label);
382
+
383
+ switch (entry.type) {
384
+ case 'message': {
385
+ const msg = entry.message;
386
+ parts.push(msg.role);
387
+ if (msg.content) parts.push(extractContent(msg.content));
388
+ if (msg.role === 'bashExecution' && msg.command) parts.push(msg.command);
389
+ break;
390
+ }
391
+ case 'custom_message':
392
+ parts.push(entry.customType);
393
+ parts.push(
394
+ typeof entry.content === 'string' ? entry.content : extractContent(entry.content)
395
+ );
396
+ break;
397
+ case 'compaction':
398
+ parts.push('compaction');
399
+ break;
400
+ case 'branch_summary':
401
+ parts.push('branch summary', entry.summary);
402
+ break;
403
+ case 'model_change':
404
+ parts.push('model', entry.modelId);
405
+ break;
406
+ case 'thinking_level_change':
407
+ parts.push('thinking', entry.thinkingLevel);
408
+ break;
409
+ case 'turn_start':
410
+ parts.push('turn', 'start', String(entry.turnIndex));
411
+ break;
412
+ case 'turn_end':
413
+ parts.push('turn', 'end', String(entry.turnIndex));
414
+ break;
415
+ case 'system_prompt':
416
+ parts.push('system prompt', entry.content);
417
+ break;
418
+ case 'tool_definitions':
419
+ parts.push('tool definitions', ...entry.tools.map((t) => t.name));
420
+ break;
421
+ }
422
+
423
+ return parts.join(' ').toLowerCase();
424
+ }
425
+
426
+ /**
427
+ * Filter flat nodes based on current filterMode and searchQuery.
428
+ */
429
+ function filterNodes(flatNodes, currentLeafId) {
430
+ const searchTokens = searchQuery.toLowerCase().split(/\s+/).filter(Boolean);
431
+
432
+ const filtered = flatNodes.filter((flatNode) => {
433
+ const entry = flatNode.node.entry;
434
+ const label = flatNode.node.label;
435
+ const isCurrentLeaf = entry.id === currentLeafId;
436
+
437
+ // Always show current leaf
438
+ if (isCurrentLeaf) return true;
439
+
440
+ // Hide assistant messages with only tool calls (no text) unless error/aborted
441
+ if (entry.type === 'message' && entry.message.role === 'assistant') {
442
+ const msg = entry.message;
443
+ const hasText = hasTextContent(msg.content);
444
+ const isErrorOrAborted =
445
+ msg.stopReason && msg.stopReason !== 'stop' && msg.stopReason !== 'toolUse';
446
+ if (!hasText && !isErrorOrAborted) return false;
447
+ }
448
+
449
+ // Apply filter mode
450
+ const isSettingsEntry = [
451
+ 'label',
452
+ 'custom',
453
+ 'model_change',
454
+ 'thinking_level_change',
455
+ 'turn_start',
456
+ 'turn_end',
457
+ 'system_prompt',
458
+ 'tool_definitions'
459
+ ].includes(entry.type);
460
+ let passesFilter = true;
461
+
462
+ switch (filterMode) {
463
+ case 'user-only':
464
+ passesFilter = entry.type === 'message' && entry.message.role === 'user';
465
+ break;
466
+ case 'no-tools':
467
+ passesFilter =
468
+ !isSettingsEntry && !(entry.type === 'message' && entry.message.role === 'toolResult');
469
+ break;
470
+ case 'labeled-only':
471
+ passesFilter = label !== undefined;
472
+ break;
473
+ case 'all':
474
+ passesFilter = true;
475
+ break;
476
+ default: // 'default'
477
+ passesFilter = !isSettingsEntry;
478
+ break;
479
+ }
480
+
481
+ if (!passesFilter) return false;
482
+
483
+ // Apply search filter
484
+ if (searchTokens.length > 0) {
485
+ const nodeText = getSearchableText(entry, label);
486
+ if (!searchTokens.every((t) => nodeText.includes(t))) return false;
487
+ }
488
+
489
+ return true;
490
+ });
491
+
492
+ // Recalculate visual structure based on visible tree
493
+ recalculateVisualStructure(filtered, flatNodes);
494
+
495
+ return filtered;
496
+ }
497
+
498
+ /**
499
+ * Recompute indentation/connectors for the filtered view
500
+ *
501
+ * Filtering can hide intermediate entries; descendants attach to the nearest visible ancestor.
502
+ * Keep indentation semantics aligned with flattenTree() so single-child chains don't drift right.
503
+ */
504
+ function recalculateVisualStructure(filteredNodes, allFlatNodes) {
505
+ if (filteredNodes.length === 0) return;
506
+
507
+ const visibleIds = new Set(filteredNodes.map((n) => n.node.entry.id));
508
+
509
+ // Build entry map for parent lookup (using full tree)
510
+ const entryMap = new Map();
511
+ for (const flatNode of allFlatNodes) {
512
+ entryMap.set(flatNode.node.entry.id, flatNode);
513
+ }
514
+
515
+ // Find nearest visible ancestor for a node
516
+ function findVisibleAncestor(nodeId) {
517
+ let currentId = entryMap.get(nodeId)?.node.entry.parentId;
518
+ while (currentId != null) {
519
+ if (visibleIds.has(currentId)) {
520
+ return currentId;
521
+ }
522
+ currentId = entryMap.get(currentId)?.node.entry.parentId;
523
+ }
524
+ return null;
525
+ }
526
+
527
+ // Build visible tree structure
528
+ const visibleParent = new Map();
529
+ const visibleChildren = new Map();
530
+ visibleChildren.set(null, []); // root-level nodes
531
+
532
+ for (const flatNode of filteredNodes) {
533
+ const nodeId = flatNode.node.entry.id;
534
+ const ancestorId = findVisibleAncestor(nodeId);
535
+ visibleParent.set(nodeId, ancestorId);
536
+
537
+ if (!visibleChildren.has(ancestorId)) {
538
+ visibleChildren.set(ancestorId, []);
539
+ }
540
+ visibleChildren.get(ancestorId).push(nodeId);
541
+ }
542
+
543
+ // Update multipleRoots based on visible roots
544
+ const visibleRootIds = visibleChildren.get(null);
545
+ const multipleRoots = visibleRootIds.length > 1;
546
+
547
+ // Build a map for quick lookup: nodeId → FlatNode
548
+ const filteredNodeMap = new Map();
549
+ for (const flatNode of filteredNodes) {
550
+ filteredNodeMap.set(flatNode.node.entry.id, flatNode);
551
+ }
552
+
553
+ // DFS traversal of visible tree, applying same indentation rules as flattenTree()
554
+ // Stack items: [nodeId, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild]
555
+ const stack = [];
556
+
557
+ // Add visible roots in reverse order (to process in forward order via stack)
558
+ for (let i = visibleRootIds.length - 1; i >= 0; i--) {
559
+ const isLast = i === visibleRootIds.length - 1;
560
+ stack.push([
561
+ visibleRootIds[i],
562
+ multipleRoots ? 1 : 0,
563
+ multipleRoots,
564
+ multipleRoots,
565
+ isLast,
566
+ [],
567
+ multipleRoots
568
+ ]);
569
+ }
570
+
571
+ while (stack.length > 0) {
572
+ const [nodeId, indent, justBranched, showConnector, isLast, gutters, isVirtualRootChild] =
573
+ stack.pop();
574
+
575
+ const flatNode = filteredNodeMap.get(nodeId);
576
+ if (!flatNode) continue;
577
+
578
+ // Update this node's visual properties
579
+ flatNode.indent = indent;
580
+ flatNode.showConnector = showConnector;
581
+ flatNode.isLast = isLast;
582
+ flatNode.gutters = gutters;
583
+ flatNode.isVirtualRootChild = isVirtualRootChild;
584
+ flatNode.multipleRoots = multipleRoots;
585
+
586
+ // Get visible children of this node
587
+ const children = visibleChildren.get(nodeId) || [];
588
+ const multipleChildren = children.length > 1;
589
+
590
+ // Calculate child indent using same rules as flattenTree():
591
+ // - Parent branches (multiple children): children get +1
592
+ // - Just branched and indent > 0: children get +1 for visual grouping
593
+ // - Single-child chain: stay flat
594
+ let childIndent;
595
+ if (multipleChildren) {
596
+ childIndent = indent + 1;
597
+ } else if (justBranched && indent > 0) {
598
+ childIndent = indent + 1;
599
+ } else {
600
+ childIndent = indent;
601
+ }
602
+
603
+ // Build gutters for children (same logic as flattenTree)
604
+ const connectorDisplayed = showConnector && !isVirtualRootChild;
605
+ const currentDisplayIndent = multipleRoots ? Math.max(0, indent - 1) : indent;
606
+ const connectorPosition = Math.max(0, currentDisplayIndent - 1);
607
+ const childGutters = connectorDisplayed
608
+ ? [...gutters, { position: connectorPosition, show: !isLast }]
609
+ : gutters;
610
+
611
+ // Add children in reverse order (to process in forward order via stack)
612
+ for (let i = children.length - 1; i >= 0; i--) {
613
+ const childIsLast = i === children.length - 1;
614
+ stack.push([
615
+ children[i],
616
+ childIndent,
617
+ multipleChildren,
618
+ multipleChildren,
619
+ childIsLast,
620
+ childGutters,
621
+ false
622
+ ]);
623
+ }
624
+ }
625
+ }
626
+
627
+ // ============================================================
628
+ // TREE DISPLAY TEXT (pure data -> string)
629
+ // ============================================================
630
+
631
+ function shortenPath(p) {
632
+ if (typeof p !== 'string') return '';
633
+ if (p.startsWith('/Users/')) {
634
+ const parts = p.split('/');
635
+ if (parts.length > 2) return '~' + p.slice(('/Users/' + parts[2]).length);
636
+ }
637
+ if (p.startsWith('/home/')) {
638
+ const parts = p.split('/');
639
+ if (parts.length > 2) return '~' + p.slice(('/home/' + parts[2]).length);
640
+ }
641
+ return p;
642
+ }
643
+
644
+ function formatToolCall(name, args) {
645
+ switch (name) {
646
+ case 'read': {
647
+ const path = shortenPath(String(args.path || args.file_path || ''));
648
+ const offset = args.offset;
649
+ const limit = args.limit;
650
+ let display = path;
651
+ if (offset !== undefined || limit !== undefined) {
652
+ const start = offset ?? 1;
653
+ const end = limit !== undefined ? start + limit - 1 : '';
654
+ display += `:${start}${end ? `-${end}` : ''}`;
655
+ }
656
+ return `[read: ${display}]`;
657
+ }
658
+ case 'write':
659
+ return `[write: ${shortenPath(String(args.path || args.file_path || ''))}]`;
660
+ case 'edit':
661
+ return `[edit: ${shortenPath(String(args.path || args.file_path || ''))}]`;
662
+ case 'bash': {
663
+ const rawCmd = String(args.command || '');
664
+ const cmd = rawCmd
665
+ .replace(/[\n\t]/g, ' ')
666
+ .trim()
667
+ .slice(0, 50);
668
+ return `[bash: ${cmd}${rawCmd.length > 50 ? '...' : ''}]`;
669
+ }
670
+ case 'grep':
671
+ return `[grep: /${args.pattern || ''}/ in ${shortenPath(String(args.path || '.'))}]`;
672
+ case 'find':
673
+ return `[find: ${args.pattern || ''} in ${shortenPath(String(args.path || '.'))}]`;
674
+ case 'ls':
675
+ return `[ls: ${shortenPath(String(args.path || '.'))}]`;
676
+ default: {
677
+ const argsStr = JSON.stringify(args).slice(0, 40);
678
+ return `[${name}: ${argsStr}${JSON.stringify(args).length > 40 ? '...' : ''}]`;
679
+ }
680
+ }
681
+ }
682
+
683
+ function escapeHtml(text) {
684
+ const div = document.createElement('div');
685
+ div.textContent = text;
686
+ return div.innerHTML;
687
+ }
688
+
689
+ /**
690
+ * Truncate string to maxLen chars, append "..." if truncated.
691
+ */
692
+ function truncate(s, maxLen = 100) {
693
+ if (s.length <= maxLen) return s;
694
+ return s.slice(0, maxLen) + '...';
695
+ }
696
+
697
+ /**
698
+ * Get display text for tree node (returns HTML string).
699
+ */
700
+ function getTreeNodeDisplayHtml(entry, label) {
701
+ const normalize = (s) => s.replace(/[\n\t]/g, ' ').trim();
702
+ const labelHtml = label ? `<span class="tree-label">[${escapeHtml(label)}]</span> ` : '';
703
+
704
+ switch (entry.type) {
705
+ case 'message': {
706
+ const msg = entry.message;
707
+ if (msg.role === 'user') {
708
+ const content = truncate(normalize(extractContent(msg.content)));
709
+ return labelHtml + `<span class="tree-role-user">user:</span> ${escapeHtml(content)}`;
710
+ }
711
+ if (msg.role === 'assistant') {
712
+ const textContent = truncate(normalize(extractContent(msg.content)));
713
+ if (textContent) {
714
+ return (
715
+ labelHtml +
716
+ `<span class="tree-role-assistant">assistant:</span> ${escapeHtml(textContent)}`
717
+ );
718
+ }
719
+ if (msg.stopReason === 'aborted') {
720
+ return (
721
+ labelHtml +
722
+ `<span class="tree-role-assistant">assistant:</span> <span class="tree-muted">(aborted)</span>`
723
+ );
724
+ }
725
+ if (msg.errorMessage) {
726
+ return (
727
+ labelHtml +
728
+ `<span class="tree-role-assistant">assistant:</span> <span class="tree-error">${escapeHtml(truncate(msg.errorMessage))}</span>`
729
+ );
730
+ }
731
+ return (
732
+ labelHtml +
733
+ `<span class="tree-role-assistant">assistant:</span> <span class="tree-muted">(no text)</span>`
734
+ );
735
+ }
736
+ if (msg.role === 'toolResult') {
737
+ const toolCall = msg.toolCallId ? toolCallMap.get(msg.toolCallId) : null;
738
+ if (toolCall) {
739
+ return (
740
+ labelHtml +
741
+ `<span class="tree-role-tool">${escapeHtml(formatToolCall(toolCall.name, toolCall.arguments))}</span>`
742
+ );
743
+ }
744
+ return labelHtml + `<span class="tree-role-tool">[${msg.toolName || 'tool'}]</span>`;
745
+ }
746
+ if (msg.role === 'bashExecution') {
747
+ const cmd = truncate(normalize(msg.command || ''));
748
+ return labelHtml + `<span class="tree-role-tool">[bash]:</span> ${escapeHtml(cmd)}`;
749
+ }
750
+ return labelHtml + `<span class="tree-muted">[${msg.role}]</span>`;
751
+ }
752
+ case 'compaction':
753
+ return (
754
+ labelHtml +
755
+ `<span class="tree-compaction">[compaction: ${Math.round(entry.tokensBefore / 1000)}k tokens]</span>`
756
+ );
757
+ case 'branch_summary': {
758
+ const summary = truncate(normalize(entry.summary || ''));
759
+ return (
760
+ labelHtml +
761
+ `<span class="tree-branch-summary">[branch summary]:</span> ${escapeHtml(summary)}`
762
+ );
763
+ }
764
+ case 'custom_message': {
765
+ const content =
766
+ typeof entry.content === 'string' ? entry.content : extractContent(entry.content);
767
+ return (
768
+ labelHtml +
769
+ `<span class="tree-custom">[${escapeHtml(entry.customType)}]:</span> ${escapeHtml(truncate(normalize(content)))}`
770
+ );
771
+ }
772
+ case 'model_change':
773
+ return labelHtml + `<span class="tree-muted">[model: ${entry.modelId}]</span>`;
774
+ case 'thinking_level_change':
775
+ return labelHtml + `<span class="tree-muted">[thinking: ${entry.thinkingLevel}]</span>`;
776
+ case 'turn_start':
777
+ return labelHtml + `<span class="tree-muted">[turn ${entry.turnIndex + 1}]</span>`;
778
+ case 'turn_end': {
779
+ const dur = typeof entry.durationMs === 'number' ? formatDuration(entry.durationMs) : '';
780
+ return (
781
+ labelHtml +
782
+ `<span class="tree-muted">[turn ${entry.turnIndex + 1} end${dur ? ' · ' + dur : ''}]</span>`
783
+ );
784
+ }
785
+ case 'system_prompt': {
786
+ const preview = truncate(entry.content.replace(/[\n\t]/g, ' ').trim(), 60);
787
+ return labelHtml + `<span class="tree-muted">[system prompt] ${escapeHtml(preview)}</span>`;
788
+ }
789
+ case 'tool_definitions': {
790
+ const names = entry.tools.map((t) => t.name).join(', ');
791
+ const preview = truncate(names, 60);
792
+ return (
793
+ labelHtml +
794
+ `<span class="tree-muted">[tools: ${escapeHtml(preview)}] (${entry.tools.length})</span>`
795
+ );
796
+ }
797
+ default:
798
+ return labelHtml + `<span class="tree-muted">[${entry.type}]</span>`;
799
+ }
800
+ }
801
+
802
+ // ============================================================
803
+ // TREE RENDERING (DOM manipulation)
804
+ // ============================================================
805
+
806
+ let currentLeafId = leafId;
807
+ let currentTargetId = urlTargetId || leafId;
808
+ let treeRendered = false;
809
+
810
+ function renderTree() {
811
+ const tree = buildTree();
812
+ const activePathIds = buildActivePathIds(currentLeafId);
813
+ const flatNodes = flattenTree(tree, activePathIds);
814
+ const filtered = filterNodes(flatNodes, currentLeafId);
815
+ const container = document.getElementById('tree-container');
816
+
817
+ // Full render only on first call or when filter/search changes
818
+ if (!treeRendered) {
819
+ container.innerHTML = '';
820
+
821
+ for (const flatNode of filtered) {
822
+ const entry = flatNode.node.entry;
823
+ const isOnPath = activePathIds.has(entry.id);
824
+ const isTarget = entry.id === currentTargetId;
825
+
826
+ const div = document.createElement('div');
827
+ div.className = 'tree-node';
828
+ if (isOnPath) div.classList.add('in-path');
829
+ if (isTarget) div.classList.add('active');
830
+ div.dataset.id = entry.id;
831
+
832
+ const prefix = buildTreePrefix(flatNode);
833
+ const prefixSpan = document.createElement('span');
834
+ prefixSpan.className = 'tree-prefix';
835
+ prefixSpan.textContent = prefix;
836
+
837
+ const marker = document.createElement('span');
838
+ marker.className = 'tree-marker';
839
+ marker.textContent = isOnPath ? '•' : ' ';
840
+
841
+ const content = document.createElement('span');
842
+ content.className = 'tree-content';
843
+ content.innerHTML = getTreeNodeDisplayHtml(entry, flatNode.node.label);
844
+
845
+ div.appendChild(prefixSpan);
846
+ div.appendChild(marker);
847
+ div.appendChild(content);
848
+ // Navigate to the newest leaf through this node, but scroll to the clicked node
849
+ div.addEventListener('click', () => {
850
+ const leafId = findNewestLeaf(entry.id);
851
+ navigateTo(leafId, 'target', entry.id);
852
+ });
853
+
854
+ container.appendChild(div);
855
+ }
856
+
857
+ treeRendered = true;
858
+ } else {
859
+ // Just update markers and classes
860
+ const nodes = container.querySelectorAll('.tree-node');
861
+ for (const node of nodes) {
862
+ const id = node.dataset.id;
863
+ const isOnPath = activePathIds.has(id);
864
+ const isTarget = id === currentTargetId;
865
+
866
+ node.classList.toggle('in-path', isOnPath);
867
+ node.classList.toggle('active', isTarget);
868
+
869
+ const marker = node.querySelector('.tree-marker');
870
+ if (marker) {
871
+ marker.textContent = isOnPath ? '•' : ' ';
872
+ }
873
+ }
874
+ }
875
+
876
+ document.getElementById('tree-status').textContent =
877
+ `${filtered.length} / ${flatNodes.length} entries`;
878
+
879
+ // Scroll active node into view after layout
880
+ setTimeout(() => {
881
+ const activeNode = container.querySelector('.tree-node.active');
882
+ if (activeNode) {
883
+ activeNode.scrollIntoView({ block: 'nearest' });
884
+ }
885
+ }, 0);
886
+ }
887
+
888
+ function forceTreeRerender() {
889
+ treeRendered = false;
890
+ renderTree();
891
+ }
892
+
893
+ // ============================================================
894
+ // MESSAGE RENDERING
895
+ // ============================================================
896
+
897
+ function formatTokens(count) {
898
+ if (count < 1000) return count.toString();
899
+ if (count < 10000) return (count / 1000).toFixed(1) + 'k';
900
+ if (count < 1000000) return Math.round(count / 1000) + 'k';
901
+ return (count / 1000000).toFixed(1) + 'M';
902
+ }
903
+
904
+ function formatTimestamp(ts) {
905
+ if (!ts) return '';
906
+ const date = new Date(ts);
907
+ return date.toLocaleTimeString(undefined, {
908
+ hour: '2-digit',
909
+ minute: '2-digit',
910
+ second: '2-digit'
911
+ });
912
+ }
913
+
914
+ function formatDuration(ms) {
915
+ if (ms < 1000) return `${ms}ms`;
916
+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
917
+ const mins = Math.floor(ms / 60000);
918
+ const secs = Math.round((ms % 60000) / 1000);
919
+ return `${mins}m ${secs}s`;
920
+ }
921
+
922
+ function replaceTabs(text) {
923
+ return text.replace(/\t/g, ' ');
924
+ }
925
+
926
+ /** Safely coerce value to string for display. Returns null if invalid type. */
927
+ function str(value) {
928
+ if (typeof value === 'string') return value;
929
+ if (value == null) return '';
930
+ return null;
931
+ }
932
+
933
+ function getLanguageFromPath(filePath) {
934
+ const ext = filePath.split('.').pop()?.toLowerCase();
935
+ const extToLang = {
936
+ ts: 'typescript',
937
+ tsx: 'typescript',
938
+ js: 'javascript',
939
+ jsx: 'javascript',
940
+ py: 'python',
941
+ rb: 'ruby',
942
+ rs: 'rust',
943
+ go: 'go',
944
+ java: 'java',
945
+ c: 'c',
946
+ cpp: 'cpp',
947
+ h: 'c',
948
+ hpp: 'cpp',
949
+ cs: 'csharp',
950
+ php: 'php',
951
+ sh: 'bash',
952
+ bash: 'bash',
953
+ zsh: 'bash',
954
+ sql: 'sql',
955
+ html: 'html',
956
+ css: 'css',
957
+ scss: 'scss',
958
+ json: 'json',
959
+ yaml: 'yaml',
960
+ yml: 'yaml',
961
+ xml: 'xml',
962
+ md: 'markdown',
963
+ dockerfile: 'dockerfile'
964
+ };
965
+ return extToLang[ext];
966
+ }
967
+
968
+ function findToolResult(toolCallId) {
969
+ for (const entry of entries) {
970
+ if (entry.type === 'message' && entry.message.role === 'toolResult') {
971
+ if (entry.message.toolCallId === toolCallId) {
972
+ return entry.message;
973
+ }
974
+ }
975
+ }
976
+ return null;
977
+ }
978
+
979
+ function formatExpandableOutput(text, maxLines, lang) {
980
+ text = replaceTabs(text);
981
+ const lines = text.split('\n');
982
+ const displayLines = lines.slice(0, maxLines);
983
+ const remaining = lines.length - maxLines;
984
+
985
+ if (lang) {
986
+ let highlighted;
987
+ try {
988
+ highlighted = hljs.highlight(text, { language: lang }).value;
989
+ } catch {
990
+ highlighted = escapeHtml(text);
991
+ }
992
+
993
+ if (remaining > 0) {
994
+ const previewCode = displayLines.join('\n');
995
+ let previewHighlighted;
996
+ try {
997
+ previewHighlighted = hljs.highlight(previewCode, { language: lang }).value;
998
+ } catch {
999
+ previewHighlighted = escapeHtml(previewCode);
1000
+ }
1001
+
1002
+ return `<div class="tool-output expandable" onclick="this.classList.toggle('expanded')">
1003
+ <div class="output-preview"><pre><code class="hljs">${previewHighlighted}</code></pre>
1004
+ <div class="expand-hint">... (${remaining} more lines)</div></div>
1005
+ <div class="output-full"><pre><code class="hljs">${highlighted}</code></pre></div></div>`;
1006
+ }
1007
+
1008
+ return `<div class="tool-output"><pre><code class="hljs">${highlighted}</code></pre></div>`;
1009
+ }
1010
+
1011
+ // Plain text output
1012
+ if (remaining > 0) {
1013
+ let out =
1014
+ '<div class="tool-output expandable" onclick="this.classList.toggle(\'expanded\')">';
1015
+ out += '<div class="output-preview">';
1016
+ for (const line of displayLines) {
1017
+ out += `<div>${escapeHtml(replaceTabs(line))}</div>`;
1018
+ }
1019
+ out += `<div class="expand-hint">... (${remaining} more lines)</div></div>`;
1020
+ out += '<div class="output-full">';
1021
+ for (const line of lines) {
1022
+ out += `<div>${escapeHtml(replaceTabs(line))}</div>`;
1023
+ }
1024
+ out += '</div></div>';
1025
+ return out;
1026
+ }
1027
+
1028
+ let out = '<div class="tool-output">';
1029
+ for (const line of displayLines) {
1030
+ out += `<div>${escapeHtml(replaceTabs(line))}</div>`;
1031
+ }
1032
+ out += '</div>';
1033
+ return out;
1034
+ }
1035
+
1036
+ function renderToolCall(call) {
1037
+ const result = findToolResult(call.id);
1038
+ const isError = result?.isError || false;
1039
+ const statusClass = result ? (isError ? 'error' : 'success') : 'pending';
1040
+
1041
+ const getResultText = () => {
1042
+ if (!result) return '';
1043
+ const textBlocks = result.content.filter((c) => c.type === 'text');
1044
+ return textBlocks.map((c) => c.text).join('\n');
1045
+ };
1046
+
1047
+ const getResultImages = () => {
1048
+ if (!result) return [];
1049
+ return result.content.filter((c) => c.type === 'image');
1050
+ };
1051
+
1052
+ const renderResultImages = () => {
1053
+ const images = getResultImages();
1054
+ if (images.length === 0) return '';
1055
+ return (
1056
+ '<div class="tool-images">' +
1057
+ images
1058
+ .map((img) => `<img src="data:${img.mimeType};base64,${img.data}" class="tool-image" />`)
1059
+ .join('') +
1060
+ '</div>'
1061
+ );
1062
+ };
1063
+
1064
+ let html = `<div class="tool-execution ${statusClass}">`;
1065
+ const args = call.arguments || {};
1066
+ const name = call.name;
1067
+
1068
+ const invalidArg = '<span class="tool-error">[invalid arg]</span>';
1069
+
1070
+ switch (name) {
1071
+ case 'bash': {
1072
+ const command = str(args.command);
1073
+ const cmdDisplay = command === null ? invalidArg : escapeHtml(command || '...');
1074
+ html += `<div class="tool-command">$ ${cmdDisplay}</div>`;
1075
+ if (result) {
1076
+ const output = getResultText().trim();
1077
+ if (output) html += formatExpandableOutput(output, 5);
1078
+ }
1079
+ break;
1080
+ }
1081
+ case 'read': {
1082
+ const filePath = str(args.file_path ?? args.path);
1083
+ const offset = args.offset;
1084
+ const limit = args.limit;
1085
+
1086
+ let pathHtml = filePath === null ? invalidArg : escapeHtml(shortenPath(filePath || ''));
1087
+ if (filePath !== null && (offset !== undefined || limit !== undefined)) {
1088
+ const startLine = offset ?? 1;
1089
+ const endLine = limit !== undefined ? startLine + limit - 1 : '';
1090
+ pathHtml += `<span class="line-numbers">:${startLine}${endLine ? '-' + endLine : ''}</span>`;
1091
+ }
1092
+
1093
+ html += `<div class="tool-header"><span class="tool-name">read</span> <span class="tool-path">${pathHtml}</span></div>`;
1094
+ if (result) {
1095
+ html += renderResultImages();
1096
+ const output = getResultText();
1097
+ const lang = filePath ? getLanguageFromPath(filePath) : null;
1098
+ if (output) html += formatExpandableOutput(output, 10, lang);
1099
+ }
1100
+ break;
1101
+ }
1102
+ case 'write': {
1103
+ const filePath = str(args.file_path ?? args.path);
1104
+ const content = str(args.content);
1105
+
1106
+ html += `<div class="tool-header"><span class="tool-name">write</span> <span class="tool-path">${filePath === null ? invalidArg : escapeHtml(shortenPath(filePath || ''))}</span>`;
1107
+ if (content !== null && content) {
1108
+ const lines = content.split('\n');
1109
+ if (lines.length > 10) html += ` <span class="line-count">(${lines.length} lines)</span>`;
1110
+ }
1111
+ html += '</div>';
1112
+
1113
+ if (content === null) {
1114
+ html += `<div class="tool-error">[invalid content arg - expected string]</div>`;
1115
+ } else if (content) {
1116
+ const lang = filePath ? getLanguageFromPath(filePath) : null;
1117
+ html += formatExpandableOutput(content, 10, lang);
1118
+ }
1119
+ if (result) {
1120
+ const output = getResultText().trim();
1121
+ if (output) html += `<div class="tool-output"><div>${escapeHtml(output)}</div></div>`;
1122
+ }
1123
+ break;
1124
+ }
1125
+ case 'edit': {
1126
+ const filePath = str(args.file_path ?? args.path);
1127
+ html += `<div class="tool-header"><span class="tool-name">edit</span> <span class="tool-path">${filePath === null ? invalidArg : escapeHtml(shortenPath(filePath || ''))}</span></div>`;
1128
+
1129
+ if (result?.details?.diff) {
1130
+ const diffLines = result.details.diff.split('\n');
1131
+ html += '<div class="tool-diff">';
1132
+ for (const line of diffLines) {
1133
+ const cls = line.match(/^\+/)
1134
+ ? 'diff-added'
1135
+ : line.match(/^-/)
1136
+ ? 'diff-removed'
1137
+ : 'diff-context';
1138
+ html += `<div class="${cls}">${escapeHtml(replaceTabs(line))}</div>`;
1139
+ }
1140
+ html += '</div>';
1141
+ } else if (result) {
1142
+ const output = getResultText().trim();
1143
+ if (output) html += `<div class="tool-output"><pre>${escapeHtml(output)}</pre></div>`;
1144
+ }
1145
+ break;
1146
+ }
1147
+ default: {
1148
+ // Check for pre-rendered custom tool HTML
1149
+ const rendered = renderedTools?.[call.id];
1150
+ if (rendered?.callHtml || rendered?.resultHtml) {
1151
+ // Custom tool with pre-rendered HTML from TUI renderer
1152
+ if (rendered.callHtml) {
1153
+ html += `<div class="tool-header ansi-rendered">${rendered.callHtml}</div>`;
1154
+ } else {
1155
+ html += `<div class="tool-header"><span class="tool-name">${escapeHtml(name)}</span></div>`;
1156
+ }
1157
+
1158
+ if (rendered.resultHtml) {
1159
+ // Apply same truncation as built-in tools (10 lines)
1160
+ const lines = rendered.resultHtml.split('\n');
1161
+ if (lines.length > 10) {
1162
+ const preview = lines.slice(0, 10).join('\n');
1163
+ html += `<div class="tool-output expandable ansi-rendered" onclick="this.classList.toggle('expanded')">
1164
+ <div class="output-preview">${preview}<div class="expand-hint">... (${lines.length - 10} more lines)</div></div>
1165
+ <div class="output-full">${rendered.resultHtml}</div>
1166
+ </div>`;
1167
+ } else {
1168
+ html += `<div class="tool-output ansi-rendered">${rendered.resultHtml}</div>`;
1169
+ }
1170
+ } else if (result) {
1171
+ // Fallback to JSON for result if no pre-rendered HTML
1172
+ const output = getResultText();
1173
+ if (output) html += formatExpandableOutput(output, 10);
1174
+ }
1175
+ } else {
1176
+ // Fallback to JSON display (existing behavior)
1177
+ html += `<div class="tool-header"><span class="tool-name">${escapeHtml(name)}</span></div>`;
1178
+ html += `<div class="tool-output"><pre>${escapeHtml(JSON.stringify(args, null, 2))}</pre></div>`;
1179
+ if (result) {
1180
+ const output = getResultText();
1181
+ if (output) html += formatExpandableOutput(output, 10);
1182
+ }
1183
+ }
1184
+ }
1185
+ }
1186
+
1187
+ html += '</div>';
1188
+ return html;
1189
+ }
1190
+
1191
+ /**
1192
+ * Download the session data as a JSONL file.
1193
+ * Reconstructs the original format: header line + entry lines.
1194
+ */
1195
+ window.downloadSessionJson = function () {
1196
+ // Build JSONL content: header first, then all entries
1197
+ const lines = [];
1198
+ if (header) {
1199
+ lines.push(JSON.stringify({ type: 'header', ...header }));
1200
+ }
1201
+ for (const entry of entries) {
1202
+ lines.push(JSON.stringify(entry));
1203
+ }
1204
+ const jsonlContent = lines.join('\n');
1205
+
1206
+ // Create download
1207
+ const blob = new Blob([jsonlContent], { type: 'application/x-ndjson' });
1208
+ const url = URL.createObjectURL(blob);
1209
+ const a = document.createElement('a');
1210
+ a.href = url;
1211
+ a.download = `${header?.id || 'session'}.jsonl`;
1212
+ document.body.appendChild(a);
1213
+ a.click();
1214
+ document.body.removeChild(a);
1215
+ URL.revokeObjectURL(url);
1216
+ };
1217
+
1218
+ // ============================================================
1219
+ // LLM VIEW — shows the exact Message[] the LLM receives
1220
+ // Pre-computed at export time via buildSessionContext + convertToLlm.
1221
+ // ============================================================
1222
+
1223
+ // llmMessages is pre-computed at export time and embedded in session data.
1224
+ // Each message has: role, content, _source (original AgentMessage role), plus original fields.
1225
+ const llmMessages = data.llmMessages || null;
1226
+
1227
+ function renderLlmMessages(messages) {
1228
+ let html =
1229
+ '<div style="margin-bottom: var(--line-height); color: var(--muted); font-size: 11px;">' +
1230
+ messages.length +
1231
+ ' messages in LLM context (this is what the model receives each turn)</div>';
1232
+
1233
+ for (let i = 0; i < messages.length; i++) {
1234
+ const msg = messages[i];
1235
+ const role = msg.role;
1236
+ const errorClass = role === 'toolResult' && msg.isError ? ' llm-error' : '';
1237
+ const sourceLabel =
1238
+ msg._source && msg._source !== role ? ' (from ' + escapeHtml(msg._source) + ')' : '';
1239
+
1240
+ let headerExtra = '';
1241
+ if (role === 'toolResult') {
1242
+ const toolName = msg.toolName || toolCallMap.get(msg.toolCallId)?.name || '?';
1243
+ headerExtra = ' — ' + escapeHtml(toolName) + (msg.isError ? ' [ERROR]' : '');
1244
+ }
1245
+ if (role === 'assistant' && msg.model) {
1246
+ headerExtra = ' — ' + escapeHtml(msg.provider ? msg.provider + '/' + msg.model : msg.model);
1247
+ }
1248
+
1249
+ html += '<div class="llm-msg llm-role-' + role + errorClass + '">';
1250
+ html +=
1251
+ '<div class="llm-msg-header"><span class="llm-msg-index">#' +
1252
+ i +
1253
+ '</span>' +
1254
+ escapeHtml(role) +
1255
+ headerExtra +
1256
+ sourceLabel +
1257
+ '</div>';
1258
+ html +=
1259
+ '<div class="llm-msg-body' +
1260
+ (needsExpand(msg) ? ' expandable' : '') +
1261
+ '" onclick="this.classList.toggle(\'expanded\')">';
1262
+ html += renderLlmContent(msg);
1263
+ html += '</div></div>';
1264
+ }
1265
+
1266
+ return html;
1267
+ }
1268
+
1269
+ function needsExpand(msg) {
1270
+ const text = extractLlmText(msg);
1271
+ return text.length > 800;
1272
+ }
1273
+
1274
+ function extractLlmText(msg) {
1275
+ if (typeof msg.content === 'string') return msg.content;
1276
+ if (Array.isArray(msg.content)) {
1277
+ return msg.content
1278
+ .map((c) => {
1279
+ if (c.type === 'text') return c.text || '';
1280
+ if (c.type === 'toolCall') return '[tool_use: ' + c.name + ']';
1281
+ if (c.type === 'thinking') return '[thinking]';
1282
+ if (c.type === 'image') return '[image]';
1283
+ return '[' + c.type + ']';
1284
+ })
1285
+ .join('');
1286
+ }
1287
+ return '';
1288
+ }
1289
+
1290
+ function renderLlmContent(msg) {
1291
+ const content = msg.content;
1292
+ if (typeof content === 'string') return escapeHtml(content);
1293
+ if (!Array.isArray(content)) return escapeHtml(JSON.stringify(content, null, 2));
1294
+
1295
+ let html = '';
1296
+ for (const block of content) {
1297
+ if (block.type === 'text' && block.text) {
1298
+ html += '<div class="llm-content-block">' + escapeHtml(block.text) + '</div>';
1299
+ } else if (block.type === 'thinking' && block.thinking) {
1300
+ html +=
1301
+ '<div class="llm-content-block"><div class="llm-block-label">thinking</div>' +
1302
+ escapeHtml(block.thinking) +
1303
+ '</div>';
1304
+ } else if (block.type === 'toolCall') {
1305
+ html +=
1306
+ '<div class="llm-tool-call"><div class="llm-block-label">tool_use</div>' +
1307
+ '<div><span class="llm-tool-name">' +
1308
+ escapeHtml(block.name) +
1309
+ '</span>' +
1310
+ '(<span class="llm-tool-id">' +
1311
+ escapeHtml(block.id) +
1312
+ '</span>)</div>' +
1313
+ '<pre style="margin:2px 0;font-size:10px;overflow-x:auto">' +
1314
+ escapeHtml(JSON.stringify(block.arguments, null, 2)) +
1315
+ '</pre></div>';
1316
+ } else if (block.type === 'image') {
1317
+ html +=
1318
+ '<div class="llm-content-block"><div class="llm-block-label">image</div>[base64 image]</div>';
1319
+ } else {
1320
+ html +=
1321
+ '<div class="llm-content-block">' + escapeHtml(JSON.stringify(block, null, 2)) + '</div>';
1322
+ }
1323
+ }
1324
+ return html;
1325
+ }
1326
+
1327
+ /**
1328
+ * Build a shareable URL for a specific message.
1329
+ * URL format: base?gistId&leafId=<leafId>&targetId=<entryId>
1330
+ */
1331
+ function buildShareUrl(entryId) {
1332
+ // Check for injected base URL (used when loaded in iframe via srcdoc)
1333
+ const baseUrlMeta = document.querySelector('meta[name="pi-share-base-url"]');
1334
+ const baseUrl = baseUrlMeta ? baseUrlMeta.content : window.location.href.split('?')[0];
1335
+
1336
+ const url = new URL(window.location.href);
1337
+ // Find the gist ID (first query param without value, e.g., ?abc123)
1338
+ const gistId = Array.from(url.searchParams.keys()).find((k) => !url.searchParams.get(k));
1339
+
1340
+ // Build the share URL
1341
+ const params = new URLSearchParams();
1342
+ params.set('leafId', currentLeafId);
1343
+ params.set('targetId', entryId);
1344
+
1345
+ // If we have an injected base URL (iframe context), use it directly
1346
+ if (baseUrlMeta) {
1347
+ return `${baseUrl}&${params.toString()}`;
1348
+ }
1349
+
1350
+ // Otherwise build from current location (direct file access)
1351
+ url.search = gistId ? `?${gistId}&${params.toString()}` : `?${params.toString()}`;
1352
+ return url.toString();
1353
+ }
1354
+
1355
+ /**
1356
+ * Copy text to clipboard with visual feedback.
1357
+ * Uses navigator.clipboard with fallback to execCommand for HTTP contexts.
1358
+ */
1359
+ async function copyToClipboard(text, button) {
1360
+ let success = false;
1361
+ try {
1362
+ if (navigator.clipboard && navigator.clipboard.writeText) {
1363
+ await navigator.clipboard.writeText(text);
1364
+ success = true;
1365
+ }
1366
+ } catch (err) {
1367
+ // Clipboard API failed, try fallback
1368
+ }
1369
+
1370
+ // Fallback for HTTP or when Clipboard API is unavailable
1371
+ if (!success) {
1372
+ try {
1373
+ const textarea = document.createElement('textarea');
1374
+ textarea.value = text;
1375
+ textarea.style.position = 'fixed';
1376
+ textarea.style.opacity = '0';
1377
+ document.body.appendChild(textarea);
1378
+ textarea.select();
1379
+ success = document.execCommand('copy');
1380
+ document.body.removeChild(textarea);
1381
+ } catch (err) {
1382
+ console.error('Failed to copy:', err);
1383
+ }
1384
+ }
1385
+
1386
+ if (success && button) {
1387
+ const originalHtml = button.innerHTML;
1388
+ button.innerHTML = '✓';
1389
+ button.classList.add('copied');
1390
+ setTimeout(() => {
1391
+ button.innerHTML = originalHtml;
1392
+ button.classList.remove('copied');
1393
+ }, 1500);
1394
+ }
1395
+ }
1396
+
1397
+ /**
1398
+ * Render the copy-link button HTML for a message.
1399
+ */
1400
+ function renderCopyLinkButton(entryId) {
1401
+ return `<button class="copy-link-btn" data-entry-id="${entryId}" title="Copy link to this message">
1402
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1403
+ <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>
1404
+ <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
1405
+ </svg>
1406
+ </button>`;
1407
+ }
1408
+
1409
+ function renderTurnLabel(entryId) {
1410
+ const info = turnInfoByMessageId.get(entryId);
1411
+ if (!info) return '';
1412
+ const dur = typeof info.durationMs === 'number' ? formatDuration(info.durationMs) : '';
1413
+ return `<div class="turn-label-inline"><span class="turn-label-text">T${info.turnIndex + 1}</span>${dur ? `<span class="turn-label-dur">${dur}</span>` : ''}</div>`;
1414
+ }
1415
+
1416
+ function renderEntry(entry) {
1417
+ const ts = formatTimestamp(entry.timestamp);
1418
+ const tsHtml = ts ? `<div class="message-timestamp">${ts}</div>` : '';
1419
+ const entryId = `entry-${entry.id}`;
1420
+ const copyBtnHtml = renderCopyLinkButton(entry.id);
1421
+ const turnLabel = renderTurnLabel(entry.id);
1422
+
1423
+ if (entry.type === 'message') {
1424
+ const msg = entry.message;
1425
+
1426
+ if (msg.role === 'user') {
1427
+ let html = `<div class="user-message${turnLabel ? ' has-turn-label' : ''}" id="${entryId}">${turnLabel}${copyBtnHtml}${tsHtml}`;
1428
+ const content = msg.content;
1429
+
1430
+ if (Array.isArray(content)) {
1431
+ const images = content.filter((c) => c.type === 'image');
1432
+ if (images.length > 0) {
1433
+ html += '<div class="message-images">';
1434
+ for (const img of images) {
1435
+ html += `<img src="data:${img.mimeType};base64,${img.data}" class="message-image" />`;
1436
+ }
1437
+ html += '</div>';
1438
+ }
1439
+ }
1440
+
1441
+ const text =
1442
+ typeof content === 'string'
1443
+ ? content
1444
+ : content
1445
+ .filter((c) => c.type === 'text')
1446
+ .map((c) => c.text)
1447
+ .join('\n');
1448
+ if (text.trim()) {
1449
+ html += `<div class="markdown-content">${safeMarkedParse(text)}</div>`;
1450
+ }
1451
+ html += '</div>';
1452
+ return html;
1453
+ }
1454
+
1455
+ if (msg.role === 'assistant') {
1456
+ let html = `<div class="assistant-message${turnLabel ? ' has-turn-label' : ''}" id="${entryId}">${turnLabel}${copyBtnHtml}${tsHtml}`;
1457
+
1458
+ for (const block of msg.content) {
1459
+ if (block.type === 'text' && block.text.trim()) {
1460
+ html += `<div class="assistant-text markdown-content">${safeMarkedParse(block.text)}</div>`;
1461
+ } else if (block.type === 'thinking' && block.thinking.trim()) {
1462
+ html += `<div class="thinking-block">
1463
+ <div class="thinking-text">${escapeHtml(block.thinking)}</div>
1464
+ <div class="thinking-collapsed">Thinking ...</div>
1465
+ </div>`;
1466
+ }
1467
+ }
1468
+
1469
+ const toolCalls = msg.content.filter((b) => b.type === 'toolCall');
1470
+ if (toolCalls.length > 1) {
1471
+ html += `<div class="parallel-tools"><div class="parallel-label">⋮ ${toolCalls.length} parallel</div>`;
1472
+ for (const block of toolCalls) {
1473
+ html += renderToolCall(block);
1474
+ }
1475
+ html += '</div>';
1476
+ } else {
1477
+ for (const block of toolCalls) {
1478
+ html += renderToolCall(block);
1479
+ }
1480
+ }
1481
+
1482
+ if (msg.stopReason === 'aborted') {
1483
+ html += '<div class="error-text">Aborted</div>';
1484
+ } else if (msg.stopReason === 'error') {
1485
+ html += `<div class="error-text">Error: ${escapeHtml(msg.errorMessage || 'Unknown error')}</div>`;
1486
+ }
1487
+
1488
+ html += '</div>';
1489
+ return html;
1490
+ }
1491
+
1492
+ if (msg.role === 'bashExecution') {
1493
+ const isError = msg.cancelled || (msg.exitCode !== 0 && msg.exitCode !== null);
1494
+ let html = `<div class="tool-execution ${isError ? 'error' : 'success'}" id="${entryId}">${tsHtml}`;
1495
+ html += `<div class="tool-command">$ ${escapeHtml(msg.command)}</div>`;
1496
+ if (msg.output) html += formatExpandableOutput(msg.output, 10);
1497
+ if (msg.cancelled) {
1498
+ html += '<div style="color: var(--warning)">(cancelled)</div>';
1499
+ } else if (msg.exitCode !== 0 && msg.exitCode !== null) {
1500
+ html += `<div style="color: var(--error)">(exit ${msg.exitCode})</div>`;
1501
+ }
1502
+ html += '</div>';
1503
+ return html;
1504
+ }
1505
+
1506
+ if (msg.role === 'toolResult') return '';
1507
+ }
1508
+
1509
+ if (entry.type === 'model_change') {
1510
+ return `<div class="model-change" id="${entryId}">${tsHtml}Switched to model: <span class="model-name">${escapeHtml(entry.provider)}/${escapeHtml(entry.modelId)}</span></div>`;
1511
+ }
1512
+
1513
+ if (entry.type === 'turn_start') {
1514
+ // Turn info is shown inline on the first message — skip separate rendering
1515
+ return '';
1516
+ }
1517
+
1518
+ if (entry.type === 'turn_end') {
1519
+ // Duration is shown on turn_start — skip rendering turn_end
1520
+ return '';
1521
+ }
1522
+
1523
+ if (entry.type === 'system_prompt') {
1524
+ // System prompt is already shown in the header — skip inline rendering
1525
+ return '';
1526
+ }
1527
+
1528
+ if (entry.type === 'tool_definitions') {
1529
+ // Tool definitions are metadata — skip inline rendering (visible in tree view)
1530
+ return '';
1531
+ }
1532
+
1533
+ if (entry.type === 'compaction') {
1534
+ return `<div class="compaction" id="${entryId}" onclick="this.classList.toggle('expanded')">
1535
+ <div class="compaction-label">[compaction]</div>
1536
+ <div class="compaction-collapsed">Compacted from ${entry.tokensBefore.toLocaleString()} tokens</div>
1537
+ <div class="compaction-content"><strong>Compacted from ${entry.tokensBefore.toLocaleString()} tokens</strong>\n\n${escapeHtml(entry.summary)}</div>
1538
+ </div>`;
1539
+ }
1540
+
1541
+ if (entry.type === 'branch_summary') {
1542
+ return `<div class="branch-summary" id="${entryId}">${tsHtml}
1543
+ <div class="branch-summary-header">Branch Summary</div>
1544
+ <div class="markdown-content">${safeMarkedParse(entry.summary)}</div>
1545
+ </div>`;
1546
+ }
1547
+
1548
+ if (entry.type === 'custom_message' && entry.display) {
1549
+ return `<div class="hook-message" id="${entryId}">${tsHtml}
1550
+ <div class="hook-type">[${escapeHtml(entry.customType)}]</div>
1551
+ <div class="markdown-content">${safeMarkedParse(typeof entry.content === 'string' ? entry.content : JSON.stringify(entry.content))}</div>
1552
+ </div>`;
1553
+ }
1554
+
1555
+ return '';
1556
+ }
1557
+
1558
+ // ============================================================
1559
+ // HEADER / STATS
1560
+ // ============================================================
1561
+
1562
+ function computeStats(entryList) {
1563
+ let userMessages = 0,
1564
+ assistantMessages = 0,
1565
+ toolResults = 0;
1566
+ let customMessages = 0,
1567
+ compactions = 0,
1568
+ branchSummaries = 0,
1569
+ toolCalls = 0;
1570
+ let turnCount = 0,
1571
+ totalDurationMs = 0,
1572
+ totalLlmDurationMs = 0,
1573
+ totalToolDurationMs = 0;
1574
+ const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
1575
+ const cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
1576
+ const models = new Set();
1577
+
1578
+ for (const entry of entryList) {
1579
+ if (entry.type === 'turn_end') {
1580
+ turnCount++;
1581
+ if (typeof entry.durationMs === 'number') totalDurationMs += entry.durationMs;
1582
+ }
1583
+
1584
+ if (entry.type === 'message') {
1585
+ const msg = entry.message;
1586
+ if (msg.role === 'user') userMessages++;
1587
+ if (msg.role === 'assistant') {
1588
+ assistantMessages++;
1589
+ if (msg.model) models.add(msg.provider ? `${msg.provider}/${msg.model}` : msg.model);
1590
+ if (msg.usage) {
1591
+ tokens.input += msg.usage.input || 0;
1592
+ tokens.output += msg.usage.output || 0;
1593
+ tokens.cacheRead += msg.usage.cacheRead || 0;
1594
+ tokens.cacheWrite += msg.usage.cacheWrite || 0;
1595
+ if (msg.usage.cost) {
1596
+ cost.input += msg.usage.cost.input || 0;
1597
+ cost.output += msg.usage.cost.output || 0;
1598
+ cost.cacheRead += msg.usage.cost.cacheRead || 0;
1599
+ cost.cacheWrite += msg.usage.cost.cacheWrite || 0;
1600
+ }
1601
+ }
1602
+ toolCalls += msg.content.filter((c) => c.type === 'toolCall').length;
1603
+ if (typeof entry.durationMs === 'number') totalLlmDurationMs += entry.durationMs;
1604
+ }
1605
+ if (msg.role === 'toolResult') {
1606
+ toolResults++;
1607
+ if (typeof entry.durationMs === 'number') totalToolDurationMs += entry.durationMs;
1608
+ }
1609
+ } else if (entry.type === 'compaction') {
1610
+ compactions++;
1611
+ } else if (entry.type === 'branch_summary') {
1612
+ branchSummaries++;
1613
+ } else if (entry.type === 'custom_message') {
1614
+ customMessages++;
1615
+ }
1616
+ }
1617
+
1618
+ return {
1619
+ userMessages,
1620
+ assistantMessages,
1621
+ toolResults,
1622
+ customMessages,
1623
+ compactions,
1624
+ branchSummaries,
1625
+ toolCalls,
1626
+ turnCount,
1627
+ totalDurationMs,
1628
+ totalLlmDurationMs,
1629
+ totalToolDurationMs,
1630
+ tokens,
1631
+ cost,
1632
+ models: Array.from(models)
1633
+ };
1634
+ }
1635
+
1636
+ const globalStats = computeStats(entries);
1637
+
1638
+ function renderHeader() {
1639
+ const totalCost =
1640
+ globalStats.cost.input +
1641
+ globalStats.cost.output +
1642
+ globalStats.cost.cacheRead +
1643
+ globalStats.cost.cacheWrite;
1644
+
1645
+ const tokenParts = [];
1646
+ if (globalStats.tokens.input) tokenParts.push(`↑${formatTokens(globalStats.tokens.input)}`);
1647
+ if (globalStats.tokens.output) tokenParts.push(`↓${formatTokens(globalStats.tokens.output)}`);
1648
+ if (globalStats.tokens.cacheRead)
1649
+ tokenParts.push(`R${formatTokens(globalStats.tokens.cacheRead)}`);
1650
+ if (globalStats.tokens.cacheWrite)
1651
+ tokenParts.push(`W${formatTokens(globalStats.tokens.cacheWrite)}`);
1652
+
1653
+ const msgParts = [];
1654
+ if (globalStats.userMessages) msgParts.push(`${globalStats.userMessages} user`);
1655
+ if (globalStats.assistantMessages) msgParts.push(`${globalStats.assistantMessages} assistant`);
1656
+ if (globalStats.toolResults) msgParts.push(`${globalStats.toolResults} tool results`);
1657
+ if (globalStats.customMessages) msgParts.push(`${globalStats.customMessages} custom`);
1658
+ if (globalStats.compactions) msgParts.push(`${globalStats.compactions} compactions`);
1659
+ if (globalStats.branchSummaries)
1660
+ msgParts.push(`${globalStats.branchSummaries} branch summaries`);
1661
+
1662
+ let html = `
1663
+ <div class="header">
1664
+ <h1>Session: ${escapeHtml(header?.id || 'unknown')}</h1>
1665
+ <div class="help-bar">
1666
+ <span>Ctrl+T toggle thinking · Ctrl+O toggle tools</span>
1667
+ <button class="download-json-btn" onclick="downloadSessionJson()" title="Download session as JSONL">↓ JSONL</button>
1668
+ </div>
1669
+ <div class="header-info">
1670
+ <div class="info-item"><span class="info-label">Date:</span><span class="info-value">${header?.timestamp ? new Date(header.timestamp).toLocaleString() : 'unknown'}</span></div>
1671
+ <div class="info-item"><span class="info-label">Models:</span><span class="info-value">${globalStats.models.join(', ') || 'unknown'}</span></div>
1672
+ <div class="info-item"><span class="info-label">Messages:</span><span class="info-value">${msgParts.join(', ') || '0'}</span></div>
1673
+ <div class="info-item"><span class="info-label">Tool Calls:</span><span class="info-value">${globalStats.toolCalls}</span></div>
1674
+ <div class="info-item"><span class="info-label">Turns:</span><span class="info-value">${globalStats.turnCount || '—'}</span></div>
1675
+ <div class="info-item"><span class="info-label">Duration:</span><span class="info-value">${globalStats.totalDurationMs ? formatDuration(globalStats.totalDurationMs) : '—'}${globalStats.totalLlmDurationMs ? ' (LLM ' + formatDuration(globalStats.totalLlmDurationMs) + ', Tools ' + formatDuration(globalStats.totalToolDurationMs) + ')' : ''}</span></div>
1676
+ <div class="info-item"><span class="info-label">Tokens:</span><span class="info-value">${tokenParts.join(' ') || '0'}</span></div>
1677
+ <div class="info-item"><span class="info-label">Cost:</span><span class="info-value">$${totalCost.toFixed(3)}</span></div>
1678
+ </div>
1679
+ </div>`;
1680
+
1681
+ // Resolve system prompt from JSONL system_prompt entry
1682
+ const effectiveSystemPrompt = (() => {
1683
+ for (let i = entries.length - 1; i >= 0; i--) {
1684
+ if (entries[i].type === 'system_prompt') return entries[i].content;
1685
+ }
1686
+ return null;
1687
+ })();
1688
+ if (effectiveSystemPrompt) {
1689
+ const lines = effectiveSystemPrompt.split('\n');
1690
+ const previewLines = 10;
1691
+ if (lines.length > previewLines) {
1692
+ const preview = lines.slice(0, previewLines).join('\n');
1693
+ const remaining = lines.length - previewLines;
1694
+ html += `<div class="system-prompt expandable" onclick="this.classList.toggle('expanded')">
1695
+ <div class="system-prompt-header">System Prompt</div>
1696
+ <div class="system-prompt-preview">${escapeHtml(preview)}</div>
1697
+ <div class="system-prompt-expand-hint">... (${remaining} more lines, click to expand)</div>
1698
+ <div class="system-prompt-full">${escapeHtml(effectiveSystemPrompt)}</div>
1699
+ </div>`;
1700
+ } else {
1701
+ html += `<div class="system-prompt">
1702
+ <div class="system-prompt-header">System Prompt</div>
1703
+ <div class="system-prompt-full" style="display: block">${escapeHtml(effectiveSystemPrompt)}</div>
1704
+ </div>`;
1705
+ }
1706
+ }
1707
+
1708
+ // Resolve tools from JSONL tool_definitions entry
1709
+ const effectiveTools = (() => {
1710
+ for (let i = entries.length - 1; i >= 0; i--) {
1711
+ if (entries[i].type === 'tool_definitions') return entries[i].tools;
1712
+ }
1713
+ return null;
1714
+ })();
1715
+
1716
+ if (effectiveTools && effectiveTools.length > 0) {
1717
+ html += `<div class="tools-list">
1718
+ <div class="tools-header">Available Tools</div>
1719
+ <div class="tools-content">
1720
+ ${effectiveTools
1721
+ .map((t) => {
1722
+ const hasParams =
1723
+ t.parameters &&
1724
+ typeof t.parameters === 'object' &&
1725
+ t.parameters.properties &&
1726
+ Object.keys(t.parameters.properties).length > 0;
1727
+ if (!hasParams) {
1728
+ return `<div class="tool-item"><span class="tool-item-name">${escapeHtml(t.name)}</span> - <span class="tool-item-desc">${escapeHtml(t.description)}</span></div>`;
1729
+ }
1730
+ const params = t.parameters;
1731
+ const properties = params.properties;
1732
+ const required = params.required || [];
1733
+ let paramsHtml = '';
1734
+ for (const [name, prop] of Object.entries(properties)) {
1735
+ const isRequired = required.includes(name);
1736
+ const typeStr = prop.type || 'any';
1737
+ const reqLabel = isRequired
1738
+ ? '<span class="tool-param-required">required</span>'
1739
+ : '<span class="tool-param-optional">optional</span>';
1740
+ paramsHtml += `<div class="tool-param"><span class="tool-param-name">${escapeHtml(name)}</span> <span class="tool-param-type">${escapeHtml(typeStr)}</span> ${reqLabel}`;
1741
+ if (prop.description) {
1742
+ paramsHtml += `<div class="tool-param-desc">${escapeHtml(prop.description)}</div>`;
1743
+ }
1744
+ paramsHtml += `</div>`;
1745
+ }
1746
+ return `<div class="tool-item" onclick="this.classList.toggle('params-expanded')"><span class="tool-item-name">${escapeHtml(t.name)}</span> - <span class="tool-item-desc">${escapeHtml(t.description)}</span> <span class="tool-params-hint"></span><div class="tool-params-content">${paramsHtml}</div></div>`;
1747
+ })
1748
+ .join('')}
1749
+ </div>
1750
+ </div>`;
1751
+ }
1752
+
1753
+ return html;
1754
+ }
1755
+
1756
+ // ============================================================
1757
+ // NAVIGATION
1758
+ // ============================================================
1759
+
1760
+ // Cache for rendered entry DOM nodes
1761
+ const entryCache = new Map();
1762
+
1763
+ function renderEntryToNode(entry) {
1764
+ // Check cache first
1765
+ if (entryCache.has(entry.id)) {
1766
+ return entryCache.get(entry.id).cloneNode(true);
1767
+ }
1768
+
1769
+ // Render to HTML string, then parse to node
1770
+ const html = renderEntry(entry);
1771
+ if (!html) return null;
1772
+
1773
+ const template = document.createElement('template');
1774
+ template.innerHTML = html;
1775
+ const node = template.content.firstElementChild;
1776
+
1777
+ // Cache the node
1778
+ if (node) {
1779
+ entryCache.set(entry.id, node.cloneNode(true));
1780
+ }
1781
+ return node;
1782
+ }
1783
+
1784
+ function navigateTo(targetId, scrollMode = 'target', scrollToEntryId = null) {
1785
+ currentLeafId = targetId;
1786
+ currentTargetId = scrollToEntryId || targetId;
1787
+ const path = getPath(targetId);
1788
+
1789
+ renderTree();
1790
+
1791
+ document.getElementById('header-container').innerHTML = renderHeader();
1792
+
1793
+ // Build messages — either normal entry view or LLM view
1794
+ const messagesEl = document.getElementById('messages');
1795
+
1796
+ if (filterMode === 'llm' && llmMessages) {
1797
+ messagesEl.innerHTML = renderLlmMessages(llmMessages);
1798
+ } else {
1799
+ const fragment = document.createDocumentFragment();
1800
+
1801
+ for (const entry of path) {
1802
+ const node = renderEntryToNode(entry);
1803
+ if (node) {
1804
+ fragment.appendChild(node);
1805
+ }
1806
+ }
1807
+
1808
+ messagesEl.innerHTML = '';
1809
+ messagesEl.appendChild(fragment);
1810
+
1811
+ // Attach click handlers for copy-link buttons
1812
+ messagesEl.querySelectorAll('.copy-link-btn').forEach((btn) => {
1813
+ btn.addEventListener('click', (e) => {
1814
+ e.stopPropagation();
1815
+ const entryId = btn.dataset.entryId;
1816
+ const shareUrl = buildShareUrl(entryId);
1817
+ copyToClipboard(shareUrl, btn);
1818
+ });
1819
+ });
1820
+ }
1821
+
1822
+ // Use setTimeout(0) to ensure DOM is fully laid out before scrolling
1823
+ setTimeout(() => {
1824
+ const content = document.getElementById('content');
1825
+ if (scrollMode === 'bottom') {
1826
+ content.scrollTop = content.scrollHeight;
1827
+ } else if (scrollMode === 'target') {
1828
+ // If scrollToEntryId is provided, scroll to that specific entry
1829
+ const scrollTargetId = scrollToEntryId || targetId;
1830
+ const targetEl = document.getElementById(`entry-${scrollTargetId}`);
1831
+ if (targetEl) {
1832
+ targetEl.scrollIntoView({ block: 'center' });
1833
+ // Briefly highlight the target message
1834
+ if (scrollToEntryId) {
1835
+ targetEl.classList.add('highlight');
1836
+ setTimeout(() => targetEl.classList.remove('highlight'), 2000);
1837
+ }
1838
+ }
1839
+ }
1840
+ }, 0);
1841
+ }
1842
+
1843
+ // ============================================================
1844
+ // INITIALIZATION
1845
+ // ============================================================
1846
+
1847
+ // Escape HTML tags in text (but not code blocks)
1848
+ function escapeHtmlTags(text) {
1849
+ return text.replace(/<(?=[a-zA-Z\/])/g, '&lt;');
1850
+ }
1851
+
1852
+ // Configure marked with syntax highlighting and HTML escaping for text
1853
+ marked.use({
1854
+ breaks: true,
1855
+ gfm: true,
1856
+ renderer: {
1857
+ // Code blocks: syntax highlight, no HTML escaping
1858
+ code(token) {
1859
+ const code = token.text;
1860
+ const lang = token.lang;
1861
+ let highlighted;
1862
+ if (lang && hljs.getLanguage(lang)) {
1863
+ try {
1864
+ highlighted = hljs.highlight(code, { language: lang }).value;
1865
+ } catch {
1866
+ highlighted = escapeHtml(code);
1867
+ }
1868
+ } else {
1869
+ // Auto-detect language if not specified
1870
+ try {
1871
+ highlighted = hljs.highlightAuto(code).value;
1872
+ } catch {
1873
+ highlighted = escapeHtml(code);
1874
+ }
1875
+ }
1876
+ return `<pre><code class="hljs">${highlighted}</code></pre>`;
1877
+ },
1878
+ // Text content: escape HTML tags
1879
+ text(token) {
1880
+ return escapeHtmlTags(escapeHtml(token.text));
1881
+ },
1882
+ // Inline code: escape HTML
1883
+ codespan(token) {
1884
+ return `<code>${escapeHtml(token.text)}</code>`;
1885
+ }
1886
+ }
1887
+ });
1888
+
1889
+ // Simple marked parse (escaping handled in renderers)
1890
+ function safeMarkedParse(text) {
1891
+ return marked.parse(text);
1892
+ }
1893
+
1894
+ // Search input
1895
+ const searchInput = document.getElementById('tree-search');
1896
+ searchInput.addEventListener('input', (e) => {
1897
+ searchQuery = e.target.value;
1898
+ forceTreeRerender();
1899
+ });
1900
+
1901
+ // Filter buttons
1902
+ document.querySelectorAll('.filter-btn').forEach((btn) => {
1903
+ btn.addEventListener('click', () => {
1904
+ const prevMode = filterMode;
1905
+ document.querySelectorAll('.filter-btn').forEach((b) => b.classList.remove('active'));
1906
+ btn.classList.add('active');
1907
+ filterMode = btn.dataset.filter;
1908
+ forceTreeRerender();
1909
+ // Re-render main content when switching to/from LLM mode
1910
+ if (filterMode === 'llm' || prevMode === 'llm') {
1911
+ navigateTo(currentLeafId, 'none');
1912
+ }
1913
+ });
1914
+ });
1915
+
1916
+ // Sidebar toggle
1917
+ const sidebar = document.getElementById('sidebar');
1918
+ const overlay = document.getElementById('sidebar-overlay');
1919
+ const hamburger = document.getElementById('hamburger');
1920
+
1921
+ hamburger.addEventListener('click', () => {
1922
+ sidebar.classList.add('open');
1923
+ overlay.classList.add('open');
1924
+ hamburger.style.display = 'none';
1925
+ });
1926
+
1927
+ const closeSidebar = () => {
1928
+ sidebar.classList.remove('open');
1929
+ overlay.classList.remove('open');
1930
+ hamburger.style.display = '';
1931
+ };
1932
+
1933
+ overlay.addEventListener('click', closeSidebar);
1934
+ document.getElementById('sidebar-close').addEventListener('click', closeSidebar);
1935
+
1936
+ // Toggle states
1937
+ let thinkingExpanded = true;
1938
+ let toolOutputsExpanded = false;
1939
+
1940
+ const toggleThinking = () => {
1941
+ thinkingExpanded = !thinkingExpanded;
1942
+ document.querySelectorAll('.thinking-text').forEach((el) => {
1943
+ el.style.display = thinkingExpanded ? '' : 'none';
1944
+ });
1945
+ document.querySelectorAll('.thinking-collapsed').forEach((el) => {
1946
+ el.style.display = thinkingExpanded ? 'none' : 'block';
1947
+ });
1948
+ };
1949
+
1950
+ const toggleToolOutputs = () => {
1951
+ toolOutputsExpanded = !toolOutputsExpanded;
1952
+ document.querySelectorAll('.tool-output.expandable').forEach((el) => {
1953
+ el.classList.toggle('expanded', toolOutputsExpanded);
1954
+ });
1955
+ document.querySelectorAll('.compaction').forEach((el) => {
1956
+ el.classList.toggle('expanded', toolOutputsExpanded);
1957
+ });
1958
+ };
1959
+
1960
+ // Keyboard shortcuts
1961
+ document.addEventListener('keydown', (e) => {
1962
+ if (e.key === 'Escape') {
1963
+ searchInput.value = '';
1964
+ searchQuery = '';
1965
+ navigateTo(leafId, 'bottom');
1966
+ }
1967
+ if (e.ctrlKey && e.key === 't') {
1968
+ e.preventDefault();
1969
+ toggleThinking();
1970
+ }
1971
+ if (e.ctrlKey && e.key === 'o') {
1972
+ e.preventDefault();
1973
+ toggleToolOutputs();
1974
+ }
1975
+ });
1976
+
1977
+ // Initial render
1978
+ // If URL has targetId, scroll to that specific message; otherwise stay at top
1979
+ if (leafId) {
1980
+ if (urlTargetId && byId.has(urlTargetId)) {
1981
+ // Deep link: navigate to leaf and scroll to target message
1982
+ navigateTo(leafId, 'target', urlTargetId);
1983
+ } else {
1984
+ navigateTo(leafId, 'none');
1985
+ }
1986
+ } else if (entries.length > 0) {
1987
+ // Fallback: use last entry if no leafId
1988
+ navigateTo(entries[entries.length - 1].id, 'none');
1989
+ }
1990
+ })();