@onpoint-dev-tools/crewcoder-opentui 0.0.0-stage → 0.1.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 (325) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +262 -2
  3. package/THIRD_PARTY_NOTICES.md +51 -0
  4. package/dist/App.d.ts +16 -0
  5. package/dist/App.d.ts.map +1 -0
  6. package/dist/App.js +428 -0
  7. package/dist/App.js.map +1 -0
  8. package/dist/Root.d.ts +11 -0
  9. package/dist/Root.d.ts.map +1 -0
  10. package/dist/Root.js +13 -0
  11. package/dist/Root.js.map +1 -0
  12. package/dist/alert-model.d.ts +31 -0
  13. package/dist/alert-model.d.ts.map +1 -0
  14. package/dist/alert-model.js +34 -0
  15. package/dist/alert-model.js.map +1 -0
  16. package/dist/args.d.ts +13 -0
  17. package/dist/args.d.ts.map +1 -0
  18. package/dist/args.js +63 -0
  19. package/dist/args.js.map +1 -0
  20. package/dist/attachments.d.ts +29 -0
  21. package/dist/attachments.d.ts.map +1 -0
  22. package/dist/attachments.js +38 -0
  23. package/dist/attachments.js.map +1 -0
  24. package/dist/block-panels.d.ts +43 -0
  25. package/dist/block-panels.d.ts.map +1 -0
  26. package/dist/block-panels.js +210 -0
  27. package/dist/block-panels.js.map +1 -0
  28. package/dist/cli.d.ts +3 -0
  29. package/dist/cli.d.ts.map +1 -0
  30. package/dist/cli.js +138 -0
  31. package/dist/cli.js.map +1 -0
  32. package/dist/command-format.d.ts +18 -0
  33. package/dist/command-format.d.ts.map +1 -0
  34. package/dist/command-format.js +66 -0
  35. package/dist/command-format.js.map +1 -0
  36. package/dist/command-runner.d.ts +128 -0
  37. package/dist/command-runner.d.ts.map +1 -0
  38. package/dist/command-runner.js +571 -0
  39. package/dist/command-runner.js.map +1 -0
  40. package/dist/commands.d.ts +47 -0
  41. package/dist/commands.d.ts.map +1 -0
  42. package/dist/commands.js +108 -0
  43. package/dist/commands.js.map +1 -0
  44. package/dist/components/AttachmentRow.d.ts +11 -0
  45. package/dist/components/AttachmentRow.d.ts.map +1 -0
  46. package/dist/components/AttachmentRow.js +17 -0
  47. package/dist/components/AttachmentRow.js.map +1 -0
  48. package/dist/components/Composer.d.ts +23 -0
  49. package/dist/components/Composer.d.ts.map +1 -0
  50. package/dist/components/Composer.js +45 -0
  51. package/dist/components/Composer.js.map +1 -0
  52. package/dist/components/ExtensionQuestion.d.ts +18 -0
  53. package/dist/components/ExtensionQuestion.d.ts.map +1 -0
  54. package/dist/components/ExtensionQuestion.js +45 -0
  55. package/dist/components/ExtensionQuestion.js.map +1 -0
  56. package/dist/components/GoalForm.d.ts +18 -0
  57. package/dist/components/GoalForm.d.ts.map +1 -0
  58. package/dist/components/GoalForm.js +26 -0
  59. package/dist/components/GoalForm.js.map +1 -0
  60. package/dist/components/Home.d.ts +21 -0
  61. package/dist/components/Home.d.ts.map +1 -0
  62. package/dist/components/Home.js +48 -0
  63. package/dist/components/Home.js.map +1 -0
  64. package/dist/components/MentionList.d.ts +14 -0
  65. package/dist/components/MentionList.d.ts.map +1 -0
  66. package/dist/components/MentionList.js +24 -0
  67. package/dist/components/MentionList.js.map +1 -0
  68. package/dist/components/SearchBar.d.ts +19 -0
  69. package/dist/components/SearchBar.d.ts.map +1 -0
  70. package/dist/components/SearchBar.js +28 -0
  71. package/dist/components/SearchBar.js.map +1 -0
  72. package/dist/components/Sidebar.d.ts +19 -0
  73. package/dist/components/Sidebar.d.ts.map +1 -0
  74. package/dist/components/Sidebar.js +35 -0
  75. package/dist/components/Sidebar.js.map +1 -0
  76. package/dist/components/SummaryEditor.d.ts +16 -0
  77. package/dist/components/SummaryEditor.d.ts.map +1 -0
  78. package/dist/components/SummaryEditor.js +21 -0
  79. package/dist/components/SummaryEditor.js.map +1 -0
  80. package/dist/components/Transcript.d.ts +37 -0
  81. package/dist/components/Transcript.d.ts.map +1 -0
  82. package/dist/components/Transcript.js +314 -0
  83. package/dist/components/Transcript.js.map +1 -0
  84. package/dist/components/ui/alert.d.ts +9 -0
  85. package/dist/components/ui/alert.d.ts.map +1 -0
  86. package/dist/components/ui/alert.js +18 -0
  87. package/dist/components/ui/alert.js.map +1 -0
  88. package/dist/components/ui/command-palette.d.ts +15 -0
  89. package/dist/components/ui/command-palette.d.ts.map +1 -0
  90. package/dist/components/ui/command-palette.js +14 -0
  91. package/dist/components/ui/command-palette.js.map +1 -0
  92. package/dist/components/ui/confirm.d.ts +12 -0
  93. package/dist/components/ui/confirm.d.ts.map +1 -0
  94. package/dist/components/ui/confirm.js +16 -0
  95. package/dist/components/ui/confirm.js.map +1 -0
  96. package/dist/components/ui/select.d.ts +11 -0
  97. package/dist/components/ui/select.d.ts.map +1 -0
  98. package/dist/components/ui/select.js +29 -0
  99. package/dist/components/ui/select.js.map +1 -0
  100. package/dist/components/ui/spinner.d.ts +14 -0
  101. package/dist/components/ui/spinner.d.ts.map +1 -0
  102. package/dist/components/ui/spinner.js +17 -0
  103. package/dist/components/ui/spinner.js.map +1 -0
  104. package/dist/components/ui/tool-approval.d.ts +14 -0
  105. package/dist/components/ui/tool-approval.d.ts.map +1 -0
  106. package/dist/components/ui/tool-approval.js +37 -0
  107. package/dist/components/ui/tool-approval.js.map +1 -0
  108. package/dist/components/ui/tool-call.d.ts +12 -0
  109. package/dist/components/ui/tool-call.d.ts.map +1 -0
  110. package/dist/components/ui/tool-call.js +69 -0
  111. package/dist/components/ui/tool-call.js.map +1 -0
  112. package/dist/components/ui/types.d.ts +82 -0
  113. package/dist/components/ui/types.d.ts.map +1 -0
  114. package/dist/components/ui/types.js +2 -0
  115. package/dist/components/ui/types.js.map +1 -0
  116. package/dist/crewcoder-cli.d.ts +51 -0
  117. package/dist/crewcoder-cli.d.ts.map +1 -0
  118. package/dist/crewcoder-cli.js +26 -0
  119. package/dist/crewcoder-cli.js.map +1 -0
  120. package/dist/diff-anchors.d.ts +14 -0
  121. package/dist/diff-anchors.d.ts.map +1 -0
  122. package/dist/diff-anchors.js +43 -0
  123. package/dist/diff-anchors.js.map +1 -0
  124. package/dist/footer-layout.d.ts +49 -0
  125. package/dist/footer-layout.d.ts.map +1 -0
  126. package/dist/footer-layout.js +79 -0
  127. package/dist/footer-layout.js.map +1 -0
  128. package/dist/glyphs.d.ts +32 -0
  129. package/dist/glyphs.d.ts.map +1 -0
  130. package/dist/glyphs.js +35 -0
  131. package/dist/glyphs.js.map +1 -0
  132. package/dist/goal-form.d.ts +47 -0
  133. package/dist/goal-form.d.ts.map +1 -0
  134. package/dist/goal-form.js +59 -0
  135. package/dist/goal-form.js.map +1 -0
  136. package/dist/hooks/use-animation.d.ts +6 -0
  137. package/dist/hooks/use-animation.d.ts.map +1 -0
  138. package/dist/hooks/use-animation.js +52 -0
  139. package/dist/hooks/use-animation.js.map +1 -0
  140. package/dist/hooks/use-app-colors.d.ts +6 -0
  141. package/dist/hooks/use-app-colors.d.ts.map +1 -0
  142. package/dist/hooks/use-app-colors.js +6 -0
  143. package/dist/hooks/use-app-colors.js.map +1 -0
  144. package/dist/hooks/use-glyph-set.d.ts +8 -0
  145. package/dist/hooks/use-glyph-set.d.ts.map +1 -0
  146. package/dist/hooks/use-glyph-set.js +22 -0
  147. package/dist/hooks/use-glyph-set.js.map +1 -0
  148. package/dist/hooks/use-motion.d.ts +6 -0
  149. package/dist/hooks/use-motion.d.ts.map +1 -0
  150. package/dist/hooks/use-motion.js +8 -0
  151. package/dist/hooks/use-motion.js.map +1 -0
  152. package/dist/hooks/use-terminal-focus.d.ts +16 -0
  153. package/dist/hooks/use-terminal-focus.d.ts.map +1 -0
  154. package/dist/hooks/use-terminal-focus.js +30 -0
  155. package/dist/hooks/use-terminal-focus.js.map +1 -0
  156. package/dist/hooks/use-theme.d.ts +6 -0
  157. package/dist/hooks/use-theme.d.ts.map +1 -0
  158. package/dist/hooks/use-theme.js +11 -0
  159. package/dist/hooks/use-theme.js.map +1 -0
  160. package/dist/hunk.d.ts +27 -0
  161. package/dist/hunk.d.ts.map +1 -0
  162. package/dist/hunk.js +43 -0
  163. package/dist/hunk.js.map +1 -0
  164. package/dist/image-view.d.ts +33 -0
  165. package/dist/image-view.d.ts.map +1 -0
  166. package/dist/image-view.js +51 -0
  167. package/dist/image-view.js.map +1 -0
  168. package/dist/keybindings.d.ts +28 -0
  169. package/dist/keybindings.d.ts.map +1 -0
  170. package/dist/keybindings.js +105 -0
  171. package/dist/keybindings.js.map +1 -0
  172. package/dist/lib/terminal-themes/default.d.ts +3 -0
  173. package/dist/lib/terminal-themes/default.d.ts.map +1 -0
  174. package/dist/lib/terminal-themes/default.js +49 -0
  175. package/dist/lib/terminal-themes/default.js.map +1 -0
  176. package/dist/logo-pulse.d.ts +23 -0
  177. package/dist/logo-pulse.d.ts.map +1 -0
  178. package/dist/logo-pulse.js +30 -0
  179. package/dist/logo-pulse.js.map +1 -0
  180. package/dist/markdown-style.d.ts +47 -0
  181. package/dist/markdown-style.d.ts.map +1 -0
  182. package/dist/markdown-style.js +138 -0
  183. package/dist/markdown-style.js.map +1 -0
  184. package/dist/mentions.d.ts +57 -0
  185. package/dist/mentions.d.ts.map +1 -0
  186. package/dist/mentions.js +109 -0
  187. package/dist/mentions.js.map +1 -0
  188. package/dist/palette-model.d.ts +42 -0
  189. package/dist/palette-model.d.ts.map +1 -0
  190. package/dist/palette-model.js +77 -0
  191. package/dist/palette-model.js.map +1 -0
  192. package/dist/path-suggestions.d.ts +50 -0
  193. package/dist/path-suggestions.d.ts.map +1 -0
  194. package/dist/path-suggestions.js +99 -0
  195. package/dist/path-suggestions.js.map +1 -0
  196. package/dist/picker-flows.d.ts +78 -0
  197. package/dist/picker-flows.d.ts.map +1 -0
  198. package/dist/picker-flows.js +444 -0
  199. package/dist/picker-flows.js.map +1 -0
  200. package/dist/pickers.d.ts +34 -0
  201. package/dist/pickers.d.ts.map +1 -0
  202. package/dist/pickers.js +136 -0
  203. package/dist/pickers.js.map +1 -0
  204. package/dist/prompt-history.d.ts +32 -0
  205. package/dist/prompt-history.d.ts.map +1 -0
  206. package/dist/prompt-history.js +40 -0
  207. package/dist/prompt-history.js.map +1 -0
  208. package/dist/providers/app-theme-provider.d.ts +12 -0
  209. package/dist/providers/app-theme-provider.d.ts.map +1 -0
  210. package/dist/providers/app-theme-provider.js +14 -0
  211. package/dist/providers/app-theme-provider.js.map +1 -0
  212. package/dist/providers/theme-provider.d.ts +10 -0
  213. package/dist/providers/theme-provider.d.ts.map +1 -0
  214. package/dist/providers/theme-provider.js +57 -0
  215. package/dist/providers/theme-provider.js.map +1 -0
  216. package/dist/question-model.d.ts +71 -0
  217. package/dist/question-model.d.ts.map +1 -0
  218. package/dist/question-model.js +176 -0
  219. package/dist/question-model.js.map +1 -0
  220. package/dist/search-controller.d.ts +46 -0
  221. package/dist/search-controller.d.ts.map +1 -0
  222. package/dist/search-controller.js +89 -0
  223. package/dist/search-controller.js.map +1 -0
  224. package/dist/search-jump.d.ts +27 -0
  225. package/dist/search-jump.d.ts.map +1 -0
  226. package/dist/search-jump.js +65 -0
  227. package/dist/search-jump.js.map +1 -0
  228. package/dist/session-controller.d.ts +268 -0
  229. package/dist/session-controller.d.ts.map +1 -0
  230. package/dist/session-controller.js +941 -0
  231. package/dist/session-controller.js.map +1 -0
  232. package/dist/sidebar-model.d.ts +45 -0
  233. package/dist/sidebar-model.d.ts.map +1 -0
  234. package/dist/sidebar-model.js +223 -0
  235. package/dist/sidebar-model.js.map +1 -0
  236. package/dist/sidebar.d.ts +49 -0
  237. package/dist/sidebar.d.ts.map +1 -0
  238. package/dist/sidebar.js +106 -0
  239. package/dist/sidebar.js.map +1 -0
  240. package/dist/status-line.d.ts +32 -0
  241. package/dist/status-line.d.ts.map +1 -0
  242. package/dist/status-line.js +69 -0
  243. package/dist/status-line.js.map +1 -0
  244. package/dist/syntax/filetype.d.ts +12 -0
  245. package/dist/syntax/filetype.d.ts.map +1 -0
  246. package/dist/syntax/filetype.js +28 -0
  247. package/dist/syntax/filetype.js.map +1 -0
  248. package/dist/syntax/grammars.d.ts +42 -0
  249. package/dist/syntax/grammars.d.ts.map +1 -0
  250. package/dist/syntax/grammars.js +52 -0
  251. package/dist/syntax/grammars.js.map +1 -0
  252. package/dist/text-offset.d.ts +5 -0
  253. package/dist/text-offset.d.ts.map +1 -0
  254. package/dist/text-offset.js +38 -0
  255. package/dist/text-offset.js.map +1 -0
  256. package/dist/text-wrap.d.ts +12 -0
  257. package/dist/text-wrap.d.ts.map +1 -0
  258. package/dist/text-wrap.js +53 -0
  259. package/dist/text-wrap.js.map +1 -0
  260. package/dist/theme-controller.d.ts +77 -0
  261. package/dist/theme-controller.d.ts.map +1 -0
  262. package/dist/theme-controller.js +178 -0
  263. package/dist/theme-controller.js.map +1 -0
  264. package/dist/theme.d.ts +51 -0
  265. package/dist/theme.d.ts.map +1 -0
  266. package/dist/theme.js +86 -0
  267. package/dist/theme.js.map +1 -0
  268. package/dist/tmux-check.d.ts +35 -0
  269. package/dist/tmux-check.d.ts.map +1 -0
  270. package/dist/tmux-check.js +66 -0
  271. package/dist/tmux-check.js.map +1 -0
  272. package/dist/tmux.d.ts +69 -0
  273. package/dist/tmux.d.ts.map +1 -0
  274. package/dist/tmux.js +135 -0
  275. package/dist/tmux.js.map +1 -0
  276. package/dist/tool-diff.d.ts +51 -0
  277. package/dist/tool-diff.d.ts.map +1 -0
  278. package/dist/tool-diff.js +158 -0
  279. package/dist/tool-diff.js.map +1 -0
  280. package/dist/tool-presentation.d.ts +46 -0
  281. package/dist/tool-presentation.d.ts.map +1 -0
  282. package/dist/tool-presentation.js +148 -0
  283. package/dist/tool-presentation.js.map +1 -0
  284. package/dist/tool-renderer-view.d.ts +14 -0
  285. package/dist/tool-renderer-view.d.ts.map +1 -0
  286. package/dist/tool-renderer-view.js +10 -0
  287. package/dist/tool-renderer-view.js.map +1 -0
  288. package/dist/transcript-search.d.ts +54 -0
  289. package/dist/transcript-search.d.ts.map +1 -0
  290. package/dist/transcript-search.js +160 -0
  291. package/dist/transcript-search.js.map +1 -0
  292. package/dist/transcript.d.ts +59 -0
  293. package/dist/transcript.d.ts.map +1 -0
  294. package/dist/transcript.js +123 -0
  295. package/dist/transcript.js.map +1 -0
  296. package/dist/workflow-tools.d.ts +42 -0
  297. package/dist/workflow-tools.d.ts.map +1 -0
  298. package/dist/workflow-tools.js +89 -0
  299. package/dist/workflow-tools.js.map +1 -0
  300. package/examples/themes/ember.json +75 -0
  301. package/grammars/bash/LICENSE +21 -0
  302. package/grammars/bash/highlights.scm +56 -0
  303. package/grammars/bash/tree-sitter-bash.wasm +0 -0
  304. package/grammars/css/LICENSE +21 -0
  305. package/grammars/css/highlights.scm +76 -0
  306. package/grammars/css/tree-sitter-css.wasm +0 -0
  307. package/grammars/go/LICENSE +21 -0
  308. package/grammars/go/highlights.scm +123 -0
  309. package/grammars/go/tree-sitter-go.wasm +0 -0
  310. package/grammars/html/LICENSE +21 -0
  311. package/grammars/html/highlights.scm +13 -0
  312. package/grammars/html/tree-sitter-html.wasm +0 -0
  313. package/grammars/json/LICENSE +21 -0
  314. package/grammars/json/highlights.scm +16 -0
  315. package/grammars/json/tree-sitter-json.wasm +0 -0
  316. package/grammars/python/LICENSE +21 -0
  317. package/grammars/python/highlights.scm +137 -0
  318. package/grammars/python/tree-sitter-python.wasm +0 -0
  319. package/grammars/rust/LICENSE +21 -0
  320. package/grammars/rust/highlights.scm +161 -0
  321. package/grammars/rust/tree-sitter-rust.wasm +0 -0
  322. package/grammars/yaml/LICENSE +20 -0
  323. package/grammars/yaml/highlights.scm +79 -0
  324. package/grammars/yaml/tree-sitter-yaml.wasm +0 -0
  325. package/package.json +56 -5
@@ -0,0 +1,941 @@
1
+ import { isCrewCoderRemote, parseExtensionRendererRecords } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process";
2
+ import { applyCrewCoderEvent, stopCrew } from "@onpoint-dev-tools/crewcoder-tui-core/state/event-reducer";
3
+ import { readCrewTaskSnapshot } from "@onpoint-dev-tools/crewcoder-tui-core/state/crew-tasks";
4
+ import { createInitialState, normalizeTuiMode } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store";
5
+ import { SidebarController } from "./sidebar.js";
6
+ import { IDLE_RECALL, sentMessages, stepRecall } from "./prompt-history.js";
7
+ import { attachImagePaths, pasteFromClipboard, systemClipboard } from "./attachments.js";
8
+ import { actionLabel } from "./keybindings.js";
9
+ import { listPathSuggestions, mentionRows } from "./path-suggestions.js";
10
+ import { Mentions } from "./mentions.js";
11
+ import { alertRows } from "./alert-model.js";
12
+ import { CommandRunner } from "./command-runner.js";
13
+ import { DRAFT_PREFIX, paletteCommands } from "./commands.js";
14
+ import { errorMessage, processCli } from "./crewcoder-cli.js";
15
+ import { composerRows } from "./footer-layout.js";
16
+ import { computeLineAnchors, readLocalFile } from "./diff-anchors.js";
17
+ import { pickerEntries, pickerMaxRows, pickerView } from "./palette-model.js";
18
+ import { PickerFlows } from "./picker-flows.js";
19
+ import { PICKER_COMMANDS } from "./pickers.js";
20
+ import { TranscriptSearch } from "./search-controller.js";
21
+ import { editGoalField, GOAL_FIELDS, initialGoalForm, selectGoalField, submitGoalForm } from "./goal-form.js";
22
+ import { ThemeController } from "./theme-controller.js";
23
+ import { handoffEnv, removeCrewHandoff, tmuxAttachHint, writeCrewHandoff } from "./tmux.js";
24
+ import { choiceAnswer, questionChoices, questionContentWidth, questionMaxRows, questionView } from "./question-model.js";
25
+ const CREW_IN_TMUX = "tmux";
26
+ const CREW_HERE = "here";
27
+ /** `planner + builder` or `team feature`, for the picker title and tmux names. */
28
+ function crewLabel(target) {
29
+ return target.kind === "team" ? `team ${target.team}` : target.workers.join(" + ");
30
+ }
31
+ /** Summary editor text rows for a terminal height (the editor adds border + hint). */
32
+ export function summaryEditorTextRows(terminalHeight) {
33
+ return Math.max(3, Math.min(14, terminalHeight - 5));
34
+ }
35
+ /**
36
+ * Owns the shared TUI state and the agent bridge for one terminal session.
37
+ * React subscribes through `subscribe`/`getVersion`; the reducer mutates
38
+ * `state` in place, so every change bumps `version` to trigger a render.
39
+ */
40
+ export class SessionController {
41
+ state;
42
+ cli;
43
+ bridge;
44
+ flows;
45
+ commands;
46
+ listeners = new Set();
47
+ version = 0;
48
+ pendingSkills = [];
49
+ /** The open palette or picker; at most one at a time. */
50
+ picker;
51
+ pickerQuery = "";
52
+ /** Index into `pickerEntries(picker.items, pickerQuery)`. */
53
+ pickerCursor = 0;
54
+ /** Text a picker wants in the composer; App applies it when `composerDraftVersion` changes. */
55
+ composerDraft = "";
56
+ composerDraftVersion = 0;
57
+ historyRecall = IDLE_RECALL;
58
+ /** Visual (wrapped) lines in the composer, reported by App; sizes the footer. */
59
+ composerLines = 1;
60
+ /** Shown above the composer until the next keypress or command. */
61
+ currentAlert;
62
+ /** The compaction summary being edited, if any. */
63
+ editor;
64
+ /** The bare `/goal` preflight form, if open (`goal-form.ts`). */
65
+ goalForm;
66
+ /** Hands the terminal to a full-screen program such as Hunk (`/diff`); wired by cli.tsx. */
67
+ runInTerminal;
68
+ /** `/repaint`: redraws every cell, discarding whatever else wrote to the terminal; wired by cli.tsx. */
69
+ repaint;
70
+ /** `/quit`: the same exit as Ctrl+C; wired by cli.tsx. */
71
+ quit;
72
+ /**
73
+ * Crews in tmux (`docs/CREWS.md#tmux`): the launcher and the command that starts a
74
+ * second UI on a handoff file. Wired by cli.tsx only when tmux is installed and the
75
+ * workspace is local; undefined means /crew and /team run here without asking.
76
+ */
77
+ crewTmux;
78
+ /** A /crew or /team waiting for the "here or tmux" choice. */
79
+ pendingCrew;
80
+ /** Ctrl+O: every tool's output expanded. A per-tool toggle flips its own state against this. */
81
+ allToolsExpanded = false;
82
+ /** Tools toggled individually. Keyed by identity: the reducer mutates blocks in place. */
83
+ toggledTools = new WeakSet();
84
+ /** Ctrl+T: every edit's diff hidden. A per-tool toggle flips its own diff against this. */
85
+ allDiffsHidden = false;
86
+ toggledDiffs = new WeakSet();
87
+ anchors = new WeakMap();
88
+ readFile;
89
+ /** Latest composer text, so a draft survives an overlay that unmounts the composer. */
90
+ composerText = "";
91
+ /** Cursor and scroll for the open question; reset when another request opens. */
92
+ questionNav = { requestId: "", cursor: 0, offset: 0 };
93
+ /** `@` path suggestions under the composer (`mentions.ts`). */
94
+ mentions;
95
+ clipboard;
96
+ /** The right sidebar (Ctrl+B, `/sidebar`): open state, width, crew tasks. */
97
+ sidebar;
98
+ /** The active theme and `/theme` (preview, apply, saved pick); configured by cli.tsx. */
99
+ themes;
100
+ /** Transcript search (Ctrl+F, `/find`); App scrolls to its current match. */
101
+ search;
102
+ constructor(bridge, state = createInitialState(), cli = processCli, readFile = readLocalFile,
103
+ // null, not undefined: an explicit undefined would take this default.
104
+ listPaths = isCrewCoderRemote() ? null : listPathSuggestions, clipboard = systemClipboard,
105
+ // The task store lives on the workspace's disk; remote workspaces are not local.
106
+ readTasks = isCrewCoderRemote() ? null : readCrewTaskSnapshot) {
107
+ this.sidebar = new SidebarController(this, readTasks);
108
+ this.themes = new ThemeController(this);
109
+ this.search = new TranscriptSearch(this);
110
+ this.clipboard = clipboard;
111
+ this.bridge = bridge;
112
+ this.state = state;
113
+ this.cli = cli;
114
+ this.readFile = readFile;
115
+ this.mentions = new Mentions(listPaths, {
116
+ cwd: () => this.state.cwd,
117
+ changed: () => this.notify(),
118
+ failed: (error) => this.alert({ variant: "error", title: "Could not list workspace paths", body: errorMessage(error) })
119
+ });
120
+ this.flows = new PickerFlows(this);
121
+ this.commands = new CommandRunner(this, this.flows);
122
+ // The legacy help tip refers to slash commands this preview does not ship yet.
123
+ this.state.blocks = [];
124
+ }
125
+ subscribe = (listener) => {
126
+ this.listeners.add(listener);
127
+ return () => this.listeners.delete(listener);
128
+ };
129
+ getVersion = () => this.version;
130
+ /** The open `@` list, when the composer cursor is in an `@token`. */
131
+ get mention() {
132
+ return this.mentions.current;
133
+ }
134
+ get bridgeRunning() {
135
+ return this.bridge.running;
136
+ }
137
+ // ── Pickers ────────────────────────────────────────────────────────────────
138
+ /** Ctrl+P: open the command palette, or close it when open. The composer draft survives. */
139
+ togglePalette() {
140
+ if (this.picker?.kind === "commands")
141
+ return this.closePicker();
142
+ this.preserveComposerDraft();
143
+ this.openCommandPalette();
144
+ }
145
+ /** Tab / Ctrl+I: the modes and saved workers picker (the legacy agents overlay). */
146
+ openModesPicker() {
147
+ this.preserveComposerDraft();
148
+ this.flows.open("mode");
149
+ }
150
+ openCommandPalette() {
151
+ this.openPicker({ kind: "commands", placeholder: "Search commands…", emptyText: "No commands found", items: paletteCommands(this.state.integrationProfile), loading: false });
152
+ }
153
+ /** A small picker whose items are commands or `draft:` texts (see commands.ts). */
154
+ openMenu(title, items, load) {
155
+ const menu = { kind: "menu", title, placeholder: "Search…", emptyText: "Nothing to pick", items, loading: load !== undefined };
156
+ if (load)
157
+ this.flows.load(menu, load);
158
+ else
159
+ this.openPicker(menu);
160
+ }
161
+ /** Show a picker. Replacing a loading picker of the same kind keeps the query and a moved cursor. */
162
+ openPicker(next) {
163
+ if (this.picker?.kind === "theme" && next.kind !== "theme")
164
+ this.themes.endPreview();
165
+ const refresh = this.picker?.kind === next.kind && this.picker.loading;
166
+ if (!refresh)
167
+ this.pickerQuery = "";
168
+ if (!refresh || this.pickerCursor === 0) {
169
+ const current = pickerEntries(next.items, this.pickerQuery).findIndex((item) => item.current);
170
+ this.pickerCursor = Math.max(0, current);
171
+ }
172
+ this.picker = next;
173
+ this.notify();
174
+ }
175
+ closePicker() {
176
+ if (!this.picker)
177
+ return;
178
+ // Esc on "where should the crew run" cancels the crew.
179
+ if (this.picker.kind === "crewLaunch")
180
+ this.pendingCrew = undefined;
181
+ // Leaving /theme without Enter keeps the applied theme (a no-op after Enter applied one).
182
+ if (this.picker.kind === "theme")
183
+ this.themes.endPreview();
184
+ this.picker = undefined;
185
+ this.pickerQuery = "";
186
+ this.pickerCursor = 0;
187
+ this.notify();
188
+ }
189
+ setPickerQuery(query) {
190
+ if (!this.picker)
191
+ return;
192
+ this.pickerQuery = query;
193
+ this.pickerCursor = 0;
194
+ this.previewHighlightedTheme();
195
+ this.notify();
196
+ }
197
+ movePickerCursor(delta) {
198
+ if (!this.picker)
199
+ return;
200
+ const count = pickerEntries(this.picker.items, this.pickerQuery).length;
201
+ this.pickerCursor = Math.max(0, Math.min(Math.max(0, count - 1), this.pickerCursor + delta));
202
+ this.previewHighlightedTheme();
203
+ this.notify();
204
+ }
205
+ /** In /theme the highlighted theme is shown live; Esc returns to the applied one. */
206
+ previewHighlightedTheme() {
207
+ if (this.picker?.kind !== "theme")
208
+ return;
209
+ this.themes.preview(pickerEntries(this.picker.items, this.pickerQuery)[this.pickerCursor]?.id);
210
+ }
211
+ /** Apply the highlighted item. Async choices report failures as error alerts. */
212
+ selectPickerItem() {
213
+ const picker = this.picker;
214
+ if (!picker)
215
+ return;
216
+ const item = pickerEntries(picker.items, this.pickerQuery)[this.pickerCursor];
217
+ if (!item)
218
+ return;
219
+ if (picker.kind === "theme") {
220
+ // Applied synchronously before closing, so the old theme never flashes back for a frame.
221
+ const applied = this.flows.select("theme", item.id);
222
+ this.closePicker();
223
+ applied.then(() => this.notify(), (error) => this.alert({ variant: "error", title: `Could not apply theme ${item.id}`, body: errorMessage(error) }));
224
+ return;
225
+ }
226
+ if (picker.kind === "crewLaunch") {
227
+ const pending = this.pendingCrew;
228
+ this.closePicker();
229
+ if (!pending)
230
+ return;
231
+ if (item.id === CREW_IN_TMUX)
232
+ void this.runCrewInTmux(pending);
233
+ else
234
+ this.startCrew(pending.target, pending.task, pending.command);
235
+ return;
236
+ }
237
+ this.closePicker();
238
+ if (picker.kind === "commands" || picker.kind === "menu") {
239
+ if (item.id.startsWith(DRAFT_PREFIX))
240
+ this.setComposerDraft(item.id.slice(DRAFT_PREFIX.length));
241
+ else
242
+ this.submit(item.id);
243
+ return;
244
+ }
245
+ this.flows.select(picker.kind, item.id).then(() => this.notify(), (error) => this.alert({ variant: "error", title: "Could not apply that choice", body: errorMessage(error) }));
246
+ }
247
+ /** Tab in /sessions: branch the highlighted session and open the branch. */
248
+ branchPickerItem() {
249
+ const picker = this.picker;
250
+ if (picker?.kind !== "session" || picker.loading)
251
+ return;
252
+ const item = pickerEntries(picker.items, this.pickerQuery)[this.pickerCursor];
253
+ if (!item)
254
+ return;
255
+ this.closePicker();
256
+ this.flows.branch(item.id).then(() => this.notify(), (error) => this.alert({ variant: "error", title: "Could not branch the session", body: errorMessage(error) }));
257
+ }
258
+ pickerView(terminalHeight) {
259
+ return this.picker ? pickerView(this.picker.items, this.pickerQuery, this.pickerCursor, pickerMaxRows(terminalHeight)) : undefined;
260
+ }
261
+ /**
262
+ * Rows the alert and composer take; the welcome screen hides the logo when they do not
263
+ * fit. `alertWidth` is the alert box's width, since long alert text wraps.
264
+ */
265
+ footerExtras(alertWidth) {
266
+ return {
267
+ alertRows: alertRows(this.currentAlert, alertWidth),
268
+ composerRows: composerRows(this.composerLines),
269
+ mentionRows: this.mention ? mentionRows(this.mention.items.length) : 0,
270
+ attachmentRows: this.state.attachments.length > 0 ? 1 : 0
271
+ };
272
+ }
273
+ // ── Image attachments ────────────────────────────────────────────────────────────
274
+ /**
275
+ * Ctrl+V: attach a clipboard image (or image files the clipboard text names)
276
+ * and return undefined, or return clipboard text for the composer. Remote
277
+ * mode attaches nothing: local files cannot reach the SSH host yet.
278
+ */
279
+ pasteClipboard() {
280
+ if (isCrewCoderRemote()) {
281
+ const text = this.clipboard.text();
282
+ if (!text && this.clipboard.image())
283
+ this.alert({ variant: "warning", title: "Images are not available in remote SSH mode" });
284
+ return text;
285
+ }
286
+ let result;
287
+ try {
288
+ result = pasteFromClipboard(this.clipboard, this.state.attachments);
289
+ }
290
+ catch (error) {
291
+ this.alert({ variant: "error", title: "Could not attach the clipboard image", body: errorMessage(error) });
292
+ return undefined;
293
+ }
294
+ if (result.attached.length > 0) {
295
+ this.state.attachments = [...this.state.attachments, ...result.attached];
296
+ this.notify();
297
+ }
298
+ return result.text;
299
+ }
300
+ /** Ctrl+X: drop the pending images; false when there were none. */
301
+ clearAttachments() {
302
+ if (this.state.attachments.length === 0)
303
+ return false;
304
+ this.state.attachments = [];
305
+ this.notify();
306
+ return true;
307
+ }
308
+ // ── Tool output ───────────────────────────────────────────────────────────────
309
+ toolExpansion = {
310
+ isExpanded: (block) => this.allToolsExpanded !== this.toggledTools.has(block),
311
+ toggle: (block) => this.flip(this.toggledTools, block),
312
+ isDiffShown: (block) => this.allDiffsHidden === this.toggledDiffs.has(block),
313
+ toggleDiff: (block) => this.flip(this.toggledDiffs, block),
314
+ lineAnchors: (block) => this.anchors.get(block)
315
+ };
316
+ /**
317
+ * Number a finished edit's diff with real file lines, read once from the
318
+ * local workspace (remote files are not readable here; those diffs stay plain).
319
+ */
320
+ anchorEdit(toolCallId) {
321
+ {
322
+ if (typeof toolCallId !== "string" || isCrewCoderRemote())
323
+ return;
324
+ const block = this.state.blocks.find((candidate) => candidate.type === "tool" && candidate.id === toolCallId);
325
+ // The agent's snapshot diffs (file_diff, before tool_execution_end) already carry real line numbers.
326
+ if (!block || block.fileDiffs?.length)
327
+ return;
328
+ computeLineAnchors(block, this.state.cwd, this.readFile).then((anchors) => {
329
+ if (!anchors)
330
+ return;
331
+ this.anchors.set(block, anchors);
332
+ this.notify();
333
+ }, () => undefined);
334
+ }
335
+ }
336
+ /**
337
+ * Extension tool renderers (`docs/TRANSCRIPT.md#extension-tool-renderers`): declarative
338
+ * templates from `crewcoder extension renderers --json`, through the injectable CLI so
339
+ * remote mode asks the SSH host. Loaded at startup and by `/reload`; a failure keeps the
340
+ * previous list (tools then draw as usual) and says why.
341
+ */
342
+ async loadExtensionRenderers() {
343
+ try {
344
+ const { stdout, stderr, exitCode } = await this.cli.exec(["extension", "renderers", "--json"]);
345
+ if (exitCode !== 0)
346
+ throw new Error(stderr.trim() || `extension renderers exited with code ${exitCode}`);
347
+ this.state.rendererHooks = parseExtensionRendererRecords(JSON.parse(stdout || "[]"));
348
+ this.notify();
349
+ }
350
+ catch (error) {
351
+ this.alert({ variant: "warning", title: "Could not load extension tool renderers", body: errorMessage(error) });
352
+ }
353
+ }
354
+ /**
355
+ * Ctrl+F / `/find [text]`: search the transcript. The bar takes the composer's
356
+ * place, so the draft is kept; there is nothing to search on the welcome screen.
357
+ */
358
+ openSearch(query = "") {
359
+ if (this.state.blocks.length === 0)
360
+ return this.alert({ variant: "info", title: "Nothing to search yet" });
361
+ this.preserveComposerDraft();
362
+ this.search.open(query);
363
+ }
364
+ /** Hide or show every edit's diff, resetting per-tool diff toggles. */
365
+ toggleAllDiffs() {
366
+ this.allDiffsHidden = !this.allDiffsHidden;
367
+ this.toggledDiffs = new WeakSet();
368
+ this.notify();
369
+ }
370
+ flip(set, block) {
371
+ if (set.has(block))
372
+ set.delete(block);
373
+ else
374
+ set.add(block);
375
+ this.notify();
376
+ }
377
+ /** Expand or collapse every tool's output, resetting individual toggles. */
378
+ toggleAllToolOutput() {
379
+ this.allToolsExpanded = !this.allToolsExpanded;
380
+ this.toggledTools = new WeakSet();
381
+ this.notify();
382
+ }
383
+ // ── Extension questions ────────────────────────────────────────────────────
384
+ /**
385
+ * The extension question waiting for an answer: the oldest pending
386
+ * `extension_ui` request of the active run. Only a running agent can receive
387
+ * the answer, so none shows once the run is over.
388
+ */
389
+ question() {
390
+ if (!this.bridge.running)
391
+ return undefined;
392
+ return this.state.blocks.find((block) => block.type === "extension_ui" && block.status === "pending" && block.requestId !== "");
393
+ }
394
+ questionView(terminalHeight, terminalWidth) {
395
+ const block = this.question();
396
+ if (!block)
397
+ return undefined;
398
+ const nav = this.navFor(block);
399
+ return questionView(block, questionContentWidth(terminalWidth), questionMaxRows(terminalHeight), nav.cursor, nav.offset);
400
+ }
401
+ /** Move between choices (confirm, select, component), wrapping at either end. */
402
+ moveQuestionCursor(delta) {
403
+ const block = this.question();
404
+ if (!block)
405
+ return;
406
+ const count = questionChoices(block).length;
407
+ if (count === 0)
408
+ return;
409
+ const nav = this.navFor(block);
410
+ this.questionNav = { ...nav, cursor: (((nav.cursor + delta) % count) + count) % count };
411
+ this.notify();
412
+ }
413
+ /** Scroll a question that is too long for the card; the view clamps the offset. */
414
+ scrollQuestion(delta, terminalHeight, terminalWidth) {
415
+ const block = this.question();
416
+ if (!block)
417
+ return;
418
+ const nav = this.navFor(block);
419
+ const applied = this.questionView(terminalHeight, terminalWidth)?.offset ?? nav.offset;
420
+ this.questionNav = { ...nav, offset: Math.max(0, applied + delta) };
421
+ this.notify();
422
+ }
423
+ /** Answer with the highlighted choice (Enter on confirm, select, or component). */
424
+ submitQuestionChoice() {
425
+ const block = this.question();
426
+ if (block)
427
+ this.answerQuestion(choiceAnswer(block, this.navFor(block).cursor));
428
+ }
429
+ /** Answer with a clicked choice. */
430
+ chooseQuestion(choice) {
431
+ const block = this.question();
432
+ if (block)
433
+ this.answerQuestion(choiceAnswer(block, choice));
434
+ }
435
+ /**
436
+ * Send the answer over the `ui_response` control channel; `null` cancels.
437
+ * The block is settled locally at once so the card closes; the agent's
438
+ * `extension_ui_resolved` confirms it.
439
+ */
440
+ answerQuestion(value) {
441
+ const block = this.question();
442
+ if (!block)
443
+ return;
444
+ if (!this.bridge.resolveUiRequest(block.requestId, value)) {
445
+ this.state.blocks.push({ type: "error", text: "No active CrewCoder run is waiting for this extension question." });
446
+ }
447
+ block.status = value === null ? "cancelled" : "answered";
448
+ if (value !== null)
449
+ block.answer = typeof value === "boolean" ? (value ? "yes" : "no") : value;
450
+ this.notify();
451
+ }
452
+ navFor(block) {
453
+ return this.questionNav.requestId === block.requestId ? this.questionNav : { requestId: block.requestId, cursor: 0, offset: 0 };
454
+ }
455
+ // ── Alerts, composer, editor ───────────────────────────────────────────────
456
+ alert(alert) {
457
+ this.currentAlert = alert;
458
+ this.notify();
459
+ }
460
+ dismissAlert() {
461
+ if (!this.currentAlert)
462
+ return;
463
+ this.currentAlert = undefined;
464
+ this.notify();
465
+ }
466
+ setComposerDraft(text) {
467
+ this.composerDraft = text;
468
+ this.composerDraftVersion += 1;
469
+ this.notify();
470
+ }
471
+ /** The composer's current text; restored as a draft after an overlay closes. */
472
+ setComposerText(text) {
473
+ this.composerText = text;
474
+ }
475
+ /** Keep the composer draft when an overlay that unmounts it opens on its own. */
476
+ preserveComposerDraft() {
477
+ if (this.composerText)
478
+ this.setComposerDraft(this.composerText);
479
+ }
480
+ /**
481
+ * Up/Down on the composer's first/last line: the text of the older/newer
482
+ * sent message (or the saved draft), or undefined when there is nothing
483
+ * further that way. See `prompt-history.ts`.
484
+ */
485
+ recallPrompt(direction, current) {
486
+ const step = stepRecall(this.historyRecall, direction, current, sentMessages(this.state.blocks));
487
+ if (!step)
488
+ return undefined;
489
+ this.historyRecall = step.recall;
490
+ return step.text;
491
+ }
492
+ setComposerLines(lines) {
493
+ const next = Math.max(1, lines);
494
+ if (next === this.composerLines)
495
+ return;
496
+ this.composerLines = next;
497
+ this.notify();
498
+ }
499
+ // ── /goal preflight form ─────────────────────────────────────────────────────
500
+ /** Bare `/goal`: settings for this goal only, prefilled from `config.goals`. The draft is kept. */
501
+ openGoalForm(defaults) {
502
+ this.preserveComposerDraft();
503
+ this.picker = undefined;
504
+ this.goalForm = initialGoalForm(defaults);
505
+ this.notify();
506
+ }
507
+ selectGoalField(index) {
508
+ if (!this.goalForm)
509
+ return;
510
+ this.goalForm = selectGoalField(this.goalForm, index);
511
+ this.notify();
512
+ }
513
+ moveGoalField(delta) {
514
+ if (this.goalForm)
515
+ this.selectGoalField(this.goalForm.selected + delta);
516
+ }
517
+ editGoalField(value) {
518
+ if (!this.goalForm)
519
+ return;
520
+ this.goalForm = editGoalField(this.goalForm, value);
521
+ this.notify();
522
+ }
523
+ /** Enter: the next field, or start the goal from the last one (legacy). */
524
+ goalFormEnter() {
525
+ if (!this.goalForm)
526
+ return;
527
+ if (this.goalForm.selected < GOAL_FIELDS.length - 1)
528
+ this.moveGoalField(1);
529
+ else
530
+ this.submitGoalForm();
531
+ }
532
+ /** Ctrl+S: start the goal, or show what is wrong on that field. */
533
+ submitGoalForm() {
534
+ if (!this.goalForm)
535
+ return;
536
+ const result = submitGoalForm(this.goalForm);
537
+ if ("form" in result) {
538
+ this.goalForm = result.form;
539
+ this.notify();
540
+ return;
541
+ }
542
+ this.goalForm = undefined;
543
+ this.notify();
544
+ this.commands.startGoal(result.start).then(() => this.notify(), (error) => this.alert({ variant: "error", title: "Could not start the goal", body: errorMessage(error) }));
545
+ }
546
+ closeGoalForm() {
547
+ if (!this.goalForm)
548
+ return;
549
+ this.goalForm = undefined;
550
+ this.notify();
551
+ }
552
+ openSummaryEditor(editor) {
553
+ this.picker = undefined;
554
+ this.editor = editor;
555
+ this.currentAlert = undefined;
556
+ this.notify();
557
+ }
558
+ /** Apply (with the edited text) or cancel the open compaction summary editor. */
559
+ resolveSummary(approved, summary) {
560
+ const editor = this.editor;
561
+ if (!editor)
562
+ return;
563
+ this.editor = undefined;
564
+ const context = editor.context;
565
+ if (context.mode === "live") {
566
+ if (!this.bridge.resolveCompactionPreview(context.previewId, approved, approved ? summary : undefined)) {
567
+ this.alert({ variant: "error", title: "No active run is waiting for this compaction preview" });
568
+ }
569
+ else {
570
+ this.alert(approved ? { variant: "success", title: "Edited summary sent to the running session" } : { variant: "info", title: "Compaction preview cancelled" });
571
+ }
572
+ return;
573
+ }
574
+ if (!approved) {
575
+ this.alert({ variant: "info", title: "Compaction preview cancelled" });
576
+ return;
577
+ }
578
+ this.commands.applyEditedSummary(context.sessionId, summary).then(() => this.notify(), (error) => this.alert({ variant: "error", title: "Could not apply the edited summary", body: errorMessage(error) }));
579
+ }
580
+ requestLiveCompactionPreview() {
581
+ return this.bridge.requestCompactionPreview();
582
+ }
583
+ clearScreen() {
584
+ this.search.close();
585
+ this.state.blocks = [];
586
+ this.currentAlert = undefined;
587
+ this.notify();
588
+ }
589
+ // ── Session ────────────────────────────────────────────────────────────────
590
+ /** Start, resume, or queue a follow-up for the active run. */
591
+ submit(input) {
592
+ // A sent message ends any recall; the next Up starts from the newest again.
593
+ this.historyRecall = IDLE_RECALL;
594
+ const text = input.trim();
595
+ // A pasted screenshot can be sent on its own.
596
+ if (!text && this.state.attachments.length === 0)
597
+ return;
598
+ if (text.startsWith("/")) {
599
+ this.runCommand(text);
600
+ this.notify();
601
+ return;
602
+ }
603
+ if (this.bridge.running) {
604
+ // The control channel carries text only; pending images wait for the next prompt.
605
+ if (!text)
606
+ return this.alert({ variant: "info", title: "Images are sent with the next prompt, after this turn" });
607
+ if (!this.queueFollowUp(text))
608
+ this.alert({ variant: "error", title: "Could not queue the follow-up for the active run" });
609
+ return;
610
+ }
611
+ // Image paths in the prompt (a file dropped on the terminal) attach too; the text keeps them.
612
+ if (!isCrewCoderRemote())
613
+ this.state.attachments = [...this.state.attachments, ...attachImagePaths(text, this.state.attachments)];
614
+ this.startRun(text);
615
+ }
616
+ startPrompt(text) {
617
+ this.startRun(text);
618
+ }
619
+ /**
620
+ * `/crew` and `/team`. With tmux available (local workspaces), first ask where the
621
+ * crew runs: here (quitting stops it) or in tmux (keeps running after this UI
622
+ * closes). Without tmux it runs here.
623
+ */
624
+ launchCrew(target, task, command) {
625
+ if (this.refuseBusyCrew())
626
+ return;
627
+ if (!this.crewTmux || isCrewCoderRemote())
628
+ return this.startCrew(target, task, command);
629
+ this.preserveComposerDraft();
630
+ this.pendingCrew = { target, task, command };
631
+ this.openPicker({
632
+ kind: "crewLaunch",
633
+ title: `Where should ${crewLabel(target)} run?`,
634
+ placeholder: "Search…",
635
+ emptyText: "Nothing to pick",
636
+ loading: false,
637
+ items: [
638
+ // Short: picker rows do not wrap.
639
+ { id: CREW_IN_TMUX, label: "Run in tmux", description: "survives closing CrewCoder; attach to approve" },
640
+ { id: CREW_HERE, label: "Run here", description: "quitting CrewCoder stops the crew" }
641
+ ]
642
+ });
643
+ }
644
+ /**
645
+ * Hand the crew to a second UI in tmux. Its settings and `CREWCODER_*` variables go
646
+ * in a private handoff file the new UI reads and deletes (`tmux.ts`).
647
+ */
648
+ async runCrewInTmux(pending) {
649
+ const tmux = this.crewTmux;
650
+ if (!tmux || this.refuseBusyCrew())
651
+ return;
652
+ const state = this.state;
653
+ let file;
654
+ try {
655
+ file = writeCrewHandoff({
656
+ version: 1, ...pending, cwd: state.cwd, provider: state.provider, model: state.model, effort: state.effort,
657
+ mode: state.mode, systemPrompt: state.systemPrompt, fullAccess: state.fullAccess, env: handoffEnv(process.env)
658
+ });
659
+ const placement = await tmux.launcher.launch(tmux.command(file), state.cwd, crewLabel(pending.target));
660
+ // A record that outlives the next keypress: the attach command is needed later.
661
+ state.blocks.push({ type: "user", text: pending.command });
662
+ state.blocks.push({ type: "system", text: tmuxAttachHint(placement) });
663
+ this.notify();
664
+ }
665
+ catch (error) {
666
+ if (file)
667
+ removeCrewHandoff(file);
668
+ this.alert({ variant: "error", title: "Could not start the crew in tmux", body: errorMessage(error) });
669
+ }
670
+ }
671
+ refuseBusyCrew() {
672
+ if (!this.bridge.running && !this.state.running)
673
+ return false;
674
+ this.alert({ variant: "warning", title: "Wait for the current run to finish before starting a crew", body: "Use /stop to end it." });
675
+ return true;
676
+ }
677
+ /**
678
+ * `/crew` and `/team`: stream the crew through the bridge so its roster, each
679
+ * worker's work, and approvals show live. Workers run in their own sessions;
680
+ * this session's id and transcript stay. `command` is what the user typed.
681
+ */
682
+ startCrew(target, task, command) {
683
+ if (this.refuseBusyCrew())
684
+ return;
685
+ const state = this.state;
686
+ state.blocks.push({ type: "user", text: command });
687
+ state.running = true;
688
+ // The AGENTS roster lives in the sidebar; a crew is the moment to show it.
689
+ if (!this.sidebar.open)
690
+ this.sidebar.setOpen(true);
691
+ // The agent's crew commands take no worker, budget, image, or directory options.
692
+ const options = {
693
+ target,
694
+ prompt: task,
695
+ provider: state.provider,
696
+ mode: state.mode,
697
+ model: state.model,
698
+ systemPrompt: state.systemPrompt,
699
+ effort: state.effort,
700
+ cwd: state.cwd,
701
+ approval: state.fullAccess ? "full-access" : "review"
702
+ };
703
+ try {
704
+ this.bridge.crew(options, this.onEvent);
705
+ }
706
+ catch (error) {
707
+ state.running = false;
708
+ this.alert({ variant: "error", title: "Could not start the crew", body: errorMessage(error) });
709
+ return;
710
+ }
711
+ this.notify();
712
+ }
713
+ queueFollowUp(text) {
714
+ if (!this.bridge.followUp(text))
715
+ return false;
716
+ this.state.blocks.push({ type: "user", text, background: ["Queued follow-up for the running turn."] });
717
+ this.notify();
718
+ return true;
719
+ }
720
+ /** Resolve a pending approval (the latest by default) over the live control channel. */
721
+ resolveApproval(approvalId, approved) {
722
+ const id = approvalId ?? this.pendingApproval()?.id;
723
+ const verb = approved ? "approve" : "deny";
724
+ if (!id)
725
+ return this.alert({ variant: "warning", title: `No pending approval to ${verb}` });
726
+ if (!this.bridge.running)
727
+ return this.alert({ variant: "warning", title: "No active run is waiting for approval" });
728
+ const reason = approved ? "Approved from OpenTUI control channel." : "Denied from OpenTUI control channel.";
729
+ if (!this.bridge.resolveApproval(id, approved, reason))
730
+ this.alert({ variant: "error", title: `Could not ${verb} ${id}` });
731
+ this.notify();
732
+ }
733
+ /** The approval card buttons and Ctrl+Y / Ctrl+N. */
734
+ resolvePendingApproval(approved) {
735
+ const pending = this.pendingApproval();
736
+ if (!pending?.id || !this.bridge.running)
737
+ return false;
738
+ const reason = approved ? "Approved from OpenTUI control channel." : "Denied from OpenTUI control channel.";
739
+ const resolved = this.bridge.resolveApproval(pending.id, approved, reason);
740
+ if (!resolved)
741
+ this.state.blocks.push({ type: "error", text: `Could not ${approved ? "approve" : "deny"} ${pending.id}.` });
742
+ this.notify();
743
+ return resolved;
744
+ }
745
+ pendingApproval() {
746
+ for (let index = this.state.blocks.length - 1; index >= 0; index--) {
747
+ const block = this.state.blocks[index];
748
+ if (block?.type === "approval" && block.status === "pending")
749
+ return block;
750
+ }
751
+ return undefined;
752
+ }
753
+ /** Abort the active run. Returns false when nothing was running. */
754
+ abort() {
755
+ if (!this.bridge.running && !this.state.running)
756
+ return false;
757
+ this.bridge.stop();
758
+ // A stopped crew sends no crew_end; finish its roster here.
759
+ stopCrew(this.state);
760
+ this.state.running = false;
761
+ this.state.blocks.push({ type: "system", text: "Request aborted." });
762
+ this.notify();
763
+ return true;
764
+ }
765
+ push(block) {
766
+ this.state.blocks.push(block);
767
+ this.notify();
768
+ }
769
+ changed() {
770
+ this.notify();
771
+ }
772
+ attachSkill(skill) {
773
+ if (this.pendingSkills.some((attached) => attached.name === skill.name)) {
774
+ this.alert({ variant: "info", title: `Skill already attached: ${skill.name}`, body: "It goes with your next message." });
775
+ return;
776
+ }
777
+ this.pendingSkills.push(skill);
778
+ this.alert({ variant: "success", title: `Skill attached: ${skill.name}`, body: `Goes with your next message (${this.pendingSkills.length} attached).` });
779
+ }
780
+ /** Load a saved session's history with its provider, model, effort, mode, and directories. */
781
+ resumeSession(session) {
782
+ this.bridge.stop();
783
+ this.search.close();
784
+ const state = this.state;
785
+ this.resetCrew();
786
+ state.blocks = [];
787
+ state.changedFiles = [];
788
+ state.systemPrompt = undefined;
789
+ state.worker = undefined;
790
+ if (session.provider)
791
+ state.provider = session.provider;
792
+ if (session.model)
793
+ state.model = session.model;
794
+ // A saved level the resumed model rejects (e.g. xhigh) must not ride along.
795
+ state.effort = PickerFlows.resumeEffort(state, session.effort);
796
+ state.externalDirectories = [...(session.externalDirectories ?? [])];
797
+ const mode = session.requestedMode || session.resolvedMode;
798
+ if (mode)
799
+ state.mode = normalizeTuiMode(mode);
800
+ state.sessionId = session.id;
801
+ state.running = true;
802
+ this.notify();
803
+ this.bridge.resume({ ...this.runOptions(), sessionId: session.id }, this.onEvent);
804
+ }
805
+ dispose() {
806
+ this.sidebar.dispose();
807
+ this.bridge.stop();
808
+ this.listeners.clear();
809
+ }
810
+ onEvent = (event) => {
811
+ const questionOpen = this.question() !== undefined;
812
+ applyCrewCoderEvent(this.state, event);
813
+ if (event.type === "tool_execution_end")
814
+ this.anchorEdit(event.toolCallId);
815
+ // Task tools write the store; a finished run may have moved the branch or dirtied the tree.
816
+ if (this.sidebar.open && (event.type === "tool_execution_end" || event.type === "agent_end"))
817
+ void this.sidebar.refreshTasks();
818
+ if (event.type === "agent_end")
819
+ void this.sidebar.refreshGitLabel();
820
+ // An extension question replaces the footer, picker included; keep what the user was typing.
821
+ if (event.type === "extension_ui_request" && !questionOpen && this.question()) {
822
+ this.preserveComposerDraft();
823
+ this.picker = undefined;
824
+ this.pickerQuery = "";
825
+ this.pickerCursor = 0;
826
+ }
827
+ // A live /compact preview: the loop paused for the user to edit the summary.
828
+ if (event.type === "session_compaction_preview" && typeof event.previewId === "string" && typeof event.summary === "string") {
829
+ this.preserveComposerDraft();
830
+ this.openSummaryEditor({
831
+ summary: event.summary,
832
+ context: { mode: "live", previewId: event.previewId },
833
+ source: typeof event.source === "string" ? event.source : undefined,
834
+ originalMessageCount: typeof event.originalMessageCount === "number" ? event.originalMessageCount : undefined,
835
+ retainedMessageCount: typeof event.retainedMessageCount === "number" ? event.retainedMessageCount : undefined
836
+ });
837
+ return;
838
+ }
839
+ this.notify();
840
+ };
841
+ runOptions() {
842
+ const state = this.state;
843
+ return {
844
+ provider: state.provider,
845
+ mode: state.mode,
846
+ worker: state.worker,
847
+ model: state.model,
848
+ systemPrompt: state.systemPrompt,
849
+ effort: state.effort,
850
+ cwd: state.cwd,
851
+ approval: state.fullAccess ? "full-access" : "review",
852
+ budget: state.tokenBudget,
853
+ externalDirectories: state.externalDirectories
854
+ };
855
+ }
856
+ startRun(text) {
857
+ const attachments = this.state.attachments;
858
+ if (attachments.length > 0 && isCrewCoderRemote()) {
859
+ this.alert({ variant: "error", title: "Local images cannot be sent in remote SSH mode", body: `Clear them with ${actionLabel("clearAttachments")} and send the prompt again.` });
860
+ return;
861
+ }
862
+ this.state.blocks.push({ type: "user", text: text || "(image attached)" });
863
+ // Each image shows under the user turn; the agent gets the files as --image.
864
+ for (const attachment of attachments)
865
+ this.state.blocks.push({ type: "image", attachment });
866
+ this.state.attachments = [];
867
+ this.state.running = true;
868
+ const prompt = this.withPendingSkills(text);
869
+ const images = attachments.map((attachment) => attachment.path);
870
+ this.notify();
871
+ if (this.state.sessionId && this.state.sessionId !== "new") {
872
+ this.bridge.resume({ ...this.runOptions(), prompt, images, sessionId: this.state.sessionId }, this.onEvent);
873
+ return;
874
+ }
875
+ this.bridge.run({ ...this.runOptions(), prompt, images }, this.onEvent);
876
+ }
877
+ /** Skills from /skills ride ahead of the next prompt once; the transcript shows only the typed text. */
878
+ withPendingSkills(prompt) {
879
+ if (!this.pendingSkills.length)
880
+ return prompt;
881
+ const skills = this.pendingSkills.map((skill) => `# Skill: ${skill.name}\n${skill.description}\n\n${skill.body}`).join("\n\n");
882
+ this.pendingSkills = [];
883
+ return `The user attached the following skill(s). Follow their instructions when relevant to the request below.\n\n${skills}\n\n---\n\n${prompt}`;
884
+ }
885
+ runCommand(command) {
886
+ const match = /^(\S+)\s*([\s\S]*)$/.exec(command);
887
+ const name = match?.[1] ?? command;
888
+ const rest = match?.[2] ?? "";
889
+ if (name === "/new")
890
+ return this.newSession();
891
+ if (name === "/stop") {
892
+ if (!this.abort())
893
+ this.alert({ variant: "info", title: "Nothing is running" });
894
+ return;
895
+ }
896
+ const kind = Object.hasOwn(PICKER_COMMANDS, name) ? PICKER_COMMANDS[name] : undefined;
897
+ if (kind && rest.trim()) {
898
+ this.flows.applyArgument(kind, rest.trim()).then(() => this.notify(), (error) => this.alert({ variant: "error", title: name, body: errorMessage(error) }));
899
+ return;
900
+ }
901
+ if (kind)
902
+ return this.flows.open(kind);
903
+ if (this.commands.run(name, rest))
904
+ return;
905
+ this.alert({
906
+ variant: "warning",
907
+ title: `${name} is not available in OpenTUI yet`,
908
+ body: "Use the legacy UI (crewcoder-tui) or the agent CLI for it."
909
+ });
910
+ }
911
+ /** Crews belong to the session they ran from: a stopped one is finished, its workers forgotten. */
912
+ resetCrew() {
913
+ stopCrew(this.state);
914
+ this.state.crewWorkers = [];
915
+ this.state.crewSessionIds = [];
916
+ }
917
+ newSession() {
918
+ this.bridge.stop();
919
+ this.search.close();
920
+ this.resetCrew();
921
+ this.state.sessionId = "new";
922
+ this.state.blocks = [];
923
+ this.state.running = false;
924
+ this.state.changedFiles = [];
925
+ this.state.checkpoints = [];
926
+ this.state.usage = { turns: 0 };
927
+ this.state.externalDirectories = [];
928
+ this.state.tokenBudget = undefined;
929
+ this.state.fullAccess = false;
930
+ this.state.attachments = [];
931
+ this.pendingSkills = [];
932
+ this.editor = undefined;
933
+ this.currentAlert = undefined;
934
+ }
935
+ notify() {
936
+ this.version += 1;
937
+ for (const listener of this.listeners)
938
+ listener();
939
+ }
940
+ }
941
+ //# sourceMappingURL=session-controller.js.map