@bloxystudios/bloxycode 1.0.0

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