mastracode 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (336) hide show
  1. package/AGENTS.md +27 -0
  2. package/Dockerfile +18 -0
  3. package/README.md +15 -0
  4. package/bin/opencode +84 -0
  5. package/bunfig.toml +4 -0
  6. package/package.json +113 -0
  7. package/parsers-config.ts +239 -0
  8. package/script/build.ts +167 -0
  9. package/script/postinstall.mjs +122 -0
  10. package/script/publish-registries.ts +187 -0
  11. package/script/publish.ts +70 -0
  12. package/script/schema.ts +47 -0
  13. package/src/acp/README.md +164 -0
  14. package/src/acp/agent.ts +1051 -0
  15. package/src/acp/session.ts +101 -0
  16. package/src/acp/types.ts +22 -0
  17. package/src/agent/agent.ts +398 -0
  18. package/src/agent/generate.txt +75 -0
  19. package/src/agent/prompt/compaction.txt +12 -0
  20. package/src/agent/prompt/explore.txt +18 -0
  21. package/src/agent/prompt/summary.txt +10 -0
  22. package/src/agent/prompt/title.txt +36 -0
  23. package/src/auth/index.ts +70 -0
  24. package/src/bun/index.ts +114 -0
  25. package/src/bus/bus-event.ts +43 -0
  26. package/src/bus/global.ts +10 -0
  27. package/src/bus/index.ts +105 -0
  28. package/src/cli/bootstrap.ts +17 -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 +391 -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 +1408 -0
  44. package/src/cli/cmd/import.ts +98 -0
  45. package/src/cli/cmd/mcp.ts +654 -0
  46. package/src/cli/cmd/models.ts +77 -0
  47. package/src/cli/cmd/pr.ts +112 -0
  48. package/src/cli/cmd/run.ts +368 -0
  49. package/src/cli/cmd/serve.ts +31 -0
  50. package/src/cli/cmd/session.ts +106 -0
  51. package/src/cli/cmd/stats.ts +298 -0
  52. package/src/cli/cmd/tui/app.tsx +686 -0
  53. package/src/cli/cmd/tui/attach.ts +30 -0
  54. package/src/cli/cmd/tui/component/border.tsx +21 -0
  55. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  56. package/src/cli/cmd/tui/component/dialog-command.tsx +124 -0
  57. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  58. package/src/cli/cmd/tui/component/dialog-model.tsx +230 -0
  59. package/src/cli/cmd/tui/component/dialog-provider.tsx +224 -0
  60. package/src/cli/cmd/tui/component/dialog-session-list.tsx +102 -0
  61. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  62. package/src/cli/cmd/tui/component/dialog-stash.tsx +86 -0
  63. package/src/cli/cmd/tui/component/dialog-status.tsx +162 -0
  64. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  65. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  66. package/src/cli/cmd/tui/component/did-you-know.tsx +85 -0
  67. package/src/cli/cmd/tui/component/logo.tsx +27 -0
  68. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +574 -0
  69. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  70. package/src/cli/cmd/tui/component/prompt/index.tsx +1117 -0
  71. package/src/cli/cmd/tui/component/prompt/stash.tsx +101 -0
  72. package/src/cli/cmd/tui/component/tips.ts +103 -0
  73. package/src/cli/cmd/tui/component/todo-item.tsx +32 -0
  74. package/src/cli/cmd/tui/context/args.tsx +14 -0
  75. package/src/cli/cmd/tui/context/directory.ts +13 -0
  76. package/src/cli/cmd/tui/context/exit.tsx +23 -0
  77. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  78. package/src/cli/cmd/tui/context/keybind.tsx +101 -0
  79. package/src/cli/cmd/tui/context/kv.tsx +49 -0
  80. package/src/cli/cmd/tui/context/local.tsx +339 -0
  81. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  82. package/src/cli/cmd/tui/context/route.tsx +46 -0
  83. package/src/cli/cmd/tui/context/sdk.tsx +74 -0
  84. package/src/cli/cmd/tui/context/sync.tsx +372 -0
  85. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  86. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  87. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  88. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  89. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  90. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  91. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  92. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  93. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  94. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  95. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  96. package/src/cli/cmd/tui/context/theme/gruvbox.json +95 -0
  97. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  98. package/src/cli/cmd/tui/context/theme/lucent-orng.json +227 -0
  99. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  100. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  101. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  102. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  103. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  104. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  105. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  106. package/src/cli/cmd/tui/context/theme/orng.json +245 -0
  107. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  108. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  109. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  110. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  111. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  112. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  113. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  114. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  115. package/src/cli/cmd/tui/context/theme.tsx +1109 -0
  116. package/src/cli/cmd/tui/event.ts +40 -0
  117. package/src/cli/cmd/tui/routes/home.tsx +140 -0
  118. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +64 -0
  119. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +109 -0
  120. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  121. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  122. package/src/cli/cmd/tui/routes/session/footer.tsx +88 -0
  123. package/src/cli/cmd/tui/routes/session/header.tsx +141 -0
  124. package/src/cli/cmd/tui/routes/session/index.tsx +1885 -0
  125. package/src/cli/cmd/tui/routes/session/sidebar.tsx +322 -0
  126. package/src/cli/cmd/tui/spawn.ts +60 -0
  127. package/src/cli/cmd/tui/thread.ts +120 -0
  128. package/src/cli/cmd/tui/ui/dialog-alert.tsx +57 -0
  129. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +83 -0
  130. package/src/cli/cmd/tui/ui/dialog-help.tsx +38 -0
  131. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +77 -0
  132. package/src/cli/cmd/tui/ui/dialog-select.tsx +332 -0
  133. package/src/cli/cmd/tui/ui/dialog.tsx +170 -0
  134. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  135. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  136. package/src/cli/cmd/tui/util/clipboard.ts +127 -0
  137. package/src/cli/cmd/tui/util/editor.ts +32 -0
  138. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  139. package/src/cli/cmd/tui/worker.ts +63 -0
  140. package/src/cli/cmd/uninstall.ts +344 -0
  141. package/src/cli/cmd/upgrade.ts +67 -0
  142. package/src/cli/cmd/web.ts +84 -0
  143. package/src/cli/error.ts +56 -0
  144. package/src/cli/ui.ts +84 -0
  145. package/src/cli/upgrade.ts +25 -0
  146. package/src/command/index.ts +80 -0
  147. package/src/command/template/initialize.txt +10 -0
  148. package/src/command/template/review.txt +97 -0
  149. package/src/config/config.ts +997 -0
  150. package/src/config/markdown.ts +41 -0
  151. package/src/env/index.ts +26 -0
  152. package/src/file/ignore.ts +83 -0
  153. package/src/file/index.ts +328 -0
  154. package/src/file/ripgrep.ts +393 -0
  155. package/src/file/time.ts +64 -0
  156. package/src/file/watcher.ts +103 -0
  157. package/src/flag/flag.ts +46 -0
  158. package/src/format/formatter.ts +315 -0
  159. package/src/format/index.ts +137 -0
  160. package/src/global/index.ts +52 -0
  161. package/src/id/id.ts +73 -0
  162. package/src/ide/index.ts +76 -0
  163. package/src/index.ts +158 -0
  164. package/src/installation/index.ts +196 -0
  165. package/src/lsp/client.ts +229 -0
  166. package/src/lsp/index.ts +485 -0
  167. package/src/lsp/language.ts +116 -0
  168. package/src/lsp/server.ts +1895 -0
  169. package/src/mcp/auth.ts +135 -0
  170. package/src/mcp/index.ts +654 -0
  171. package/src/mcp/oauth-callback.ts +200 -0
  172. package/src/mcp/oauth-provider.ts +154 -0
  173. package/src/patch/index.ts +622 -0
  174. package/src/permission/index.ts +199 -0
  175. package/src/plugin/index.ts +91 -0
  176. package/src/project/bootstrap.ts +31 -0
  177. package/src/project/instance.ts +78 -0
  178. package/src/project/project.ts +221 -0
  179. package/src/project/state.ts +65 -0
  180. package/src/project/vcs.ts +76 -0
  181. package/src/provider/auth.ts +143 -0
  182. package/src/provider/models-macro.ts +11 -0
  183. package/src/provider/models.ts +106 -0
  184. package/src/provider/provider.ts +1056 -0
  185. package/src/provider/sdk/openai-compatible/src/README.md +5 -0
  186. package/src/provider/sdk/openai-compatible/src/index.ts +2 -0
  187. package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +100 -0
  188. package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +303 -0
  189. package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +22 -0
  190. package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +18 -0
  191. package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +22 -0
  192. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +207 -0
  193. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +1713 -0
  194. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +177 -0
  195. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +1 -0
  196. package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +88 -0
  197. package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +128 -0
  198. package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +115 -0
  199. package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +65 -0
  200. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +104 -0
  201. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +103 -0
  202. package/src/provider/transform.ts +455 -0
  203. package/src/pty/index.ts +231 -0
  204. package/src/server/error.ts +36 -0
  205. package/src/server/project.ts +79 -0
  206. package/src/server/server.ts +2642 -0
  207. package/src/server/tui.ts +71 -0
  208. package/src/session/compaction.ts +223 -0
  209. package/src/session/index.ts +458 -0
  210. package/src/session/llm-mastra.ts +412 -0
  211. package/src/session/llm-shared.ts +172 -0
  212. package/src/session/llm.ts +439 -0
  213. package/src/session/message-v2.ts +675 -0
  214. package/src/session/message.ts +189 -0
  215. package/src/session/processor.ts +171 -0
  216. package/src/session/prompt/anthropic-20250930.txt +166 -0
  217. package/src/session/prompt/anthropic.txt +105 -0
  218. package/src/session/prompt/anthropic_spoof.txt +1 -0
  219. package/src/session/prompt/beast.txt +147 -0
  220. package/src/session/prompt/build-switch.txt +5 -0
  221. package/src/session/prompt/codex.txt +318 -0
  222. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  223. package/src/session/prompt/gemini.txt +155 -0
  224. package/src/session/prompt/max-steps.txt +16 -0
  225. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  226. package/src/session/prompt/plan.txt +26 -0
  227. package/src/session/prompt/polaris.txt +107 -0
  228. package/src/session/prompt/qwen.txt +109 -0
  229. package/src/session/prompt.ts +1454 -0
  230. package/src/session/retry.ts +86 -0
  231. package/src/session/revert.ts +108 -0
  232. package/src/session/status.ts +76 -0
  233. package/src/session/summary.ts +194 -0
  234. package/src/session/system.ts +120 -0
  235. package/src/session/todo.ts +37 -0
  236. package/src/share/share-next.ts +194 -0
  237. package/src/share/share.ts +87 -0
  238. package/src/shell/shell.ts +67 -0
  239. package/src/skill/index.ts +1 -0
  240. package/src/skill/skill.ts +83 -0
  241. package/src/snapshot/index.ts +197 -0
  242. package/src/storage/storage.ts +226 -0
  243. package/src/tool/bash.ts +306 -0
  244. package/src/tool/bash.txt +158 -0
  245. package/src/tool/batch.ts +175 -0
  246. package/src/tool/batch.txt +24 -0
  247. package/src/tool/codesearch.ts +138 -0
  248. package/src/tool/codesearch.txt +12 -0
  249. package/src/tool/edit.ts +675 -0
  250. package/src/tool/edit.txt +10 -0
  251. package/src/tool/glob.ts +65 -0
  252. package/src/tool/glob.txt +6 -0
  253. package/src/tool/grep.ts +121 -0
  254. package/src/tool/grep.txt +8 -0
  255. package/src/tool/invalid.ts +17 -0
  256. package/src/tool/ls.ts +110 -0
  257. package/src/tool/ls.txt +1 -0
  258. package/src/tool/lsp-diagnostics.ts +26 -0
  259. package/src/tool/lsp-diagnostics.txt +1 -0
  260. package/src/tool/lsp-hover.ts +31 -0
  261. package/src/tool/lsp-hover.txt +1 -0
  262. package/src/tool/lsp.ts +87 -0
  263. package/src/tool/lsp.txt +19 -0
  264. package/src/tool/multiedit.ts +46 -0
  265. package/src/tool/multiedit.txt +41 -0
  266. package/src/tool/patch.ts +233 -0
  267. package/src/tool/patch.txt +1 -0
  268. package/src/tool/read.ts +219 -0
  269. package/src/tool/read.txt +12 -0
  270. package/src/tool/registry.ts +162 -0
  271. package/src/tool/skill.ts +100 -0
  272. package/src/tool/task.ts +136 -0
  273. package/src/tool/task.txt +60 -0
  274. package/src/tool/todo.ts +39 -0
  275. package/src/tool/todoread.txt +14 -0
  276. package/src/tool/todowrite.txt +167 -0
  277. package/src/tool/tool.ts +71 -0
  278. package/src/tool/webfetch.ts +187 -0
  279. package/src/tool/webfetch.txt +13 -0
  280. package/src/tool/websearch.ts +150 -0
  281. package/src/tool/websearch.txt +11 -0
  282. package/src/tool/write.ts +110 -0
  283. package/src/tool/write.txt +8 -0
  284. package/src/util/archive.ts +16 -0
  285. package/src/util/color.ts +19 -0
  286. package/src/util/context.ts +25 -0
  287. package/src/util/defer.ts +12 -0
  288. package/src/util/eventloop.ts +20 -0
  289. package/src/util/filesystem.ts +83 -0
  290. package/src/util/fn.ts +11 -0
  291. package/src/util/iife.ts +3 -0
  292. package/src/util/keybind.ts +102 -0
  293. package/src/util/lazy.ts +11 -0
  294. package/src/util/locale.ts +81 -0
  295. package/src/util/lock.ts +98 -0
  296. package/src/util/log.ts +180 -0
  297. package/src/util/queue.ts +32 -0
  298. package/src/util/rpc.ts +42 -0
  299. package/src/util/scrap.ts +10 -0
  300. package/src/util/signal.ts +12 -0
  301. package/src/util/timeout.ts +14 -0
  302. package/src/util/token.ts +7 -0
  303. package/src/util/wildcard.ts +54 -0
  304. package/sst-env.d.ts +9 -0
  305. package/test/agent/agent.test.ts +146 -0
  306. package/test/bun.test.ts +53 -0
  307. package/test/cli/github-remote.test.ts +80 -0
  308. package/test/config/agent-color.test.ts +66 -0
  309. package/test/config/config.test.ts +535 -0
  310. package/test/config/markdown.test.ts +89 -0
  311. package/test/file/ignore.test.ts +10 -0
  312. package/test/fixture/fixture.ts +34 -0
  313. package/test/fixture/lsp/fake-lsp-server.js +77 -0
  314. package/test/ide/ide.test.ts +82 -0
  315. package/test/keybind.test.ts +421 -0
  316. package/test/lsp/client.test.ts +95 -0
  317. package/test/mcp/headers.test.ts +153 -0
  318. package/test/patch/patch.test.ts +348 -0
  319. package/test/preload.ts +57 -0
  320. package/test/project/project.test.ts +72 -0
  321. package/test/provider/provider.test.ts +1809 -0
  322. package/test/provider/transform.test.ts +411 -0
  323. package/test/session/retry.test.ts +61 -0
  324. package/test/session/session.test.ts +71 -0
  325. package/test/skill/skill.test.ts +131 -0
  326. package/test/snapshot/snapshot.test.ts +939 -0
  327. package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
  328. package/test/tool/bash.test.ts +434 -0
  329. package/test/tool/grep.test.ts +108 -0
  330. package/test/tool/patch.test.ts +259 -0
  331. package/test/tool/read.test.ts +42 -0
  332. package/test/util/iife.test.ts +36 -0
  333. package/test/util/lazy.test.ts +50 -0
  334. package/test/util/timeout.test.ts +21 -0
  335. package/test/util/wildcard.test.ts +55 -0
  336. package/tsconfig.json +16 -0
@@ -0,0 +1,1117 @@
1
+ import { BoxRenderable, TextareaRenderable, MouseEvent, PasteEvent, t, dim, fg, type KeyBinding } from "@opentui/core"
2
+ import { createEffect, createMemo, type JSX, onMount, createSignal, onCleanup, Show, Switch, Match } from "solid-js"
3
+ import "opentui-spinner/solid"
4
+ import { useLocal } from "@tui/context/local"
5
+ import { useTheme } from "@tui/context/theme"
6
+ import { EmptyBorder } from "@tui/component/border"
7
+ import { useSDK } from "@tui/context/sdk"
8
+ import { useRoute } from "@tui/context/route"
9
+ import { useSync } from "@tui/context/sync"
10
+ import { Identifier } from "@/id/id"
11
+ import { createStore, produce } from "solid-js/store"
12
+ import { useKeybind } from "@tui/context/keybind"
13
+ import { Keybind } from "@/util/keybind"
14
+ import { usePromptHistory, type PromptInfo } from "./history"
15
+ import { usePromptStash } from "./stash"
16
+ import { DialogStash } from "../dialog-stash"
17
+ import { type AutocompleteRef, Autocomplete } from "./autocomplete"
18
+ import { useCommandDialog } from "../dialog-command"
19
+ import { useRenderer, useTerminalDimensions } from "@opentui/solid"
20
+ import { Editor } from "@tui/util/editor"
21
+ import { useExit } from "../../context/exit"
22
+ import { Clipboard } from "../../util/clipboard"
23
+ import type { FilePart } from "@opencode-ai/sdk/v2"
24
+ import { TuiEvent } from "../../event"
25
+ import { iife } from "@/util/iife"
26
+ import { Locale } from "@/util/locale"
27
+ import { createColors, createFrames } from "../../ui/spinner.ts"
28
+ import { useDialog } from "@tui/ui/dialog"
29
+ import { DialogProvider as DialogProviderConnect } from "../dialog-provider"
30
+ import { DialogAlert } from "../../ui/dialog-alert"
31
+ import { useToast } from "../../ui/toast"
32
+
33
+ export type PromptProps = {
34
+ sessionID?: string
35
+ disabled?: boolean
36
+ onSubmit?: () => void
37
+ ref?: (ref: PromptRef) => void
38
+ hint?: JSX.Element
39
+ showPlaceholder?: boolean
40
+ }
41
+
42
+ export type PromptRef = {
43
+ focused: boolean
44
+ current: PromptInfo
45
+ set(prompt: PromptInfo): void
46
+ reset(): void
47
+ blur(): void
48
+ focus(): void
49
+ submit(): void
50
+ }
51
+
52
+ const PLACEHOLDERS = ["Fix a TODO in the codebase", "What is the tech stack of this project?", "Fix broken tests"]
53
+
54
+ const TEXTAREA_ACTIONS = [
55
+ "submit",
56
+ "newline",
57
+ "move-left",
58
+ "move-right",
59
+ "move-up",
60
+ "move-down",
61
+ "select-left",
62
+ "select-right",
63
+ "select-up",
64
+ "select-down",
65
+ "line-home",
66
+ "line-end",
67
+ "select-line-home",
68
+ "select-line-end",
69
+ "visual-line-home",
70
+ "visual-line-end",
71
+ "select-visual-line-home",
72
+ "select-visual-line-end",
73
+ "buffer-home",
74
+ "buffer-end",
75
+ "select-buffer-home",
76
+ "select-buffer-end",
77
+ "delete-line",
78
+ "delete-to-line-end",
79
+ "delete-to-line-start",
80
+ "backspace",
81
+ "delete",
82
+ "undo",
83
+ "redo",
84
+ "word-forward",
85
+ "word-backward",
86
+ "select-word-forward",
87
+ "select-word-backward",
88
+ "delete-word-forward",
89
+ "delete-word-backward",
90
+ ] as const
91
+
92
+ function mapTextareaKeybindings(
93
+ keybinds: Record<string, Keybind.Info[]>,
94
+ action: (typeof TEXTAREA_ACTIONS)[number],
95
+ ): KeyBinding[] {
96
+ const configKey = `input_${action.replace(/-/g, "_")}`
97
+ const bindings = keybinds[configKey]
98
+ if (!bindings) return []
99
+ return bindings.map((binding) => ({
100
+ name: binding.name,
101
+ ctrl: binding.ctrl || undefined,
102
+ meta: binding.meta || undefined,
103
+ shift: binding.shift || undefined,
104
+ super: binding.super || undefined,
105
+ action,
106
+ }))
107
+ }
108
+
109
+ export function Prompt(props: PromptProps) {
110
+ let input: TextareaRenderable
111
+ let anchor: BoxRenderable
112
+ let autocomplete: AutocompleteRef
113
+
114
+ const keybind = useKeybind()
115
+ const local = useLocal()
116
+ const sdk = useSDK()
117
+ const route = useRoute()
118
+ const sync = useSync()
119
+ const dialog = useDialog()
120
+ const toast = useToast()
121
+ const status = createMemo(() => sync.data.session_status?.[props.sessionID ?? ""] ?? { type: "idle" })
122
+ const history = usePromptHistory()
123
+ const stash = usePromptStash()
124
+ const command = useCommandDialog()
125
+ const renderer = useRenderer()
126
+ const dimensions = useTerminalDimensions()
127
+ const tall = createMemo(() => dimensions().height > 40)
128
+ const wide = createMemo(() => dimensions().width > 120)
129
+ const { theme, syntax } = useTheme()
130
+
131
+ function promptModelWarning() {
132
+ toast.show({
133
+ variant: "warning",
134
+ message: "Connect a provider to send prompts",
135
+ duration: 3000,
136
+ })
137
+ if (sync.data.provider.length === 0) {
138
+ dialog.replace(() => <DialogProviderConnect />)
139
+ }
140
+ }
141
+
142
+ const textareaKeybindings = createMemo(() => {
143
+ const keybinds = keybind.all
144
+
145
+ return [
146
+ { name: "return", action: "submit" },
147
+ { name: "return", meta: true, action: "newline" },
148
+ ...TEXTAREA_ACTIONS.flatMap((action) => mapTextareaKeybindings(keybinds, action)),
149
+ ] satisfies KeyBinding[]
150
+ })
151
+
152
+ const fileStyleId = syntax().getStyleId("extmark.file")!
153
+ const agentStyleId = syntax().getStyleId("extmark.agent")!
154
+ const pasteStyleId = syntax().getStyleId("extmark.paste")!
155
+ let promptPartTypeId: number
156
+
157
+ sdk.event.on(TuiEvent.PromptAppend.type, (evt) => {
158
+ input.insertText(evt.properties.text)
159
+ setTimeout(() => {
160
+ input.getLayoutNode().markDirty()
161
+ input.gotoBufferEnd()
162
+ renderer.requestRender()
163
+ }, 0)
164
+ })
165
+
166
+ createEffect(() => {
167
+ if (props.disabled) input.cursorColor = theme.backgroundElement
168
+ if (!props.disabled) input.cursorColor = theme.text
169
+ })
170
+
171
+ const [store, setStore] = createStore<{
172
+ prompt: PromptInfo
173
+ mode: "normal" | "shell"
174
+ extmarkToPartIndex: Map<number, number>
175
+ interrupt: number
176
+ placeholder: number
177
+ }>({
178
+ placeholder: Math.floor(Math.random() * PLACEHOLDERS.length),
179
+ prompt: {
180
+ input: "",
181
+ parts: [],
182
+ },
183
+ mode: "normal",
184
+ extmarkToPartIndex: new Map(),
185
+ interrupt: 0,
186
+ })
187
+
188
+ command.register(() => {
189
+ return [
190
+ {
191
+ title: "Clear prompt",
192
+ value: "prompt.clear",
193
+ category: "Prompt",
194
+ disabled: true,
195
+ onSelect: (dialog) => {
196
+ input.extmarks.clear()
197
+ input.clear()
198
+ dialog.clear()
199
+ },
200
+ },
201
+ {
202
+ title: "Submit prompt",
203
+ value: "prompt.submit",
204
+ disabled: true,
205
+ keybind: "input_submit",
206
+ category: "Prompt",
207
+ onSelect: (dialog) => {
208
+ if (!input.focused) return
209
+ submit()
210
+ dialog.clear()
211
+ },
212
+ },
213
+ {
214
+ title: "Paste",
215
+ value: "prompt.paste",
216
+ disabled: true,
217
+ keybind: "input_paste",
218
+ category: "Prompt",
219
+ onSelect: async () => {
220
+ const content = await Clipboard.read()
221
+ if (content?.mime.startsWith("image/")) {
222
+ await pasteImage({
223
+ filename: "clipboard",
224
+ mime: content.mime,
225
+ content: content.data,
226
+ })
227
+ }
228
+ },
229
+ },
230
+ {
231
+ title: "Interrupt session",
232
+ value: "session.interrupt",
233
+ keybind: "session_interrupt",
234
+ disabled: status().type === "idle",
235
+ category: "Session",
236
+ onSelect: (dialog) => {
237
+ if (autocomplete.visible) return
238
+ if (!input.focused) return
239
+ // TODO: this should be its own command
240
+ if (store.mode === "shell") {
241
+ setStore("mode", "normal")
242
+ return
243
+ }
244
+ if (!props.sessionID) return
245
+
246
+ setStore("interrupt", store.interrupt + 1)
247
+
248
+ setTimeout(() => {
249
+ setStore("interrupt", 0)
250
+ }, 5000)
251
+
252
+ if (store.interrupt >= 2) {
253
+ sdk.client.session.abort({
254
+ sessionID: props.sessionID,
255
+ })
256
+ setStore("interrupt", 0)
257
+ }
258
+ dialog.clear()
259
+ },
260
+ },
261
+ {
262
+ title: "Open editor",
263
+ category: "Session",
264
+ keybind: "editor_open",
265
+ value: "prompt.editor",
266
+ onSelect: async (dialog, trigger) => {
267
+ dialog.clear()
268
+
269
+ // replace summarized text parts with the actual text
270
+ const text = store.prompt.parts
271
+ .filter((p) => p.type === "text")
272
+ .reduce((acc, p) => {
273
+ if (!p.source) return acc
274
+ return acc.replace(p.source.text.value, p.text)
275
+ }, store.prompt.input)
276
+
277
+ const nonTextParts = store.prompt.parts.filter((p) => p.type !== "text")
278
+
279
+ const value = trigger === "prompt" ? "" : text
280
+ const content = await Editor.open({ value, renderer })
281
+ if (!content) return
282
+
283
+ input.setText(content)
284
+
285
+ // Update positions for nonTextParts based on their location in new content
286
+ // Filter out parts whose virtual text was deleted
287
+ // this handles a case where the user edits the text in the editor
288
+ // such that the virtual text moves around or is deleted
289
+ const updatedNonTextParts = nonTextParts
290
+ .map((part) => {
291
+ let virtualText = ""
292
+ if (part.type === "file" && part.source?.text) {
293
+ virtualText = part.source.text.value
294
+ } else if (part.type === "agent" && part.source) {
295
+ virtualText = part.source.value
296
+ }
297
+
298
+ if (!virtualText) return part
299
+
300
+ const newStart = content.indexOf(virtualText)
301
+ // if the virtual text is deleted, remove the part
302
+ if (newStart === -1) return null
303
+
304
+ const newEnd = newStart + virtualText.length
305
+
306
+ if (part.type === "file" && part.source?.text) {
307
+ return {
308
+ ...part,
309
+ source: {
310
+ ...part.source,
311
+ text: {
312
+ ...part.source.text,
313
+ start: newStart,
314
+ end: newEnd,
315
+ },
316
+ },
317
+ }
318
+ }
319
+
320
+ if (part.type === "agent" && part.source) {
321
+ return {
322
+ ...part,
323
+ source: {
324
+ ...part.source,
325
+ start: newStart,
326
+ end: newEnd,
327
+ },
328
+ }
329
+ }
330
+
331
+ return part
332
+ })
333
+ .filter((part) => part !== null)
334
+
335
+ setStore("prompt", {
336
+ input: content,
337
+ // keep only the non-text parts because the text parts were
338
+ // already expanded inline
339
+ parts: updatedNonTextParts,
340
+ })
341
+ restoreExtmarksFromParts(updatedNonTextParts)
342
+ input.cursorOffset = Bun.stringWidth(content)
343
+ },
344
+ },
345
+ ]
346
+ })
347
+
348
+ createEffect(() => {
349
+ input.focus()
350
+ })
351
+
352
+ onMount(() => {
353
+ promptPartTypeId = input.extmarks.registerType("prompt-part")
354
+ })
355
+
356
+ function restoreExtmarksFromParts(parts: PromptInfo["parts"]) {
357
+ input.extmarks.clear()
358
+ setStore("extmarkToPartIndex", new Map())
359
+
360
+ parts.forEach((part, partIndex) => {
361
+ let start = 0
362
+ let end = 0
363
+ let virtualText = ""
364
+ let styleId: number | undefined
365
+
366
+ if (part.type === "file" && part.source?.text) {
367
+ start = part.source.text.start
368
+ end = part.source.text.end
369
+ virtualText = part.source.text.value
370
+ styleId = fileStyleId
371
+ } else if (part.type === "agent" && part.source) {
372
+ start = part.source.start
373
+ end = part.source.end
374
+ virtualText = part.source.value
375
+ styleId = agentStyleId
376
+ } else if (part.type === "text" && part.source?.text) {
377
+ start = part.source.text.start
378
+ end = part.source.text.end
379
+ virtualText = part.source.text.value
380
+ styleId = pasteStyleId
381
+ }
382
+
383
+ if (virtualText) {
384
+ const extmarkId = input.extmarks.create({
385
+ start,
386
+ end,
387
+ virtual: true,
388
+ styleId,
389
+ typeId: promptPartTypeId,
390
+ })
391
+ setStore("extmarkToPartIndex", (map: Map<number, number>) => {
392
+ const newMap = new Map(map)
393
+ newMap.set(extmarkId, partIndex)
394
+ return newMap
395
+ })
396
+ }
397
+ })
398
+ }
399
+
400
+ function syncExtmarksWithPromptParts() {
401
+ const allExtmarks = input.extmarks.getAllForTypeId(promptPartTypeId)
402
+ setStore(
403
+ produce((draft) => {
404
+ const newMap = new Map<number, number>()
405
+ const newParts: typeof draft.prompt.parts = []
406
+
407
+ for (const extmark of allExtmarks) {
408
+ const partIndex = draft.extmarkToPartIndex.get(extmark.id)
409
+ if (partIndex !== undefined) {
410
+ const part = draft.prompt.parts[partIndex]
411
+ if (part) {
412
+ if (part.type === "agent" && part.source) {
413
+ part.source.start = extmark.start
414
+ part.source.end = extmark.end
415
+ } else if (part.type === "file" && part.source?.text) {
416
+ part.source.text.start = extmark.start
417
+ part.source.text.end = extmark.end
418
+ } else if (part.type === "text" && part.source?.text) {
419
+ part.source.text.start = extmark.start
420
+ part.source.text.end = extmark.end
421
+ }
422
+ newMap.set(extmark.id, newParts.length)
423
+ newParts.push(part)
424
+ }
425
+ }
426
+ }
427
+
428
+ draft.extmarkToPartIndex = newMap
429
+ draft.prompt.parts = newParts
430
+ }),
431
+ )
432
+ }
433
+
434
+ command.register(() => [
435
+ {
436
+ title: "Stash prompt",
437
+ value: "prompt.stash",
438
+ category: "Prompt",
439
+ disabled: !store.prompt.input,
440
+ onSelect: (dialog) => {
441
+ if (!store.prompt.input) return
442
+ stash.push({
443
+ input: store.prompt.input,
444
+ parts: store.prompt.parts,
445
+ })
446
+ input.extmarks.clear()
447
+ input.clear()
448
+ setStore("prompt", { input: "", parts: [] })
449
+ setStore("extmarkToPartIndex", new Map())
450
+ dialog.clear()
451
+ },
452
+ },
453
+ {
454
+ title: "Stash pop",
455
+ value: "prompt.stash.pop",
456
+ category: "Prompt",
457
+ disabled: stash.list().length === 0,
458
+ onSelect: (dialog) => {
459
+ const entry = stash.pop()
460
+ if (entry) {
461
+ input.setText(entry.input)
462
+ setStore("prompt", { input: entry.input, parts: entry.parts })
463
+ restoreExtmarksFromParts(entry.parts)
464
+ input.gotoBufferEnd()
465
+ }
466
+ dialog.clear()
467
+ },
468
+ },
469
+ {
470
+ title: "Stash list",
471
+ value: "prompt.stash.list",
472
+ category: "Prompt",
473
+ disabled: stash.list().length === 0,
474
+ onSelect: (dialog) => {
475
+ dialog.replace(() => (
476
+ <DialogStash
477
+ onSelect={(entry) => {
478
+ input.setText(entry.input)
479
+ setStore("prompt", { input: entry.input, parts: entry.parts })
480
+ restoreExtmarksFromParts(entry.parts)
481
+ input.gotoBufferEnd()
482
+ }}
483
+ />
484
+ ))
485
+ },
486
+ },
487
+ ])
488
+
489
+ props.ref?.({
490
+ get focused() {
491
+ return input.focused
492
+ },
493
+ get current() {
494
+ return store.prompt
495
+ },
496
+ focus() {
497
+ input.focus()
498
+ },
499
+ blur() {
500
+ input.blur()
501
+ },
502
+ set(prompt) {
503
+ input.setText(prompt.input)
504
+ setStore("prompt", prompt)
505
+ restoreExtmarksFromParts(prompt.parts)
506
+ input.gotoBufferEnd()
507
+ },
508
+ reset() {
509
+ input.clear()
510
+ input.extmarks.clear()
511
+ setStore("prompt", {
512
+ input: "",
513
+ parts: [],
514
+ })
515
+ setStore("extmarkToPartIndex", new Map())
516
+ },
517
+ submit() {
518
+ submit()
519
+ },
520
+ })
521
+
522
+ async function submit() {
523
+ if (props.disabled) return
524
+ if (autocomplete?.visible) return
525
+ if (!store.prompt.input) return
526
+ const trimmed = store.prompt.input.trim()
527
+ if (trimmed === "exit" || trimmed === "quit" || trimmed === ":q") {
528
+ exit()
529
+ return
530
+ }
531
+ const selectedModel = local.model.current()
532
+ if (!selectedModel) {
533
+ promptModelWarning()
534
+ return
535
+ }
536
+ const sessionID = props.sessionID
537
+ ? props.sessionID
538
+ : await (async () => {
539
+ const sessionID = await sdk.client.session.create({}).then((x) => x.data!.id)
540
+ return sessionID
541
+ })()
542
+ const messageID = Identifier.ascending("message")
543
+ let inputText = store.prompt.input
544
+
545
+ // Expand pasted text inline before submitting
546
+ const allExtmarks = input.extmarks.getAllForTypeId(promptPartTypeId)
547
+ const sortedExtmarks = allExtmarks.sort((a: { start: number }, b: { start: number }) => b.start - a.start)
548
+
549
+ for (const extmark of sortedExtmarks) {
550
+ const partIndex = store.extmarkToPartIndex.get(extmark.id)
551
+ if (partIndex !== undefined) {
552
+ const part = store.prompt.parts[partIndex]
553
+ if (part?.type === "text" && part.text) {
554
+ const before = inputText.slice(0, extmark.start)
555
+ const after = inputText.slice(extmark.end)
556
+ inputText = before + part.text + after
557
+ }
558
+ }
559
+ }
560
+
561
+ // Filter out text parts (pasted content) since they're now expanded inline
562
+ const nonTextParts = store.prompt.parts.filter((part) => part.type !== "text")
563
+
564
+ // Capture mode before it gets reset
565
+ const currentMode = store.mode
566
+
567
+ if (store.mode === "shell") {
568
+ sdk.client.session.shell({
569
+ sessionID,
570
+ agent: local.agent.current().name,
571
+ model: {
572
+ providerID: selectedModel.providerID,
573
+ modelID: selectedModel.modelID,
574
+ },
575
+ command: inputText,
576
+ })
577
+ setStore("mode", "normal")
578
+ } else if (
579
+ inputText.startsWith("/") &&
580
+ iife(() => {
581
+ const command = inputText.split(" ")[0].slice(1)
582
+ console.log(command)
583
+ return sync.data.command.some((x) => x.name === command)
584
+ })
585
+ ) {
586
+ let [command, ...args] = inputText.split(" ")
587
+ sdk.client.session.command({
588
+ sessionID,
589
+ command: command.slice(1),
590
+ arguments: args.join(" "),
591
+ agent: local.agent.current().name,
592
+ model: `${selectedModel.providerID}/${selectedModel.modelID}`,
593
+ messageID,
594
+ })
595
+ } else {
596
+ sdk.client.session.prompt({
597
+ sessionID,
598
+ ...selectedModel,
599
+ messageID,
600
+ agent: local.agent.current().name,
601
+ model: selectedModel,
602
+ parts: [
603
+ {
604
+ id: Identifier.ascending("part"),
605
+ type: "text",
606
+ text: inputText,
607
+ },
608
+ ...nonTextParts.map((x) => ({
609
+ id: Identifier.ascending("part"),
610
+ ...x,
611
+ })),
612
+ ],
613
+ })
614
+ }
615
+ history.append({
616
+ ...store.prompt,
617
+ mode: currentMode,
618
+ })
619
+ input.extmarks.clear()
620
+ setStore("prompt", {
621
+ input: "",
622
+ parts: [],
623
+ })
624
+ setStore("extmarkToPartIndex", new Map())
625
+ props.onSubmit?.()
626
+
627
+ // temporary hack to make sure the message is sent
628
+ if (!props.sessionID)
629
+ setTimeout(() => {
630
+ route.navigate({
631
+ type: "session",
632
+ sessionID,
633
+ })
634
+ }, 50)
635
+ input.clear()
636
+ }
637
+ const exit = useExit()
638
+
639
+ function pasteText(text: string, virtualText: string) {
640
+ const currentOffset = input.visualCursor.offset
641
+ const extmarkStart = currentOffset
642
+ const extmarkEnd = extmarkStart + virtualText.length
643
+
644
+ input.insertText(virtualText + " ")
645
+
646
+ const extmarkId = input.extmarks.create({
647
+ start: extmarkStart,
648
+ end: extmarkEnd,
649
+ virtual: true,
650
+ styleId: pasteStyleId,
651
+ typeId: promptPartTypeId,
652
+ })
653
+
654
+ setStore(
655
+ produce((draft) => {
656
+ const partIndex = draft.prompt.parts.length
657
+ draft.prompt.parts.push({
658
+ type: "text" as const,
659
+ text,
660
+ source: {
661
+ text: {
662
+ start: extmarkStart,
663
+ end: extmarkEnd,
664
+ value: virtualText,
665
+ },
666
+ },
667
+ })
668
+ draft.extmarkToPartIndex.set(extmarkId, partIndex)
669
+ }),
670
+ )
671
+ }
672
+
673
+ async function pasteImage(file: { filename?: string; content: string; mime: string }) {
674
+ const currentOffset = input.visualCursor.offset
675
+ const extmarkStart = currentOffset
676
+ const count = store.prompt.parts.filter((x) => x.type === "file").length
677
+ const virtualText = `[Image ${count + 1}]`
678
+ const extmarkEnd = extmarkStart + virtualText.length
679
+ const textToInsert = virtualText + " "
680
+
681
+ input.insertText(textToInsert)
682
+
683
+ const extmarkId = input.extmarks.create({
684
+ start: extmarkStart,
685
+ end: extmarkEnd,
686
+ virtual: true,
687
+ styleId: pasteStyleId,
688
+ typeId: promptPartTypeId,
689
+ })
690
+
691
+ const part: Omit<FilePart, "id" | "messageID" | "sessionID"> = {
692
+ type: "file" as const,
693
+ mime: file.mime,
694
+ filename: file.filename,
695
+ url: `data:${file.mime};base64,${file.content}`,
696
+ source: {
697
+ type: "file",
698
+ path: file.filename ?? "",
699
+ text: {
700
+ start: extmarkStart,
701
+ end: extmarkEnd,
702
+ value: virtualText,
703
+ },
704
+ },
705
+ }
706
+ setStore(
707
+ produce((draft) => {
708
+ const partIndex = draft.prompt.parts.length
709
+ draft.prompt.parts.push(part)
710
+ draft.extmarkToPartIndex.set(extmarkId, partIndex)
711
+ }),
712
+ )
713
+ return
714
+ }
715
+
716
+ const highlight = createMemo(() => {
717
+ if (keybind.leader) return theme.border
718
+ if (store.mode === "shell") return theme.primary
719
+ return local.agent.color(local.agent.current().name)
720
+ })
721
+
722
+ const spinnerDef = createMemo(() => {
723
+ const color = local.agent.color(local.agent.current().name)
724
+ return {
725
+ frames: createFrames({
726
+ color,
727
+ style: "blocks",
728
+ inactiveFactor: 0.6,
729
+ // enableFading: false,
730
+ minAlpha: 0.3,
731
+ }),
732
+ color: createColors({
733
+ color,
734
+ style: "blocks",
735
+ inactiveFactor: 0.6,
736
+ // enableFading: false,
737
+ minAlpha: 0.3,
738
+ }),
739
+ }
740
+ })
741
+
742
+ return (
743
+ <>
744
+ <Autocomplete
745
+ sessionID={props.sessionID}
746
+ ref={(r) => (autocomplete = r)}
747
+ anchor={() => anchor}
748
+ input={() => input}
749
+ setPrompt={(cb) => {
750
+ setStore("prompt", produce(cb))
751
+ }}
752
+ setExtmark={(partIndex, extmarkId) => {
753
+ setStore("extmarkToPartIndex", (map: Map<number, number>) => {
754
+ const newMap = new Map(map)
755
+ newMap.set(extmarkId, partIndex)
756
+ return newMap
757
+ })
758
+ }}
759
+ value={store.prompt.input}
760
+ fileStyleId={fileStyleId}
761
+ agentStyleId={agentStyleId}
762
+ promptPartTypeId={() => promptPartTypeId}
763
+ />
764
+ <box ref={(r) => (anchor = r)}>
765
+ <box
766
+ border={["left"]}
767
+ borderColor={highlight()}
768
+ customBorderChars={{
769
+ ...EmptyBorder,
770
+ vertical: "┃",
771
+ bottomLeft: "╹",
772
+ }}
773
+ >
774
+ <box
775
+ paddingLeft={2}
776
+ paddingRight={1}
777
+ paddingTop={1}
778
+ flexShrink={0}
779
+ backgroundColor={theme.backgroundElement}
780
+ flexGrow={1}
781
+ >
782
+ <textarea
783
+ placeholder={props.sessionID ? undefined : `Ask anything... "${PLACEHOLDERS[store.placeholder]}"`}
784
+ textColor={keybind.leader ? theme.textMuted : theme.text}
785
+ focusedTextColor={keybind.leader ? theme.textMuted : theme.text}
786
+ minHeight={1}
787
+ maxHeight={6}
788
+ onContentChange={() => {
789
+ const value = input.plainText
790
+ setStore("prompt", "input", value)
791
+ autocomplete.onInput(value)
792
+ syncExtmarksWithPromptParts()
793
+ }}
794
+ keyBindings={textareaKeybindings()}
795
+ onKeyDown={async (e) => {
796
+ if (props.disabled) {
797
+ e.preventDefault()
798
+ return
799
+ }
800
+ // Handle clipboard paste (Ctrl+V) - check for images first on Windows
801
+ // This is needed because Windows terminal doesn't properly send image data
802
+ // through bracketed paste, so we need to intercept the keypress and
803
+ // directly read from clipboard before the terminal handles it
804
+ if (keybind.match("input_paste", e)) {
805
+ const content = await Clipboard.read()
806
+ if (content?.mime.startsWith("image/")) {
807
+ e.preventDefault()
808
+ await pasteImage({
809
+ filename: "clipboard",
810
+ mime: content.mime,
811
+ content: content.data,
812
+ })
813
+ return
814
+ }
815
+ // If no image, let the default paste behavior continue
816
+ }
817
+ if (keybind.match("input_clear", e) && store.prompt.input !== "") {
818
+ input.clear()
819
+ input.extmarks.clear()
820
+ setStore("prompt", {
821
+ input: "",
822
+ parts: [],
823
+ })
824
+ setStore("extmarkToPartIndex", new Map())
825
+ return
826
+ }
827
+ if (keybind.match("app_exit", e)) {
828
+ if (store.prompt.input === "") {
829
+ await exit()
830
+ // Don't preventDefault - let textarea potentially handle the event
831
+ e.preventDefault()
832
+ return
833
+ }
834
+ }
835
+ if (e.name === "!" && input.visualCursor.offset === 0) {
836
+ setStore("mode", "shell")
837
+ e.preventDefault()
838
+ return
839
+ }
840
+ if (store.mode === "shell") {
841
+ if ((e.name === "backspace" && input.visualCursor.offset === 0) || e.name === "escape") {
842
+ setStore("mode", "normal")
843
+ e.preventDefault()
844
+ return
845
+ }
846
+ }
847
+ if (store.mode === "normal") autocomplete.onKeyDown(e)
848
+ if (!autocomplete.visible) {
849
+ if (
850
+ (keybind.match("history_previous", e) && input.cursorOffset === 0) ||
851
+ (keybind.match("history_next", e) && input.cursorOffset === input.plainText.length)
852
+ ) {
853
+ const direction = keybind.match("history_previous", e) ? -1 : 1
854
+ const item = history.move(direction, input.plainText)
855
+
856
+ if (item) {
857
+ input.setText(item.input)
858
+ setStore("prompt", item)
859
+ setStore("mode", item.mode ?? "normal")
860
+ restoreExtmarksFromParts(item.parts)
861
+ e.preventDefault()
862
+ if (direction === -1) input.cursorOffset = 0
863
+ if (direction === 1) input.cursorOffset = input.plainText.length
864
+ }
865
+ return
866
+ }
867
+
868
+ if (keybind.match("history_previous", e) && input.visualCursor.visualRow === 0) input.cursorOffset = 0
869
+ if (keybind.match("history_next", e) && input.visualCursor.visualRow === input.height - 1)
870
+ input.cursorOffset = input.plainText.length
871
+ }
872
+ }}
873
+ onSubmit={submit}
874
+ onPaste={async (event: PasteEvent) => {
875
+ if (props.disabled) {
876
+ event.preventDefault()
877
+ return
878
+ }
879
+
880
+ // Normalize line endings at the boundary
881
+ // Windows ConPTY/Terminal often sends CR-only newlines in bracketed paste
882
+ // Replace CRLF first, then any remaining CR
883
+ const normalizedText = event.text.replace(/\r\n/g, "\n").replace(/\r/g, "\n")
884
+ const pastedContent = normalizedText.trim()
885
+ if (!pastedContent) {
886
+ command.trigger("prompt.paste")
887
+ return
888
+ }
889
+
890
+ // trim ' from the beginning and end of the pasted content. just
891
+ // ' and nothing else
892
+ const filepath = pastedContent.replace(/^'+|'+$/g, "").replace(/\\ /g, " ")
893
+ const isUrl = /^(https?):\/\//.test(filepath)
894
+ if (!isUrl) {
895
+ try {
896
+ const file = Bun.file(filepath)
897
+ // Handle SVG as raw text content, not as base64 image
898
+ if (file.type === "image/svg+xml") {
899
+ event.preventDefault()
900
+ const content = await file.text().catch(() => {})
901
+ if (content) {
902
+ pasteText(content, `[SVG: ${file.name ?? "image"}]`)
903
+ return
904
+ }
905
+ }
906
+ if (file.type.startsWith("image/")) {
907
+ event.preventDefault()
908
+ const content = await file
909
+ .arrayBuffer()
910
+ .then((buffer) => Buffer.from(buffer).toString("base64"))
911
+ .catch(() => {})
912
+ if (content) {
913
+ await pasteImage({
914
+ filename: file.name,
915
+ mime: file.type,
916
+ content,
917
+ })
918
+ return
919
+ }
920
+ }
921
+ } catch {}
922
+ }
923
+
924
+ const lineCount = (pastedContent.match(/\n/g)?.length ?? 0) + 1
925
+ if (
926
+ (lineCount >= 3 || pastedContent.length > 150) &&
927
+ !sync.data.config.experimental?.disable_paste_summary
928
+ ) {
929
+ event.preventDefault()
930
+ pasteText(pastedContent, `[Pasted ~${lineCount} lines]`)
931
+ return
932
+ }
933
+
934
+ // Force layout update and render for the pasted content
935
+ setTimeout(() => {
936
+ input.getLayoutNode().markDirty()
937
+ input.gotoBufferEnd()
938
+ renderer.requestRender()
939
+ }, 0)
940
+ }}
941
+ ref={(r: TextareaRenderable) => {
942
+ input = r
943
+ setTimeout(() => {
944
+ input.cursorColor = theme.text
945
+ }, 0)
946
+ }}
947
+ onMouseDown={(r: MouseEvent) => r.target?.focus()}
948
+ focusedBackgroundColor={theme.backgroundElement}
949
+ cursorColor={theme.text}
950
+ syntaxStyle={syntax()}
951
+ />
952
+ <Show when={tall()}>
953
+ <box flexDirection="row" flexShrink={0} paddingTop={1} gap={1}>
954
+ <text fg={highlight()}>
955
+ {store.mode === "shell" ? "Shell" : Locale.titlecase(local.agent.current().name)}{" "}
956
+ </text>
957
+ <Show when={store.mode === "normal"}>
958
+ <box flexDirection="row" gap={1}>
959
+ <text flexShrink={0} fg={keybind.leader ? theme.textMuted : theme.text}>
960
+ {local.model.parsed().model}
961
+ </text>
962
+ <text fg={theme.textMuted}>{local.model.parsed().provider}</text>
963
+ </box>
964
+ </Show>
965
+ </box>
966
+ </Show>
967
+ </box>
968
+ </box>
969
+ <box
970
+ height={1}
971
+ border={["left"]}
972
+ borderColor={highlight()}
973
+ customBorderChars={{
974
+ ...EmptyBorder,
975
+ vertical: theme.backgroundElement.a !== 0 ? "╹" : " ",
976
+ }}
977
+ >
978
+ <box
979
+ height={1}
980
+ border={["bottom"]}
981
+ borderColor={theme.backgroundElement}
982
+ customBorderChars={
983
+ theme.backgroundElement.a !== 0
984
+ ? {
985
+ ...EmptyBorder,
986
+ horizontal: "▀",
987
+ }
988
+ : {
989
+ ...EmptyBorder,
990
+ horizontal: " ",
991
+ }
992
+ }
993
+ />
994
+ </box>
995
+ <box flexDirection="row" justifyContent="space-between">
996
+ <Switch>
997
+ <Match when={status().type !== "idle"}>
998
+ <box
999
+ flexDirection="row"
1000
+ gap={1}
1001
+ flexGrow={1}
1002
+ justifyContent={status().type === "retry" ? "space-between" : "flex-start"}
1003
+ >
1004
+ <box flexShrink={0} flexDirection="row" gap={1}>
1005
+ {/* @ts-ignore // SpinnerOptions doesn't support marginLeft */}
1006
+ <spinner marginLeft={1} color={spinnerDef().color} frames={spinnerDef().frames} interval={40} />
1007
+ <box flexDirection="row" gap={1} flexShrink={0}>
1008
+ {(() => {
1009
+ const retry = createMemo(() => {
1010
+ const s = status()
1011
+ if (s.type !== "retry") return
1012
+ return s
1013
+ })
1014
+ const message = createMemo(() => {
1015
+ const r = retry()
1016
+ if (!r) return
1017
+ if (r.message.includes("exceeded your current quota") && r.message.includes("gemini"))
1018
+ return "gemini is way too hot right now"
1019
+ if (r.message.length > 80) return r.message.slice(0, 80) + "..."
1020
+ return r.message
1021
+ })
1022
+ const isTruncated = createMemo(() => {
1023
+ const r = retry()
1024
+ if (!r) return false
1025
+ return r.message.length > 120
1026
+ })
1027
+ const [seconds, setSeconds] = createSignal(0)
1028
+ onMount(() => {
1029
+ const timer = setInterval(() => {
1030
+ const next = retry()?.next
1031
+ if (next) setSeconds(Math.round((next - Date.now()) / 1000))
1032
+ }, 1000)
1033
+
1034
+ onCleanup(() => {
1035
+ clearTimeout(timer)
1036
+ })
1037
+ })
1038
+ const handleMessageClick = () => {
1039
+ const r = retry()
1040
+ if (!r) return
1041
+ if (isTruncated()) {
1042
+ DialogAlert.show(dialog, "Retry Error", r.message)
1043
+ }
1044
+ }
1045
+
1046
+ const retryText = () => {
1047
+ const r = retry()
1048
+ if (!r) return ""
1049
+ const baseMessage = message()
1050
+ const truncatedHint = isTruncated() ? " (click to expand)" : ""
1051
+ const retryInfo = ` [retrying ${seconds() > 0 ? `in ${seconds()}s ` : ""}attempt #${r.attempt}]`
1052
+ return baseMessage + truncatedHint + retryInfo
1053
+ }
1054
+
1055
+ return (
1056
+ <Show when={retry()}>
1057
+ <box onMouseUp={handleMessageClick}>
1058
+ <text fg={theme.error}>{retryText()}</text>
1059
+ </box>
1060
+ </Show>
1061
+ )
1062
+ })()}
1063
+ </box>
1064
+ </box>
1065
+ <text fg={store.interrupt > 0 ? theme.primary : theme.text}>
1066
+ esc{" "}
1067
+ <span style={{ fg: store.interrupt > 0 ? theme.primary : theme.textMuted }}>
1068
+ {store.interrupt > 0 ? "again to interrupt" : "interrupt"}
1069
+ </span>
1070
+ </text>
1071
+ </box>
1072
+ </Match>
1073
+ <Match when={!tall()}>
1074
+ <box flexDirection="row" gap={1}>
1075
+ <text fg={highlight()}>
1076
+ {store.mode === "shell" ? "Shell" : Locale.titlecase(local.agent.current().name)}{" "}
1077
+ </text>
1078
+ <Show when={store.mode === "normal"}>
1079
+ <box flexDirection="row" gap={1}>
1080
+ <text flexShrink={0} fg={keybind.leader ? theme.textMuted : theme.text}>
1081
+ {local.model.parsed().model}
1082
+ </text>
1083
+ <text fg={theme.textMuted}>{local.model.parsed().provider}</text>
1084
+ </box>
1085
+ </Show>
1086
+ </box>
1087
+ </Match>
1088
+ </Switch>
1089
+ <box gap={2} flexDirection="row" marginLeft="auto">
1090
+ <Switch>
1091
+ <Match when={store.mode === "normal"}>
1092
+ <Show when={wide()}>
1093
+ <text fg={theme.text}>
1094
+ {keybind.print("agent_cycle")} <span style={{ fg: theme.textMuted }}>switch agent</span>
1095
+ </text>
1096
+ </Show>
1097
+ <Show when={!wide()}>
1098
+ <text fg={theme.text}>
1099
+ {keybind.print("sidebar_toggle")} <span style={{ fg: theme.textMuted }}>sidebar</span>
1100
+ </text>
1101
+ </Show>
1102
+ <text fg={theme.text}>
1103
+ {keybind.print("command_list")} <span style={{ fg: theme.textMuted }}>commands</span>
1104
+ </text>
1105
+ </Match>
1106
+ <Match when={store.mode === "shell"}>
1107
+ <text fg={theme.text}>
1108
+ esc <span style={{ fg: theme.textMuted }}>exit shell mode</span>
1109
+ </text>
1110
+ </Match>
1111
+ </Switch>
1112
+ </box>
1113
+ </box>
1114
+ </box>
1115
+ </>
1116
+ )
1117
+ }