bincode-cli 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (300) hide show
  1. package/AGENTS.md +27 -0
  2. package/README.md +15 -0
  3. package/bin/bincode +98 -0
  4. package/bunfig.toml +4 -0
  5. package/package.json +124 -0
  6. package/parsers-config.ts +239 -0
  7. package/script/build.ts +167 -0
  8. package/script/postinstall.mjs +206 -0
  9. package/script/publish.ts +99 -0
  10. package/script/schema.ts +47 -0
  11. package/src/acp/README.md +164 -0
  12. package/src/acp/agent.ts +1051 -0
  13. package/src/acp/session.ts +101 -0
  14. package/src/acp/types.ts +22 -0
  15. package/src/agent/agent.ts +398 -0
  16. package/src/agent/generate.txt +75 -0
  17. package/src/agent/prompt/compaction.txt +12 -0
  18. package/src/agent/prompt/explore.txt +18 -0
  19. package/src/agent/prompt/summary.txt +10 -0
  20. package/src/agent/prompt/title.txt +36 -0
  21. package/src/auth/bineric-login.ts +506 -0
  22. package/src/auth/index.ts +70 -0
  23. package/src/bun/index.ts +114 -0
  24. package/src/bus/bus-event.ts +43 -0
  25. package/src/bus/global.ts +10 -0
  26. package/src/bus/index.ts +105 -0
  27. package/src/cli/auth-check.ts +61 -0
  28. package/src/cli/bootstrap.ts +21 -0
  29. package/src/cli/cmd/acp.ts +88 -0
  30. package/src/cli/cmd/agent.ts +256 -0
  31. package/src/cli/cmd/auth.ts +436 -0
  32. package/src/cli/cmd/cmd.ts +7 -0
  33. package/src/cli/cmd/debug/config.ts +15 -0
  34. package/src/cli/cmd/debug/file.ts +91 -0
  35. package/src/cli/cmd/debug/index.ts +43 -0
  36. package/src/cli/cmd/debug/lsp.ts +48 -0
  37. package/src/cli/cmd/debug/ripgrep.ts +83 -0
  38. package/src/cli/cmd/debug/scrap.ts +15 -0
  39. package/src/cli/cmd/debug/skill.ts +15 -0
  40. package/src/cli/cmd/debug/snapshot.ts +48 -0
  41. package/src/cli/cmd/export.ts +88 -0
  42. package/src/cli/cmd/generate.ts +38 -0
  43. package/src/cli/cmd/github.ts +1399 -0
  44. package/src/cli/cmd/import.ts +98 -0
  45. package/src/cli/cmd/login.ts +112 -0
  46. package/src/cli/cmd/logout.ts +38 -0
  47. package/src/cli/cmd/mcp.ts +654 -0
  48. package/src/cli/cmd/models.ts +77 -0
  49. package/src/cli/cmd/pr.ts +112 -0
  50. package/src/cli/cmd/run.ts +368 -0
  51. package/src/cli/cmd/serve.ts +31 -0
  52. package/src/cli/cmd/session.ts +106 -0
  53. package/src/cli/cmd/stats.ts +298 -0
  54. package/src/cli/cmd/tui/app.tsx +669 -0
  55. package/src/cli/cmd/tui/attach.ts +30 -0
  56. package/src/cli/cmd/tui/component/border.tsx +21 -0
  57. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  58. package/src/cli/cmd/tui/component/dialog-command.tsx +123 -0
  59. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  60. package/src/cli/cmd/tui/component/dialog-model.tsx +223 -0
  61. package/src/cli/cmd/tui/component/dialog-provider.tsx +224 -0
  62. package/src/cli/cmd/tui/component/dialog-session-list.tsx +102 -0
  63. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  64. package/src/cli/cmd/tui/component/dialog-status.tsx +162 -0
  65. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  66. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  67. package/src/cli/cmd/tui/component/logo.tsx +32 -0
  68. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +560 -0
  69. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  70. package/src/cli/cmd/tui/component/prompt/index.tsx +1052 -0
  71. package/src/cli/cmd/tui/context/args.tsx +14 -0
  72. package/src/cli/cmd/tui/context/directory.ts +13 -0
  73. package/src/cli/cmd/tui/context/exit.tsx +23 -0
  74. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  75. package/src/cli/cmd/tui/context/keybind.tsx +101 -0
  76. package/src/cli/cmd/tui/context/kv.tsx +49 -0
  77. package/src/cli/cmd/tui/context/local.tsx +339 -0
  78. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  79. package/src/cli/cmd/tui/context/route.tsx +46 -0
  80. package/src/cli/cmd/tui/context/sdk.tsx +74 -0
  81. package/src/cli/cmd/tui/context/sync.tsx +372 -0
  82. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  83. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  84. package/src/cli/cmd/tui/context/theme/bincode.json +245 -0
  85. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  86. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  87. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  88. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  89. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  90. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  91. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  92. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  93. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  94. package/src/cli/cmd/tui/context/theme/gruvbox.json +95 -0
  95. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  96. package/src/cli/cmd/tui/context/theme/lucent-orng.json +227 -0
  97. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  98. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  99. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  100. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  101. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  102. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  103. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  104. package/src/cli/cmd/tui/context/theme/orng.json +245 -0
  105. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  106. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  107. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  108. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  109. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  110. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  111. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  112. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  113. package/src/cli/cmd/tui/context/theme.tsx +1109 -0
  114. package/src/cli/cmd/tui/event.ts +40 -0
  115. package/src/cli/cmd/tui/routes/home.tsx +105 -0
  116. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +64 -0
  117. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +109 -0
  118. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  119. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  120. package/src/cli/cmd/tui/routes/session/footer.tsx +88 -0
  121. package/src/cli/cmd/tui/routes/session/header.tsx +141 -0
  122. package/src/cli/cmd/tui/routes/session/index.tsx +1888 -0
  123. package/src/cli/cmd/tui/routes/session/sidebar.tsx +321 -0
  124. package/src/cli/cmd/tui/spawn.ts +60 -0
  125. package/src/cli/cmd/tui/thread.ts +120 -0
  126. package/src/cli/cmd/tui/ui/dialog-alert.tsx +57 -0
  127. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +83 -0
  128. package/src/cli/cmd/tui/ui/dialog-help.tsx +38 -0
  129. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +77 -0
  130. package/src/cli/cmd/tui/ui/dialog-select.tsx +330 -0
  131. package/src/cli/cmd/tui/ui/dialog.tsx +170 -0
  132. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  133. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  134. package/src/cli/cmd/tui/util/clipboard.ts +127 -0
  135. package/src/cli/cmd/tui/util/editor.ts +32 -0
  136. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  137. package/src/cli/cmd/tui/worker.ts +63 -0
  138. package/src/cli/cmd/uninstall.ts +344 -0
  139. package/src/cli/cmd/upgrade.ts +67 -0
  140. package/src/cli/cmd/web.ts +84 -0
  141. package/src/cli/error.ts +55 -0
  142. package/src/cli/ui.ts +84 -0
  143. package/src/cli/upgrade.ts +25 -0
  144. package/src/command/index.ts +80 -0
  145. package/src/command/template/initialize.txt +10 -0
  146. package/src/command/template/review.txt +97 -0
  147. package/src/config/config.ts +995 -0
  148. package/src/config/markdown.ts +41 -0
  149. package/src/env/index.ts +26 -0
  150. package/src/file/ignore.ts +83 -0
  151. package/src/file/index.ts +328 -0
  152. package/src/file/ripgrep.ts +393 -0
  153. package/src/file/time.ts +64 -0
  154. package/src/file/watcher.ts +103 -0
  155. package/src/flag/flag.ts +46 -0
  156. package/src/format/formatter.ts +315 -0
  157. package/src/format/index.ts +137 -0
  158. package/src/global/index.ts +52 -0
  159. package/src/id/id.ts +73 -0
  160. package/src/ide/index.ts +76 -0
  161. package/src/index.ts +217 -0
  162. package/src/installation/index.ts +196 -0
  163. package/src/lsp/client.ts +229 -0
  164. package/src/lsp/index.ts +485 -0
  165. package/src/lsp/language.ts +116 -0
  166. package/src/lsp/server.ts +1895 -0
  167. package/src/mcp/auth.ts +135 -0
  168. package/src/mcp/index.ts +654 -0
  169. package/src/mcp/oauth-callback.ts +200 -0
  170. package/src/mcp/oauth-provider.ts +154 -0
  171. package/src/patch/index.ts +622 -0
  172. package/src/permission/index.ts +199 -0
  173. package/src/plugin/index.ts +101 -0
  174. package/src/project/bootstrap.ts +31 -0
  175. package/src/project/instance.ts +78 -0
  176. package/src/project/project.ts +221 -0
  177. package/src/project/state.ts +65 -0
  178. package/src/project/vcs.ts +76 -0
  179. package/src/provider/auth.ts +143 -0
  180. package/src/provider/models-macro.ts +11 -0
  181. package/src/provider/models.ts +106 -0
  182. package/src/provider/provider.ts +1071 -0
  183. package/src/provider/sdk/openai-compatible/src/README.md +5 -0
  184. package/src/provider/sdk/openai-compatible/src/index.ts +2 -0
  185. package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +101 -0
  186. package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +303 -0
  187. package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +22 -0
  188. package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +18 -0
  189. package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +22 -0
  190. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +207 -0
  191. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +1713 -0
  192. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +177 -0
  193. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +1 -0
  194. package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +88 -0
  195. package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +128 -0
  196. package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +115 -0
  197. package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +65 -0
  198. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +104 -0
  199. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +103 -0
  200. package/src/provider/transform.ts +455 -0
  201. package/src/pty/index.ts +231 -0
  202. package/src/server/error.ts +36 -0
  203. package/src/server/project.ts +79 -0
  204. package/src/server/server.ts +2642 -0
  205. package/src/server/tui.ts +71 -0
  206. package/src/session/compaction.ts +223 -0
  207. package/src/session/index.ts +458 -0
  208. package/src/session/llm.ts +201 -0
  209. package/src/session/message-v2.ts +659 -0
  210. package/src/session/message.ts +189 -0
  211. package/src/session/processor.ts +409 -0
  212. package/src/session/prompt/anthropic-20250930.txt +166 -0
  213. package/src/session/prompt/anthropic.txt +104 -0
  214. package/src/session/prompt/anthropic_spoof.txt +1 -0
  215. package/src/session/prompt/beast.txt +147 -0
  216. package/src/session/prompt/build-switch.txt +5 -0
  217. package/src/session/prompt/codex.txt +318 -0
  218. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  219. package/src/session/prompt/gemini.txt +155 -0
  220. package/src/session/prompt/max-steps.txt +16 -0
  221. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  222. package/src/session/prompt/plan.txt +26 -0
  223. package/src/session/prompt/polaris.txt +106 -0
  224. package/src/session/prompt/qwen.txt +109 -0
  225. package/src/session/prompt.ts +1446 -0
  226. package/src/session/retry.ts +86 -0
  227. package/src/session/revert.ts +108 -0
  228. package/src/session/status.ts +76 -0
  229. package/src/session/summary.ts +194 -0
  230. package/src/session/system.ts +120 -0
  231. package/src/session/todo.ts +37 -0
  232. package/src/share/share-next.ts +194 -0
  233. package/src/share/share.ts +87 -0
  234. package/src/shell/shell.ts +67 -0
  235. package/src/skill/index.ts +1 -0
  236. package/src/skill/skill.ts +83 -0
  237. package/src/snapshot/index.ts +197 -0
  238. package/src/storage/storage.ts +226 -0
  239. package/src/tool/bash.ts +306 -0
  240. package/src/tool/bash.txt +158 -0
  241. package/src/tool/batch.ts +175 -0
  242. package/src/tool/batch.txt +24 -0
  243. package/src/tool/codesearch.ts +138 -0
  244. package/src/tool/codesearch.txt +12 -0
  245. package/src/tool/edit.ts +675 -0
  246. package/src/tool/edit.txt +10 -0
  247. package/src/tool/glob.ts +65 -0
  248. package/src/tool/glob.txt +6 -0
  249. package/src/tool/grep.ts +121 -0
  250. package/src/tool/grep.txt +8 -0
  251. package/src/tool/invalid.ts +17 -0
  252. package/src/tool/ls.ts +110 -0
  253. package/src/tool/ls.txt +1 -0
  254. package/src/tool/lsp-diagnostics.ts +26 -0
  255. package/src/tool/lsp-diagnostics.txt +1 -0
  256. package/src/tool/lsp-hover.ts +31 -0
  257. package/src/tool/lsp-hover.txt +1 -0
  258. package/src/tool/lsp.ts +87 -0
  259. package/src/tool/lsp.txt +19 -0
  260. package/src/tool/multiedit.ts +46 -0
  261. package/src/tool/multiedit.txt +41 -0
  262. package/src/tool/patch.ts +233 -0
  263. package/src/tool/patch.txt +1 -0
  264. package/src/tool/read.ts +219 -0
  265. package/src/tool/read.txt +12 -0
  266. package/src/tool/registry.ts +162 -0
  267. package/src/tool/skill.ts +100 -0
  268. package/src/tool/task.ts +136 -0
  269. package/src/tool/task.txt +60 -0
  270. package/src/tool/todo.ts +39 -0
  271. package/src/tool/todoread.txt +14 -0
  272. package/src/tool/todowrite.txt +167 -0
  273. package/src/tool/tool.ts +71 -0
  274. package/src/tool/webfetch.ts +187 -0
  275. package/src/tool/webfetch.txt +13 -0
  276. package/src/tool/websearch.ts +150 -0
  277. package/src/tool/websearch.txt +11 -0
  278. package/src/tool/write.ts +110 -0
  279. package/src/tool/write.txt +8 -0
  280. package/src/util/archive.ts +16 -0
  281. package/src/util/color.ts +19 -0
  282. package/src/util/context.ts +25 -0
  283. package/src/util/defer.ts +12 -0
  284. package/src/util/eventloop.ts +20 -0
  285. package/src/util/filesystem.ts +83 -0
  286. package/src/util/fn.ts +11 -0
  287. package/src/util/iife.ts +3 -0
  288. package/src/util/keybind.ts +102 -0
  289. package/src/util/lazy.ts +11 -0
  290. package/src/util/locale.ts +81 -0
  291. package/src/util/lock.ts +98 -0
  292. package/src/util/log.ts +180 -0
  293. package/src/util/queue.ts +32 -0
  294. package/src/util/rpc.ts +42 -0
  295. package/src/util/scrap.ts +10 -0
  296. package/src/util/signal.ts +12 -0
  297. package/src/util/timeout.ts +14 -0
  298. package/src/util/token.ts +7 -0
  299. package/src/util/wildcard.ts +54 -0
  300. package/tsconfig.json +16 -0
@@ -0,0 +1,1888 @@
1
+ import {
2
+ createContext,
3
+ createEffect,
4
+ createMemo,
5
+ createSignal,
6
+ For,
7
+ Match,
8
+ on,
9
+ Show,
10
+ Switch,
11
+ useContext,
12
+ type Component,
13
+ } from "solid-js"
14
+ import { Dynamic } from "solid-js/web"
15
+ import path from "path"
16
+ import { useRoute, useRouteData } from "@tui/context/route"
17
+ import { useSync } from "@tui/context/sync"
18
+ import { SplitBorder } from "@tui/component/border"
19
+ import { useTheme } from "@tui/context/theme"
20
+ import {
21
+ BoxRenderable,
22
+ ScrollBoxRenderable,
23
+ addDefaultParsers,
24
+ MacOSScrollAccel,
25
+ RGBA,
26
+ type ScrollAcceleration,
27
+ } from "@opentui/core"
28
+ import { Prompt, type PromptRef } from "@tui/component/prompt"
29
+ import type { AssistantMessage, Part, ToolPart, UserMessage, TextPart, ReasoningPart } from "@bincode-ai/sdk/v2"
30
+ import { useLocal } from "@tui/context/local"
31
+ import { Locale } from "@/util/locale"
32
+ import type { Tool } from "@/tool/tool"
33
+ import type { ReadTool } from "@/tool/read"
34
+ import type { WriteTool } from "@/tool/write"
35
+ import { BashTool } from "@/tool/bash"
36
+ import type { GlobTool } from "@/tool/glob"
37
+ import { TodoWriteTool } from "@/tool/todo"
38
+ import type { GrepTool } from "@/tool/grep"
39
+ import type { ListTool } from "@/tool/ls"
40
+ import type { EditTool } from "@/tool/edit"
41
+ import type { PatchTool } from "@/tool/patch"
42
+ import type { WebFetchTool } from "@/tool/webfetch"
43
+ import type { TaskTool } from "@/tool/task"
44
+ import { useKeyboard, useRenderer, useTerminalDimensions, type BoxProps, type JSX } from "@opentui/solid"
45
+ import { useSDK } from "@tui/context/sdk"
46
+ import { useCommandDialog } from "@tui/component/dialog-command"
47
+ import { useKeybind } from "@tui/context/keybind"
48
+ import { Header } from "./header"
49
+ import { parsePatch } from "diff"
50
+ import { useDialog } from "../../ui/dialog"
51
+ import { DialogMessage } from "./dialog-message"
52
+ import type { PromptInfo } from "../../component/prompt/history"
53
+ import { iife } from "@/util/iife"
54
+ import { DialogConfirm } from "@tui/ui/dialog-confirm"
55
+ import { DialogPrompt } from "@tui/ui/dialog-prompt"
56
+ import { DialogTimeline } from "./dialog-timeline"
57
+ import { DialogForkFromTimeline } from "./dialog-fork-from-timeline"
58
+ import { DialogSessionRename } from "../../component/dialog-session-rename"
59
+ import { Sidebar } from "./sidebar"
60
+ import { LANGUAGE_EXTENSIONS } from "@/lsp/language"
61
+ import parsers from "../../../../../../parsers-config.ts"
62
+ import { Clipboard } from "../../util/clipboard"
63
+ import { Toast, useToast } from "../../ui/toast"
64
+ import { useKV } from "../../context/kv.tsx"
65
+ import { Editor } from "../../util/editor"
66
+ import stripAnsi from "strip-ansi"
67
+ import { Footer } from "./footer.tsx"
68
+ import { usePromptRef } from "../../context/prompt"
69
+ import { Filesystem } from "@/util/filesystem"
70
+ import { DialogSubagent } from "./dialog-subagent.tsx"
71
+
72
+ addDefaultParsers(parsers.parsers)
73
+
74
+ class CustomSpeedScroll implements ScrollAcceleration {
75
+ constructor(private speed: number) {}
76
+
77
+ tick(_now?: number): number {
78
+ return this.speed
79
+ }
80
+
81
+ reset(): void {}
82
+ }
83
+
84
+ const context = createContext<{
85
+ width: number
86
+ conceal: () => boolean
87
+ showThinking: () => boolean
88
+ showTimestamps: () => boolean
89
+ usernameVisible: () => boolean
90
+ showDetails: () => boolean
91
+ userMessageMarkdown: () => boolean
92
+ diffWrapMode: () => "word" | "none"
93
+ sync: ReturnType<typeof useSync>
94
+ }>()
95
+
96
+ function use() {
97
+ const ctx = useContext(context)
98
+ if (!ctx) throw new Error("useContext must be used within a Session component")
99
+ return ctx
100
+ }
101
+
102
+ export function Session() {
103
+ const route = useRouteData("session")
104
+ const { navigate } = useRoute()
105
+ const sync = useSync()
106
+ const kv = useKV()
107
+ const { theme } = useTheme()
108
+ const promptRef = usePromptRef()
109
+ const session = createMemo(() => sync.session.get(route.sessionID)!)
110
+ const messages = createMemo(() => sync.data.message[route.sessionID] ?? [])
111
+ const permissions = createMemo(() => sync.data.permission[route.sessionID] ?? [])
112
+
113
+ const pending = createMemo(() => {
114
+ return messages().findLast((x) => x.role === "assistant" && !x.time.completed)?.id
115
+ })
116
+
117
+ const lastAssistant = createMemo(() => {
118
+ return messages().findLast((x) => x.role === "assistant")
119
+ })
120
+
121
+ const dimensions = useTerminalDimensions()
122
+ const [sidebar, setSidebar] = createSignal<"show" | "hide" | "auto">(kv.get("sidebar", "auto"))
123
+ const [conceal, setConceal] = createSignal(true)
124
+ const [showThinking, setShowThinking] = createSignal(kv.get("thinking_visibility", true))
125
+ const [showTimestamps, setShowTimestamps] = createSignal(kv.get("timestamps", "hide") === "show")
126
+ const [usernameVisible, setUsernameVisible] = createSignal(kv.get("username_visible", true))
127
+ const [showDetails, setShowDetails] = createSignal(kv.get("tool_details_visibility", true))
128
+ const [showScrollbar, setShowScrollbar] = createSignal(kv.get("scrollbar_visible", false))
129
+ const [userMessageMarkdown, setUserMessageMarkdown] = createSignal(kv.get("user_message_markdown", true))
130
+ const [diffWrapMode, setDiffWrapMode] = createSignal<"word" | "none">("word")
131
+
132
+ const wide = createMemo(() => dimensions().width > 120)
133
+ const tall = createMemo(() => dimensions().height > 40)
134
+ const sidebarVisible = createMemo(() => {
135
+ if (session()?.parentID) return false
136
+ if (sidebar() === "show") return true
137
+ if (sidebar() === "auto" && wide()) return true
138
+ return false
139
+ })
140
+ const sidebarOverlay = createMemo(() => sidebarVisible() && !wide())
141
+ const contentWidth = createMemo(() => dimensions().width - (sidebarVisible() && !sidebarOverlay() ? 42 : 0) - 4)
142
+
143
+ const scrollAcceleration = createMemo(() => {
144
+ const tui = sync.data.config.tui
145
+ if (tui?.scroll_acceleration?.enabled) {
146
+ return new MacOSScrollAccel()
147
+ }
148
+ if (tui?.scroll_speed) {
149
+ return new CustomSpeedScroll(tui.scroll_speed)
150
+ }
151
+
152
+ return new CustomSpeedScroll(3)
153
+ })
154
+
155
+ createEffect(async () => {
156
+ await sync.session
157
+ .sync(route.sessionID)
158
+ .then(() => {
159
+ if (scroll) scroll.scrollBy(100_000)
160
+ })
161
+ .catch((e) => {
162
+ console.error(e)
163
+ toast.show({
164
+ message: `Session not found: ${route.sessionID}`,
165
+ variant: "error",
166
+ })
167
+ return navigate({ type: "home" })
168
+ })
169
+ })
170
+
171
+ const toast = useToast()
172
+ const sdk = useSDK()
173
+
174
+ // Handle initial prompt from fork
175
+ createEffect(() => {
176
+ if (route.initialPrompt && prompt) {
177
+ prompt.set(route.initialPrompt)
178
+ }
179
+ })
180
+
181
+ // Auto-navigate to whichever session currently needs permission input
182
+ createEffect(() => {
183
+ const currentSession = session()
184
+ if (!currentSession) return
185
+ const currentPermissions = permissions()
186
+ let targetID = currentPermissions.length > 0 ? currentSession.id : undefined
187
+
188
+ if (!targetID) {
189
+ const child = sync.data.session.find(
190
+ (x) => x.parentID === currentSession.id && (sync.data.permission[x.id]?.length ?? 0) > 0,
191
+ )
192
+ if (child) targetID = child.id
193
+ }
194
+
195
+ if (targetID && targetID !== currentSession.id) {
196
+ navigate({
197
+ type: "session",
198
+ sessionID: targetID,
199
+ })
200
+ }
201
+ })
202
+
203
+ let scroll: ScrollBoxRenderable
204
+ let prompt: PromptRef
205
+ const keybind = useKeybind()
206
+
207
+ // Helper: Find next visible message boundary in direction
208
+ const findNextVisibleMessage = (direction: "next" | "prev"): string | null => {
209
+ const children = scroll.getChildren()
210
+ const messagesList = messages()
211
+ const scrollTop = scroll.y
212
+
213
+ // Get visible messages sorted by position, filtering for valid non-synthetic, non-ignored content
214
+ const visibleMessages = children
215
+ .filter((c) => {
216
+ if (!c.id) return false
217
+ const message = messagesList.find((m) => m.id === c.id)
218
+ if (!message) return false
219
+
220
+ // Check if message has valid non-synthetic, non-ignored text parts
221
+ const parts = sync.data.part[message.id]
222
+ if (!parts || !Array.isArray(parts)) return false
223
+
224
+ return parts.some((part) => part && part.type === "text" && !part.synthetic && !part.ignored)
225
+ })
226
+ .sort((a, b) => a.y - b.y)
227
+
228
+ if (visibleMessages.length === 0) return null
229
+
230
+ if (direction === "next") {
231
+ // Find first message below current position
232
+ return visibleMessages.find((c) => c.y > scrollTop + 10)?.id ?? null
233
+ }
234
+ // Find last message above current position
235
+ return [...visibleMessages].reverse().find((c) => c.y < scrollTop - 10)?.id ?? null
236
+ }
237
+
238
+ // Helper: Scroll to message in direction or fallback to page scroll
239
+ const scrollToMessage = (direction: "next" | "prev", dialog: ReturnType<typeof useDialog>) => {
240
+ const targetID = findNextVisibleMessage(direction)
241
+
242
+ if (!targetID) {
243
+ scroll.scrollBy(direction === "next" ? scroll.height : -scroll.height)
244
+ dialog.clear()
245
+ return
246
+ }
247
+
248
+ const child = scroll.getChildren().find((c) => c.id === targetID)
249
+ if (child) scroll.scrollBy(child.y - scroll.y - 1)
250
+ dialog.clear()
251
+ }
252
+
253
+ useKeyboard((evt) => {
254
+ if (dialog.stack.length > 0) return
255
+
256
+ const first = permissions()[0]
257
+ if (first) {
258
+ const response = iife(() => {
259
+ if (evt.ctrl || evt.meta) return
260
+ if (evt.name === "return") return "once"
261
+ if (evt.name === "a") return "always"
262
+ if (evt.name === "d") return "reject"
263
+ if (evt.name === "escape") return "reject"
264
+ return
265
+ })
266
+ if (response) {
267
+ sdk.client.permission.respond({
268
+ permissionID: first.id,
269
+ sessionID: route.sessionID,
270
+ response: response,
271
+ })
272
+ }
273
+ }
274
+ })
275
+
276
+ function toBottom() {
277
+ setTimeout(() => {
278
+ if (scroll) scroll.scrollTo(scroll.scrollHeight)
279
+ }, 50)
280
+ }
281
+
282
+ const local = useLocal()
283
+
284
+ function moveChild(direction: number) {
285
+ const parentID = session()?.parentID ?? session()?.id
286
+ let children = sync.data.session
287
+ .filter((x) => x.parentID === parentID || x.id === parentID)
288
+ .toSorted((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
289
+ if (children.length === 1) return
290
+ let next = children.findIndex((x) => x.id === session()?.id) + direction
291
+ if (next >= children.length) next = 0
292
+ if (next < 0) next = children.length - 1
293
+ if (children[next]) {
294
+ navigate({
295
+ type: "session",
296
+ sessionID: children[next].id,
297
+ })
298
+ }
299
+ }
300
+
301
+ const command = useCommandDialog()
302
+ command.register(() => [
303
+ // ...(sync.data.config.share !== "disabled"
304
+ // ? [
305
+ // {
306
+ // title: "Share session",
307
+ // value: "session.share",
308
+ // suggested: route.type === "session",
309
+ // keybind: "session_share" as const,
310
+ // disabled: !!session()?.share?.url,
311
+ // category: "Session",
312
+ // onSelect: async (dialog: any) => {
313
+ // await sdk.client.session
314
+ // .share({
315
+ // sessionID: route.sessionID,
316
+ // })
317
+ // .then((res) =>
318
+ // Clipboard.copy(res.data!.share!.url).catch(() =>
319
+ // toast.show({ message: "Failed to copy URL to clipboard", variant: "error" }),
320
+ // ),
321
+ // )
322
+ // .then(() => toast.show({ message: "Share URL copied to clipboard!", variant: "success" }))
323
+ // .catch(() => toast.show({ message: "Failed to share session", variant: "error" }))
324
+ // dialog.clear()
325
+ // },
326
+ // },
327
+ // ]
328
+ // : []),
329
+ {
330
+ title: "Rename session",
331
+ value: "session.rename",
332
+ keybind: "session_rename",
333
+ category: "Session",
334
+ onSelect: (dialog) => {
335
+ dialog.replace(() => <DialogSessionRename session={route.sessionID} />)
336
+ },
337
+ },
338
+ {
339
+ title: "Jump to message",
340
+ value: "session.timeline",
341
+ keybind: "session_timeline",
342
+ category: "Session",
343
+ onSelect: (dialog) => {
344
+ dialog.replace(() => (
345
+ <DialogTimeline
346
+ onMove={(messageID) => {
347
+ const child = scroll.getChildren().find((child) => {
348
+ return child.id === messageID
349
+ })
350
+ if (child) scroll.scrollBy(child.y - scroll.y - 1)
351
+ }}
352
+ sessionID={route.sessionID}
353
+ setPrompt={(promptInfo) => prompt.set(promptInfo)}
354
+ />
355
+ ))
356
+ },
357
+ },
358
+ {
359
+ title: "Fork from message",
360
+ value: "session.fork",
361
+ keybind: "session_fork",
362
+ category: "Session",
363
+ onSelect: (dialog) => {
364
+ dialog.replace(() => (
365
+ <DialogForkFromTimeline
366
+ onMove={(messageID) => {
367
+ const child = scroll.getChildren().find((child) => {
368
+ return child.id === messageID
369
+ })
370
+ if (child) scroll.scrollBy(child.y - scroll.y - 1)
371
+ }}
372
+ sessionID={route.sessionID}
373
+ />
374
+ ))
375
+ },
376
+ },
377
+ {
378
+ title: "Compact session",
379
+ value: "session.compact",
380
+ keybind: "session_compact",
381
+ category: "Session",
382
+ onSelect: (dialog) => {
383
+ const selectedModel = local.model.current()
384
+ if (!selectedModel) {
385
+ toast.show({
386
+ variant: "warning",
387
+ message: "Connect a provider to summarize this session",
388
+ duration: 3000,
389
+ })
390
+ return
391
+ }
392
+ sdk.client.session.summarize({
393
+ sessionID: route.sessionID,
394
+ modelID: selectedModel.modelID,
395
+ providerID: selectedModel.providerID,
396
+ })
397
+ dialog.clear()
398
+ },
399
+ },
400
+ // {
401
+ // title: "Unshare session",
402
+ // value: "session.unshare",
403
+ // keybind: "session_unshare",
404
+ // disabled: !session()?.share?.url,
405
+ // category: "Session",
406
+ // onSelect: async (dialog) => {
407
+ // await sdk.client.session
408
+ // .unshare({
409
+ // sessionID: route.sessionID,
410
+ // })
411
+ // .then(() => toast.show({ message: "Session unshared successfully", variant: "success" }))
412
+ // .catch(() => toast.show({ message: "Failed to unshare session", variant: "error" }))
413
+ // dialog.clear()
414
+ // },
415
+ // },
416
+ {
417
+ title: "Undo previous message",
418
+ value: "session.undo",
419
+ keybind: "messages_undo",
420
+ category: "Session",
421
+ onSelect: async (dialog) => {
422
+ const status = sync.data.session_status?.[route.sessionID]
423
+ if (status?.type !== "idle") await sdk.client.session.abort({ sessionID: route.sessionID }).catch(() => {})
424
+ const revert = session().revert?.messageID
425
+ const message = messages().findLast((x) => (!revert || x.id < revert) && x.role === "user")
426
+ if (!message) return
427
+ sdk.client.session
428
+ .revert({
429
+ sessionID: route.sessionID,
430
+ messageID: message.id,
431
+ })
432
+ .then(() => {
433
+ toBottom()
434
+ })
435
+ const parts = sync.data.part[message.id]
436
+ prompt.set(
437
+ parts.reduce(
438
+ (agg, part) => {
439
+ if (part.type === "text") {
440
+ if (!part.synthetic) agg.input += part.text
441
+ }
442
+ if (part.type === "file") agg.parts.push(part)
443
+ return agg
444
+ },
445
+ { input: "", parts: [] as PromptInfo["parts"] },
446
+ ),
447
+ )
448
+ dialog.clear()
449
+ },
450
+ },
451
+ {
452
+ title: "Redo",
453
+ value: "session.redo",
454
+ keybind: "messages_redo",
455
+ disabled: !session()?.revert?.messageID,
456
+ category: "Session",
457
+ onSelect: (dialog) => {
458
+ dialog.clear()
459
+ const messageID = session().revert?.messageID
460
+ if (!messageID) return
461
+ const message = messages().find((x) => x.role === "user" && x.id > messageID)
462
+ if (!message) {
463
+ sdk.client.session.unrevert({
464
+ sessionID: route.sessionID,
465
+ })
466
+ prompt.set({ input: "", parts: [] })
467
+ return
468
+ }
469
+ sdk.client.session.revert({
470
+ sessionID: route.sessionID,
471
+ messageID: message.id,
472
+ })
473
+ },
474
+ },
475
+ {
476
+ title: sidebarVisible() ? "Hide sidebar" : "Show sidebar",
477
+ value: "session.sidebar.toggle",
478
+ keybind: "sidebar_toggle",
479
+ category: "Session",
480
+ onSelect: (dialog) => {
481
+ setSidebar((prev) => {
482
+ if (prev === "auto") return sidebarVisible() ? "hide" : "show"
483
+ if (prev === "show") return "hide"
484
+ return "show"
485
+ })
486
+ if (sidebar() === "show") kv.set("sidebar", "auto")
487
+ if (sidebar() === "hide") kv.set("sidebar", "hide")
488
+ dialog.clear()
489
+ },
490
+ },
491
+ {
492
+ title: usernameVisible() ? "Hide username" : "Show username",
493
+ value: "session.username_visible.toggle",
494
+ keybind: "username_toggle",
495
+ category: "Session",
496
+ onSelect: (dialog) => {
497
+ setUsernameVisible((prev) => {
498
+ const next = !prev
499
+ kv.set("username_visible", next)
500
+ return next
501
+ })
502
+ dialog.clear()
503
+ },
504
+ },
505
+ {
506
+ title: "Toggle code concealment",
507
+ value: "session.toggle.conceal",
508
+ keybind: "messages_toggle_conceal" as any,
509
+ category: "Session",
510
+ onSelect: (dialog) => {
511
+ setConceal((prev) => !prev)
512
+ dialog.clear()
513
+ },
514
+ },
515
+ {
516
+ title: showTimestamps() ? "Hide timestamps" : "Show timestamps",
517
+ value: "session.toggle.timestamps",
518
+ category: "Session",
519
+ onSelect: (dialog) => {
520
+ setShowTimestamps((prev) => {
521
+ const next = !prev
522
+ kv.set("timestamps", next ? "show" : "hide")
523
+ return next
524
+ })
525
+ dialog.clear()
526
+ },
527
+ },
528
+ {
529
+ title: showThinking() ? "Hide thinking" : "Show thinking",
530
+ value: "session.toggle.thinking",
531
+ category: "Session",
532
+ onSelect: (dialog) => {
533
+ setShowThinking((prev) => {
534
+ const next = !prev
535
+ kv.set("thinking_visibility", next)
536
+ return next
537
+ })
538
+ dialog.clear()
539
+ },
540
+ },
541
+ {
542
+ title: "Toggle diff wrapping",
543
+ value: "session.toggle.diffwrap",
544
+ category: "Session",
545
+ onSelect: (dialog) => {
546
+ setDiffWrapMode((prev) => (prev === "word" ? "none" : "word"))
547
+ dialog.clear()
548
+ },
549
+ },
550
+ {
551
+ title: showDetails() ? "Hide tool details" : "Show tool details",
552
+ value: "session.toggle.actions",
553
+ keybind: "tool_details",
554
+ category: "Session",
555
+ onSelect: (dialog) => {
556
+ const newValue = !showDetails()
557
+ setShowDetails(newValue)
558
+ kv.set("tool_details_visibility", newValue)
559
+ dialog.clear()
560
+ },
561
+ },
562
+ {
563
+ title: "Toggle session scrollbar",
564
+ value: "session.toggle.scrollbar",
565
+ keybind: "scrollbar_toggle",
566
+ category: "Session",
567
+ onSelect: (dialog) => {
568
+ setShowScrollbar((prev) => {
569
+ const next = !prev
570
+ kv.set("scrollbar_visible", next)
571
+ return next
572
+ })
573
+ dialog.clear()
574
+ },
575
+ },
576
+ {
577
+ title: userMessageMarkdown() ? "Disable user message markdown" : "Enable user message markdown",
578
+ value: "session.toggle.user_message_markdown",
579
+ category: "Session",
580
+ onSelect: (dialog) => {
581
+ setUserMessageMarkdown((prev) => {
582
+ const next = !prev
583
+ kv.set("user_message_markdown", next)
584
+ return next
585
+ })
586
+ dialog.clear()
587
+ },
588
+ },
589
+ {
590
+ title: "Page up",
591
+ value: "session.page.up",
592
+ keybind: "messages_page_up",
593
+ category: "Session",
594
+ disabled: true,
595
+ onSelect: (dialog) => {
596
+ scroll.scrollBy(-scroll.height / 2)
597
+ dialog.clear()
598
+ },
599
+ },
600
+ {
601
+ title: "Page down",
602
+ value: "session.page.down",
603
+ keybind: "messages_page_down",
604
+ category: "Session",
605
+ disabled: true,
606
+ onSelect: (dialog) => {
607
+ scroll.scrollBy(scroll.height / 2)
608
+ dialog.clear()
609
+ },
610
+ },
611
+ {
612
+ title: "Half page up",
613
+ value: "session.half.page.up",
614
+ keybind: "messages_half_page_up",
615
+ category: "Session",
616
+ disabled: true,
617
+ onSelect: (dialog) => {
618
+ scroll.scrollBy(-scroll.height / 4)
619
+ dialog.clear()
620
+ },
621
+ },
622
+ {
623
+ title: "Half page down",
624
+ value: "session.half.page.down",
625
+ keybind: "messages_half_page_down",
626
+ category: "Session",
627
+ disabled: true,
628
+ onSelect: (dialog) => {
629
+ scroll.scrollBy(scroll.height / 4)
630
+ dialog.clear()
631
+ },
632
+ },
633
+ {
634
+ title: "First message",
635
+ value: "session.first",
636
+ keybind: "messages_first",
637
+ category: "Session",
638
+ disabled: true,
639
+ onSelect: (dialog) => {
640
+ scroll.scrollTo(0)
641
+ dialog.clear()
642
+ },
643
+ },
644
+ {
645
+ title: "Last message",
646
+ value: "session.last",
647
+ keybind: "messages_last",
648
+ category: "Session",
649
+ disabled: true,
650
+ onSelect: (dialog) => {
651
+ scroll.scrollTo(scroll.scrollHeight)
652
+ dialog.clear()
653
+ },
654
+ },
655
+ {
656
+ title: "Jump to last user message",
657
+ value: "session.messages_last_user",
658
+ keybind: "messages_last_user",
659
+ category: "Session",
660
+ onSelect: () => {
661
+ const messages = sync.data.message[route.sessionID]
662
+ if (!messages || !messages.length) return
663
+
664
+ // Find the most recent user message with non-ignored, non-synthetic text parts
665
+ for (let i = messages.length - 1; i >= 0; i--) {
666
+ const message = messages[i]
667
+ if (!message || message.role !== "user") continue
668
+
669
+ const parts = sync.data.part[message.id]
670
+ if (!parts || !Array.isArray(parts)) continue
671
+
672
+ const hasValidTextPart = parts.some(
673
+ (part) => part && part.type === "text" && !part.synthetic && !part.ignored,
674
+ )
675
+
676
+ if (hasValidTextPart) {
677
+ const child = scroll.getChildren().find((child) => {
678
+ return child.id === message.id
679
+ })
680
+ if (child) scroll.scrollBy(child.y - scroll.y - 1)
681
+ break
682
+ }
683
+ }
684
+ },
685
+ },
686
+ {
687
+ title: "Next message",
688
+ value: "session.message.next",
689
+ keybind: "messages_next",
690
+ category: "Session",
691
+ disabled: true,
692
+ onSelect: (dialog) => scrollToMessage("next", dialog),
693
+ },
694
+ {
695
+ title: "Previous message",
696
+ value: "session.message.previous",
697
+ keybind: "messages_previous",
698
+ category: "Session",
699
+ disabled: true,
700
+ onSelect: (dialog) => scrollToMessage("prev", dialog),
701
+ },
702
+ {
703
+ title: "Copy last assistant message",
704
+ value: "messages.copy",
705
+ keybind: "messages_copy",
706
+ category: "Session",
707
+ onSelect: (dialog) => {
708
+ const revertID = session()?.revert?.messageID
709
+ const lastAssistantMessage = messages().findLast(
710
+ (msg) => msg.role === "assistant" && (!revertID || msg.id < revertID),
711
+ )
712
+ if (!lastAssistantMessage) {
713
+ toast.show({ message: "No assistant messages found", variant: "error" })
714
+ dialog.clear()
715
+ return
716
+ }
717
+
718
+ const parts = sync.data.part[lastAssistantMessage.id] ?? []
719
+ const textParts = parts.filter((part) => part.type === "text")
720
+ if (textParts.length === 0) {
721
+ toast.show({ message: "No text parts found in last assistant message", variant: "error" })
722
+ dialog.clear()
723
+ return
724
+ }
725
+
726
+ const text = textParts
727
+ .map((part) => part.text)
728
+ .join("\n")
729
+ .trim()
730
+ if (!text) {
731
+ toast.show({
732
+ message: "No text content found in last assistant message",
733
+ variant: "error",
734
+ })
735
+ dialog.clear()
736
+ return
737
+ }
738
+
739
+ const base64 = Buffer.from(text).toString("base64")
740
+ const osc52 = `\x1b]52;c;${base64}\x07`
741
+ const finalOsc52 = process.env["TMUX"] ? `\x1bPtmux;\x1b${osc52}\x1b\\` : osc52
742
+ /* @ts-expect-error */
743
+ renderer.writeOut(finalOsc52)
744
+ Clipboard.copy(text)
745
+ .then(() => toast.show({ message: "Message copied to clipboard!", variant: "success" }))
746
+ .catch(() => toast.show({ message: "Failed to copy to clipboard", variant: "error" }))
747
+ dialog.clear()
748
+ },
749
+ },
750
+ {
751
+ title: "Copy session transcript",
752
+ value: "session.copy",
753
+ keybind: "session_copy",
754
+ category: "Session",
755
+ onSelect: async (dialog) => {
756
+ try {
757
+ // Format session transcript as markdown
758
+ const sessionData = session()
759
+ const sessionMessages = messages()
760
+
761
+ let transcript = `# ${sessionData.title}\n\n`
762
+ transcript += `**Session ID:** ${sessionData.id}\n`
763
+ transcript += `**Created:** ${new Date(sessionData.time.created).toLocaleString()}\n`
764
+ transcript += `**Updated:** ${new Date(sessionData.time.updated).toLocaleString()}\n\n`
765
+ transcript += `---\n\n`
766
+
767
+ for (const msg of sessionMessages) {
768
+ const parts = sync.data.part[msg.id] ?? []
769
+ const role = msg.role === "user" ? "User" : "Assistant"
770
+ transcript += `## ${role}\n\n`
771
+
772
+ for (const part of parts) {
773
+ if (part.type === "text" && !part.synthetic) {
774
+ transcript += `${part.text}\n\n`
775
+ } else if (part.type === "tool") {
776
+ transcript += `\`\`\`\nTool: ${part.tool}\n\`\`\`\n\n`
777
+ }
778
+ }
779
+
780
+ transcript += `---\n\n`
781
+ }
782
+
783
+ // Copy to clipboard
784
+ await Clipboard.copy(transcript)
785
+ toast.show({ message: "Session transcript copied to clipboard!", variant: "success" })
786
+ } catch (error) {
787
+ toast.show({ message: "Failed to copy session transcript", variant: "error" })
788
+ }
789
+ dialog.clear()
790
+ },
791
+ },
792
+ {
793
+ title: "Export session transcript to file",
794
+ value: "session.export",
795
+ keybind: "session_export",
796
+ category: "Session",
797
+ onSelect: async (dialog) => {
798
+ try {
799
+ // Format session transcript as markdown
800
+ const sessionData = session()
801
+ const sessionMessages = messages()
802
+
803
+ let transcript = `# ${sessionData.title}\n\n`
804
+ transcript += `**Session ID:** ${sessionData.id}\n`
805
+ transcript += `**Created:** ${new Date(sessionData.time.created).toLocaleString()}\n`
806
+ transcript += `**Updated:** ${new Date(sessionData.time.updated).toLocaleString()}\n\n`
807
+ transcript += `---\n\n`
808
+
809
+ for (const msg of sessionMessages) {
810
+ const parts = sync.data.part[msg.id] ?? []
811
+ const role = msg.role === "user" ? "User" : "Assistant"
812
+ transcript += `## ${role}\n\n`
813
+
814
+ for (const part of parts) {
815
+ if (part.type === "text" && !part.synthetic) {
816
+ transcript += `${part.text}\n\n`
817
+ } else if (part.type === "tool") {
818
+ transcript += `\`\`\`\nTool: ${part.tool}\n\`\`\`\n\n`
819
+ }
820
+ }
821
+
822
+ transcript += `---\n\n`
823
+ }
824
+
825
+ // Prompt for optional filename
826
+ const customFilename = await DialogPrompt.show(dialog, "Export filename", {
827
+ value: `session-${sessionData.id.slice(0, 8)}.md`,
828
+ })
829
+
830
+ // Cancel if user pressed escape
831
+ if (customFilename === null) return
832
+
833
+ // Save to file in current working directory
834
+ const exportDir = process.cwd()
835
+ const filename = customFilename.trim()
836
+ const filepath = path.join(exportDir, filename)
837
+
838
+ await Bun.write(filepath, transcript)
839
+
840
+ // Open with EDITOR if available
841
+ const result = await Editor.open({ value: transcript, renderer })
842
+ if (result !== undefined) {
843
+ // User edited the file, save the changes
844
+ await Bun.write(filepath, result)
845
+ }
846
+
847
+ toast.show({ message: `Session exported to ${filename}`, variant: "success" })
848
+ } catch (error) {
849
+ toast.show({ message: "Failed to export session", variant: "error" })
850
+ }
851
+ dialog.clear()
852
+ },
853
+ },
854
+ {
855
+ title: "Next child session",
856
+ value: "session.child.next",
857
+ keybind: "session_child_cycle",
858
+ category: "Session",
859
+ disabled: true,
860
+ onSelect: (dialog) => {
861
+ moveChild(1)
862
+ dialog.clear()
863
+ },
864
+ },
865
+ {
866
+ title: "Previous child session",
867
+ value: "session.child.previous",
868
+ keybind: "session_child_cycle_reverse",
869
+ category: "Session",
870
+ disabled: true,
871
+ onSelect: (dialog) => {
872
+ moveChild(-1)
873
+ dialog.clear()
874
+ },
875
+ },
876
+ {
877
+ title: "Go to parent session",
878
+ value: "session.parent",
879
+ keybind: "session_parent",
880
+ category: "Session",
881
+ disabled: true,
882
+ onSelect: (dialog) => {
883
+ const parentID = session()?.parentID
884
+ if (parentID) {
885
+ navigate({
886
+ type: "session",
887
+ sessionID: parentID,
888
+ })
889
+ }
890
+ dialog.clear()
891
+ },
892
+ },
893
+ ])
894
+
895
+ const revertInfo = createMemo(() => session()?.revert)
896
+ const revertMessageID = createMemo(() => revertInfo()?.messageID)
897
+
898
+ const revertDiffFiles = createMemo(() => {
899
+ const diffText = revertInfo()?.diff ?? ""
900
+ if (!diffText) return []
901
+
902
+ try {
903
+ const patches = parsePatch(diffText)
904
+ return patches.map((patch) => {
905
+ const filename = patch.newFileName || patch.oldFileName || "unknown"
906
+ const cleanFilename = filename.replace(/^[ab]\//, "")
907
+ return {
908
+ filename: cleanFilename,
909
+ additions: patch.hunks.reduce(
910
+ (sum, hunk) => sum + hunk.lines.filter((line) => line.startsWith("+")).length,
911
+ 0,
912
+ ),
913
+ deletions: patch.hunks.reduce(
914
+ (sum, hunk) => sum + hunk.lines.filter((line) => line.startsWith("-")).length,
915
+ 0,
916
+ ),
917
+ }
918
+ })
919
+ } catch (error) {
920
+ return []
921
+ }
922
+ })
923
+
924
+ const revertRevertedMessages = createMemo(() => {
925
+ const messageID = revertMessageID()
926
+ if (!messageID) return []
927
+ return messages().filter((x) => x.id >= messageID && x.role === "user")
928
+ })
929
+
930
+ const revert = createMemo(() => {
931
+ const info = revertInfo()
932
+ if (!info) return
933
+ if (!info.messageID) return
934
+ return {
935
+ messageID: info.messageID,
936
+ reverted: revertRevertedMessages(),
937
+ diff: info.diff,
938
+ diffFiles: revertDiffFiles(),
939
+ }
940
+ })
941
+
942
+ const dialog = useDialog()
943
+ const renderer = useRenderer()
944
+
945
+ // snap to bottom when session changes
946
+ createEffect(on(() => route.sessionID, toBottom))
947
+
948
+ return (
949
+ <context.Provider
950
+ value={{
951
+ get width() {
952
+ return contentWidth()
953
+ },
954
+ conceal,
955
+ showThinking,
956
+ showTimestamps,
957
+ usernameVisible,
958
+ showDetails,
959
+ userMessageMarkdown,
960
+ diffWrapMode,
961
+ sync,
962
+ }}
963
+ >
964
+ <box flexDirection="row">
965
+ <box flexGrow={1} paddingBottom={1} paddingTop={1} paddingLeft={2} paddingRight={2} gap={1}>
966
+ <Show when={session()}>
967
+ <Show when={!sidebarVisible() || sidebarOverlay()}>
968
+ <Header />
969
+ </Show>
970
+ <scrollbox
971
+ ref={(r) => (scroll = r)}
972
+ viewportOptions={{
973
+ paddingRight: showScrollbar() ? 1 : 0,
974
+ }}
975
+ verticalScrollbarOptions={{
976
+ paddingLeft: 1,
977
+ visible: showScrollbar(),
978
+ trackOptions: {
979
+ backgroundColor: theme.backgroundElement,
980
+ foregroundColor: theme.border,
981
+ },
982
+ }}
983
+ stickyScroll={true}
984
+ stickyStart="bottom"
985
+ flexGrow={1}
986
+ scrollAcceleration={scrollAcceleration()}
987
+ >
988
+ <For each={messages()}>
989
+ {(message, index) => (
990
+ <Switch>
991
+ <Match when={message.id === revert()?.messageID}>
992
+ {(function () {
993
+ const command = useCommandDialog()
994
+ const [hover, setHover] = createSignal(false)
995
+ const dialog = useDialog()
996
+
997
+ const handleUnrevert = async () => {
998
+ const confirmed = await DialogConfirm.show(
999
+ dialog,
1000
+ "Confirm Redo",
1001
+ "Are you sure you want to restore the reverted messages?",
1002
+ )
1003
+ if (confirmed) {
1004
+ command.trigger("session.redo")
1005
+ }
1006
+ }
1007
+
1008
+ return (
1009
+ <box
1010
+ onMouseOver={() => setHover(true)}
1011
+ onMouseOut={() => setHover(false)}
1012
+ onMouseUp={handleUnrevert}
1013
+ marginTop={1}
1014
+ flexShrink={0}
1015
+ border={["left"]}
1016
+ customBorderChars={SplitBorder.customBorderChars}
1017
+ borderColor={theme.backgroundPanel}
1018
+ >
1019
+ <box
1020
+ paddingTop={1}
1021
+ paddingBottom={1}
1022
+ paddingLeft={2}
1023
+ backgroundColor={hover() ? theme.backgroundElement : theme.backgroundPanel}
1024
+ >
1025
+ <text fg={theme.textMuted}>{revert()!.reverted.length} message reverted</text>
1026
+ <text fg={theme.textMuted}>
1027
+ <span style={{ fg: theme.text }}>{keybind.print("messages_redo")}</span> or /redo to
1028
+ restore
1029
+ </text>
1030
+ <Show when={revert()!.diffFiles?.length}>
1031
+ <box marginTop={1}>
1032
+ <For each={revert()!.diffFiles}>
1033
+ {(file) => (
1034
+ <text fg={theme.text}>
1035
+ {file.filename}
1036
+ <Show when={file.additions > 0}>
1037
+ <span style={{ fg: theme.diffAdded }}> +{file.additions}</span>
1038
+ </Show>
1039
+ <Show when={file.deletions > 0}>
1040
+ <span style={{ fg: theme.diffRemoved }}> -{file.deletions}</span>
1041
+ </Show>
1042
+ </text>
1043
+ )}
1044
+ </For>
1045
+ </box>
1046
+ </Show>
1047
+ </box>
1048
+ </box>
1049
+ )
1050
+ })()}
1051
+ </Match>
1052
+ <Match when={revert()?.messageID && message.id >= revert()!.messageID}>
1053
+ <></>
1054
+ </Match>
1055
+ <Match when={message.role === "user"}>
1056
+ <UserMessage
1057
+ index={index()}
1058
+ onMouseUp={() => {
1059
+ if (renderer.getSelection()?.getSelectedText()) return
1060
+ dialog.replace(() => (
1061
+ <DialogMessage
1062
+ messageID={message.id}
1063
+ sessionID={route.sessionID}
1064
+ setPrompt={(promptInfo) => prompt.set(promptInfo)}
1065
+ />
1066
+ ))
1067
+ }}
1068
+ message={message as UserMessage}
1069
+ parts={sync.data.part[message.id] ?? []}
1070
+ pending={pending()}
1071
+ />
1072
+ </Match>
1073
+ <Match when={message.role === "assistant"}>
1074
+ <AssistantMessage
1075
+ last={lastAssistant()?.id === message.id}
1076
+ message={message as AssistantMessage}
1077
+ parts={sync.data.part[message.id] ?? []}
1078
+ />
1079
+ </Match>
1080
+ </Switch>
1081
+ )}
1082
+ </For>
1083
+ </scrollbox>
1084
+ <box flexShrink={0}>
1085
+ <Prompt
1086
+ ref={(r) => {
1087
+ prompt = r
1088
+ promptRef.set(r)
1089
+ }}
1090
+ disabled={permissions().length > 0}
1091
+ onSubmit={() => {
1092
+ toBottom()
1093
+ }}
1094
+ sessionID={route.sessionID}
1095
+ />
1096
+ </box>
1097
+ <Show when={(!sidebarVisible() || sidebarOverlay()) && tall()}>
1098
+ <Footer />
1099
+ </Show>
1100
+ </Show>
1101
+ <Toast />
1102
+ </box>
1103
+ <Show when={sidebarVisible() && !sidebarOverlay()}>
1104
+ <Sidebar sessionID={route.sessionID} />
1105
+ </Show>
1106
+ <Show when={sidebarOverlay()}>
1107
+ <box
1108
+ position="absolute"
1109
+ left={0}
1110
+ top={0}
1111
+ width={dimensions().width}
1112
+ height={dimensions().height}
1113
+ backgroundColor={RGBA.fromInts(0, 0, 0, 150)}
1114
+ zIndex={100}
1115
+ flexDirection="row"
1116
+ justifyContent="flex-end"
1117
+ onMouseUp={() => setSidebar("hide")}
1118
+ >
1119
+ <box onMouseUp={(e) => e.stopPropagation()}>
1120
+ <Sidebar sessionID={route.sessionID} />
1121
+ </box>
1122
+ </box>
1123
+ </Show>
1124
+ </box>
1125
+ </context.Provider>
1126
+ )
1127
+ }
1128
+
1129
+ const MIME_BADGE: Record<string, string> = {
1130
+ "text/plain": "txt",
1131
+ "image/png": "img",
1132
+ "image/jpeg": "img",
1133
+ "image/gif": "img",
1134
+ "image/webp": "img",
1135
+ "application/pdf": "pdf",
1136
+ "application/x-directory": "dir",
1137
+ }
1138
+
1139
+ function UserMessage(props: {
1140
+ message: UserMessage
1141
+ parts: Part[]
1142
+ onMouseUp: () => void
1143
+ index: number
1144
+ pending?: string
1145
+ }) {
1146
+ const ctx = use()
1147
+ const local = useLocal()
1148
+ const text = createMemo(() => props.parts.flatMap((x) => (x.type === "text" && !x.synthetic ? [x] : []))[0])
1149
+ const files = createMemo(() => props.parts.flatMap((x) => (x.type === "file" ? [x] : [])))
1150
+ const sync = useSync()
1151
+ const { theme, syntax } = useTheme()
1152
+ const [hover, setHover] = createSignal(false)
1153
+ const queued = createMemo(() => props.pending && props.message.id > props.pending)
1154
+ const color = createMemo(() => (queued() ? theme.accent : local.agent.color(props.message.agent)))
1155
+
1156
+ const compaction = createMemo(() => props.parts.find((x) => x.type === "compaction"))
1157
+
1158
+ return (
1159
+ <>
1160
+ <Show when={text()}>
1161
+ <box
1162
+ id={props.message.id}
1163
+ border={["left"]}
1164
+ borderColor={color()}
1165
+ customBorderChars={SplitBorder.customBorderChars}
1166
+ marginTop={props.index === 0 ? 0 : 1}
1167
+ >
1168
+ <box
1169
+ onMouseOver={() => {
1170
+ setHover(true)
1171
+ }}
1172
+ onMouseOut={() => {
1173
+ setHover(false)
1174
+ }}
1175
+ onMouseUp={props.onMouseUp}
1176
+ paddingTop={1}
1177
+ paddingBottom={1}
1178
+ paddingLeft={2}
1179
+ backgroundColor={hover() ? theme.backgroundElement : theme.backgroundPanel}
1180
+ flexShrink={0}
1181
+ >
1182
+ <Switch>
1183
+ <Match when={ctx.userMessageMarkdown()}>
1184
+ <code
1185
+ filetype="markdown"
1186
+ drawUnstyledText={false}
1187
+ streaming={false}
1188
+ syntaxStyle={syntax()}
1189
+ content={text()?.text ?? ""}
1190
+ conceal={ctx.conceal()}
1191
+ fg={theme.text}
1192
+ />
1193
+ </Match>
1194
+ <Match when={!ctx.userMessageMarkdown()}>
1195
+ <text fg={theme.text}>{text()?.text}</text>
1196
+ </Match>
1197
+ </Switch>
1198
+ <Show when={files().length}>
1199
+ <box flexDirection="row" paddingBottom={1} paddingTop={1} gap={1} flexWrap="wrap">
1200
+ <For each={files()}>
1201
+ {(file) => {
1202
+ const bg = createMemo(() => {
1203
+ if (file.mime.startsWith("image/")) return theme.accent
1204
+ if (file.mime === "application/pdf") return theme.primary
1205
+ return theme.secondary
1206
+ })
1207
+ return (
1208
+ <text fg={theme.text}>
1209
+ <span style={{ bg: bg(), fg: theme.background }}> {MIME_BADGE[file.mime] ?? file.mime} </span>
1210
+ <span style={{ bg: theme.backgroundElement, fg: theme.textMuted }}> {file.filename} </span>
1211
+ </text>
1212
+ )
1213
+ }}
1214
+ </For>
1215
+ </box>
1216
+ </Show>
1217
+ <text fg={theme.textMuted}>
1218
+ {ctx.usernameVisible() ? `${sync.data.config.username ?? "You "}` : "You "}
1219
+ <Show
1220
+ when={queued()}
1221
+ fallback={
1222
+ <Show when={ctx.showTimestamps()}>
1223
+ <span style={{ fg: theme.textMuted }}>
1224
+ {ctx.usernameVisible() ? " · " : " "}
1225
+ {Locale.todayTimeOrDateTime(props.message.time.created)}
1226
+ </span>
1227
+ </Show>
1228
+ }
1229
+ >
1230
+ <span> </span>
1231
+ <span style={{ bg: theme.accent, fg: theme.backgroundPanel, bold: true }}> QUEUED </span>
1232
+ </Show>
1233
+ </text>
1234
+ </box>
1235
+ </box>
1236
+ </Show>
1237
+ <Show when={compaction()}>
1238
+ <box
1239
+ marginTop={1}
1240
+ border={["top"]}
1241
+ title=" Compaction "
1242
+ titleAlignment="center"
1243
+ borderColor={theme.borderActive}
1244
+ />
1245
+ </Show>
1246
+ </>
1247
+ )
1248
+ }
1249
+
1250
+ function AssistantMessage(props: { message: AssistantMessage; parts: Part[]; last: boolean }) {
1251
+ const local = useLocal()
1252
+ const { theme } = useTheme()
1253
+ const sync = useSync()
1254
+ const messages = createMemo(() => sync.data.message[props.message.sessionID] ?? [])
1255
+
1256
+ const final = createMemo(() => {
1257
+ return props.message.finish && !["tool-calls", "unknown"].includes(props.message.finish)
1258
+ })
1259
+
1260
+ const duration = createMemo(() => {
1261
+ if (!final()) return 0
1262
+ if (!props.message.time.completed) return 0
1263
+ const user = messages().find((x) => x.role === "user" && x.id === props.message.parentID)
1264
+ if (!user || !user.time) return 0
1265
+ return props.message.time.completed - user.time.created
1266
+ })
1267
+
1268
+ return (
1269
+ <>
1270
+ <For each={props.parts}>
1271
+ {(part, index) => {
1272
+ const component = createMemo(() => PART_MAPPING[part.type as keyof typeof PART_MAPPING])
1273
+ return (
1274
+ <Show when={component()}>
1275
+ <Dynamic
1276
+ last={index() === props.parts.length - 1}
1277
+ component={component()}
1278
+ part={part as any}
1279
+ message={props.message}
1280
+ />
1281
+ </Show>
1282
+ )
1283
+ }}
1284
+ </For>
1285
+ <Show when={props.message.error}>
1286
+ <box
1287
+ border={["left"]}
1288
+ paddingTop={1}
1289
+ paddingBottom={1}
1290
+ paddingLeft={2}
1291
+ marginTop={1}
1292
+ backgroundColor={theme.backgroundPanel}
1293
+ customBorderChars={SplitBorder.customBorderChars}
1294
+ borderColor={theme.error}
1295
+ >
1296
+ <text fg={theme.textMuted}>{props.message.error?.data.message}</text>
1297
+ </box>
1298
+ </Show>
1299
+ <Switch>
1300
+ <Match when={props.last || final()}>
1301
+ <box paddingLeft={3}>
1302
+ <text marginTop={1}>
1303
+ <span style={{ fg: local.agent.color(props.message.mode) }}>▣ </span>{" "}
1304
+ <span style={{ fg: theme.text }}>{Locale.titlecase(props.message.mode)}</span>
1305
+ <span style={{ fg: theme.textMuted }}> · {props.message.modelID}</span>
1306
+ <Show when={duration()}>
1307
+ <span style={{ fg: theme.textMuted }}> · {Locale.duration(duration())}</span>
1308
+ </Show>
1309
+ </text>
1310
+ </box>
1311
+ </Match>
1312
+ </Switch>
1313
+ </>
1314
+ )
1315
+ }
1316
+
1317
+ const PART_MAPPING = {
1318
+ text: TextPart,
1319
+ tool: ToolPart,
1320
+ reasoning: ReasoningPart,
1321
+ }
1322
+
1323
+ function ReasoningPart(props: { last: boolean; part: ReasoningPart; message: AssistantMessage }) {
1324
+ const { theme, subtleSyntax } = useTheme()
1325
+ const ctx = use()
1326
+ const content = createMemo(() => {
1327
+ // Filter out redacted reasoning chunks from OpenRouter
1328
+ // OpenRouter sends encrypted reasoning data that appears as [REDACTED]
1329
+ return props.part.text.replace("[REDACTED]", "").trim()
1330
+ })
1331
+ return (
1332
+ <Show when={content() && ctx.showThinking()}>
1333
+ <box
1334
+ id={"text-" + props.part.id}
1335
+ paddingLeft={2}
1336
+ marginTop={1}
1337
+ flexDirection="column"
1338
+ border={["left"]}
1339
+ customBorderChars={SplitBorder.customBorderChars}
1340
+ borderColor={theme.backgroundElement}
1341
+ >
1342
+ <code
1343
+ filetype="markdown"
1344
+ drawUnstyledText={false}
1345
+ streaming={true}
1346
+ syntaxStyle={subtleSyntax()}
1347
+ content={"_Thinking:_ " + content()}
1348
+ conceal={ctx.conceal()}
1349
+ fg={theme.textMuted}
1350
+ />
1351
+ </box>
1352
+ </Show>
1353
+ )
1354
+ }
1355
+
1356
+ function TextPart(props: { last: boolean; part: TextPart; message: AssistantMessage }) {
1357
+ const ctx = use()
1358
+ const { theme, syntax } = useTheme()
1359
+ return (
1360
+ <Show when={props.part.text.trim()}>
1361
+ <box id={"text-" + props.part.id} paddingLeft={3} marginTop={1} flexShrink={0}>
1362
+ <code
1363
+ filetype="markdown"
1364
+ drawUnstyledText={false}
1365
+ streaming={true}
1366
+ syntaxStyle={syntax()}
1367
+ content={props.part.text.trim()}
1368
+ conceal={ctx.conceal()}
1369
+ fg={theme.text}
1370
+ />
1371
+ </box>
1372
+ </Show>
1373
+ )
1374
+ }
1375
+
1376
+ // Pending messages moved to individual tool pending functions
1377
+
1378
+ function ToolPart(props: { last: boolean; part: ToolPart; message: AssistantMessage }) {
1379
+ const { theme } = useTheme()
1380
+ const { showDetails } = use()
1381
+ const sync = useSync()
1382
+ const [margin, setMargin] = createSignal(0)
1383
+ const component = createMemo(() => {
1384
+ // Hide tool if showDetails is false and tool completed successfully
1385
+ // But always show if there's an error or permission is required
1386
+ const shouldHide =
1387
+ !showDetails() &&
1388
+ props.part.state.status === "completed" &&
1389
+ !sync.data.permission[props.message.sessionID]?.some((x) => x.callID === props.part.callID)
1390
+
1391
+ if (shouldHide) {
1392
+ return undefined
1393
+ }
1394
+
1395
+ const render = ToolRegistry.render(props.part.tool) ?? GenericTool
1396
+
1397
+ const metadata = props.part.state.status === "pending" ? {} : (props.part.state.metadata ?? {})
1398
+ const input = props.part.state.input ?? {}
1399
+ const container = ToolRegistry.container(props.part.tool)
1400
+ const permissions = sync.data.permission[props.message.sessionID] ?? []
1401
+ const permissionIndex = permissions.findIndex((x) => x.callID === props.part.callID)
1402
+ const permission = permissions[permissionIndex]
1403
+
1404
+ const style: BoxProps =
1405
+ container === "block" || permission
1406
+ ? {
1407
+ border: permissionIndex === 0 ? (["left", "right"] as const) : (["left"] as const),
1408
+ paddingTop: 1,
1409
+ paddingBottom: 1,
1410
+ paddingLeft: 2,
1411
+ marginTop: 1,
1412
+ gap: 1,
1413
+ backgroundColor: theme.backgroundPanel,
1414
+ customBorderChars: SplitBorder.customBorderChars,
1415
+ borderColor: permissionIndex === 0 ? theme.warning : theme.background,
1416
+ }
1417
+ : {
1418
+ paddingLeft: 3,
1419
+ }
1420
+
1421
+ return (
1422
+ <box
1423
+ marginTop={margin()}
1424
+ {...style}
1425
+ renderBefore={function () {
1426
+ const el = this as BoxRenderable
1427
+ const parent = el.parent
1428
+ if (!parent) {
1429
+ return
1430
+ }
1431
+ if (el.height > 1) {
1432
+ setMargin(1)
1433
+ return
1434
+ }
1435
+ const children = parent.getChildren()
1436
+ const index = children.indexOf(el)
1437
+ const previous = children[index - 1]
1438
+ if (!previous) {
1439
+ setMargin(0)
1440
+ return
1441
+ }
1442
+ if (previous.height > 1 || previous.id.startsWith("text-")) {
1443
+ setMargin(1)
1444
+ return
1445
+ }
1446
+ }}
1447
+ >
1448
+ <Dynamic
1449
+ component={render}
1450
+ input={input}
1451
+ tool={props.part.tool}
1452
+ metadata={metadata}
1453
+ permission={permission?.metadata ?? {}}
1454
+ output={props.part.state.status === "completed" ? props.part.state.output : undefined}
1455
+ />
1456
+ {props.part.state.status === "error" && (
1457
+ <box paddingLeft={2}>
1458
+ <text fg={theme.error}>{props.part.state.error.replace("Error: ", "")}</text>
1459
+ </box>
1460
+ )}
1461
+ {permission && (
1462
+ <box gap={1}>
1463
+ <text fg={theme.text}>Permission required to run this tool:</text>
1464
+ <box flexDirection="row" gap={2}>
1465
+ <text fg={theme.text}>
1466
+ <b>enter</b>
1467
+ <span style={{ fg: theme.textMuted }}> accept</span>
1468
+ </text>
1469
+ <text fg={theme.text}>
1470
+ <b>a</b>
1471
+ <span style={{ fg: theme.textMuted }}> accept always</span>
1472
+ </text>
1473
+ <text fg={theme.text}>
1474
+ <b>d</b>
1475
+ <span style={{ fg: theme.textMuted }}> deny</span>
1476
+ </text>
1477
+ </box>
1478
+ </box>
1479
+ )}
1480
+ </box>
1481
+ )
1482
+ })
1483
+
1484
+ return <Show when={component()}>{component()}</Show>
1485
+ }
1486
+
1487
+ type ToolProps<T extends Tool.Info> = {
1488
+ input: Partial<Tool.InferParameters<T>>
1489
+ metadata: Partial<Tool.InferMetadata<T>>
1490
+ permission: Record<string, any>
1491
+ tool: string
1492
+ output?: string
1493
+ }
1494
+ function GenericTool(props: ToolProps<any>) {
1495
+ return (
1496
+ <ToolTitle icon="⚙" fallback="Writing command..." when={true}>
1497
+ {props.tool} {input(props.input)}
1498
+ </ToolTitle>
1499
+ )
1500
+ }
1501
+
1502
+ type ToolRegistration<T extends Tool.Info = any> = {
1503
+ name: string
1504
+ container: "inline" | "block"
1505
+ render?: Component<ToolProps<T>>
1506
+ }
1507
+ const ToolRegistry = (() => {
1508
+ const state: Record<string, ToolRegistration> = {}
1509
+ function register<T extends Tool.Info>(input: ToolRegistration<T>) {
1510
+ state[input.name] = input
1511
+ return input
1512
+ }
1513
+ return {
1514
+ register,
1515
+ container(name: string) {
1516
+ return state[name]?.container
1517
+ },
1518
+ render(name: string) {
1519
+ return state[name]?.render
1520
+ },
1521
+ }
1522
+ })()
1523
+
1524
+ function ToolTitle(props: { fallback: string; when: any; icon: string; children: JSX.Element }) {
1525
+ const { theme } = useTheme()
1526
+ return (
1527
+ <text paddingLeft={3} fg={props.when ? theme.textMuted : theme.text}>
1528
+ <Show fallback={<>~ {props.fallback}</>} when={props.when}>
1529
+ <span style={{ bold: true }}>{props.icon}</span> {props.children}
1530
+ </Show>
1531
+ </text>
1532
+ )
1533
+ }
1534
+
1535
+ ToolRegistry.register<typeof BashTool>({
1536
+ name: "bash",
1537
+ container: "block",
1538
+ render(props) {
1539
+ const output = createMemo(() => stripAnsi(props.metadata.output?.trim() ?? ""))
1540
+ const { theme } = useTheme()
1541
+ return (
1542
+ <>
1543
+ <ToolTitle icon="#" fallback="Writing command..." when={props.input.command}>
1544
+ {props.input.description || "Shell"}
1545
+ </ToolTitle>
1546
+ <Show when={props.input.command}>
1547
+ <text fg={theme.text}>$ {props.input.command}</text>
1548
+ </Show>
1549
+ <Show when={output()}>
1550
+ <box>
1551
+ <text fg={theme.text}>{output()}</text>
1552
+ </box>
1553
+ </Show>
1554
+ </>
1555
+ )
1556
+ },
1557
+ })
1558
+
1559
+ ToolRegistry.register<typeof ReadTool>({
1560
+ name: "read",
1561
+ container: "inline",
1562
+ render(props) {
1563
+ return (
1564
+ <>
1565
+ <ToolTitle icon="→" fallback="Reading file..." when={props.input.filePath}>
1566
+ Read {normalizePath(props.input.filePath!)} {input(props.input, ["filePath"])}
1567
+ </ToolTitle>
1568
+ </>
1569
+ )
1570
+ },
1571
+ })
1572
+
1573
+ ToolRegistry.register<typeof WriteTool>({
1574
+ name: "write",
1575
+ container: "block",
1576
+ render(props) {
1577
+ const { theme, syntax } = useTheme()
1578
+ const code = createMemo(() => {
1579
+ if (!props.input.content) return ""
1580
+ return props.input.content
1581
+ })
1582
+
1583
+ const diagnostics = createMemo(() => {
1584
+ const filePath = Filesystem.normalizePath(props.input.filePath ?? "")
1585
+ return props.metadata.diagnostics?.[filePath] ?? []
1586
+ })
1587
+
1588
+ const done = !!props.input.filePath
1589
+
1590
+ return (
1591
+ <>
1592
+ <ToolTitle icon="←" fallback="Preparing write..." when={done}>
1593
+ Wrote {props.input.filePath}
1594
+ </ToolTitle>
1595
+ <Show when={done}>
1596
+ <line_number fg={theme.textMuted} minWidth={3} paddingRight={1}>
1597
+ <code
1598
+ conceal={false}
1599
+ fg={theme.text}
1600
+ filetype={filetype(props.input.filePath!)}
1601
+ syntaxStyle={syntax()}
1602
+ content={code()}
1603
+ />
1604
+ </line_number>
1605
+ </Show>
1606
+ <Show when={diagnostics().length}>
1607
+ <For each={diagnostics()}>
1608
+ {(diagnostic) => (
1609
+ <text fg={theme.error}>
1610
+ Error [{diagnostic.range.start.line}:{diagnostic.range.start.character}]: {diagnostic.message}
1611
+ </text>
1612
+ )}
1613
+ </For>
1614
+ </Show>
1615
+ </>
1616
+ )
1617
+ },
1618
+ })
1619
+
1620
+ ToolRegistry.register<typeof GlobTool>({
1621
+ name: "glob",
1622
+ container: "inline",
1623
+ render(props) {
1624
+ return (
1625
+ <>
1626
+ <ToolTitle icon="✱" fallback="Finding files..." when={props.input.pattern}>
1627
+ Glob "{props.input.pattern}" <Show when={props.input.path}>in {normalizePath(props.input.path)} </Show>
1628
+ <Show when={props.metadata.count}>({props.metadata.count} matches)</Show>
1629
+ </ToolTitle>
1630
+ </>
1631
+ )
1632
+ },
1633
+ })
1634
+
1635
+ ToolRegistry.register<typeof GrepTool>({
1636
+ name: "grep",
1637
+ container: "inline",
1638
+ render(props) {
1639
+ return (
1640
+ <ToolTitle icon="✱" fallback="Searching content..." when={props.input.pattern}>
1641
+ Grep "{props.input.pattern}" <Show when={props.input.path}>in {normalizePath(props.input.path)} </Show>
1642
+ <Show when={props.metadata.matches}>({props.metadata.matches} matches)</Show>
1643
+ </ToolTitle>
1644
+ )
1645
+ },
1646
+ })
1647
+
1648
+ ToolRegistry.register<typeof ListTool>({
1649
+ name: "list",
1650
+ container: "inline",
1651
+ render(props) {
1652
+ const dir = createMemo(() => {
1653
+ if (props.input.path) {
1654
+ return normalizePath(props.input.path)
1655
+ }
1656
+ return ""
1657
+ })
1658
+ return (
1659
+ <>
1660
+ <ToolTitle icon="→" fallback="Listing directory..." when={props.input.path !== undefined}>
1661
+ List {dir()}
1662
+ </ToolTitle>
1663
+ </>
1664
+ )
1665
+ },
1666
+ })
1667
+
1668
+ ToolRegistry.register<typeof TaskTool>({
1669
+ name: "task",
1670
+ container: "block",
1671
+ render(props) {
1672
+ const { theme } = useTheme()
1673
+ const keybind = useKeybind()
1674
+ const dialog = useDialog()
1675
+ const renderer = useRenderer()
1676
+
1677
+ return (
1678
+ <>
1679
+ <ToolTitle icon="◉" fallback="Delegating..." when={props.input.subagent_type ?? props.input.description}>
1680
+ {Locale.titlecase(props.input.subagent_type ?? "unknown")} Task "{props.input.description}"
1681
+ </ToolTitle>
1682
+ <Show when={props.metadata.summary?.length}>
1683
+ <box>
1684
+ <For each={props.metadata.summary ?? []}>
1685
+ {(task, index) => {
1686
+ const summary = props.metadata.summary ?? []
1687
+ return (
1688
+ <text style={{ fg: task.state.status === "error" ? theme.error : theme.textMuted }}>
1689
+ {index() === summary.length - 1 ? "└" : "├"} {Locale.titlecase(task.tool)}{" "}
1690
+ {task.state.status === "completed" ? task.state.title : ""}
1691
+ </text>
1692
+ )
1693
+ }}
1694
+ </For>
1695
+ </box>
1696
+ </Show>
1697
+ <text fg={theme.text}>
1698
+ {keybind.print("session_child_cycle")}, {keybind.print("session_child_cycle_reverse")}
1699
+ <span style={{ fg: theme.textMuted }}> to navigate between subagent sessions</span>
1700
+ </text>
1701
+ </>
1702
+ )
1703
+ },
1704
+ })
1705
+
1706
+ ToolRegistry.register<typeof WebFetchTool>({
1707
+ name: "webfetch",
1708
+ container: "inline",
1709
+ render(props) {
1710
+ return (
1711
+ <ToolTitle icon="%" fallback="Fetching from the web..." when={(props.input as any).url}>
1712
+ WebFetch {(props.input as any).url}
1713
+ </ToolTitle>
1714
+ )
1715
+ },
1716
+ })
1717
+
1718
+ ToolRegistry.register({
1719
+ name: "codesearch",
1720
+ container: "inline",
1721
+ render(props: ToolProps<any>) {
1722
+ const input = props.input as any
1723
+ const metadata = props.metadata as any
1724
+ return (
1725
+ <ToolTitle icon="◇" fallback="Searching code..." when={input.query}>
1726
+ Exa Code Search "{input.query}" <Show when={metadata.results}>({metadata.results} results)</Show>
1727
+ </ToolTitle>
1728
+ )
1729
+ },
1730
+ })
1731
+
1732
+ ToolRegistry.register({
1733
+ name: "websearch",
1734
+ container: "inline",
1735
+ render(props: ToolProps<any>) {
1736
+ const input = props.input as any
1737
+ const metadata = props.metadata as any
1738
+ return (
1739
+ <ToolTitle icon="◈" fallback="Searching web..." when={input.query}>
1740
+ Exa Web Search "{input.query}" <Show when={metadata.numResults}>({metadata.numResults} results)</Show>
1741
+ </ToolTitle>
1742
+ )
1743
+ },
1744
+ })
1745
+
1746
+ ToolRegistry.register<typeof EditTool>({
1747
+ name: "edit",
1748
+ container: "block",
1749
+ render(props) {
1750
+ const ctx = use()
1751
+ const { theme, syntax } = useTheme()
1752
+
1753
+ const view = createMemo(() => {
1754
+ const diffStyle = ctx.sync.data.config.tui?.diff_style
1755
+ if (diffStyle === "stacked") return "unified"
1756
+ // Default to "auto" behavior
1757
+ return ctx.width > 120 ? "split" : "unified"
1758
+ })
1759
+
1760
+ const ft = createMemo(() => filetype(props.input.filePath))
1761
+
1762
+ const diffContent = createMemo(() => props.metadata.diff ?? props.permission["diff"])
1763
+
1764
+ const diagnostics = createMemo(() => {
1765
+ const filePath = Filesystem.normalizePath(props.input.filePath ?? "")
1766
+ const arr = props.metadata.diagnostics?.[filePath] ?? []
1767
+ return arr.filter((x) => x.severity === 1).slice(0, 3)
1768
+ })
1769
+
1770
+ return (
1771
+ <>
1772
+ <ToolTitle icon="←" fallback="Preparing edit..." when={props.input.filePath}>
1773
+ Edit {normalizePath(props.input.filePath!)}{" "}
1774
+ {input({
1775
+ replaceAll: props.input.replaceAll,
1776
+ })}
1777
+ </ToolTitle>
1778
+ <Show when={diffContent()}>
1779
+ <box paddingLeft={1}>
1780
+ <diff
1781
+ diff={diffContent()}
1782
+ view={view()}
1783
+ filetype={ft()}
1784
+ syntaxStyle={syntax()}
1785
+ showLineNumbers={true}
1786
+ width="100%"
1787
+ wrapMode={ctx.diffWrapMode()}
1788
+ fg={theme.text}
1789
+ addedBg={theme.diffAddedBg}
1790
+ removedBg={theme.diffRemovedBg}
1791
+ contextBg={theme.diffContextBg}
1792
+ addedSignColor={theme.diffHighlightAdded}
1793
+ removedSignColor={theme.diffHighlightRemoved}
1794
+ lineNumberFg={theme.diffLineNumber}
1795
+ lineNumberBg={theme.diffContextBg}
1796
+ addedLineNumberBg={theme.diffAddedLineNumberBg}
1797
+ removedLineNumberBg={theme.diffRemovedLineNumberBg}
1798
+ />
1799
+ </box>
1800
+ </Show>
1801
+ <Show when={diagnostics().length}>
1802
+ <box>
1803
+ <For each={diagnostics()}>
1804
+ {(diagnostic) => (
1805
+ <text fg={theme.error}>
1806
+ Error [{diagnostic.range.start.line + 1}:{diagnostic.range.start.character + 1}] {diagnostic.message}
1807
+ </text>
1808
+ )}
1809
+ </For>
1810
+ </box>
1811
+ </Show>
1812
+ </>
1813
+ )
1814
+ },
1815
+ })
1816
+
1817
+ ToolRegistry.register<typeof PatchTool>({
1818
+ name: "patch",
1819
+ container: "block",
1820
+ render(props) {
1821
+ const { theme } = useTheme()
1822
+ return (
1823
+ <>
1824
+ <ToolTitle icon="%" fallback="Preparing patch..." when={true}>
1825
+ Patch
1826
+ </ToolTitle>
1827
+ <Show when={props.output}>
1828
+ <box>
1829
+ <text fg={theme.text}>{props.output?.trim()}</text>
1830
+ </box>
1831
+ </Show>
1832
+ </>
1833
+ )
1834
+ },
1835
+ })
1836
+
1837
+ ToolRegistry.register<typeof TodoWriteTool>({
1838
+ name: "todowrite",
1839
+ container: "block",
1840
+ render(props) {
1841
+ const { theme } = useTheme()
1842
+ return (
1843
+ <>
1844
+ <Show when={!props.input.todos?.length}>
1845
+ <ToolTitle icon="⚙" fallback="Updating todos..." when={true}>
1846
+ Updating todos...
1847
+ </ToolTitle>
1848
+ </Show>
1849
+ <Show when={props.metadata.todos?.length}>
1850
+ <box>
1851
+ <For each={props.input.todos ?? []}>
1852
+ {(todo) => (
1853
+ <text style={{ fg: todo.status === "in_progress" ? theme.success : theme.textMuted }}>
1854
+ [{todo.status === "completed" ? "✓" : " "}] {todo.content}
1855
+ </text>
1856
+ )}
1857
+ </For>
1858
+ </box>
1859
+ </Show>
1860
+ </>
1861
+ )
1862
+ },
1863
+ })
1864
+
1865
+ function normalizePath(input?: string) {
1866
+ if (!input) return ""
1867
+ if (path.isAbsolute(input)) {
1868
+ return path.relative(process.cwd(), input) || "."
1869
+ }
1870
+ return input
1871
+ }
1872
+
1873
+ function input(input: Record<string, any>, omit?: string[]): string {
1874
+ const primitives = Object.entries(input).filter(([key, value]) => {
1875
+ if (omit?.includes(key)) return false
1876
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean"
1877
+ })
1878
+ if (primitives.length === 0) return ""
1879
+ return `[${primitives.map(([key, value]) => `${key}=${value}`).join(", ")}]`
1880
+ }
1881
+
1882
+ function filetype(input?: string) {
1883
+ if (!input) return "none"
1884
+ const ext = path.extname(input)
1885
+ const language = LANGUAGE_EXTENSIONS[ext]
1886
+ if (["typescriptreact", "javascriptreact", "javascript"].includes(language)) return "typescript"
1887
+ return language
1888
+ }