indusagi-coding-agent 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 (240) hide show
  1. package/CHANGELOG.md +2249 -0
  2. package/README.md +546 -0
  3. package/dist/cli/args.js +282 -0
  4. package/dist/cli/config-selector.js +30 -0
  5. package/dist/cli/file-processor.js +78 -0
  6. package/dist/cli/list-models.js +91 -0
  7. package/dist/cli/session-picker.js +31 -0
  8. package/dist/cli.js +10 -0
  9. package/dist/config.js +158 -0
  10. package/dist/core/agent-session.js +2097 -0
  11. package/dist/core/auth-storage.js +278 -0
  12. package/dist/core/bash-executor.js +211 -0
  13. package/dist/core/compaction/branch-summarization.js +241 -0
  14. package/dist/core/compaction/compaction.js +606 -0
  15. package/dist/core/compaction/index.js +6 -0
  16. package/dist/core/compaction/utils.js +137 -0
  17. package/dist/core/diagnostics.js +1 -0
  18. package/dist/core/event-bus.js +24 -0
  19. package/dist/core/exec.js +70 -0
  20. package/dist/core/export-html/ansi-to-html.js +248 -0
  21. package/dist/core/export-html/index.js +221 -0
  22. package/dist/core/export-html/template.css +905 -0
  23. package/dist/core/export-html/template.html +54 -0
  24. package/dist/core/export-html/template.js +1549 -0
  25. package/dist/core/export-html/tool-renderer.js +56 -0
  26. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  27. package/dist/core/export-html/vendor/marked.min.js +6 -0
  28. package/dist/core/extensions/index.js +8 -0
  29. package/dist/core/extensions/loader.js +395 -0
  30. package/dist/core/extensions/runner.js +499 -0
  31. package/dist/core/extensions/types.js +31 -0
  32. package/dist/core/extensions/wrapper.js +101 -0
  33. package/dist/core/footer-data-provider.js +133 -0
  34. package/dist/core/index.js +8 -0
  35. package/dist/core/keybindings.js +140 -0
  36. package/dist/core/messages.js +122 -0
  37. package/dist/core/model-registry.js +454 -0
  38. package/dist/core/model-resolver.js +309 -0
  39. package/dist/core/package-manager.js +1142 -0
  40. package/dist/core/prompt-templates.js +250 -0
  41. package/dist/core/resource-loader.js +569 -0
  42. package/dist/core/sdk.js +225 -0
  43. package/dist/core/session-manager.js +1078 -0
  44. package/dist/core/settings-manager.js +430 -0
  45. package/dist/core/skills.js +339 -0
  46. package/dist/core/system-prompt.js +136 -0
  47. package/dist/core/timings.js +24 -0
  48. package/dist/core/tools/bash.js +226 -0
  49. package/dist/core/tools/edit-diff.js +242 -0
  50. package/dist/core/tools/edit.js +145 -0
  51. package/dist/core/tools/find.js +205 -0
  52. package/dist/core/tools/grep.js +238 -0
  53. package/dist/core/tools/index.js +60 -0
  54. package/dist/core/tools/ls.js +117 -0
  55. package/dist/core/tools/path-utils.js +52 -0
  56. package/dist/core/tools/read.js +165 -0
  57. package/dist/core/tools/truncate.js +204 -0
  58. package/dist/core/tools/write.js +77 -0
  59. package/dist/index.js +41 -0
  60. package/dist/main.js +565 -0
  61. package/dist/migrations.js +260 -0
  62. package/dist/modes/index.js +7 -0
  63. package/dist/modes/interactive/components/armin.js +328 -0
  64. package/dist/modes/interactive/components/assistant-message.js +86 -0
  65. package/dist/modes/interactive/components/bash-execution.js +155 -0
  66. package/dist/modes/interactive/components/bordered-loader.js +47 -0
  67. package/dist/modes/interactive/components/branch-summary-message.js +41 -0
  68. package/dist/modes/interactive/components/compaction-summary-message.js +42 -0
  69. package/dist/modes/interactive/components/config-selector.js +458 -0
  70. package/dist/modes/interactive/components/countdown-timer.js +27 -0
  71. package/dist/modes/interactive/components/custom-editor.js +61 -0
  72. package/dist/modes/interactive/components/custom-message.js +80 -0
  73. package/dist/modes/interactive/components/diff.js +132 -0
  74. package/dist/modes/interactive/components/dynamic-border.js +19 -0
  75. package/dist/modes/interactive/components/extension-editor.js +96 -0
  76. package/dist/modes/interactive/components/extension-input.js +54 -0
  77. package/dist/modes/interactive/components/extension-selector.js +70 -0
  78. package/dist/modes/interactive/components/footer.js +213 -0
  79. package/dist/modes/interactive/components/index.js +31 -0
  80. package/dist/modes/interactive/components/keybinding-hints.js +60 -0
  81. package/dist/modes/interactive/components/login-dialog.js +138 -0
  82. package/dist/modes/interactive/components/model-selector.js +253 -0
  83. package/dist/modes/interactive/components/oauth-selector.js +91 -0
  84. package/dist/modes/interactive/components/scoped-models-selector.js +262 -0
  85. package/dist/modes/interactive/components/session-selector-search.js +145 -0
  86. package/dist/modes/interactive/components/session-selector.js +698 -0
  87. package/dist/modes/interactive/components/settings-selector.js +250 -0
  88. package/dist/modes/interactive/components/show-images-selector.js +33 -0
  89. package/dist/modes/interactive/components/skill-invocation-message.js +44 -0
  90. package/dist/modes/interactive/components/theme-selector.js +43 -0
  91. package/dist/modes/interactive/components/thinking-selector.js +45 -0
  92. package/dist/modes/interactive/components/tool-execution.js +608 -0
  93. package/dist/modes/interactive/components/tree-selector.js +892 -0
  94. package/dist/modes/interactive/components/user-message-selector.js +109 -0
  95. package/dist/modes/interactive/components/user-message.js +15 -0
  96. package/dist/modes/interactive/components/visual-truncate.js +32 -0
  97. package/dist/modes/interactive/interactive-mode.js +3576 -0
  98. package/dist/modes/interactive/theme/dark.json +85 -0
  99. package/dist/modes/interactive/theme/light.json +84 -0
  100. package/dist/modes/interactive/theme/theme-schema.json +335 -0
  101. package/dist/modes/interactive/theme/theme.js +938 -0
  102. package/dist/modes/print-mode.js +96 -0
  103. package/dist/modes/rpc/rpc-client.js +390 -0
  104. package/dist/modes/rpc/rpc-mode.js +448 -0
  105. package/dist/modes/rpc/rpc-types.js +7 -0
  106. package/dist/utils/changelog.js +86 -0
  107. package/dist/utils/clipboard-image.js +116 -0
  108. package/dist/utils/clipboard.js +58 -0
  109. package/dist/utils/frontmatter.js +25 -0
  110. package/dist/utils/git.js +5 -0
  111. package/dist/utils/image-convert.js +34 -0
  112. package/dist/utils/image-resize.js +180 -0
  113. package/dist/utils/mime.js +25 -0
  114. package/dist/utils/photon.js +120 -0
  115. package/dist/utils/shell.js +164 -0
  116. package/dist/utils/sleep.js +16 -0
  117. package/dist/utils/tools-manager.js +186 -0
  118. package/docs/compaction.md +390 -0
  119. package/docs/custom-provider.md +538 -0
  120. package/docs/development.md +69 -0
  121. package/docs/extensions.md +1733 -0
  122. package/docs/images/doom-extension.png +0 -0
  123. package/docs/images/interactive-mode.png +0 -0
  124. package/docs/images/tree-view.png +0 -0
  125. package/docs/json.md +79 -0
  126. package/docs/keybindings.md +162 -0
  127. package/docs/models.md +193 -0
  128. package/docs/packages.md +163 -0
  129. package/docs/prompt-templates.md +67 -0
  130. package/docs/providers.md +147 -0
  131. package/docs/rpc.md +1048 -0
  132. package/docs/sdk.md +957 -0
  133. package/docs/session.md +412 -0
  134. package/docs/settings.md +216 -0
  135. package/docs/shell-aliases.md +13 -0
  136. package/docs/skills.md +226 -0
  137. package/docs/terminal-setup.md +65 -0
  138. package/docs/themes.md +295 -0
  139. package/docs/tree.md +219 -0
  140. package/docs/tui.md +887 -0
  141. package/docs/windows.md +17 -0
  142. package/examples/README.md +25 -0
  143. package/examples/extensions/README.md +192 -0
  144. package/examples/extensions/antigravity-image-gen.ts +414 -0
  145. package/examples/extensions/auto-commit-on-exit.ts +49 -0
  146. package/examples/extensions/bookmark.ts +50 -0
  147. package/examples/extensions/claude-rules.ts +86 -0
  148. package/examples/extensions/confirm-destructive.ts +59 -0
  149. package/examples/extensions/custom-compaction.ts +115 -0
  150. package/examples/extensions/custom-footer.ts +65 -0
  151. package/examples/extensions/custom-header.ts +73 -0
  152. package/examples/extensions/custom-provider-anthropic/index.ts +605 -0
  153. package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
  154. package/examples/extensions/custom-provider-anthropic/package.json +19 -0
  155. package/examples/extensions/custom-provider-gitlab-duo/index.ts +350 -0
  156. package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
  157. package/examples/extensions/custom-provider-gitlab-duo/test.ts +83 -0
  158. package/examples/extensions/dirty-repo-guard.ts +56 -0
  159. package/examples/extensions/doom-overlay/README.md +46 -0
  160. package/examples/extensions/doom-overlay/doom/build/doom.js +21 -0
  161. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  162. package/examples/extensions/doom-overlay/doom/build.sh +152 -0
  163. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -0
  164. package/examples/extensions/doom-overlay/doom-component.ts +133 -0
  165. package/examples/extensions/doom-overlay/doom-engine.ts +173 -0
  166. package/examples/extensions/doom-overlay/doom-keys.ts +105 -0
  167. package/examples/extensions/doom-overlay/index.ts +74 -0
  168. package/examples/extensions/doom-overlay/wad-finder.ts +51 -0
  169. package/examples/extensions/event-bus.ts +43 -0
  170. package/examples/extensions/file-trigger.ts +41 -0
  171. package/examples/extensions/git-checkpoint.ts +53 -0
  172. package/examples/extensions/handoff.ts +151 -0
  173. package/examples/extensions/hello.ts +25 -0
  174. package/examples/extensions/inline-bash.ts +94 -0
  175. package/examples/extensions/input-transform.ts +43 -0
  176. package/examples/extensions/interactive-shell.ts +196 -0
  177. package/examples/extensions/mac-system-theme.ts +47 -0
  178. package/examples/extensions/message-renderer.ts +60 -0
  179. package/examples/extensions/modal-editor.ts +86 -0
  180. package/examples/extensions/model-status.ts +31 -0
  181. package/examples/extensions/notify.ts +25 -0
  182. package/examples/extensions/overlay-qa-tests.ts +882 -0
  183. package/examples/extensions/overlay-test.ts +151 -0
  184. package/examples/extensions/permission-gate.ts +34 -0
  185. package/examples/extensions/pirate.ts +47 -0
  186. package/examples/extensions/plan-mode/README.md +65 -0
  187. package/examples/extensions/plan-mode/index.ts +341 -0
  188. package/examples/extensions/plan-mode/utils.ts +168 -0
  189. package/examples/extensions/preset.ts +399 -0
  190. package/examples/extensions/protected-paths.ts +30 -0
  191. package/examples/extensions/qna.ts +120 -0
  192. package/examples/extensions/question.ts +265 -0
  193. package/examples/extensions/questionnaire.ts +428 -0
  194. package/examples/extensions/rainbow-editor.ts +88 -0
  195. package/examples/extensions/sandbox/index.ts +318 -0
  196. package/examples/extensions/sandbox/package-lock.json +92 -0
  197. package/examples/extensions/sandbox/package.json +19 -0
  198. package/examples/extensions/send-user-message.ts +97 -0
  199. package/examples/extensions/session-name.ts +27 -0
  200. package/examples/extensions/shutdown-command.ts +63 -0
  201. package/examples/extensions/snake.ts +344 -0
  202. package/examples/extensions/space-invaders.ts +561 -0
  203. package/examples/extensions/ssh.ts +220 -0
  204. package/examples/extensions/status-line.ts +40 -0
  205. package/examples/extensions/subagent/README.md +172 -0
  206. package/examples/extensions/subagent/agents/planner.md +37 -0
  207. package/examples/extensions/subagent/agents/reviewer.md +35 -0
  208. package/examples/extensions/subagent/agents/scout.md +50 -0
  209. package/examples/extensions/subagent/agents/worker.md +24 -0
  210. package/examples/extensions/subagent/agents.ts +127 -0
  211. package/examples/extensions/subagent/index.ts +964 -0
  212. package/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
  213. package/examples/extensions/subagent/prompts/implement.md +10 -0
  214. package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
  215. package/examples/extensions/summarize.ts +196 -0
  216. package/examples/extensions/timed-confirm.ts +70 -0
  217. package/examples/extensions/todo.ts +300 -0
  218. package/examples/extensions/tool-override.ts +144 -0
  219. package/examples/extensions/tools.ts +147 -0
  220. package/examples/extensions/trigger-compact.ts +40 -0
  221. package/examples/extensions/truncated-tool.ts +193 -0
  222. package/examples/extensions/widget-placement.ts +17 -0
  223. package/examples/extensions/with-deps/index.ts +36 -0
  224. package/examples/extensions/with-deps/package-lock.json +31 -0
  225. package/examples/extensions/with-deps/package.json +22 -0
  226. package/examples/sdk/01-minimal.ts +22 -0
  227. package/examples/sdk/02-custom-model.ts +50 -0
  228. package/examples/sdk/03-custom-prompt.ts +55 -0
  229. package/examples/sdk/04-skills.ts +46 -0
  230. package/examples/sdk/05-tools.ts +56 -0
  231. package/examples/sdk/06-extensions.ts +88 -0
  232. package/examples/sdk/07-context-files.ts +40 -0
  233. package/examples/sdk/08-prompt-templates.ts +47 -0
  234. package/examples/sdk/09-api-keys-and-oauth.ts +48 -0
  235. package/examples/sdk/10-settings.ts +38 -0
  236. package/examples/sdk/11-sessions.ts +48 -0
  237. package/examples/sdk/12-full-control.ts +82 -0
  238. package/examples/sdk/13-codex-oauth.ts +37 -0
  239. package/examples/sdk/README.md +144 -0
  240. package/package.json +85 -0
@@ -0,0 +1,3576 @@
1
+ /**
2
+ * Interactive mode for the coding agent.
3
+ * Handles TUI rendering and user interaction, delegating business logic to AgentSession.
4
+ */
5
+ import * as crypto from "node:crypto";
6
+ import * as fs from "node:fs";
7
+ import * as os from "node:os";
8
+ import * as path from "node:path";
9
+ import { getOAuthProviders, } from "indusagi/ai";
10
+ import { CombinedAutocompleteProvider, Container, fuzzyFilter, Loader, Markdown, matchesKey, ProcessTerminal, Spacer, Text, TruncatedText, TUI, visibleWidth, } from "indusagi/tui";
11
+ import { spawn, spawnSync } from "child_process";
12
+ import { APP_NAME, getAuthPath, getDebugLogPath, getShareViewerUrl, isBunBinary, isBunRuntime, VERSION, } from "../../config.js";
13
+ import { parseSkillBlock } from "../../core/agent-session.js";
14
+ import { FooterDataProvider } from "../../core/footer-data-provider.js";
15
+ import { KeybindingsManager } from "../../core/keybindings.js";
16
+ import { createCompactionSummaryMessage } from "../../core/messages.js";
17
+ import { resolveModelScope } from "../../core/model-resolver.js";
18
+ import { SessionManager } from "../../core/session-manager.js";
19
+ import { getChangelogPath, getNewEntries, parseChangelog } from "../../utils/changelog.js";
20
+ import { copyToClipboard } from "../../utils/clipboard.js";
21
+ import { extensionForImageMimeType, readClipboardImage } from "../../utils/clipboard-image.js";
22
+ import { ensureTool } from "../../utils/tools-manager.js";
23
+ import { ArminComponent } from "./components/armin.js";
24
+ import { AssistantMessageComponent } from "./components/assistant-message.js";
25
+ import { BashExecutionComponent } from "./components/bash-execution.js";
26
+ import { BorderedLoader } from "./components/bordered-loader.js";
27
+ import { BranchSummaryMessageComponent } from "./components/branch-summary-message.js";
28
+ import { CompactionSummaryMessageComponent } from "./components/compaction-summary-message.js";
29
+ import { CustomEditor } from "./components/custom-editor.js";
30
+ import { CustomMessageComponent } from "./components/custom-message.js";
31
+ import { DynamicBorder } from "./components/dynamic-border.js";
32
+ import { ExtensionEditorComponent } from "./components/extension-editor.js";
33
+ import { ExtensionInputComponent } from "./components/extension-input.js";
34
+ import { ExtensionSelectorComponent } from "./components/extension-selector.js";
35
+ import { FooterComponent } from "./components/footer.js";
36
+ import { appKey, appKeyHint, editorKey, keyHint, rawKeyHint } from "./components/keybinding-hints.js";
37
+ import { LoginDialogComponent } from "./components/login-dialog.js";
38
+ import { ModelSelectorComponent } from "./components/model-selector.js";
39
+ import { OAuthSelectorComponent } from "./components/oauth-selector.js";
40
+ import { ScopedModelsSelectorComponent } from "./components/scoped-models-selector.js";
41
+ import { SessionSelectorComponent } from "./components/session-selector.js";
42
+ import { SettingsSelectorComponent } from "./components/settings-selector.js";
43
+ import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
44
+ import { ToolExecutionComponent } from "./components/tool-execution.js";
45
+ import { TreeSelectorComponent } from "./components/tree-selector.js";
46
+ import { UserMessageComponent } from "./components/user-message.js";
47
+ import { UserMessageSelectorComponent } from "./components/user-message-selector.js";
48
+ import { getAvailableThemes, getAvailableThemesWithPaths, getEditorTheme, getMarkdownTheme, getThemeByName, initTheme, onThemeChange, setRegisteredThemes, setTheme, setThemeInstance, Theme, theme, } from "./theme/theme.js";
49
+ function isExpandable(obj) {
50
+ return typeof obj === "object" && obj !== null && "setExpanded" in obj && typeof obj.setExpanded === "function";
51
+ }
52
+ export class InteractiveMode {
53
+ // Convenience accessors
54
+ get agent() {
55
+ return this.session.agent;
56
+ }
57
+ get sessionManager() {
58
+ return this.session.sessionManager;
59
+ }
60
+ get settingsManager() {
61
+ return this.session.settingsManager;
62
+ }
63
+ constructor(session, options = {}) {
64
+ this.options = options;
65
+ this.isInitialized = false;
66
+ this.loadingAnimation = undefined;
67
+ this.pendingWorkingMessage = undefined;
68
+ this.defaultWorkingMessage = "Working...";
69
+ this.lastSigintTime = 0;
70
+ this.lastEscapeTime = 0;
71
+ this.changelogMarkdown = undefined;
72
+ // Status line tracking (for mutating immediately-sequential status updates)
73
+ this.lastStatusSpacer = undefined;
74
+ this.lastStatusText = undefined;
75
+ // Streaming message tracking
76
+ this.streamingComponent = undefined;
77
+ this.streamingMessage = undefined;
78
+ // Tool execution tracking: toolCallId -> component
79
+ this.pendingTools = new Map();
80
+ // Tool output expansion state
81
+ this.toolOutputExpanded = false;
82
+ // Thinking block visibility state
83
+ this.hideThinkingBlock = false;
84
+ // Skill commands: command name -> skill file path
85
+ this.skillCommands = new Map();
86
+ // Track if editor is in bash mode (text starts with !)
87
+ this.isBashMode = false;
88
+ // Track current bash execution component
89
+ this.bashComponent = undefined;
90
+ // Track pending bash components (shown in pending area, moved to chat on submit)
91
+ this.pendingBashComponents = [];
92
+ // Auto-compaction state
93
+ this.autoCompactionLoader = undefined;
94
+ // Auto-retry state
95
+ this.retryLoader = undefined;
96
+ // Messages queued while compaction is running
97
+ this.compactionQueuedMessages = [];
98
+ // Shutdown state
99
+ this.shutdownRequested = false;
100
+ // Extension UI state
101
+ this.extensionSelector = undefined;
102
+ this.extensionInput = undefined;
103
+ this.extensionEditor = undefined;
104
+ // Extension widgets (components rendered above/below the editor)
105
+ this.extensionWidgetsAbove = new Map();
106
+ this.extensionWidgetsBelow = new Map();
107
+ // Custom footer from extension (undefined = use built-in footer)
108
+ this.customFooter = undefined;
109
+ // Built-in header (logo + keybinding hints + changelog)
110
+ this.builtInHeader = undefined;
111
+ // Custom header from extension (undefined = use built-in header)
112
+ this.customHeader = undefined;
113
+ /**
114
+ * Gracefully shutdown the agent.
115
+ * Emits shutdown event to extensions, then exits.
116
+ */
117
+ this.isShuttingDown = false;
118
+ this.session = session;
119
+ this.version = VERSION;
120
+ this.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor());
121
+ this.chatContainer = new Container();
122
+ this.pendingMessagesContainer = new Container();
123
+ this.statusContainer = new Container();
124
+ this.widgetContainerAbove = new Container();
125
+ this.widgetContainerBelow = new Container();
126
+ this.keybindings = KeybindingsManager.create();
127
+ const editorPaddingX = this.settingsManager.getEditorPaddingX();
128
+ this.defaultEditor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, { paddingX: editorPaddingX });
129
+ this.editor = this.defaultEditor;
130
+ this.editorContainer = new Container();
131
+ this.editorContainer.addChild(this.editor);
132
+ this.footerDataProvider = new FooterDataProvider();
133
+ this.footer = new FooterComponent(session, this.footerDataProvider);
134
+ this.footer.setAutoCompactEnabled(session.autoCompactionEnabled);
135
+ // Load hide thinking block setting
136
+ this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
137
+ // Register themes from resource loader and initialize
138
+ setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
139
+ initTheme(this.settingsManager.getTheme(), true);
140
+ }
141
+ setupAutocomplete(fdPath) {
142
+ // Define commands for autocomplete
143
+ const slashCommands = [
144
+ { name: "settings", description: "Open settings menu" },
145
+ {
146
+ name: "model",
147
+ description: "Select model (opens selector UI)",
148
+ getArgumentCompletions: (prefix) => {
149
+ // Get available models (scoped or from registry)
150
+ const models = this.session.scopedModels.length > 0
151
+ ? this.session.scopedModels.map((s) => s.model)
152
+ : this.session.modelRegistry.getAvailable();
153
+ if (models.length === 0)
154
+ return null;
155
+ // Create items with provider/id format
156
+ const items = models.map((m) => ({
157
+ id: m.id,
158
+ provider: m.provider,
159
+ label: `${m.provider}/${m.id}`,
160
+ }));
161
+ // Fuzzy filter by model ID + provider (allows "opus anthropic" to match)
162
+ const filtered = fuzzyFilter(items, prefix, (item) => `${item.id} ${item.provider}`);
163
+ if (filtered.length === 0)
164
+ return null;
165
+ return filtered.map((item) => ({
166
+ value: item.label,
167
+ label: item.id,
168
+ description: item.provider,
169
+ }));
170
+ },
171
+ },
172
+ { name: "scoped-models", description: "Enable/disable models for Ctrl+P cycling" },
173
+ { name: "export", description: "Export session to HTML file" },
174
+ { name: "share", description: "Share session as a secret GitHub gist" },
175
+ { name: "copy", description: "Copy last agent message to clipboard" },
176
+ { name: "name", description: "Set session display name" },
177
+ { name: "session", description: "Show session info and stats" },
178
+ { name: "changelog", description: "Show changelog entries" },
179
+ { name: "hotkeys", description: "Show all keyboard shortcuts" },
180
+ { name: "fork", description: "Create a new fork from a previous message" },
181
+ { name: "tree", description: "Navigate session tree (switch branches)" },
182
+ { name: "login", description: "Login with OAuth provider" },
183
+ { name: "logout", description: "Logout from OAuth provider" },
184
+ { name: "new", description: "Start a new session" },
185
+ { name: "compact", description: "Manually compact the session context" },
186
+ { name: "resume", description: "Resume a different session" },
187
+ { name: "reload", description: "Reload extensions, skills, prompts, and themes" },
188
+ ];
189
+ // Convert prompt templates to SlashCommand format for autocomplete
190
+ const templateCommands = this.session.promptTemplates.map((cmd) => ({
191
+ name: cmd.name,
192
+ description: cmd.description,
193
+ }));
194
+ // Convert extension commands to SlashCommand format
195
+ const extensionCommands = (this.session.extensionRunner?.getRegisteredCommands() ?? []).map((cmd) => ({
196
+ name: cmd.name,
197
+ description: cmd.description ?? "(extension command)",
198
+ getArgumentCompletions: cmd.getArgumentCompletions,
199
+ }));
200
+ // Build skill commands from session.skills (if enabled)
201
+ this.skillCommands.clear();
202
+ const skillCommandList = [];
203
+ if (this.settingsManager.getEnableSkillCommands()) {
204
+ for (const skill of this.session.resourceLoader.getSkills().skills) {
205
+ const commandName = `skill:${skill.name}`;
206
+ this.skillCommands.set(commandName, skill.filePath);
207
+ skillCommandList.push({ name: commandName, description: skill.description });
208
+ }
209
+ }
210
+ // Setup autocomplete
211
+ this.autocompleteProvider = new CombinedAutocompleteProvider([...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList], process.cwd(), fdPath);
212
+ this.defaultEditor.setAutocompleteProvider(this.autocompleteProvider);
213
+ }
214
+ rebuildAutocomplete() {
215
+ this.setupAutocomplete(this.fdPath);
216
+ }
217
+ async init() {
218
+ if (this.isInitialized)
219
+ return;
220
+ // Load changelog (only show new entries, skip for resumed sessions)
221
+ this.changelogMarkdown = this.getChangelogForDisplay();
222
+ // Setup autocomplete with fd tool for file path completion
223
+ this.fdPath = await ensureTool("fd");
224
+ this.setupAutocomplete(this.fdPath);
225
+ // Add header with keybindings from config (unless silenced)
226
+ if (this.options.verbose || !this.settingsManager.getQuietStartup()) {
227
+ const logo = theme.bold(theme.fg("accent", APP_NAME)) + theme.fg("dim", ` v${this.version}`);
228
+ // Build startup instructions using keybinding hint helpers
229
+ const kb = this.keybindings;
230
+ const hint = (action, desc) => appKeyHint(kb, action, desc);
231
+ const instructions = [
232
+ hint("interrupt", "to interrupt"),
233
+ hint("clear", "to clear"),
234
+ rawKeyHint(`${appKey(kb, "clear")} twice`, "to exit"),
235
+ hint("exit", "to exit (empty)"),
236
+ hint("suspend", "to suspend"),
237
+ keyHint("deleteToLineEnd", "to delete to end"),
238
+ hint("cycleThinkingLevel", "to cycle thinking level"),
239
+ rawKeyHint(`${appKey(kb, "cycleModelForward")}/${appKey(kb, "cycleModelBackward")}`, "to cycle models"),
240
+ hint("selectModel", "to select model"),
241
+ hint("expandTools", "to expand tools"),
242
+ hint("toggleThinking", "to expand thinking"),
243
+ hint("externalEditor", "for external editor"),
244
+ rawKeyHint("/", "for commands"),
245
+ rawKeyHint("!", "to run bash"),
246
+ rawKeyHint("!!", "to run bash (no context)"),
247
+ hint("followUp", "to queue follow-up"),
248
+ hint("dequeue", "to edit all queued messages"),
249
+ hint("pasteImage", "to paste image"),
250
+ rawKeyHint("drop files", "to attach"),
251
+ ].join("\n");
252
+ this.builtInHeader = new Text(`${logo}\n${instructions}`, 1, 0);
253
+ // Setup UI layout
254
+ this.ui.addChild(new Spacer(1));
255
+ this.ui.addChild(this.builtInHeader);
256
+ this.ui.addChild(new Spacer(1));
257
+ // Add changelog if provided
258
+ if (this.changelogMarkdown) {
259
+ this.ui.addChild(new DynamicBorder());
260
+ if (this.settingsManager.getCollapseChangelog()) {
261
+ const versionMatch = this.changelogMarkdown.match(/##\s+\[?(\d+\.\d+\.\d+)\]?/);
262
+ const latestVersion = versionMatch ? versionMatch[1] : this.version;
263
+ const condensedText = `Updated to v${latestVersion}. Use ${theme.bold("/changelog")} to view full changelog.`;
264
+ this.ui.addChild(new Text(condensedText, 1, 0));
265
+ }
266
+ else {
267
+ this.ui.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0));
268
+ this.ui.addChild(new Spacer(1));
269
+ this.ui.addChild(new Markdown(this.changelogMarkdown.trim(), 1, 0, this.getMarkdownThemeWithSettings()));
270
+ this.ui.addChild(new Spacer(1));
271
+ }
272
+ this.ui.addChild(new DynamicBorder());
273
+ }
274
+ }
275
+ else {
276
+ // Minimal header when silenced
277
+ this.builtInHeader = new Text("", 0, 0);
278
+ if (this.changelogMarkdown) {
279
+ // Still show changelog notification even in silent mode
280
+ this.ui.addChild(new Spacer(1));
281
+ const versionMatch = this.changelogMarkdown.match(/##\s+\[?(\d+\.\d+\.\d+)\]?/);
282
+ const latestVersion = versionMatch ? versionMatch[1] : this.version;
283
+ const condensedText = `Updated to v${latestVersion}. Use ${theme.bold("/changelog")} to view full changelog.`;
284
+ this.ui.addChild(new Text(condensedText, 1, 0));
285
+ }
286
+ }
287
+ this.ui.addChild(this.chatContainer);
288
+ this.ui.addChild(this.pendingMessagesContainer);
289
+ this.ui.addChild(this.statusContainer);
290
+ this.renderWidgets(); // Initialize with default spacer
291
+ this.ui.addChild(this.widgetContainerAbove);
292
+ this.ui.addChild(this.editorContainer);
293
+ this.ui.addChild(this.widgetContainerBelow);
294
+ this.ui.addChild(this.footer);
295
+ this.ui.setFocus(this.editor);
296
+ this.setupKeyHandlers();
297
+ this.setupEditorSubmitHandler();
298
+ // Start the UI
299
+ this.ui.start();
300
+ this.isInitialized = true;
301
+ // Set terminal title
302
+ this.updateTerminalTitle();
303
+ // Initialize extensions with TUI-based UI context
304
+ await this.initExtensions();
305
+ // Subscribe to agent events
306
+ this.subscribeToAgent();
307
+ // Set up theme file watcher
308
+ onThemeChange(() => {
309
+ this.ui.invalidate();
310
+ this.updateEditorBorderColor();
311
+ this.ui.requestRender();
312
+ });
313
+ // Set up git branch watcher (uses provider instead of footer)
314
+ this.footerDataProvider.onBranchChange(() => {
315
+ this.ui.requestRender();
316
+ });
317
+ // Initialize available provider count for footer display
318
+ await this.updateAvailableProviderCount();
319
+ }
320
+ /**
321
+ * Update terminal title with session name and cwd.
322
+ */
323
+ updateTerminalTitle() {
324
+ const cwdBasename = path.basename(process.cwd());
325
+ const sessionName = this.sessionManager.getSessionName();
326
+ if (sessionName) {
327
+ this.ui.terminal.setTitle(`π - ${sessionName} - ${cwdBasename}`);
328
+ }
329
+ else {
330
+ this.ui.terminal.setTitle(`π - ${cwdBasename}`);
331
+ }
332
+ }
333
+ /**
334
+ * Run the interactive mode. This is the main entry point.
335
+ * Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop.
336
+ */
337
+ async run() {
338
+ await this.init();
339
+ // Start version check asynchronously
340
+ this.checkForNewVersion().then((newVersion) => {
341
+ if (newVersion) {
342
+ this.showNewVersionNotification(newVersion);
343
+ }
344
+ });
345
+ this.renderInitialMessages();
346
+ // Show startup warnings
347
+ const { migratedProviders, modelFallbackMessage, initialMessage, initialImages, initialMessages } = this.options;
348
+ if (migratedProviders && migratedProviders.length > 0) {
349
+ this.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(", ")}`);
350
+ }
351
+ const modelsJsonError = this.session.modelRegistry.getError();
352
+ if (modelsJsonError) {
353
+ this.showError(`models.json error: ${modelsJsonError}`);
354
+ }
355
+ if (modelFallbackMessage) {
356
+ this.showWarning(modelFallbackMessage);
357
+ }
358
+ // Process initial messages
359
+ if (initialMessage) {
360
+ try {
361
+ await this.session.prompt(initialMessage, { images: initialImages });
362
+ }
363
+ catch (error) {
364
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
365
+ this.showError(errorMessage);
366
+ }
367
+ }
368
+ if (initialMessages) {
369
+ for (const message of initialMessages) {
370
+ try {
371
+ await this.session.prompt(message);
372
+ }
373
+ catch (error) {
374
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
375
+ this.showError(errorMessage);
376
+ }
377
+ }
378
+ }
379
+ // Main interactive loop
380
+ while (true) {
381
+ const userInput = await this.getUserInput();
382
+ try {
383
+ await this.session.prompt(userInput);
384
+ }
385
+ catch (error) {
386
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
387
+ this.showError(errorMessage);
388
+ }
389
+ }
390
+ }
391
+ /**
392
+ * Check npm registry for a newer version.
393
+ */
394
+ async checkForNewVersion() {
395
+ if (process.env.INDUSAGI_SKIP_VERSION_CHECK)
396
+ return undefined;
397
+ try {
398
+ const response = await fetch("https://registry.npmjs.org/indusagi-coding-agent/latest");
399
+ if (!response.ok)
400
+ return undefined;
401
+ const data = (await response.json());
402
+ const latestVersion = data.version;
403
+ if (latestVersion && latestVersion !== this.version) {
404
+ return latestVersion;
405
+ }
406
+ return undefined;
407
+ }
408
+ catch {
409
+ return undefined;
410
+ }
411
+ }
412
+ /**
413
+ * Get changelog entries to display on startup.
414
+ * Only shows new entries since last seen version, skips for resumed sessions.
415
+ */
416
+ getChangelogForDisplay() {
417
+ // Skip changelog for resumed/continued sessions (already have messages)
418
+ if (this.session.state.messages.length > 0) {
419
+ return undefined;
420
+ }
421
+ const lastVersion = this.settingsManager.getLastChangelogVersion();
422
+ const changelogPath = getChangelogPath();
423
+ const entries = parseChangelog(changelogPath);
424
+ if (!lastVersion) {
425
+ // Fresh install - just record the version, don't show changelog
426
+ this.settingsManager.setLastChangelogVersion(VERSION);
427
+ return undefined;
428
+ }
429
+ else {
430
+ const newEntries = getNewEntries(entries, lastVersion);
431
+ if (newEntries.length > 0) {
432
+ this.settingsManager.setLastChangelogVersion(VERSION);
433
+ return newEntries.map((e) => e.content).join("\n\n");
434
+ }
435
+ }
436
+ return undefined;
437
+ }
438
+ getMarkdownThemeWithSettings() {
439
+ return {
440
+ ...getMarkdownTheme(),
441
+ codeBlockIndent: this.settingsManager.getCodeBlockIndent(),
442
+ };
443
+ }
444
+ // =========================================================================
445
+ // Extension System
446
+ // =========================================================================
447
+ formatDisplayPath(p) {
448
+ const home = os.homedir();
449
+ let result = p;
450
+ // Replace home directory with ~
451
+ if (result.startsWith(home)) {
452
+ result = `~${result.slice(home.length)}`;
453
+ }
454
+ return result;
455
+ }
456
+ /**
457
+ * Get a short path relative to the package root for display.
458
+ */
459
+ getShortPath(fullPath, source) {
460
+ // For npm packages, show path relative to node_modules/pkg/
461
+ const npmMatch = fullPath.match(/node_modules\/(@?[^/]+(?:\/[^/]+)?)\/(.*)/);
462
+ if (npmMatch && source.startsWith("npm:")) {
463
+ return npmMatch[2];
464
+ }
465
+ // For git packages, show path relative to repo root
466
+ const gitMatch = fullPath.match(/git\/[^/]+\/[^/]+\/(.*)/);
467
+ if (gitMatch && source.startsWith("git:")) {
468
+ return gitMatch[1];
469
+ }
470
+ // For local/auto, just use formatDisplayPath
471
+ return this.formatDisplayPath(fullPath);
472
+ }
473
+ getDisplaySourceInfo(source, scope) {
474
+ if (source === "local") {
475
+ if (scope === "user") {
476
+ return { label: "user", color: "muted" };
477
+ }
478
+ if (scope === "project") {
479
+ return { label: "project", color: "muted" };
480
+ }
481
+ if (scope === "temporary") {
482
+ return { label: "path", scopeLabel: "temp", color: "muted" };
483
+ }
484
+ return { label: "path", color: "muted" };
485
+ }
486
+ if (source === "cli") {
487
+ return { label: "path", scopeLabel: scope === "temporary" ? "temp" : undefined, color: "muted" };
488
+ }
489
+ const scopeLabel = scope === "user" ? "user" : scope === "project" ? "project" : scope === "temporary" ? "temp" : undefined;
490
+ return { label: source, scopeLabel, color: "accent" };
491
+ }
492
+ getScopeGroup(source, scope) {
493
+ if (source === "cli" || scope === "temporary")
494
+ return "path";
495
+ if (scope === "user")
496
+ return "user";
497
+ if (scope === "project")
498
+ return "project";
499
+ return "path";
500
+ }
501
+ isPackageSource(source) {
502
+ return source.startsWith("npm:") || source.startsWith("git:");
503
+ }
504
+ buildScopeGroups(paths, metadata) {
505
+ const groups = {
506
+ user: { scope: "user", paths: [], packages: new Map() },
507
+ project: { scope: "project", paths: [], packages: new Map() },
508
+ path: { scope: "path", paths: [], packages: new Map() },
509
+ };
510
+ for (const p of paths) {
511
+ const meta = this.findMetadata(p, metadata);
512
+ const source = meta?.source ?? "local";
513
+ const scope = meta?.scope ?? "project";
514
+ const groupKey = this.getScopeGroup(source, scope);
515
+ const group = groups[groupKey];
516
+ if (this.isPackageSource(source)) {
517
+ const list = group.packages.get(source) ?? [];
518
+ list.push(p);
519
+ group.packages.set(source, list);
520
+ }
521
+ else {
522
+ group.paths.push(p);
523
+ }
524
+ }
525
+ return [groups.user, groups.project, groups.path].filter((group) => group.paths.length > 0 || group.packages.size > 0);
526
+ }
527
+ formatScopeGroups(groups, options) {
528
+ const lines = [];
529
+ for (const group of groups) {
530
+ lines.push(` ${theme.fg("accent", group.scope)}`);
531
+ const sortedPaths = [...group.paths].sort((a, b) => a.localeCompare(b));
532
+ for (const p of sortedPaths) {
533
+ lines.push(theme.fg("dim", ` ${options.formatPath(p)}`));
534
+ }
535
+ const sortedPackages = Array.from(group.packages.entries()).sort(([a], [b]) => a.localeCompare(b));
536
+ for (const [source, paths] of sortedPackages) {
537
+ lines.push(` ${theme.fg("mdLink", source)}`);
538
+ const sortedPackagePaths = [...paths].sort((a, b) => a.localeCompare(b));
539
+ for (const p of sortedPackagePaths) {
540
+ lines.push(theme.fg("dim", ` ${options.formatPackagePath(p, source)}`));
541
+ }
542
+ }
543
+ }
544
+ return lines.join("\n");
545
+ }
546
+ /**
547
+ * Find metadata for a path, checking parent directories if exact match fails.
548
+ * Package manager stores metadata for directories, but we display file paths.
549
+ */
550
+ findMetadata(p, metadata) {
551
+ // Try exact match first
552
+ const exact = metadata.get(p);
553
+ if (exact)
554
+ return exact;
555
+ // Try parent directories (package manager stores directory paths)
556
+ let current = p;
557
+ while (current.includes("/")) {
558
+ current = current.substring(0, current.lastIndexOf("/"));
559
+ const parent = metadata.get(current);
560
+ if (parent)
561
+ return parent;
562
+ }
563
+ return undefined;
564
+ }
565
+ /**
566
+ * Format a path with its source/scope info from metadata.
567
+ */
568
+ formatPathWithSource(p, metadata) {
569
+ const meta = this.findMetadata(p, metadata);
570
+ if (meta) {
571
+ const shortPath = this.getShortPath(p, meta.source);
572
+ const { label, scopeLabel } = this.getDisplaySourceInfo(meta.source, meta.scope);
573
+ const labelText = scopeLabel ? `${label} (${scopeLabel})` : label;
574
+ return `${labelText} ${shortPath}`;
575
+ }
576
+ return this.formatDisplayPath(p);
577
+ }
578
+ /**
579
+ * Format resource diagnostics with nice collision display using metadata.
580
+ */
581
+ formatDiagnostics(diagnostics, metadata) {
582
+ const lines = [];
583
+ // Group collision diagnostics by name
584
+ const collisions = new Map();
585
+ const otherDiagnostics = [];
586
+ for (const d of diagnostics) {
587
+ if (d.type === "collision" && d.collision) {
588
+ const list = collisions.get(d.collision.name) ?? [];
589
+ list.push(d);
590
+ collisions.set(d.collision.name, list);
591
+ }
592
+ else {
593
+ otherDiagnostics.push(d);
594
+ }
595
+ }
596
+ // Format collision diagnostics grouped by name
597
+ for (const [name, collisionList] of collisions) {
598
+ const first = collisionList[0]?.collision;
599
+ if (!first)
600
+ continue;
601
+ lines.push(theme.fg("warning", ` "${name}" collision:`));
602
+ // Show winner
603
+ lines.push(theme.fg("dim", ` ${theme.fg("success", "✓")} ${this.formatPathWithSource(first.winnerPath, metadata)}`));
604
+ // Show all losers
605
+ for (const d of collisionList) {
606
+ if (d.collision) {
607
+ lines.push(theme.fg("dim", ` ${theme.fg("warning", "✗")} ${this.formatPathWithSource(d.collision.loserPath, metadata)} (skipped)`));
608
+ }
609
+ }
610
+ }
611
+ // Format other diagnostics (skill name collisions, parse errors, etc.)
612
+ for (const d of otherDiagnostics) {
613
+ if (d.path) {
614
+ // Use metadata-aware formatting for paths
615
+ const sourceInfo = this.formatPathWithSource(d.path, metadata);
616
+ lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${sourceInfo}`));
617
+ lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${d.message}`));
618
+ }
619
+ else {
620
+ lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${d.message}`));
621
+ }
622
+ }
623
+ return lines.join("\n");
624
+ }
625
+ showLoadedResources(options) {
626
+ const shouldShow = options?.force || this.options.verbose || !this.settingsManager.getQuietStartup();
627
+ if (!shouldShow) {
628
+ return;
629
+ }
630
+ const metadata = this.session.resourceLoader.getPathMetadata();
631
+ const sectionHeader = (name, color = "mdHeading") => theme.fg(color, `[${name}]`);
632
+ const contextFiles = this.session.resourceLoader.getAgentsFiles().agentsFiles;
633
+ if (contextFiles.length > 0) {
634
+ const contextList = contextFiles.map((f) => theme.fg("dim", ` ${this.formatDisplayPath(f.path)}`)).join("\n");
635
+ this.chatContainer.addChild(new Text(`${sectionHeader("Context")}\n${contextList}`, 0, 0));
636
+ this.chatContainer.addChild(new Spacer(1));
637
+ }
638
+ const skills = this.session.resourceLoader.getSkills().skills;
639
+ if (skills.length > 0) {
640
+ const skillPaths = skills.map((s) => s.filePath);
641
+ const groups = this.buildScopeGroups(skillPaths, metadata);
642
+ const skillList = this.formatScopeGroups(groups, {
643
+ formatPath: (p) => this.formatDisplayPath(p),
644
+ formatPackagePath: (p, source) => this.getShortPath(p, source),
645
+ });
646
+ this.chatContainer.addChild(new Text(`${sectionHeader("Skills")}\n${skillList}`, 0, 0));
647
+ this.chatContainer.addChild(new Spacer(1));
648
+ }
649
+ const skillDiagnostics = this.session.resourceLoader.getSkills().diagnostics;
650
+ if (skillDiagnostics.length > 0) {
651
+ const warningLines = this.formatDiagnostics(skillDiagnostics, metadata);
652
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Skill conflicts]")}\n${warningLines}`, 0, 0));
653
+ this.chatContainer.addChild(new Spacer(1));
654
+ }
655
+ const templates = this.session.promptTemplates;
656
+ if (templates.length > 0) {
657
+ const templatePaths = templates.map((t) => t.filePath);
658
+ const groups = this.buildScopeGroups(templatePaths, metadata);
659
+ const templateByPath = new Map(templates.map((t) => [t.filePath, t]));
660
+ const templateList = this.formatScopeGroups(groups, {
661
+ formatPath: (p) => {
662
+ const template = templateByPath.get(p);
663
+ return template ? `/${template.name}` : this.formatDisplayPath(p);
664
+ },
665
+ formatPackagePath: (p) => {
666
+ const template = templateByPath.get(p);
667
+ return template ? `/${template.name}` : this.formatDisplayPath(p);
668
+ },
669
+ });
670
+ this.chatContainer.addChild(new Text(`${sectionHeader("Prompts")}\n${templateList}`, 0, 0));
671
+ this.chatContainer.addChild(new Spacer(1));
672
+ }
673
+ const promptDiagnostics = this.session.resourceLoader.getPrompts().diagnostics;
674
+ if (promptDiagnostics.length > 0) {
675
+ const warningLines = this.formatDiagnostics(promptDiagnostics, metadata);
676
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Prompt conflicts]")}\n${warningLines}`, 0, 0));
677
+ this.chatContainer.addChild(new Spacer(1));
678
+ }
679
+ const extensionPaths = options?.extensionPaths ?? [];
680
+ if (extensionPaths.length > 0) {
681
+ const groups = this.buildScopeGroups(extensionPaths, metadata);
682
+ const extList = this.formatScopeGroups(groups, {
683
+ formatPath: (p) => this.formatDisplayPath(p),
684
+ formatPackagePath: (p, source) => this.getShortPath(p, source),
685
+ });
686
+ this.chatContainer.addChild(new Text(`${sectionHeader("Extensions", "mdHeading")}\n${extList}`, 0, 0));
687
+ this.chatContainer.addChild(new Spacer(1));
688
+ }
689
+ const extensionDiagnostics = [];
690
+ const extensionErrors = this.session.resourceLoader.getExtensions().errors;
691
+ if (extensionErrors.length > 0) {
692
+ for (const error of extensionErrors) {
693
+ extensionDiagnostics.push({ type: "error", message: error.error, path: error.path });
694
+ }
695
+ }
696
+ const shortcutDiagnostics = this.session.extensionRunner?.getShortcutDiagnostics() ?? [];
697
+ extensionDiagnostics.push(...shortcutDiagnostics);
698
+ if (extensionDiagnostics.length > 0) {
699
+ const warningLines = this.formatDiagnostics(extensionDiagnostics, metadata);
700
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Extension issues]")}\n${warningLines}`, 0, 0));
701
+ this.chatContainer.addChild(new Spacer(1));
702
+ }
703
+ // Show loaded themes (excluding built-in)
704
+ const loadedThemes = this.session.resourceLoader.getThemes().themes;
705
+ const customThemes = loadedThemes.filter((t) => t.sourcePath);
706
+ if (customThemes.length > 0) {
707
+ const themePaths = customThemes.map((t) => t.sourcePath);
708
+ const groups = this.buildScopeGroups(themePaths, metadata);
709
+ const themeList = this.formatScopeGroups(groups, {
710
+ formatPath: (p) => this.formatDisplayPath(p),
711
+ formatPackagePath: (p, source) => this.getShortPath(p, source),
712
+ });
713
+ this.chatContainer.addChild(new Text(`${sectionHeader("Themes")}\n${themeList}`, 0, 0));
714
+ this.chatContainer.addChild(new Spacer(1));
715
+ }
716
+ const themeDiagnostics = this.session.resourceLoader.getThemes().diagnostics;
717
+ if (themeDiagnostics.length > 0) {
718
+ const warningLines = this.formatDiagnostics(themeDiagnostics, metadata);
719
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Theme conflicts]")}\n${warningLines}`, 0, 0));
720
+ this.chatContainer.addChild(new Spacer(1));
721
+ }
722
+ }
723
+ /**
724
+ * Initialize the extension system with TUI-based UI context.
725
+ */
726
+ async initExtensions() {
727
+ const extensionRunner = this.session.extensionRunner;
728
+ if (!extensionRunner) {
729
+ this.showLoadedResources({ extensionPaths: [], force: false });
730
+ return;
731
+ }
732
+ // Create extension UI context
733
+ const uiContext = this.createExtensionUIContext();
734
+ await this.session.bindExtensions({
735
+ uiContext,
736
+ commandContextActions: {
737
+ waitForIdle: () => this.session.agent.waitForIdle(),
738
+ newSession: async (options) => {
739
+ if (this.loadingAnimation) {
740
+ this.loadingAnimation.stop();
741
+ this.loadingAnimation = undefined;
742
+ }
743
+ this.statusContainer.clear();
744
+ const success = await this.session.newSession({ parentSession: options?.parentSession });
745
+ if (!success) {
746
+ return { cancelled: true };
747
+ }
748
+ if (options?.setup) {
749
+ await options.setup(this.sessionManager);
750
+ }
751
+ this.chatContainer.clear();
752
+ this.pendingMessagesContainer.clear();
753
+ this.compactionQueuedMessages = [];
754
+ this.streamingComponent = undefined;
755
+ this.streamingMessage = undefined;
756
+ this.pendingTools.clear();
757
+ this.chatContainer.addChild(new Spacer(1));
758
+ this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ New session started")}`, 1, 1));
759
+ this.ui.requestRender();
760
+ return { cancelled: false };
761
+ },
762
+ fork: async (entryId) => {
763
+ const result = await this.session.fork(entryId);
764
+ if (result.cancelled) {
765
+ return { cancelled: true };
766
+ }
767
+ this.chatContainer.clear();
768
+ this.renderInitialMessages();
769
+ this.editor.setText(result.selectedText);
770
+ this.showStatus("Forked to new session");
771
+ return { cancelled: false };
772
+ },
773
+ navigateTree: async (targetId, options) => {
774
+ const result = await this.session.navigateTree(targetId, {
775
+ summarize: options?.summarize,
776
+ customInstructions: options?.customInstructions,
777
+ replaceInstructions: options?.replaceInstructions,
778
+ label: options?.label,
779
+ });
780
+ if (result.cancelled) {
781
+ return { cancelled: true };
782
+ }
783
+ this.chatContainer.clear();
784
+ this.renderInitialMessages();
785
+ if (result.editorText) {
786
+ this.editor.setText(result.editorText);
787
+ }
788
+ this.showStatus("Navigated to selected point");
789
+ return { cancelled: false };
790
+ },
791
+ },
792
+ shutdownHandler: () => {
793
+ this.shutdownRequested = true;
794
+ },
795
+ onError: (error) => {
796
+ this.showExtensionError(error.extensionPath, error.error, error.stack);
797
+ },
798
+ });
799
+ this.setupExtensionShortcuts(extensionRunner);
800
+ this.showLoadedResources({ extensionPaths: extensionRunner.getExtensionPaths(), force: false });
801
+ }
802
+ /**
803
+ * Get a registered tool definition by name (for custom rendering).
804
+ */
805
+ getRegisteredToolDefinition(toolName) {
806
+ const tools = this.session.extensionRunner?.getAllRegisteredTools() ?? [];
807
+ const registeredTool = tools.find((t) => t.definition.name === toolName);
808
+ return registeredTool?.definition;
809
+ }
810
+ /**
811
+ * Set up keyboard shortcuts registered by extensions.
812
+ */
813
+ setupExtensionShortcuts(extensionRunner) {
814
+ const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
815
+ if (shortcuts.size === 0)
816
+ return;
817
+ // Create a context for shortcut handlers
818
+ const createContext = () => ({
819
+ ui: this.createExtensionUIContext(),
820
+ hasUI: true,
821
+ cwd: process.cwd(),
822
+ sessionManager: this.sessionManager,
823
+ modelRegistry: this.session.modelRegistry,
824
+ model: this.session.model,
825
+ isIdle: () => !this.session.isStreaming,
826
+ abort: () => this.session.abort(),
827
+ hasPendingMessages: () => this.session.pendingMessageCount > 0,
828
+ shutdown: () => {
829
+ this.shutdownRequested = true;
830
+ },
831
+ getContextUsage: () => this.session.getContextUsage(),
832
+ compact: (options) => {
833
+ void (async () => {
834
+ try {
835
+ const result = await this.executeCompaction(options?.customInstructions, false);
836
+ if (result) {
837
+ options?.onComplete?.(result);
838
+ }
839
+ }
840
+ catch (error) {
841
+ const err = error instanceof Error ? error : new Error(String(error));
842
+ options?.onError?.(err);
843
+ }
844
+ })();
845
+ },
846
+ });
847
+ // Set up the extension shortcut handler on the default editor
848
+ this.defaultEditor.onExtensionShortcut = (data) => {
849
+ for (const [shortcutStr, shortcut] of shortcuts) {
850
+ // Cast to KeyId - extension shortcuts use the same format
851
+ if (matchesKey(data, shortcutStr)) {
852
+ // Run handler async, don't block input
853
+ Promise.resolve(shortcut.handler(createContext())).catch((err) => {
854
+ this.showError(`Shortcut handler error: ${err instanceof Error ? err.message : String(err)}`);
855
+ });
856
+ return true;
857
+ }
858
+ }
859
+ return false;
860
+ };
861
+ }
862
+ /**
863
+ * Set extension status text in the footer.
864
+ */
865
+ setExtensionStatus(key, text) {
866
+ this.footerDataProvider.setExtensionStatus(key, text);
867
+ this.ui.requestRender();
868
+ }
869
+ /**
870
+ * Set an extension widget (string array or custom component).
871
+ */
872
+ setExtensionWidget(key, content, options) {
873
+ const placement = options?.placement ?? "aboveEditor";
874
+ const removeExisting = (map) => {
875
+ const existing = map.get(key);
876
+ if (existing?.dispose)
877
+ existing.dispose();
878
+ map.delete(key);
879
+ };
880
+ removeExisting(this.extensionWidgetsAbove);
881
+ removeExisting(this.extensionWidgetsBelow);
882
+ if (content === undefined) {
883
+ this.renderWidgets();
884
+ return;
885
+ }
886
+ let component;
887
+ if (Array.isArray(content)) {
888
+ // Wrap string array in a Container with Text components
889
+ const container = new Container();
890
+ for (const line of content.slice(0, InteractiveMode.MAX_WIDGET_LINES)) {
891
+ container.addChild(new Text(line, 1, 0));
892
+ }
893
+ if (content.length > InteractiveMode.MAX_WIDGET_LINES) {
894
+ container.addChild(new Text(theme.fg("muted", "... (widget truncated)"), 1, 0));
895
+ }
896
+ component = container;
897
+ }
898
+ else {
899
+ // Factory function - create component
900
+ component = content(this.ui, theme);
901
+ }
902
+ const targetMap = placement === "belowEditor" ? this.extensionWidgetsBelow : this.extensionWidgetsAbove;
903
+ targetMap.set(key, component);
904
+ this.renderWidgets();
905
+ }
906
+ clearExtensionWidgets() {
907
+ for (const widget of this.extensionWidgetsAbove.values()) {
908
+ widget.dispose?.();
909
+ }
910
+ for (const widget of this.extensionWidgetsBelow.values()) {
911
+ widget.dispose?.();
912
+ }
913
+ this.extensionWidgetsAbove.clear();
914
+ this.extensionWidgetsBelow.clear();
915
+ this.renderWidgets();
916
+ }
917
+ resetExtensionUI() {
918
+ if (this.extensionSelector) {
919
+ this.hideExtensionSelector();
920
+ }
921
+ if (this.extensionInput) {
922
+ this.hideExtensionInput();
923
+ }
924
+ if (this.extensionEditor) {
925
+ this.hideExtensionEditor();
926
+ }
927
+ this.ui.hideOverlay();
928
+ this.setExtensionFooter(undefined);
929
+ this.setExtensionHeader(undefined);
930
+ this.clearExtensionWidgets();
931
+ this.footerDataProvider.clearExtensionStatuses();
932
+ this.footer.invalidate();
933
+ this.setCustomEditorComponent(undefined);
934
+ this.defaultEditor.onExtensionShortcut = undefined;
935
+ this.updateTerminalTitle();
936
+ if (this.loadingAnimation) {
937
+ this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${appKey(this.keybindings, "interrupt")} to interrupt)`);
938
+ }
939
+ }
940
+ // Maximum total widget lines to prevent viewport overflow
941
+ static { this.MAX_WIDGET_LINES = 10; }
942
+ /**
943
+ * Render all extension widgets to the widget container.
944
+ */
945
+ renderWidgets() {
946
+ if (!this.widgetContainerAbove || !this.widgetContainerBelow)
947
+ return;
948
+ this.renderWidgetContainer(this.widgetContainerAbove, this.extensionWidgetsAbove, true, true);
949
+ this.renderWidgetContainer(this.widgetContainerBelow, this.extensionWidgetsBelow, false, false);
950
+ this.ui.requestRender();
951
+ }
952
+ renderWidgetContainer(container, widgets, spacerWhenEmpty, leadingSpacer) {
953
+ container.clear();
954
+ if (widgets.size === 0) {
955
+ if (spacerWhenEmpty) {
956
+ container.addChild(new Spacer(1));
957
+ }
958
+ return;
959
+ }
960
+ if (leadingSpacer) {
961
+ container.addChild(new Spacer(1));
962
+ }
963
+ for (const component of widgets.values()) {
964
+ container.addChild(component);
965
+ }
966
+ }
967
+ /**
968
+ * Set a custom footer component, or restore the built-in footer.
969
+ */
970
+ setExtensionFooter(factory) {
971
+ // Dispose existing custom footer
972
+ if (this.customFooter?.dispose) {
973
+ this.customFooter.dispose();
974
+ }
975
+ // Remove current footer from UI
976
+ if (this.customFooter) {
977
+ this.ui.removeChild(this.customFooter);
978
+ }
979
+ else {
980
+ this.ui.removeChild(this.footer);
981
+ }
982
+ if (factory) {
983
+ // Create and add custom footer, passing the data provider
984
+ this.customFooter = factory(this.ui, theme, this.footerDataProvider);
985
+ this.ui.addChild(this.customFooter);
986
+ }
987
+ else {
988
+ // Restore built-in footer
989
+ this.customFooter = undefined;
990
+ this.ui.addChild(this.footer);
991
+ }
992
+ this.ui.requestRender();
993
+ }
994
+ /**
995
+ * Set a custom header component, or restore the built-in header.
996
+ */
997
+ setExtensionHeader(factory) {
998
+ // Header may not be initialized yet if called during early initialization
999
+ if (!this.builtInHeader) {
1000
+ return;
1001
+ }
1002
+ // Dispose existing custom header
1003
+ if (this.customHeader?.dispose) {
1004
+ this.customHeader.dispose();
1005
+ }
1006
+ // Remove current header from UI
1007
+ if (this.customHeader) {
1008
+ this.ui.removeChild(this.customHeader);
1009
+ }
1010
+ else {
1011
+ this.ui.removeChild(this.builtInHeader);
1012
+ }
1013
+ if (factory) {
1014
+ // Create and add custom header at position 1 (after initial spacer)
1015
+ this.customHeader = factory(this.ui, theme);
1016
+ this.ui.children.splice(1, 0, this.customHeader);
1017
+ }
1018
+ else {
1019
+ // Restore built-in header at position 1
1020
+ this.customHeader = undefined;
1021
+ this.ui.children.splice(1, 0, this.builtInHeader);
1022
+ }
1023
+ this.ui.requestRender();
1024
+ }
1025
+ /**
1026
+ * Create the ExtensionUIContext for extensions.
1027
+ */
1028
+ createExtensionUIContext() {
1029
+ return {
1030
+ select: (title, options, opts) => this.showExtensionSelector(title, options, opts),
1031
+ confirm: (title, message, opts) => this.showExtensionConfirm(title, message, opts),
1032
+ input: (title, placeholder, opts) => this.showExtensionInput(title, placeholder, opts),
1033
+ notify: (message, type) => this.showExtensionNotify(message, type),
1034
+ setStatus: (key, text) => this.setExtensionStatus(key, text),
1035
+ setWorkingMessage: (message) => {
1036
+ if (this.loadingAnimation) {
1037
+ if (message) {
1038
+ this.loadingAnimation.setMessage(message);
1039
+ }
1040
+ else {
1041
+ this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${appKey(this.keybindings, "interrupt")} to interrupt)`);
1042
+ }
1043
+ }
1044
+ else {
1045
+ // Queue message for when loadingAnimation is created (handles agent_start race)
1046
+ this.pendingWorkingMessage = message;
1047
+ }
1048
+ },
1049
+ setWidget: (key, content, options) => this.setExtensionWidget(key, content, options),
1050
+ setFooter: (factory) => this.setExtensionFooter(factory),
1051
+ setHeader: (factory) => this.setExtensionHeader(factory),
1052
+ setTitle: (title) => this.ui.terminal.setTitle(title),
1053
+ custom: (factory, options) => this.showExtensionCustom(factory, options),
1054
+ setEditorText: (text) => this.editor.setText(text),
1055
+ getEditorText: () => this.editor.getText(),
1056
+ editor: (title, prefill) => this.showExtensionEditor(title, prefill),
1057
+ setEditorComponent: (factory) => this.setCustomEditorComponent(factory),
1058
+ get theme() {
1059
+ return theme;
1060
+ },
1061
+ getAllThemes: () => getAvailableThemesWithPaths(),
1062
+ getTheme: (name) => getThemeByName(name),
1063
+ setTheme: (themeOrName) => {
1064
+ if (themeOrName instanceof Theme) {
1065
+ setThemeInstance(themeOrName);
1066
+ this.ui.requestRender();
1067
+ return { success: true };
1068
+ }
1069
+ const result = setTheme(themeOrName, true);
1070
+ if (result.success) {
1071
+ this.ui.requestRender();
1072
+ }
1073
+ return result;
1074
+ },
1075
+ };
1076
+ }
1077
+ /**
1078
+ * Show a selector for extensions.
1079
+ */
1080
+ showExtensionSelector(title, options, opts) {
1081
+ return new Promise((resolve) => {
1082
+ if (opts?.signal?.aborted) {
1083
+ resolve(undefined);
1084
+ return;
1085
+ }
1086
+ const onAbort = () => {
1087
+ this.hideExtensionSelector();
1088
+ resolve(undefined);
1089
+ };
1090
+ opts?.signal?.addEventListener("abort", onAbort, { once: true });
1091
+ this.extensionSelector = new ExtensionSelectorComponent(title, options, (option) => {
1092
+ opts?.signal?.removeEventListener("abort", onAbort);
1093
+ this.hideExtensionSelector();
1094
+ resolve(option);
1095
+ }, () => {
1096
+ opts?.signal?.removeEventListener("abort", onAbort);
1097
+ this.hideExtensionSelector();
1098
+ resolve(undefined);
1099
+ }, { tui: this.ui, timeout: opts?.timeout });
1100
+ this.editorContainer.clear();
1101
+ this.editorContainer.addChild(this.extensionSelector);
1102
+ this.ui.setFocus(this.extensionSelector);
1103
+ this.ui.requestRender();
1104
+ });
1105
+ }
1106
+ /**
1107
+ * Hide the extension selector.
1108
+ */
1109
+ hideExtensionSelector() {
1110
+ this.extensionSelector?.dispose();
1111
+ this.editorContainer.clear();
1112
+ this.editorContainer.addChild(this.editor);
1113
+ this.extensionSelector = undefined;
1114
+ this.ui.setFocus(this.editor);
1115
+ this.ui.requestRender();
1116
+ }
1117
+ /**
1118
+ * Show a confirmation dialog for extensions.
1119
+ */
1120
+ async showExtensionConfirm(title, message, opts) {
1121
+ const result = await this.showExtensionSelector(`${title}\n${message}`, ["Yes", "No"], opts);
1122
+ return result === "Yes";
1123
+ }
1124
+ /**
1125
+ * Show a text input for extensions.
1126
+ */
1127
+ showExtensionInput(title, placeholder, opts) {
1128
+ return new Promise((resolve) => {
1129
+ if (opts?.signal?.aborted) {
1130
+ resolve(undefined);
1131
+ return;
1132
+ }
1133
+ const onAbort = () => {
1134
+ this.hideExtensionInput();
1135
+ resolve(undefined);
1136
+ };
1137
+ opts?.signal?.addEventListener("abort", onAbort, { once: true });
1138
+ this.extensionInput = new ExtensionInputComponent(title, placeholder, (value) => {
1139
+ opts?.signal?.removeEventListener("abort", onAbort);
1140
+ this.hideExtensionInput();
1141
+ resolve(value);
1142
+ }, () => {
1143
+ opts?.signal?.removeEventListener("abort", onAbort);
1144
+ this.hideExtensionInput();
1145
+ resolve(undefined);
1146
+ }, { tui: this.ui, timeout: opts?.timeout });
1147
+ this.editorContainer.clear();
1148
+ this.editorContainer.addChild(this.extensionInput);
1149
+ this.ui.setFocus(this.extensionInput);
1150
+ this.ui.requestRender();
1151
+ });
1152
+ }
1153
+ /**
1154
+ * Hide the extension input.
1155
+ */
1156
+ hideExtensionInput() {
1157
+ this.extensionInput?.dispose();
1158
+ this.editorContainer.clear();
1159
+ this.editorContainer.addChild(this.editor);
1160
+ this.extensionInput = undefined;
1161
+ this.ui.setFocus(this.editor);
1162
+ this.ui.requestRender();
1163
+ }
1164
+ /**
1165
+ * Show a multi-line editor for extensions (with Ctrl+G support).
1166
+ */
1167
+ showExtensionEditor(title, prefill) {
1168
+ return new Promise((resolve) => {
1169
+ this.extensionEditor = new ExtensionEditorComponent(this.ui, this.keybindings, title, prefill, (value) => {
1170
+ this.hideExtensionEditor();
1171
+ resolve(value);
1172
+ }, () => {
1173
+ this.hideExtensionEditor();
1174
+ resolve(undefined);
1175
+ });
1176
+ this.editorContainer.clear();
1177
+ this.editorContainer.addChild(this.extensionEditor);
1178
+ this.ui.setFocus(this.extensionEditor);
1179
+ this.ui.requestRender();
1180
+ });
1181
+ }
1182
+ /**
1183
+ * Hide the extension editor.
1184
+ */
1185
+ hideExtensionEditor() {
1186
+ this.editorContainer.clear();
1187
+ this.editorContainer.addChild(this.editor);
1188
+ this.extensionEditor = undefined;
1189
+ this.ui.setFocus(this.editor);
1190
+ this.ui.requestRender();
1191
+ }
1192
+ /**
1193
+ * Set a custom editor component from an extension.
1194
+ * Pass undefined to restore the default editor.
1195
+ */
1196
+ setCustomEditorComponent(factory) {
1197
+ // Save text from current editor before switching
1198
+ const currentText = this.editor.getText();
1199
+ this.editorContainer.clear();
1200
+ if (factory) {
1201
+ // Create the custom editor with tui, theme, and keybindings
1202
+ const newEditor = factory(this.ui, getEditorTheme(), this.keybindings);
1203
+ // Wire up callbacks from the default editor
1204
+ newEditor.onSubmit = this.defaultEditor.onSubmit;
1205
+ newEditor.onChange = this.defaultEditor.onChange;
1206
+ // Copy text from previous editor
1207
+ newEditor.setText(currentText);
1208
+ // Copy appearance settings if supported
1209
+ if (newEditor.borderColor !== undefined) {
1210
+ newEditor.borderColor = this.defaultEditor.borderColor;
1211
+ }
1212
+ if (newEditor.setPaddingX !== undefined) {
1213
+ newEditor.setPaddingX(this.defaultEditor.getPaddingX());
1214
+ }
1215
+ // Set autocomplete if supported
1216
+ if (newEditor.setAutocompleteProvider && this.autocompleteProvider) {
1217
+ newEditor.setAutocompleteProvider(this.autocompleteProvider);
1218
+ }
1219
+ // If extending CustomEditor, copy app-level handlers
1220
+ // Use duck typing since instanceof fails across jiti module boundaries
1221
+ const customEditor = newEditor;
1222
+ if ("actionHandlers" in customEditor && customEditor.actionHandlers instanceof Map) {
1223
+ customEditor.onEscape = this.defaultEditor.onEscape;
1224
+ customEditor.onCtrlD = this.defaultEditor.onCtrlD;
1225
+ customEditor.onPasteImage = this.defaultEditor.onPasteImage;
1226
+ customEditor.onExtensionShortcut = (data) => this.defaultEditor.onExtensionShortcut?.(data);
1227
+ // Copy action handlers (clear, suspend, model switching, etc.)
1228
+ for (const [action, handler] of this.defaultEditor.actionHandlers) {
1229
+ customEditor.actionHandlers.set(action, handler);
1230
+ }
1231
+ }
1232
+ this.editor = newEditor;
1233
+ }
1234
+ else {
1235
+ // Restore default editor with text from custom editor
1236
+ this.defaultEditor.setText(currentText);
1237
+ this.editor = this.defaultEditor;
1238
+ }
1239
+ this.editorContainer.addChild(this.editor);
1240
+ this.ui.setFocus(this.editor);
1241
+ this.ui.requestRender();
1242
+ }
1243
+ /**
1244
+ * Show a notification for extensions.
1245
+ */
1246
+ showExtensionNotify(message, type) {
1247
+ if (type === "error") {
1248
+ this.showError(message);
1249
+ }
1250
+ else if (type === "warning") {
1251
+ this.showWarning(message);
1252
+ }
1253
+ else {
1254
+ this.showStatus(message);
1255
+ }
1256
+ }
1257
+ /** Show a custom component with keyboard focus. Overlay mode renders on top of existing content. */
1258
+ async showExtensionCustom(factory, options) {
1259
+ const savedText = this.editor.getText();
1260
+ const isOverlay = options?.overlay ?? false;
1261
+ const restoreEditor = () => {
1262
+ this.editorContainer.clear();
1263
+ this.editorContainer.addChild(this.editor);
1264
+ this.editor.setText(savedText);
1265
+ this.ui.setFocus(this.editor);
1266
+ this.ui.requestRender();
1267
+ };
1268
+ return new Promise((resolve, reject) => {
1269
+ let component;
1270
+ let closed = false;
1271
+ const close = (result) => {
1272
+ if (closed)
1273
+ return;
1274
+ closed = true;
1275
+ if (isOverlay)
1276
+ this.ui.hideOverlay();
1277
+ else
1278
+ restoreEditor();
1279
+ // Note: both branches above already call requestRender
1280
+ resolve(result);
1281
+ try {
1282
+ component?.dispose?.();
1283
+ }
1284
+ catch {
1285
+ /* ignore dispose errors */
1286
+ }
1287
+ };
1288
+ Promise.resolve(factory(this.ui, theme, this.keybindings, close))
1289
+ .then((c) => {
1290
+ if (closed)
1291
+ return;
1292
+ component = c;
1293
+ if (isOverlay) {
1294
+ // Resolve overlay options - can be static or dynamic function
1295
+ const resolveOptions = () => {
1296
+ if (options?.overlayOptions) {
1297
+ const opts = typeof options.overlayOptions === "function"
1298
+ ? options.overlayOptions()
1299
+ : options.overlayOptions;
1300
+ return opts;
1301
+ }
1302
+ // Fallback: use component's width property if available
1303
+ const w = component.width;
1304
+ return w ? { width: w } : undefined;
1305
+ };
1306
+ const handle = this.ui.showOverlay(component, resolveOptions());
1307
+ // Expose handle to caller for visibility control
1308
+ options?.onHandle?.(handle);
1309
+ }
1310
+ else {
1311
+ this.editorContainer.clear();
1312
+ this.editorContainer.addChild(component);
1313
+ this.ui.setFocus(component);
1314
+ this.ui.requestRender();
1315
+ }
1316
+ })
1317
+ .catch((err) => {
1318
+ if (closed)
1319
+ return;
1320
+ if (!isOverlay)
1321
+ restoreEditor();
1322
+ reject(err);
1323
+ });
1324
+ });
1325
+ }
1326
+ /**
1327
+ * Show an extension error in the UI.
1328
+ */
1329
+ showExtensionError(extensionPath, error, stack) {
1330
+ const errorMsg = `Extension "${extensionPath}" error: ${error}`;
1331
+ const errorText = new Text(theme.fg("error", errorMsg), 1, 0);
1332
+ this.chatContainer.addChild(errorText);
1333
+ if (stack) {
1334
+ // Show stack trace in dim color, indented
1335
+ const stackLines = stack
1336
+ .split("\n")
1337
+ .slice(1) // Skip first line (duplicates error message)
1338
+ .map((line) => theme.fg("dim", ` ${line.trim()}`))
1339
+ .join("\n");
1340
+ if (stackLines) {
1341
+ this.chatContainer.addChild(new Text(stackLines, 1, 0));
1342
+ }
1343
+ }
1344
+ this.ui.requestRender();
1345
+ }
1346
+ // =========================================================================
1347
+ // Key Handlers
1348
+ // =========================================================================
1349
+ setupKeyHandlers() {
1350
+ // Set up handlers on defaultEditor - they use this.editor for text access
1351
+ // so they work correctly regardless of which editor is active
1352
+ this.defaultEditor.onEscape = () => {
1353
+ if (this.loadingAnimation) {
1354
+ this.restoreQueuedMessagesToEditor({ abort: true });
1355
+ }
1356
+ else if (this.session.isBashRunning) {
1357
+ this.session.abortBash();
1358
+ }
1359
+ else if (this.isBashMode) {
1360
+ this.editor.setText("");
1361
+ this.isBashMode = false;
1362
+ this.updateEditorBorderColor();
1363
+ }
1364
+ else if (!this.editor.getText().trim()) {
1365
+ // Double-escape with empty editor triggers /tree or /fork based on setting
1366
+ const now = Date.now();
1367
+ if (now - this.lastEscapeTime < 500) {
1368
+ if (this.settingsManager.getDoubleEscapeAction() === "tree") {
1369
+ this.showTreeSelector();
1370
+ }
1371
+ else {
1372
+ this.showUserMessageSelector();
1373
+ }
1374
+ this.lastEscapeTime = 0;
1375
+ }
1376
+ else {
1377
+ this.lastEscapeTime = now;
1378
+ }
1379
+ }
1380
+ };
1381
+ // Register app action handlers
1382
+ this.defaultEditor.onAction("clear", () => this.handleCtrlC());
1383
+ this.defaultEditor.onCtrlD = () => this.handleCtrlD();
1384
+ this.defaultEditor.onAction("suspend", () => this.handleCtrlZ());
1385
+ this.defaultEditor.onAction("cycleThinkingLevel", () => this.cycleThinkingLevel());
1386
+ this.defaultEditor.onAction("cycleModelForward", () => this.cycleModel("forward"));
1387
+ this.defaultEditor.onAction("cycleModelBackward", () => this.cycleModel("backward"));
1388
+ // Global debug handler on TUI (works regardless of focus)
1389
+ this.ui.onDebug = () => this.handleDebugCommand();
1390
+ this.defaultEditor.onAction("selectModel", () => this.showModelSelector());
1391
+ this.defaultEditor.onAction("expandTools", () => this.toggleToolOutputExpansion());
1392
+ this.defaultEditor.onAction("toggleThinking", () => this.toggleThinkingBlockVisibility());
1393
+ this.defaultEditor.onAction("externalEditor", () => this.openExternalEditor());
1394
+ this.defaultEditor.onAction("followUp", () => this.handleFollowUp());
1395
+ this.defaultEditor.onAction("dequeue", () => this.handleDequeue());
1396
+ this.defaultEditor.onChange = (text) => {
1397
+ const wasBashMode = this.isBashMode;
1398
+ this.isBashMode = text.trimStart().startsWith("!");
1399
+ if (wasBashMode !== this.isBashMode) {
1400
+ this.updateEditorBorderColor();
1401
+ }
1402
+ };
1403
+ // Handle clipboard image paste (triggered on Ctrl+V)
1404
+ this.defaultEditor.onPasteImage = () => {
1405
+ this.handleClipboardImagePaste();
1406
+ };
1407
+ }
1408
+ async handleClipboardImagePaste() {
1409
+ try {
1410
+ const image = await readClipboardImage();
1411
+ if (!image) {
1412
+ return;
1413
+ }
1414
+ // Write to temp file
1415
+ const tmpDir = os.tmpdir();
1416
+ const ext = extensionForImageMimeType(image.mimeType) ?? "png";
1417
+ const fileName = `indusagi-clipboard-${crypto.randomUUID()}.${ext}`;
1418
+ const filePath = path.join(tmpDir, fileName);
1419
+ fs.writeFileSync(filePath, Buffer.from(image.bytes));
1420
+ // Insert file path directly
1421
+ this.editor.insertTextAtCursor?.(filePath);
1422
+ this.ui.requestRender();
1423
+ }
1424
+ catch {
1425
+ // Silently ignore clipboard errors (may not have permission, etc.)
1426
+ }
1427
+ }
1428
+ setupEditorSubmitHandler() {
1429
+ this.defaultEditor.onSubmit = async (text) => {
1430
+ text = text.trim();
1431
+ if (!text)
1432
+ return;
1433
+ // Handle commands
1434
+ if (text === "/settings") {
1435
+ this.showSettingsSelector();
1436
+ this.editor.setText("");
1437
+ return;
1438
+ }
1439
+ if (text === "/scoped-models") {
1440
+ this.editor.setText("");
1441
+ await this.showModelsSelector();
1442
+ return;
1443
+ }
1444
+ if (text === "/model" || text.startsWith("/model ")) {
1445
+ const searchTerm = text.startsWith("/model ") ? text.slice(7).trim() : undefined;
1446
+ this.editor.setText("");
1447
+ await this.handleModelCommand(searchTerm);
1448
+ return;
1449
+ }
1450
+ if (text.startsWith("/export")) {
1451
+ await this.handleExportCommand(text);
1452
+ this.editor.setText("");
1453
+ return;
1454
+ }
1455
+ if (text === "/share") {
1456
+ await this.handleShareCommand();
1457
+ this.editor.setText("");
1458
+ return;
1459
+ }
1460
+ if (text === "/copy") {
1461
+ this.handleCopyCommand();
1462
+ this.editor.setText("");
1463
+ return;
1464
+ }
1465
+ if (text === "/name" || text.startsWith("/name ")) {
1466
+ this.handleNameCommand(text);
1467
+ this.editor.setText("");
1468
+ return;
1469
+ }
1470
+ if (text === "/session") {
1471
+ this.handleSessionCommand();
1472
+ this.editor.setText("");
1473
+ return;
1474
+ }
1475
+ if (text === "/changelog") {
1476
+ this.handleChangelogCommand();
1477
+ this.editor.setText("");
1478
+ return;
1479
+ }
1480
+ if (text === "/hotkeys") {
1481
+ this.handleHotkeysCommand();
1482
+ this.editor.setText("");
1483
+ return;
1484
+ }
1485
+ if (text === "/fork") {
1486
+ this.showUserMessageSelector();
1487
+ this.editor.setText("");
1488
+ return;
1489
+ }
1490
+ if (text === "/tree") {
1491
+ this.showTreeSelector();
1492
+ this.editor.setText("");
1493
+ return;
1494
+ }
1495
+ if (text === "/login") {
1496
+ this.showOAuthSelector("login");
1497
+ this.editor.setText("");
1498
+ return;
1499
+ }
1500
+ if (text === "/logout") {
1501
+ this.showOAuthSelector("logout");
1502
+ this.editor.setText("");
1503
+ return;
1504
+ }
1505
+ if (text === "/new") {
1506
+ this.editor.setText("");
1507
+ await this.handleClearCommand();
1508
+ return;
1509
+ }
1510
+ if (text === "/compact" || text.startsWith("/compact ")) {
1511
+ const customInstructions = text.startsWith("/compact ") ? text.slice(9).trim() : undefined;
1512
+ this.editor.setText("");
1513
+ await this.handleCompactCommand(customInstructions);
1514
+ return;
1515
+ }
1516
+ if (text === "/reload") {
1517
+ this.editor.setText("");
1518
+ await this.handleReloadCommand();
1519
+ return;
1520
+ }
1521
+ if (text === "/debug") {
1522
+ this.handleDebugCommand();
1523
+ this.editor.setText("");
1524
+ return;
1525
+ }
1526
+ if (text === "/arminsayshi") {
1527
+ this.handleArminSaysHi();
1528
+ this.editor.setText("");
1529
+ return;
1530
+ }
1531
+ if (text === "/resume") {
1532
+ this.showSessionSelector();
1533
+ this.editor.setText("");
1534
+ return;
1535
+ }
1536
+ if (text === "/quit" || text === "/exit") {
1537
+ this.editor.setText("");
1538
+ await this.shutdown();
1539
+ return;
1540
+ }
1541
+ // Handle bash command (! for normal, !! for excluded from context)
1542
+ if (text.startsWith("!")) {
1543
+ const isExcluded = text.startsWith("!!");
1544
+ const command = isExcluded ? text.slice(2).trim() : text.slice(1).trim();
1545
+ if (command) {
1546
+ if (this.session.isBashRunning) {
1547
+ this.showWarning("A bash command is already running. Press Esc to cancel it first.");
1548
+ this.editor.setText(text);
1549
+ return;
1550
+ }
1551
+ this.editor.addToHistory?.(text);
1552
+ await this.handleBashCommand(command, isExcluded);
1553
+ this.isBashMode = false;
1554
+ this.updateEditorBorderColor();
1555
+ return;
1556
+ }
1557
+ }
1558
+ // Queue input during compaction (extension commands execute immediately)
1559
+ if (this.session.isCompacting) {
1560
+ if (this.isExtensionCommand(text)) {
1561
+ this.editor.addToHistory?.(text);
1562
+ this.editor.setText("");
1563
+ await this.session.prompt(text);
1564
+ }
1565
+ else {
1566
+ this.queueCompactionMessage(text, "steer");
1567
+ }
1568
+ return;
1569
+ }
1570
+ // If streaming, use prompt() with steer behavior
1571
+ // This handles extension commands (execute immediately), prompt template expansion, and queueing
1572
+ if (this.session.isStreaming) {
1573
+ this.editor.addToHistory?.(text);
1574
+ this.editor.setText("");
1575
+ await this.session.prompt(text, { streamingBehavior: "steer" });
1576
+ this.updatePendingMessagesDisplay();
1577
+ this.ui.requestRender();
1578
+ return;
1579
+ }
1580
+ // Normal message submission
1581
+ // First, move any pending bash components to chat
1582
+ this.flushPendingBashComponents();
1583
+ if (this.onInputCallback) {
1584
+ this.onInputCallback(text);
1585
+ }
1586
+ this.editor.addToHistory?.(text);
1587
+ };
1588
+ }
1589
+ subscribeToAgent() {
1590
+ this.unsubscribe = this.session.subscribe(async (event) => {
1591
+ await this.handleEvent(event);
1592
+ });
1593
+ }
1594
+ async handleEvent(event) {
1595
+ if (!this.isInitialized) {
1596
+ await this.init();
1597
+ }
1598
+ this.footer.invalidate();
1599
+ switch (event.type) {
1600
+ case "agent_start":
1601
+ // Restore main escape handler if retry handler is still active
1602
+ // (retry success event fires later, but we need main handler now)
1603
+ if (this.retryEscapeHandler) {
1604
+ this.defaultEditor.onEscape = this.retryEscapeHandler;
1605
+ this.retryEscapeHandler = undefined;
1606
+ }
1607
+ if (this.retryLoader) {
1608
+ this.retryLoader.stop();
1609
+ this.retryLoader = undefined;
1610
+ }
1611
+ if (this.loadingAnimation) {
1612
+ this.loadingAnimation.stop();
1613
+ }
1614
+ this.statusContainer.clear();
1615
+ this.loadingAnimation = new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), this.defaultWorkingMessage);
1616
+ this.statusContainer.addChild(this.loadingAnimation);
1617
+ // Apply any pending working message queued before loader existed
1618
+ if (this.pendingWorkingMessage !== undefined) {
1619
+ if (this.pendingWorkingMessage) {
1620
+ this.loadingAnimation.setMessage(this.pendingWorkingMessage);
1621
+ }
1622
+ this.pendingWorkingMessage = undefined;
1623
+ }
1624
+ this.ui.requestRender();
1625
+ break;
1626
+ case "message_start":
1627
+ if (event.message.role === "custom") {
1628
+ this.addMessageToChat(event.message);
1629
+ this.ui.requestRender();
1630
+ }
1631
+ else if (event.message.role === "user") {
1632
+ this.addMessageToChat(event.message);
1633
+ this.updatePendingMessagesDisplay();
1634
+ this.ui.requestRender();
1635
+ }
1636
+ else if (event.message.role === "assistant") {
1637
+ this.streamingComponent = new AssistantMessageComponent(undefined, this.hideThinkingBlock, this.getMarkdownThemeWithSettings());
1638
+ this.streamingMessage = event.message;
1639
+ this.chatContainer.addChild(this.streamingComponent);
1640
+ this.streamingComponent.updateContent(this.streamingMessage);
1641
+ this.ui.requestRender();
1642
+ }
1643
+ break;
1644
+ case "message_update":
1645
+ if (this.streamingComponent && event.message.role === "assistant") {
1646
+ this.streamingMessage = event.message;
1647
+ this.streamingComponent.updateContent(this.streamingMessage);
1648
+ for (const content of this.streamingMessage.content) {
1649
+ if (content.type === "toolCall") {
1650
+ if (!this.pendingTools.has(content.id)) {
1651
+ this.chatContainer.addChild(new Text("", 0, 0));
1652
+ const component = new ToolExecutionComponent(content.name, content.arguments, {
1653
+ showImages: this.settingsManager.getShowImages(),
1654
+ }, this.getRegisteredToolDefinition(content.name), this.ui);
1655
+ component.setExpanded(this.toolOutputExpanded);
1656
+ this.chatContainer.addChild(component);
1657
+ this.pendingTools.set(content.id, component);
1658
+ }
1659
+ else {
1660
+ const component = this.pendingTools.get(content.id);
1661
+ if (component) {
1662
+ component.updateArgs(content.arguments);
1663
+ }
1664
+ }
1665
+ }
1666
+ }
1667
+ this.ui.requestRender();
1668
+ }
1669
+ break;
1670
+ case "message_end":
1671
+ if (event.message.role === "user")
1672
+ break;
1673
+ if (this.streamingComponent && event.message.role === "assistant") {
1674
+ this.streamingMessage = event.message;
1675
+ let errorMessage;
1676
+ if (this.streamingMessage.stopReason === "aborted") {
1677
+ const retryAttempt = this.session.retryAttempt;
1678
+ errorMessage =
1679
+ retryAttempt > 0
1680
+ ? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? "s" : ""}`
1681
+ : "Operation aborted";
1682
+ this.streamingMessage.errorMessage = errorMessage;
1683
+ }
1684
+ this.streamingComponent.updateContent(this.streamingMessage);
1685
+ if (this.streamingMessage.stopReason === "aborted" || this.streamingMessage.stopReason === "error") {
1686
+ if (!errorMessage) {
1687
+ errorMessage = this.streamingMessage.errorMessage || "Error";
1688
+ }
1689
+ for (const [, component] of this.pendingTools.entries()) {
1690
+ component.updateResult({
1691
+ content: [{ type: "text", text: errorMessage }],
1692
+ isError: true,
1693
+ });
1694
+ }
1695
+ this.pendingTools.clear();
1696
+ }
1697
+ else {
1698
+ // Args are now complete - trigger diff computation for edit tools
1699
+ for (const [, component] of this.pendingTools.entries()) {
1700
+ component.setArgsComplete();
1701
+ }
1702
+ }
1703
+ this.streamingComponent = undefined;
1704
+ this.streamingMessage = undefined;
1705
+ this.footer.invalidate();
1706
+ }
1707
+ this.ui.requestRender();
1708
+ break;
1709
+ case "tool_execution_start": {
1710
+ if (!this.pendingTools.has(event.toolCallId)) {
1711
+ const component = new ToolExecutionComponent(event.toolName, event.args, {
1712
+ showImages: this.settingsManager.getShowImages(),
1713
+ }, this.getRegisteredToolDefinition(event.toolName), this.ui);
1714
+ component.setExpanded(this.toolOutputExpanded);
1715
+ this.chatContainer.addChild(component);
1716
+ this.pendingTools.set(event.toolCallId, component);
1717
+ this.ui.requestRender();
1718
+ }
1719
+ break;
1720
+ }
1721
+ case "tool_execution_update": {
1722
+ const component = this.pendingTools.get(event.toolCallId);
1723
+ if (component) {
1724
+ component.updateResult({ ...event.partialResult, isError: false }, true);
1725
+ this.ui.requestRender();
1726
+ }
1727
+ break;
1728
+ }
1729
+ case "tool_execution_end": {
1730
+ const component = this.pendingTools.get(event.toolCallId);
1731
+ if (component) {
1732
+ component.updateResult({ ...event.result, isError: event.isError });
1733
+ this.pendingTools.delete(event.toolCallId);
1734
+ this.ui.requestRender();
1735
+ }
1736
+ break;
1737
+ }
1738
+ case "agent_end":
1739
+ if (this.loadingAnimation) {
1740
+ this.loadingAnimation.stop();
1741
+ this.loadingAnimation = undefined;
1742
+ this.statusContainer.clear();
1743
+ }
1744
+ if (this.streamingComponent) {
1745
+ this.chatContainer.removeChild(this.streamingComponent);
1746
+ this.streamingComponent = undefined;
1747
+ this.streamingMessage = undefined;
1748
+ }
1749
+ this.pendingTools.clear();
1750
+ await this.checkShutdownRequested();
1751
+ this.ui.requestRender();
1752
+ break;
1753
+ case "auto_compaction_start": {
1754
+ // Keep editor active; submissions are queued during compaction.
1755
+ // Set up escape to abort auto-compaction
1756
+ this.autoCompactionEscapeHandler = this.defaultEditor.onEscape;
1757
+ this.defaultEditor.onEscape = () => {
1758
+ this.session.abortCompaction();
1759
+ };
1760
+ // Show compacting indicator with reason
1761
+ this.statusContainer.clear();
1762
+ const reasonText = event.reason === "overflow" ? "Context overflow detected, " : "";
1763
+ this.autoCompactionLoader = new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), `${reasonText}Auto-compacting... (${appKey(this.keybindings, "interrupt")} to cancel)`);
1764
+ this.statusContainer.addChild(this.autoCompactionLoader);
1765
+ this.ui.requestRender();
1766
+ break;
1767
+ }
1768
+ case "auto_compaction_end": {
1769
+ // Restore escape handler
1770
+ if (this.autoCompactionEscapeHandler) {
1771
+ this.defaultEditor.onEscape = this.autoCompactionEscapeHandler;
1772
+ this.autoCompactionEscapeHandler = undefined;
1773
+ }
1774
+ // Stop loader
1775
+ if (this.autoCompactionLoader) {
1776
+ this.autoCompactionLoader.stop();
1777
+ this.autoCompactionLoader = undefined;
1778
+ this.statusContainer.clear();
1779
+ }
1780
+ // Handle result
1781
+ if (event.aborted) {
1782
+ this.showStatus("Auto-compaction cancelled");
1783
+ }
1784
+ else if (event.result) {
1785
+ // Rebuild chat to show compacted state
1786
+ this.chatContainer.clear();
1787
+ this.rebuildChatFromMessages();
1788
+ // Add compaction component at bottom so user sees it without scrolling
1789
+ this.addMessageToChat({
1790
+ role: "compactionSummary",
1791
+ tokensBefore: event.result.tokensBefore,
1792
+ summary: event.result.summary,
1793
+ timestamp: Date.now(),
1794
+ });
1795
+ this.footer.invalidate();
1796
+ }
1797
+ else if (event.errorMessage) {
1798
+ // Compaction failed (e.g., quota exceeded, API error)
1799
+ this.chatContainer.addChild(new Spacer(1));
1800
+ this.chatContainer.addChild(new Text(theme.fg("error", event.errorMessage), 1, 0));
1801
+ }
1802
+ void this.flushCompactionQueue({ willRetry: event.willRetry });
1803
+ this.ui.requestRender();
1804
+ break;
1805
+ }
1806
+ case "auto_retry_start": {
1807
+ // Set up escape to abort retry
1808
+ this.retryEscapeHandler = this.defaultEditor.onEscape;
1809
+ this.defaultEditor.onEscape = () => {
1810
+ this.session.abortRetry();
1811
+ };
1812
+ // Show retry indicator
1813
+ this.statusContainer.clear();
1814
+ const delaySeconds = Math.round(event.delayMs / 1000);
1815
+ this.retryLoader = new Loader(this.ui, (spinner) => theme.fg("warning", spinner), (text) => theme.fg("muted", text), `Retrying (${event.attempt}/${event.maxAttempts}) in ${delaySeconds}s... (${appKey(this.keybindings, "interrupt")} to cancel)`);
1816
+ this.statusContainer.addChild(this.retryLoader);
1817
+ this.ui.requestRender();
1818
+ break;
1819
+ }
1820
+ case "auto_retry_end": {
1821
+ // Restore escape handler
1822
+ if (this.retryEscapeHandler) {
1823
+ this.defaultEditor.onEscape = this.retryEscapeHandler;
1824
+ this.retryEscapeHandler = undefined;
1825
+ }
1826
+ // Stop loader
1827
+ if (this.retryLoader) {
1828
+ this.retryLoader.stop();
1829
+ this.retryLoader = undefined;
1830
+ this.statusContainer.clear();
1831
+ }
1832
+ // Show error only on final failure (success shows normal response)
1833
+ if (!event.success) {
1834
+ this.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || "Unknown error"}`);
1835
+ }
1836
+ this.ui.requestRender();
1837
+ break;
1838
+ }
1839
+ }
1840
+ }
1841
+ /** Extract text content from a user message */
1842
+ getUserMessageText(message) {
1843
+ if (message.role !== "user")
1844
+ return "";
1845
+ const textBlocks = typeof message.content === "string"
1846
+ ? [{ type: "text", text: message.content }]
1847
+ : message.content.filter((c) => c.type === "text");
1848
+ return textBlocks.map((c) => c.text).join("");
1849
+ }
1850
+ /**
1851
+ * Show a status message in the chat.
1852
+ *
1853
+ * If multiple status messages are emitted back-to-back (without anything else being added to the chat),
1854
+ * we update the previous status line instead of appending new ones to avoid log spam.
1855
+ */
1856
+ showStatus(message) {
1857
+ const children = this.chatContainer.children;
1858
+ const last = children.length > 0 ? children[children.length - 1] : undefined;
1859
+ const secondLast = children.length > 1 ? children[children.length - 2] : undefined;
1860
+ if (last && secondLast && last === this.lastStatusText && secondLast === this.lastStatusSpacer) {
1861
+ this.lastStatusText.setText(theme.fg("dim", message));
1862
+ this.ui.requestRender();
1863
+ return;
1864
+ }
1865
+ const spacer = new Spacer(1);
1866
+ const text = new Text(theme.fg("dim", message), 1, 0);
1867
+ this.chatContainer.addChild(spacer);
1868
+ this.chatContainer.addChild(text);
1869
+ this.lastStatusSpacer = spacer;
1870
+ this.lastStatusText = text;
1871
+ this.ui.requestRender();
1872
+ }
1873
+ addMessageToChat(message, options) {
1874
+ switch (message.role) {
1875
+ case "bashExecution": {
1876
+ const component = new BashExecutionComponent(message.command, this.ui, message.excludeFromContext);
1877
+ if (message.output) {
1878
+ component.appendOutput(message.output);
1879
+ }
1880
+ component.setComplete(message.exitCode, message.cancelled, message.truncated ? { truncated: true } : undefined, message.fullOutputPath);
1881
+ this.chatContainer.addChild(component);
1882
+ break;
1883
+ }
1884
+ case "custom": {
1885
+ if (message.display) {
1886
+ const renderer = this.session.extensionRunner?.getMessageRenderer(message.customType);
1887
+ this.chatContainer.addChild(new CustomMessageComponent(message, renderer, this.getMarkdownThemeWithSettings()));
1888
+ }
1889
+ break;
1890
+ }
1891
+ case "compactionSummary": {
1892
+ this.chatContainer.addChild(new Spacer(1));
1893
+ const component = new CompactionSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());
1894
+ component.setExpanded(this.toolOutputExpanded);
1895
+ this.chatContainer.addChild(component);
1896
+ break;
1897
+ }
1898
+ case "branchSummary": {
1899
+ this.chatContainer.addChild(new Spacer(1));
1900
+ const component = new BranchSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());
1901
+ component.setExpanded(this.toolOutputExpanded);
1902
+ this.chatContainer.addChild(component);
1903
+ break;
1904
+ }
1905
+ case "user": {
1906
+ const textContent = this.getUserMessageText(message);
1907
+ if (textContent) {
1908
+ const skillBlock = parseSkillBlock(textContent);
1909
+ if (skillBlock) {
1910
+ // Render skill block (collapsible)
1911
+ this.chatContainer.addChild(new Spacer(1));
1912
+ const component = new SkillInvocationMessageComponent(skillBlock, this.getMarkdownThemeWithSettings());
1913
+ component.setExpanded(this.toolOutputExpanded);
1914
+ this.chatContainer.addChild(component);
1915
+ // Render user message separately if present
1916
+ if (skillBlock.userMessage) {
1917
+ const userComponent = new UserMessageComponent(skillBlock.userMessage, this.getMarkdownThemeWithSettings());
1918
+ this.chatContainer.addChild(userComponent);
1919
+ }
1920
+ }
1921
+ else {
1922
+ const userComponent = new UserMessageComponent(textContent, this.getMarkdownThemeWithSettings());
1923
+ this.chatContainer.addChild(userComponent);
1924
+ }
1925
+ if (options?.populateHistory) {
1926
+ this.editor.addToHistory?.(textContent);
1927
+ }
1928
+ }
1929
+ break;
1930
+ }
1931
+ case "assistant": {
1932
+ const assistantComponent = new AssistantMessageComponent(message, this.hideThinkingBlock, this.getMarkdownThemeWithSettings());
1933
+ this.chatContainer.addChild(assistantComponent);
1934
+ break;
1935
+ }
1936
+ case "toolResult": {
1937
+ // Tool results are rendered inline with tool calls, handled separately
1938
+ break;
1939
+ }
1940
+ default: {
1941
+ const _exhaustive = message;
1942
+ }
1943
+ }
1944
+ }
1945
+ /**
1946
+ * Render session context to chat. Used for initial load and rebuild after compaction.
1947
+ * @param sessionContext Session context to render
1948
+ * @param options.updateFooter Update footer state
1949
+ * @param options.populateHistory Add user messages to editor history
1950
+ */
1951
+ renderSessionContext(sessionContext, options = {}) {
1952
+ this.pendingTools.clear();
1953
+ if (options.updateFooter) {
1954
+ this.footer.invalidate();
1955
+ this.updateEditorBorderColor();
1956
+ }
1957
+ for (const message of sessionContext.messages) {
1958
+ // Assistant messages need special handling for tool calls
1959
+ if (message.role === "assistant") {
1960
+ this.addMessageToChat(message);
1961
+ // Render tool call components
1962
+ for (const content of message.content) {
1963
+ if (content.type === "toolCall") {
1964
+ const component = new ToolExecutionComponent(content.name, content.arguments, { showImages: this.settingsManager.getShowImages() }, this.getRegisteredToolDefinition(content.name), this.ui);
1965
+ component.setExpanded(this.toolOutputExpanded);
1966
+ this.chatContainer.addChild(component);
1967
+ if (message.stopReason === "aborted" || message.stopReason === "error") {
1968
+ let errorMessage;
1969
+ if (message.stopReason === "aborted") {
1970
+ const retryAttempt = this.session.retryAttempt;
1971
+ errorMessage =
1972
+ retryAttempt > 0
1973
+ ? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? "s" : ""}`
1974
+ : "Operation aborted";
1975
+ }
1976
+ else {
1977
+ errorMessage = message.errorMessage || "Error";
1978
+ }
1979
+ component.updateResult({ content: [{ type: "text", text: errorMessage }], isError: true });
1980
+ }
1981
+ else {
1982
+ this.pendingTools.set(content.id, component);
1983
+ }
1984
+ }
1985
+ }
1986
+ }
1987
+ else if (message.role === "toolResult") {
1988
+ // Match tool results to pending tool components
1989
+ const component = this.pendingTools.get(message.toolCallId);
1990
+ if (component) {
1991
+ component.updateResult(message);
1992
+ this.pendingTools.delete(message.toolCallId);
1993
+ }
1994
+ }
1995
+ else {
1996
+ // All other messages use standard rendering
1997
+ this.addMessageToChat(message, options);
1998
+ }
1999
+ }
2000
+ this.pendingTools.clear();
2001
+ this.ui.requestRender();
2002
+ }
2003
+ renderInitialMessages() {
2004
+ // Get aligned messages and entries from session context
2005
+ const context = this.sessionManager.buildSessionContext();
2006
+ this.renderSessionContext(context, {
2007
+ updateFooter: true,
2008
+ populateHistory: true,
2009
+ });
2010
+ // Show compaction info if session was compacted
2011
+ const allEntries = this.sessionManager.getEntries();
2012
+ const compactionCount = allEntries.filter((e) => e.type === "compaction").length;
2013
+ if (compactionCount > 0) {
2014
+ const times = compactionCount === 1 ? "1 time" : `${compactionCount} times`;
2015
+ this.showStatus(`Session compacted ${times}`);
2016
+ }
2017
+ }
2018
+ async getUserInput() {
2019
+ return new Promise((resolve) => {
2020
+ this.onInputCallback = (text) => {
2021
+ this.onInputCallback = undefined;
2022
+ resolve(text);
2023
+ };
2024
+ });
2025
+ }
2026
+ rebuildChatFromMessages() {
2027
+ this.chatContainer.clear();
2028
+ const context = this.sessionManager.buildSessionContext();
2029
+ this.renderSessionContext(context);
2030
+ }
2031
+ // =========================================================================
2032
+ // Key handlers
2033
+ // =========================================================================
2034
+ handleCtrlC() {
2035
+ const now = Date.now();
2036
+ if (now - this.lastSigintTime < 500) {
2037
+ void this.shutdown();
2038
+ }
2039
+ else {
2040
+ this.clearEditor();
2041
+ this.lastSigintTime = now;
2042
+ }
2043
+ }
2044
+ handleCtrlD() {
2045
+ // Only called when editor is empty (enforced by CustomEditor)
2046
+ void this.shutdown();
2047
+ }
2048
+ async shutdown() {
2049
+ if (this.isShuttingDown)
2050
+ return;
2051
+ this.isShuttingDown = true;
2052
+ // Emit shutdown event to extensions
2053
+ const extensionRunner = this.session.extensionRunner;
2054
+ if (extensionRunner?.hasHandlers("session_shutdown")) {
2055
+ await extensionRunner.emit({
2056
+ type: "session_shutdown",
2057
+ });
2058
+ }
2059
+ // Wait for any pending renders to complete
2060
+ // requestRender() uses process.nextTick(), so we wait one tick
2061
+ await new Promise((resolve) => process.nextTick(resolve));
2062
+ this.stop();
2063
+ process.exit(0);
2064
+ }
2065
+ /**
2066
+ * Check if shutdown was requested and perform shutdown if so.
2067
+ */
2068
+ async checkShutdownRequested() {
2069
+ if (!this.shutdownRequested)
2070
+ return;
2071
+ await this.shutdown();
2072
+ }
2073
+ handleCtrlZ() {
2074
+ // Set up handler to restore TUI when resumed
2075
+ process.once("SIGCONT", () => {
2076
+ this.ui.start();
2077
+ this.ui.requestRender(true);
2078
+ });
2079
+ // Stop the TUI (restore terminal to normal mode)
2080
+ this.ui.stop();
2081
+ // Send SIGTSTP to process group (pid=0 means all processes in group)
2082
+ process.kill(0, "SIGTSTP");
2083
+ }
2084
+ async handleFollowUp() {
2085
+ const text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim();
2086
+ if (!text)
2087
+ return;
2088
+ // Queue input during compaction (extension commands execute immediately)
2089
+ if (this.session.isCompacting) {
2090
+ if (this.isExtensionCommand(text)) {
2091
+ this.editor.addToHistory?.(text);
2092
+ this.editor.setText("");
2093
+ await this.session.prompt(text);
2094
+ }
2095
+ else {
2096
+ this.queueCompactionMessage(text, "followUp");
2097
+ }
2098
+ return;
2099
+ }
2100
+ // Alt+Enter queues a follow-up message (waits until agent finishes)
2101
+ // This handles extension commands (execute immediately), prompt template expansion, and queueing
2102
+ if (this.session.isStreaming) {
2103
+ this.editor.addToHistory?.(text);
2104
+ this.editor.setText("");
2105
+ await this.session.prompt(text, { streamingBehavior: "followUp" });
2106
+ this.updatePendingMessagesDisplay();
2107
+ this.ui.requestRender();
2108
+ }
2109
+ // If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)
2110
+ else if (this.editor.onSubmit) {
2111
+ this.editor.onSubmit(text);
2112
+ }
2113
+ }
2114
+ handleDequeue() {
2115
+ const restored = this.restoreQueuedMessagesToEditor();
2116
+ if (restored === 0) {
2117
+ this.showStatus("No queued messages to restore");
2118
+ }
2119
+ else {
2120
+ this.showStatus(`Restored ${restored} queued message${restored > 1 ? "s" : ""} to editor`);
2121
+ }
2122
+ }
2123
+ updateEditorBorderColor() {
2124
+ if (this.isBashMode) {
2125
+ this.editor.borderColor = theme.getBashModeBorderColor();
2126
+ }
2127
+ else {
2128
+ const level = this.session.thinkingLevel || "off";
2129
+ this.editor.borderColor = theme.getThinkingBorderColor(level);
2130
+ }
2131
+ this.ui.requestRender();
2132
+ }
2133
+ cycleThinkingLevel() {
2134
+ const newLevel = this.session.cycleThinkingLevel();
2135
+ if (newLevel === undefined) {
2136
+ this.showStatus("Current model does not support thinking");
2137
+ }
2138
+ else {
2139
+ this.footer.invalidate();
2140
+ this.updateEditorBorderColor();
2141
+ this.showStatus(`Thinking level: ${newLevel}`);
2142
+ }
2143
+ }
2144
+ async cycleModel(direction) {
2145
+ try {
2146
+ const result = await this.session.cycleModel(direction);
2147
+ if (result === undefined) {
2148
+ const msg = this.session.scopedModels.length > 0 ? "Only one model in scope" : "Only one model available";
2149
+ this.showStatus(msg);
2150
+ }
2151
+ else {
2152
+ this.footer.invalidate();
2153
+ this.updateEditorBorderColor();
2154
+ const thinkingStr = result.model.reasoning && result.thinkingLevel !== "off" ? ` (thinking: ${result.thinkingLevel})` : "";
2155
+ this.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}`);
2156
+ }
2157
+ }
2158
+ catch (error) {
2159
+ this.showError(error instanceof Error ? error.message : String(error));
2160
+ }
2161
+ }
2162
+ toggleToolOutputExpansion() {
2163
+ this.toolOutputExpanded = !this.toolOutputExpanded;
2164
+ for (const child of this.chatContainer.children) {
2165
+ if (isExpandable(child)) {
2166
+ child.setExpanded(this.toolOutputExpanded);
2167
+ }
2168
+ }
2169
+ this.ui.requestRender();
2170
+ }
2171
+ toggleThinkingBlockVisibility() {
2172
+ this.hideThinkingBlock = !this.hideThinkingBlock;
2173
+ this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);
2174
+ // Rebuild chat from session messages
2175
+ this.chatContainer.clear();
2176
+ this.rebuildChatFromMessages();
2177
+ // If streaming, re-add the streaming component with updated visibility and re-render
2178
+ if (this.streamingComponent && this.streamingMessage) {
2179
+ this.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock);
2180
+ this.streamingComponent.updateContent(this.streamingMessage);
2181
+ this.chatContainer.addChild(this.streamingComponent);
2182
+ }
2183
+ this.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? "hidden" : "visible"}`);
2184
+ }
2185
+ openExternalEditor() {
2186
+ // Determine editor (respect $VISUAL, then $EDITOR)
2187
+ const editorCmd = process.env.VISUAL || process.env.EDITOR;
2188
+ if (!editorCmd) {
2189
+ this.showWarning("No editor configured. Set $VISUAL or $EDITOR environment variable.");
2190
+ return;
2191
+ }
2192
+ const currentText = this.editor.getExpandedText?.() ?? this.editor.getText();
2193
+ const tmpFile = path.join(os.tmpdir(), `indusagi-editor-${Date.now()}.indusagi.md`);
2194
+ try {
2195
+ // Write current content to temp file
2196
+ fs.writeFileSync(tmpFile, currentText, "utf-8");
2197
+ // Stop TUI to release terminal
2198
+ this.ui.stop();
2199
+ // Split by space to support editor arguments (e.g., "code --wait")
2200
+ const [editor, ...editorArgs] = editorCmd.split(" ");
2201
+ // Spawn editor synchronously with inherited stdio for interactive editing
2202
+ const result = spawnSync(editor, [...editorArgs, tmpFile], {
2203
+ stdio: "inherit",
2204
+ });
2205
+ // On successful exit (status 0), replace editor content
2206
+ if (result.status === 0) {
2207
+ const newContent = fs.readFileSync(tmpFile, "utf-8").replace(/\n$/, "");
2208
+ this.editor.setText(newContent);
2209
+ }
2210
+ // On non-zero exit, keep original text (no action needed)
2211
+ }
2212
+ finally {
2213
+ // Clean up temp file
2214
+ try {
2215
+ fs.unlinkSync(tmpFile);
2216
+ }
2217
+ catch {
2218
+ // Ignore cleanup errors
2219
+ }
2220
+ // Restart TUI
2221
+ this.ui.start();
2222
+ // Force full re-render since external editor uses alternate screen
2223
+ this.ui.requestRender(true);
2224
+ }
2225
+ }
2226
+ // =========================================================================
2227
+ // UI helpers
2228
+ // =========================================================================
2229
+ clearEditor() {
2230
+ this.editor.setText("");
2231
+ this.ui.requestRender();
2232
+ }
2233
+ showError(errorMessage) {
2234
+ this.chatContainer.addChild(new Spacer(1));
2235
+ this.chatContainer.addChild(new Text(theme.fg("error", `Error: ${errorMessage}`), 1, 0));
2236
+ this.ui.requestRender();
2237
+ }
2238
+ showWarning(warningMessage) {
2239
+ this.chatContainer.addChild(new Spacer(1));
2240
+ this.chatContainer.addChild(new Text(theme.fg("warning", `Warning: ${warningMessage}`), 1, 0));
2241
+ this.ui.requestRender();
2242
+ }
2243
+ showNewVersionNotification(newVersion) {
2244
+ const action = isBunBinary
2245
+ ? `Download from: ${theme.fg("accent", "https://github.com/badlogic/indusagi-mono/releases/latest")}`
2246
+ : `Run: ${theme.fg("accent", `${isBunRuntime ? "bun" : "npm"} install -g indusagi-coding-agent`)}`;
2247
+ const updateInstruction = theme.fg("muted", `New version ${newVersion} is available. `) + action;
2248
+ const changelogUrl = theme.fg("accent", "https://github.com/badlogic/indusagi-mono/blob/main/packages/coding-agent/CHANGELOG.md");
2249
+ const changelogLine = theme.fg("muted", "Changelog: ") + changelogUrl;
2250
+ this.chatContainer.addChild(new Spacer(1));
2251
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
2252
+ this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Update Available"))}\n${updateInstruction}\n${changelogLine}`, 1, 0));
2253
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
2254
+ this.ui.requestRender();
2255
+ }
2256
+ /**
2257
+ * Get all queued messages (read-only).
2258
+ * Combines session queue and compaction queue.
2259
+ */
2260
+ getAllQueuedMessages() {
2261
+ return {
2262
+ steering: [
2263
+ ...this.session.getSteeringMessages(),
2264
+ ...this.compactionQueuedMessages.filter((msg) => msg.mode === "steer").map((msg) => msg.text),
2265
+ ],
2266
+ followUp: [
2267
+ ...this.session.getFollowUpMessages(),
2268
+ ...this.compactionQueuedMessages.filter((msg) => msg.mode === "followUp").map((msg) => msg.text),
2269
+ ],
2270
+ };
2271
+ }
2272
+ /**
2273
+ * Clear all queued messages and return their contents.
2274
+ * Clears both session queue and compaction queue.
2275
+ */
2276
+ clearAllQueues() {
2277
+ const { steering, followUp } = this.session.clearQueue();
2278
+ const compactionSteering = this.compactionQueuedMessages
2279
+ .filter((msg) => msg.mode === "steer")
2280
+ .map((msg) => msg.text);
2281
+ const compactionFollowUp = this.compactionQueuedMessages
2282
+ .filter((msg) => msg.mode === "followUp")
2283
+ .map((msg) => msg.text);
2284
+ this.compactionQueuedMessages = [];
2285
+ return {
2286
+ steering: [...steering, ...compactionSteering],
2287
+ followUp: [...followUp, ...compactionFollowUp],
2288
+ };
2289
+ }
2290
+ updatePendingMessagesDisplay() {
2291
+ this.pendingMessagesContainer.clear();
2292
+ const { steering: steeringMessages, followUp: followUpMessages } = this.getAllQueuedMessages();
2293
+ if (steeringMessages.length > 0 || followUpMessages.length > 0) {
2294
+ this.pendingMessagesContainer.addChild(new Spacer(1));
2295
+ for (const message of steeringMessages) {
2296
+ const text = theme.fg("dim", `Steering: ${message}`);
2297
+ this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
2298
+ }
2299
+ for (const message of followUpMessages) {
2300
+ const text = theme.fg("dim", `Follow-up: ${message}`);
2301
+ this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
2302
+ }
2303
+ const dequeueHint = this.getAppKeyDisplay("dequeue");
2304
+ const hintText = theme.fg("dim", `↳ ${dequeueHint} to edit all queued messages`);
2305
+ this.pendingMessagesContainer.addChild(new TruncatedText(hintText, 1, 0));
2306
+ }
2307
+ }
2308
+ restoreQueuedMessagesToEditor(options) {
2309
+ const { steering, followUp } = this.clearAllQueues();
2310
+ const allQueued = [...steering, ...followUp];
2311
+ if (allQueued.length === 0) {
2312
+ this.updatePendingMessagesDisplay();
2313
+ if (options?.abort) {
2314
+ this.agent.abort();
2315
+ }
2316
+ return 0;
2317
+ }
2318
+ const queuedText = allQueued.join("\n\n");
2319
+ const currentText = options?.currentText ?? this.editor.getText();
2320
+ const combinedText = [queuedText, currentText].filter((t) => t.trim()).join("\n\n");
2321
+ this.editor.setText(combinedText);
2322
+ this.updatePendingMessagesDisplay();
2323
+ if (options?.abort) {
2324
+ this.agent.abort();
2325
+ }
2326
+ return allQueued.length;
2327
+ }
2328
+ queueCompactionMessage(text, mode) {
2329
+ this.compactionQueuedMessages.push({ text, mode });
2330
+ this.editor.addToHistory?.(text);
2331
+ this.editor.setText("");
2332
+ this.updatePendingMessagesDisplay();
2333
+ this.showStatus("Queued message for after compaction");
2334
+ }
2335
+ isExtensionCommand(text) {
2336
+ if (!text.startsWith("/"))
2337
+ return false;
2338
+ const extensionRunner = this.session.extensionRunner;
2339
+ if (!extensionRunner)
2340
+ return false;
2341
+ const spaceIndex = text.indexOf(" ");
2342
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
2343
+ return !!extensionRunner.getCommand(commandName);
2344
+ }
2345
+ async flushCompactionQueue(options) {
2346
+ if (this.compactionQueuedMessages.length === 0) {
2347
+ return;
2348
+ }
2349
+ const queuedMessages = [...this.compactionQueuedMessages];
2350
+ this.compactionQueuedMessages = [];
2351
+ this.updatePendingMessagesDisplay();
2352
+ const restoreQueue = (error) => {
2353
+ this.session.clearQueue();
2354
+ this.compactionQueuedMessages = queuedMessages;
2355
+ this.updatePendingMessagesDisplay();
2356
+ this.showError(`Failed to send queued message${queuedMessages.length > 1 ? "s" : ""}: ${error instanceof Error ? error.message : String(error)}`);
2357
+ };
2358
+ try {
2359
+ if (options?.willRetry) {
2360
+ // When retry is pending, queue messages for the retry turn
2361
+ for (const message of queuedMessages) {
2362
+ if (this.isExtensionCommand(message.text)) {
2363
+ await this.session.prompt(message.text);
2364
+ }
2365
+ else if (message.mode === "followUp") {
2366
+ await this.session.followUp(message.text);
2367
+ }
2368
+ else {
2369
+ await this.session.steer(message.text);
2370
+ }
2371
+ }
2372
+ this.updatePendingMessagesDisplay();
2373
+ return;
2374
+ }
2375
+ // Find first non-extension-command message to use as prompt
2376
+ const firstPromptIndex = queuedMessages.findIndex((message) => !this.isExtensionCommand(message.text));
2377
+ if (firstPromptIndex === -1) {
2378
+ // All extension commands - execute them all
2379
+ for (const message of queuedMessages) {
2380
+ await this.session.prompt(message.text);
2381
+ }
2382
+ return;
2383
+ }
2384
+ // Execute any extension commands before the first prompt
2385
+ const preCommands = queuedMessages.slice(0, firstPromptIndex);
2386
+ const firstPrompt = queuedMessages[firstPromptIndex];
2387
+ const rest = queuedMessages.slice(firstPromptIndex + 1);
2388
+ for (const message of preCommands) {
2389
+ await this.session.prompt(message.text);
2390
+ }
2391
+ // Send first prompt (starts streaming)
2392
+ const promptPromise = this.session.prompt(firstPrompt.text).catch((error) => {
2393
+ restoreQueue(error);
2394
+ });
2395
+ // Queue remaining messages
2396
+ for (const message of rest) {
2397
+ if (this.isExtensionCommand(message.text)) {
2398
+ await this.session.prompt(message.text);
2399
+ }
2400
+ else if (message.mode === "followUp") {
2401
+ await this.session.followUp(message.text);
2402
+ }
2403
+ else {
2404
+ await this.session.steer(message.text);
2405
+ }
2406
+ }
2407
+ this.updatePendingMessagesDisplay();
2408
+ void promptPromise;
2409
+ }
2410
+ catch (error) {
2411
+ restoreQueue(error);
2412
+ }
2413
+ }
2414
+ /** Move pending bash components from pending area to chat */
2415
+ flushPendingBashComponents() {
2416
+ for (const component of this.pendingBashComponents) {
2417
+ this.pendingMessagesContainer.removeChild(component);
2418
+ this.chatContainer.addChild(component);
2419
+ }
2420
+ this.pendingBashComponents = [];
2421
+ }
2422
+ // =========================================================================
2423
+ // Selectors
2424
+ // =========================================================================
2425
+ /**
2426
+ * Shows a selector component in place of the editor.
2427
+ * @param create Factory that receives a `done` callback and returns the component and focus target
2428
+ */
2429
+ showSelector(create) {
2430
+ const done = () => {
2431
+ this.editorContainer.clear();
2432
+ this.editorContainer.addChild(this.editor);
2433
+ this.ui.setFocus(this.editor);
2434
+ };
2435
+ const { component, focus } = create(done);
2436
+ this.editorContainer.clear();
2437
+ this.editorContainer.addChild(component);
2438
+ this.ui.setFocus(focus);
2439
+ this.ui.requestRender();
2440
+ }
2441
+ showSettingsSelector() {
2442
+ this.showSelector((done) => {
2443
+ const selector = new SettingsSelectorComponent({
2444
+ autoCompact: this.session.autoCompactionEnabled,
2445
+ showImages: this.settingsManager.getShowImages(),
2446
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
2447
+ blockImages: this.settingsManager.getBlockImages(),
2448
+ enableSkillCommands: this.settingsManager.getEnableSkillCommands(),
2449
+ steeringMode: this.session.steeringMode,
2450
+ followUpMode: this.session.followUpMode,
2451
+ thinkingLevel: this.session.thinkingLevel,
2452
+ availableThinkingLevels: this.session.getAvailableThinkingLevels(),
2453
+ currentTheme: this.settingsManager.getTheme() || "dark",
2454
+ availableThemes: getAvailableThemes(),
2455
+ hideThinkingBlock: this.hideThinkingBlock,
2456
+ collapseChangelog: this.settingsManager.getCollapseChangelog(),
2457
+ doubleEscapeAction: this.settingsManager.getDoubleEscapeAction(),
2458
+ showHardwareCursor: this.settingsManager.getShowHardwareCursor(),
2459
+ editorPaddingX: this.settingsManager.getEditorPaddingX(),
2460
+ quietStartup: this.settingsManager.getQuietStartup(),
2461
+ }, {
2462
+ onAutoCompactChange: (enabled) => {
2463
+ this.session.setAutoCompactionEnabled(enabled);
2464
+ this.footer.setAutoCompactEnabled(enabled);
2465
+ },
2466
+ onShowImagesChange: (enabled) => {
2467
+ this.settingsManager.setShowImages(enabled);
2468
+ for (const child of this.chatContainer.children) {
2469
+ if (child instanceof ToolExecutionComponent) {
2470
+ child.setShowImages(enabled);
2471
+ }
2472
+ }
2473
+ },
2474
+ onAutoResizeImagesChange: (enabled) => {
2475
+ this.settingsManager.setImageAutoResize(enabled);
2476
+ },
2477
+ onBlockImagesChange: (blocked) => {
2478
+ this.settingsManager.setBlockImages(blocked);
2479
+ },
2480
+ onEnableSkillCommandsChange: (enabled) => {
2481
+ this.settingsManager.setEnableSkillCommands(enabled);
2482
+ this.rebuildAutocomplete();
2483
+ },
2484
+ onSteeringModeChange: (mode) => {
2485
+ this.session.setSteeringMode(mode);
2486
+ },
2487
+ onFollowUpModeChange: (mode) => {
2488
+ this.session.setFollowUpMode(mode);
2489
+ },
2490
+ onThinkingLevelChange: (level) => {
2491
+ this.session.setThinkingLevel(level);
2492
+ this.footer.invalidate();
2493
+ this.updateEditorBorderColor();
2494
+ },
2495
+ onThemeChange: (themeName) => {
2496
+ const result = setTheme(themeName, true);
2497
+ this.settingsManager.setTheme(themeName);
2498
+ this.ui.invalidate();
2499
+ if (!result.success) {
2500
+ this.showError(`Failed to load theme "${themeName}": ${result.error}\nFell back to dark theme.`);
2501
+ }
2502
+ },
2503
+ onThemePreview: (themeName) => {
2504
+ const result = setTheme(themeName, true);
2505
+ if (result.success) {
2506
+ this.ui.invalidate();
2507
+ this.ui.requestRender();
2508
+ }
2509
+ },
2510
+ onHideThinkingBlockChange: (hidden) => {
2511
+ this.hideThinkingBlock = hidden;
2512
+ this.settingsManager.setHideThinkingBlock(hidden);
2513
+ for (const child of this.chatContainer.children) {
2514
+ if (child instanceof AssistantMessageComponent) {
2515
+ child.setHideThinkingBlock(hidden);
2516
+ }
2517
+ }
2518
+ this.chatContainer.clear();
2519
+ this.rebuildChatFromMessages();
2520
+ },
2521
+ onCollapseChangelogChange: (collapsed) => {
2522
+ this.settingsManager.setCollapseChangelog(collapsed);
2523
+ },
2524
+ onQuietStartupChange: (enabled) => {
2525
+ this.settingsManager.setQuietStartup(enabled);
2526
+ },
2527
+ onDoubleEscapeActionChange: (action) => {
2528
+ this.settingsManager.setDoubleEscapeAction(action);
2529
+ },
2530
+ onShowHardwareCursorChange: (enabled) => {
2531
+ this.settingsManager.setShowHardwareCursor(enabled);
2532
+ this.ui.setShowHardwareCursor(enabled);
2533
+ },
2534
+ onEditorPaddingXChange: (padding) => {
2535
+ this.settingsManager.setEditorPaddingX(padding);
2536
+ this.defaultEditor.setPaddingX(padding);
2537
+ if (this.editor !== this.defaultEditor && this.editor.setPaddingX !== undefined) {
2538
+ this.editor.setPaddingX(padding);
2539
+ }
2540
+ },
2541
+ onCancel: () => {
2542
+ done();
2543
+ this.ui.requestRender();
2544
+ },
2545
+ });
2546
+ return { component: selector, focus: selector.getSettingsList() };
2547
+ });
2548
+ }
2549
+ async handleModelCommand(searchTerm) {
2550
+ if (!searchTerm) {
2551
+ this.showModelSelector();
2552
+ return;
2553
+ }
2554
+ const model = await this.findExactModelMatch(searchTerm);
2555
+ if (model) {
2556
+ try {
2557
+ await this.session.setModel(model);
2558
+ this.footer.invalidate();
2559
+ this.updateEditorBorderColor();
2560
+ this.showStatus(`Model: ${model.id}`);
2561
+ }
2562
+ catch (error) {
2563
+ this.showError(error instanceof Error ? error.message : String(error));
2564
+ }
2565
+ return;
2566
+ }
2567
+ this.showModelSelector(searchTerm);
2568
+ }
2569
+ async findExactModelMatch(searchTerm) {
2570
+ const term = searchTerm.trim();
2571
+ if (!term)
2572
+ return undefined;
2573
+ let targetProvider;
2574
+ let targetModelId = "";
2575
+ if (term.includes("/")) {
2576
+ const parts = term.split("/", 2);
2577
+ targetProvider = parts[0]?.trim().toLowerCase();
2578
+ targetModelId = parts[1]?.trim().toLowerCase() ?? "";
2579
+ }
2580
+ else {
2581
+ targetModelId = term.toLowerCase();
2582
+ }
2583
+ if (!targetModelId)
2584
+ return undefined;
2585
+ const models = await this.getModelCandidates();
2586
+ const exactMatches = models.filter((item) => {
2587
+ const idMatch = item.id.toLowerCase() === targetModelId;
2588
+ const providerMatch = !targetProvider || item.provider.toLowerCase() === targetProvider;
2589
+ return idMatch && providerMatch;
2590
+ });
2591
+ return exactMatches.length === 1 ? exactMatches[0] : undefined;
2592
+ }
2593
+ async getModelCandidates() {
2594
+ if (this.session.scopedModels.length > 0) {
2595
+ return this.session.scopedModels.map((scoped) => scoped.model);
2596
+ }
2597
+ this.session.modelRegistry.refresh();
2598
+ try {
2599
+ return await this.session.modelRegistry.getAvailable();
2600
+ }
2601
+ catch {
2602
+ return [];
2603
+ }
2604
+ }
2605
+ /** Update the footer's available provider count from current model candidates */
2606
+ async updateAvailableProviderCount() {
2607
+ const models = await this.getModelCandidates();
2608
+ const uniqueProviders = new Set(models.map((m) => m.provider));
2609
+ this.footerDataProvider.setAvailableProviderCount(uniqueProviders.size);
2610
+ }
2611
+ showModelSelector(initialSearchInput) {
2612
+ this.showSelector((done) => {
2613
+ const selector = new ModelSelectorComponent(this.ui, this.session.model, this.settingsManager, this.session.modelRegistry, this.session.scopedModels, async (model) => {
2614
+ try {
2615
+ await this.session.setModel(model);
2616
+ this.footer.invalidate();
2617
+ this.updateEditorBorderColor();
2618
+ done();
2619
+ this.showStatus(`Model: ${model.id}`);
2620
+ }
2621
+ catch (error) {
2622
+ done();
2623
+ this.showError(error instanceof Error ? error.message : String(error));
2624
+ }
2625
+ }, () => {
2626
+ done();
2627
+ this.ui.requestRender();
2628
+ }, initialSearchInput);
2629
+ return { component: selector, focus: selector };
2630
+ });
2631
+ }
2632
+ async showModelsSelector() {
2633
+ // Get all available models
2634
+ this.session.modelRegistry.refresh();
2635
+ const allModels = this.session.modelRegistry.getAvailable();
2636
+ if (allModels.length === 0) {
2637
+ this.showStatus("No models available");
2638
+ return;
2639
+ }
2640
+ // Check if session has scoped models (from previous session-only changes or CLI --models)
2641
+ const sessionScopedModels = this.session.scopedModels;
2642
+ const hasSessionScope = sessionScopedModels.length > 0;
2643
+ // Build enabled model IDs from session state or settings
2644
+ const enabledModelIds = new Set();
2645
+ let hasFilter = false;
2646
+ if (hasSessionScope) {
2647
+ // Use current session's scoped models
2648
+ for (const sm of sessionScopedModels) {
2649
+ enabledModelIds.add(`${sm.model.provider}/${sm.model.id}`);
2650
+ }
2651
+ hasFilter = true;
2652
+ }
2653
+ else {
2654
+ // Fall back to settings
2655
+ const patterns = this.settingsManager.getEnabledModels();
2656
+ if (patterns !== undefined && patterns.length > 0) {
2657
+ hasFilter = true;
2658
+ const scopedModels = await resolveModelScope(patterns, this.session.modelRegistry);
2659
+ for (const sm of scopedModels) {
2660
+ enabledModelIds.add(`${sm.model.provider}/${sm.model.id}`);
2661
+ }
2662
+ }
2663
+ }
2664
+ // Track current enabled state (session-only until persisted)
2665
+ const currentEnabledIds = new Set(enabledModelIds);
2666
+ let currentHasFilter = hasFilter;
2667
+ // Helper to update session's scoped models (session-only, no persist)
2668
+ const updateSessionModels = async (enabledIds) => {
2669
+ if (enabledIds.size > 0 && enabledIds.size < allModels.length) {
2670
+ // Use current session thinking level, not settings default
2671
+ const currentThinkingLevel = this.session.thinkingLevel;
2672
+ const newScopedModels = await resolveModelScope(Array.from(enabledIds), this.session.modelRegistry);
2673
+ this.session.setScopedModels(newScopedModels.map((sm) => ({
2674
+ model: sm.model,
2675
+ thinkingLevel: sm.thinkingLevel ?? currentThinkingLevel,
2676
+ })));
2677
+ }
2678
+ else {
2679
+ // All enabled or none enabled = no filter
2680
+ this.session.setScopedModels([]);
2681
+ }
2682
+ };
2683
+ this.showSelector((done) => {
2684
+ const selector = new ScopedModelsSelectorComponent({
2685
+ allModels,
2686
+ enabledModelIds: currentEnabledIds,
2687
+ hasEnabledModelsFilter: currentHasFilter,
2688
+ }, {
2689
+ onModelToggle: async (modelId, enabled) => {
2690
+ if (enabled) {
2691
+ currentEnabledIds.add(modelId);
2692
+ }
2693
+ else {
2694
+ currentEnabledIds.delete(modelId);
2695
+ }
2696
+ currentHasFilter = true;
2697
+ await updateSessionModels(currentEnabledIds);
2698
+ },
2699
+ onEnableAll: async (allModelIds) => {
2700
+ currentEnabledIds.clear();
2701
+ for (const id of allModelIds) {
2702
+ currentEnabledIds.add(id);
2703
+ }
2704
+ currentHasFilter = false;
2705
+ await updateSessionModels(currentEnabledIds);
2706
+ },
2707
+ onClearAll: async () => {
2708
+ currentEnabledIds.clear();
2709
+ currentHasFilter = true;
2710
+ await updateSessionModels(currentEnabledIds);
2711
+ },
2712
+ onToggleProvider: async (_provider, modelIds, enabled) => {
2713
+ for (const id of modelIds) {
2714
+ if (enabled) {
2715
+ currentEnabledIds.add(id);
2716
+ }
2717
+ else {
2718
+ currentEnabledIds.delete(id);
2719
+ }
2720
+ }
2721
+ currentHasFilter = true;
2722
+ await updateSessionModels(currentEnabledIds);
2723
+ },
2724
+ onPersist: (enabledIds) => {
2725
+ // Persist to settings
2726
+ const newPatterns = enabledIds.length === allModels.length
2727
+ ? undefined // All enabled = clear filter
2728
+ : enabledIds;
2729
+ this.settingsManager.setEnabledModels(newPatterns);
2730
+ this.showStatus("Model selection saved to settings");
2731
+ },
2732
+ onCancel: () => {
2733
+ done();
2734
+ this.ui.requestRender();
2735
+ },
2736
+ });
2737
+ return { component: selector, focus: selector };
2738
+ });
2739
+ }
2740
+ showUserMessageSelector() {
2741
+ const userMessages = this.session.getUserMessagesForForking();
2742
+ if (userMessages.length === 0) {
2743
+ this.showStatus("No messages to fork from");
2744
+ return;
2745
+ }
2746
+ this.showSelector((done) => {
2747
+ const selector = new UserMessageSelectorComponent(userMessages.map((m) => ({ id: m.entryId, text: m.text })), async (entryId) => {
2748
+ const result = await this.session.fork(entryId);
2749
+ if (result.cancelled) {
2750
+ // Extension cancelled the fork
2751
+ done();
2752
+ this.ui.requestRender();
2753
+ return;
2754
+ }
2755
+ this.chatContainer.clear();
2756
+ this.renderInitialMessages();
2757
+ this.editor.setText(result.selectedText);
2758
+ done();
2759
+ this.showStatus("Branched to new session");
2760
+ }, () => {
2761
+ done();
2762
+ this.ui.requestRender();
2763
+ });
2764
+ return { component: selector, focus: selector.getMessageList() };
2765
+ });
2766
+ }
2767
+ showTreeSelector(initialSelectedId) {
2768
+ const tree = this.sessionManager.getTree();
2769
+ const realLeafId = this.sessionManager.getLeafId();
2770
+ // Find the visible leaf for display (skip metadata entries like labels)
2771
+ let visibleLeafId = realLeafId;
2772
+ while (visibleLeafId) {
2773
+ const entry = this.sessionManager.getEntry(visibleLeafId);
2774
+ if (!entry)
2775
+ break;
2776
+ if (entry.type !== "label" && entry.type !== "custom")
2777
+ break;
2778
+ visibleLeafId = entry.parentId ?? null;
2779
+ }
2780
+ if (tree.length === 0) {
2781
+ this.showStatus("No entries in session");
2782
+ return;
2783
+ }
2784
+ this.showSelector((done) => {
2785
+ const selector = new TreeSelectorComponent(tree, visibleLeafId, this.ui.terminal.rows, async (entryId) => {
2786
+ // Selecting the visible leaf is a no-op (already there)
2787
+ if (entryId === visibleLeafId) {
2788
+ done();
2789
+ this.showStatus("Already at this point");
2790
+ return;
2791
+ }
2792
+ // Ask about summarization
2793
+ done(); // Close selector first
2794
+ // Loop until user makes a complete choice or cancels to tree
2795
+ let wantsSummary = false;
2796
+ let customInstructions;
2797
+ while (true) {
2798
+ const summaryChoice = await this.showExtensionSelector("Summarize branch?", [
2799
+ "No summary",
2800
+ "Summarize",
2801
+ "Summarize with custom prompt",
2802
+ ]);
2803
+ if (summaryChoice === undefined) {
2804
+ // User pressed escape - re-show tree selector with same selection
2805
+ this.showTreeSelector(entryId);
2806
+ return;
2807
+ }
2808
+ wantsSummary = summaryChoice !== "No summary";
2809
+ if (summaryChoice === "Summarize with custom prompt") {
2810
+ customInstructions = await this.showExtensionEditor("Custom summarization instructions");
2811
+ if (customInstructions === undefined) {
2812
+ // User cancelled - loop back to summary selector
2813
+ continue;
2814
+ }
2815
+ }
2816
+ // User made a complete choice
2817
+ break;
2818
+ }
2819
+ // Set up escape handler and loader if summarizing
2820
+ let summaryLoader;
2821
+ const originalOnEscape = this.defaultEditor.onEscape;
2822
+ if (wantsSummary) {
2823
+ this.defaultEditor.onEscape = () => {
2824
+ this.session.abortBranchSummary();
2825
+ };
2826
+ this.chatContainer.addChild(new Spacer(1));
2827
+ summaryLoader = new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), `Summarizing branch... (${appKey(this.keybindings, "interrupt")} to cancel)`);
2828
+ this.statusContainer.addChild(summaryLoader);
2829
+ this.ui.requestRender();
2830
+ }
2831
+ try {
2832
+ const result = await this.session.navigateTree(entryId, {
2833
+ summarize: wantsSummary,
2834
+ customInstructions,
2835
+ });
2836
+ if (result.aborted) {
2837
+ // Summarization aborted - re-show tree selector with same selection
2838
+ this.showStatus("Branch summarization cancelled");
2839
+ this.showTreeSelector(entryId);
2840
+ return;
2841
+ }
2842
+ if (result.cancelled) {
2843
+ this.showStatus("Navigation cancelled");
2844
+ return;
2845
+ }
2846
+ // Update UI
2847
+ this.chatContainer.clear();
2848
+ this.renderInitialMessages();
2849
+ if (result.editorText) {
2850
+ this.editor.setText(result.editorText);
2851
+ }
2852
+ this.showStatus("Navigated to selected point");
2853
+ }
2854
+ catch (error) {
2855
+ this.showError(error instanceof Error ? error.message : String(error));
2856
+ }
2857
+ finally {
2858
+ if (summaryLoader) {
2859
+ summaryLoader.stop();
2860
+ this.statusContainer.clear();
2861
+ }
2862
+ this.defaultEditor.onEscape = originalOnEscape;
2863
+ }
2864
+ }, () => {
2865
+ done();
2866
+ this.ui.requestRender();
2867
+ }, (entryId, label) => {
2868
+ this.sessionManager.appendLabelChange(entryId, label);
2869
+ this.ui.requestRender();
2870
+ }, initialSelectedId);
2871
+ return { component: selector, focus: selector };
2872
+ });
2873
+ }
2874
+ showSessionSelector() {
2875
+ this.showSelector((done) => {
2876
+ const selector = new SessionSelectorComponent((onProgress) => SessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress), SessionManager.listAll, async (sessionPath) => {
2877
+ done();
2878
+ await this.handleResumeSession(sessionPath);
2879
+ }, () => {
2880
+ done();
2881
+ this.ui.requestRender();
2882
+ }, () => {
2883
+ void this.shutdown();
2884
+ }, () => this.ui.requestRender(), {
2885
+ renameSession: async (sessionFilePath, nextName) => {
2886
+ const next = (nextName ?? "").trim();
2887
+ if (!next)
2888
+ return;
2889
+ const mgr = SessionManager.open(sessionFilePath);
2890
+ mgr.appendSessionInfo(next);
2891
+ },
2892
+ showRenameHint: true,
2893
+ }, this.sessionManager.getSessionFile());
2894
+ return { component: selector, focus: selector };
2895
+ });
2896
+ }
2897
+ async handleResumeSession(sessionPath) {
2898
+ // Stop loading animation
2899
+ if (this.loadingAnimation) {
2900
+ this.loadingAnimation.stop();
2901
+ this.loadingAnimation = undefined;
2902
+ }
2903
+ this.statusContainer.clear();
2904
+ // Clear UI state
2905
+ this.pendingMessagesContainer.clear();
2906
+ this.compactionQueuedMessages = [];
2907
+ this.streamingComponent = undefined;
2908
+ this.streamingMessage = undefined;
2909
+ this.pendingTools.clear();
2910
+ // Switch session via AgentSession (emits extension session events)
2911
+ await this.session.switchSession(sessionPath);
2912
+ // Clear and re-render the chat
2913
+ this.chatContainer.clear();
2914
+ this.renderInitialMessages();
2915
+ this.showStatus("Resumed session");
2916
+ }
2917
+ async showOAuthSelector(mode) {
2918
+ if (mode === "logout") {
2919
+ const providers = this.session.modelRegistry.authStorage.list();
2920
+ const loggedInProviders = providers.filter((p) => this.session.modelRegistry.authStorage.get(p)?.type === "oauth");
2921
+ if (loggedInProviders.length === 0) {
2922
+ this.showStatus("No OAuth providers logged in. Use /login first.");
2923
+ return;
2924
+ }
2925
+ }
2926
+ this.showSelector((done) => {
2927
+ const selector = new OAuthSelectorComponent(mode, this.session.modelRegistry.authStorage, async (providerId) => {
2928
+ done();
2929
+ if (mode === "login") {
2930
+ await this.showLoginDialog(providerId);
2931
+ }
2932
+ else {
2933
+ // Logout flow
2934
+ const providerInfo = getOAuthProviders().find((p) => p.id === providerId);
2935
+ const providerName = providerInfo?.name || providerId;
2936
+ try {
2937
+ this.session.modelRegistry.authStorage.logout(providerId);
2938
+ this.session.modelRegistry.refresh();
2939
+ await this.updateAvailableProviderCount();
2940
+ this.showStatus(`Logged out of ${providerName}`);
2941
+ }
2942
+ catch (error) {
2943
+ this.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);
2944
+ }
2945
+ }
2946
+ }, () => {
2947
+ done();
2948
+ this.ui.requestRender();
2949
+ });
2950
+ return { component: selector, focus: selector };
2951
+ });
2952
+ }
2953
+ async showLoginDialog(providerId) {
2954
+ const providerInfo = getOAuthProviders().find((p) => p.id === providerId);
2955
+ const providerName = providerInfo?.name || providerId;
2956
+ // Providers that use callback servers (can paste redirect URL)
2957
+ const usesCallbackServer = providerInfo?.usesCallbackServer ?? false;
2958
+ // Create login dialog component
2959
+ const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {
2960
+ // Completion handled below
2961
+ });
2962
+ // Show dialog in editor container
2963
+ this.editorContainer.clear();
2964
+ this.editorContainer.addChild(dialog);
2965
+ this.ui.setFocus(dialog);
2966
+ this.ui.requestRender();
2967
+ // Promise for manual code input (racing with callback server)
2968
+ let manualCodeResolve;
2969
+ let manualCodeReject;
2970
+ const manualCodePromise = new Promise((resolve, reject) => {
2971
+ manualCodeResolve = resolve;
2972
+ manualCodeReject = reject;
2973
+ });
2974
+ // Restore editor helper
2975
+ const restoreEditor = () => {
2976
+ this.editorContainer.clear();
2977
+ this.editorContainer.addChild(this.editor);
2978
+ this.ui.setFocus(this.editor);
2979
+ this.ui.requestRender();
2980
+ };
2981
+ try {
2982
+ await this.session.modelRegistry.authStorage.login(providerId, {
2983
+ onAuth: (info) => {
2984
+ dialog.showAuth(info.url, info.instructions);
2985
+ if (usesCallbackServer) {
2986
+ // Show input for manual paste, racing with callback
2987
+ dialog
2988
+ .showManualInput("Paste redirect URL below, or complete login in browser:")
2989
+ .then((value) => {
2990
+ if (value && manualCodeResolve) {
2991
+ manualCodeResolve(value);
2992
+ manualCodeResolve = undefined;
2993
+ }
2994
+ })
2995
+ .catch(() => {
2996
+ if (manualCodeReject) {
2997
+ manualCodeReject(new Error("Login cancelled"));
2998
+ manualCodeReject = undefined;
2999
+ }
3000
+ });
3001
+ }
3002
+ else if (providerId === "github-copilot") {
3003
+ // GitHub Copilot polls after onAuth
3004
+ dialog.showWaiting("Waiting for browser authentication...");
3005
+ }
3006
+ // For Anthropic: onPrompt is called immediately after
3007
+ },
3008
+ onPrompt: async (prompt) => {
3009
+ return dialog.showPrompt(prompt.message, prompt.placeholder);
3010
+ },
3011
+ onProgress: (message) => {
3012
+ dialog.showProgress(message);
3013
+ },
3014
+ onManualCodeInput: () => manualCodePromise,
3015
+ signal: dialog.signal,
3016
+ });
3017
+ // Success
3018
+ restoreEditor();
3019
+ this.session.modelRegistry.refresh();
3020
+ await this.updateAvailableProviderCount();
3021
+ this.showStatus(`Logged in to ${providerName}. Credentials saved to ${getAuthPath()}`);
3022
+ }
3023
+ catch (error) {
3024
+ restoreEditor();
3025
+ const errorMsg = error instanceof Error ? error.message : String(error);
3026
+ if (errorMsg !== "Login cancelled") {
3027
+ this.showError(`Failed to login to ${providerName}: ${errorMsg}`);
3028
+ }
3029
+ }
3030
+ }
3031
+ // =========================================================================
3032
+ // Command handlers
3033
+ // =========================================================================
3034
+ async handleReloadCommand() {
3035
+ if (this.session.isStreaming) {
3036
+ this.showWarning("Wait for the current response to finish before reloading.");
3037
+ return;
3038
+ }
3039
+ if (this.session.isCompacting) {
3040
+ this.showWarning("Wait for compaction to finish before reloading.");
3041
+ return;
3042
+ }
3043
+ this.resetExtensionUI();
3044
+ const loader = new BorderedLoader(this.ui, theme, "Reloading extensions, skills, prompts, themes...", {
3045
+ cancellable: false,
3046
+ });
3047
+ const previousEditor = this.editor;
3048
+ this.editorContainer.clear();
3049
+ this.editorContainer.addChild(loader);
3050
+ this.ui.setFocus(loader);
3051
+ this.ui.requestRender();
3052
+ const dismissLoader = (editor) => {
3053
+ loader.dispose();
3054
+ this.editorContainer.clear();
3055
+ this.editorContainer.addChild(editor);
3056
+ this.ui.setFocus(editor);
3057
+ this.ui.requestRender();
3058
+ };
3059
+ try {
3060
+ await this.session.reload();
3061
+ setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
3062
+ this.rebuildAutocomplete();
3063
+ const runner = this.session.extensionRunner;
3064
+ if (runner) {
3065
+ this.setupExtensionShortcuts(runner);
3066
+ }
3067
+ this.rebuildChatFromMessages();
3068
+ dismissLoader(this.editor);
3069
+ this.showLoadedResources({ extensionPaths: runner?.getExtensionPaths() ?? [], force: true });
3070
+ const modelsJsonError = this.session.modelRegistry.getError();
3071
+ if (modelsJsonError) {
3072
+ this.showError(`models.json error: ${modelsJsonError}`);
3073
+ }
3074
+ this.showStatus("Reloaded extensions, skills, prompts, themes");
3075
+ }
3076
+ catch (error) {
3077
+ dismissLoader(previousEditor);
3078
+ this.showError(`Reload failed: ${error instanceof Error ? error.message : String(error)}`);
3079
+ }
3080
+ }
3081
+ async handleExportCommand(text) {
3082
+ const parts = text.split(/\s+/);
3083
+ const outputPath = parts.length > 1 ? parts[1] : undefined;
3084
+ try {
3085
+ const filePath = await this.session.exportToHtml(outputPath);
3086
+ this.showStatus(`Session exported to: ${filePath}`);
3087
+ }
3088
+ catch (error) {
3089
+ this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);
3090
+ }
3091
+ }
3092
+ async handleShareCommand() {
3093
+ // Check if gh is available and logged in
3094
+ try {
3095
+ const authResult = spawnSync("gh", ["auth", "status"], { encoding: "utf-8" });
3096
+ if (authResult.status !== 0) {
3097
+ this.showError("GitHub CLI is not logged in. Run 'gh auth login' first.");
3098
+ return;
3099
+ }
3100
+ }
3101
+ catch {
3102
+ this.showError("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/");
3103
+ return;
3104
+ }
3105
+ // Export to a temp file
3106
+ const tmpFile = path.join(os.tmpdir(), "session.html");
3107
+ try {
3108
+ await this.session.exportToHtml(tmpFile);
3109
+ }
3110
+ catch (error) {
3111
+ this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);
3112
+ return;
3113
+ }
3114
+ // Show cancellable loader, replacing the editor
3115
+ const loader = new BorderedLoader(this.ui, theme, "Creating gist...");
3116
+ this.editorContainer.clear();
3117
+ this.editorContainer.addChild(loader);
3118
+ this.ui.setFocus(loader);
3119
+ this.ui.requestRender();
3120
+ const restoreEditor = () => {
3121
+ loader.dispose();
3122
+ this.editorContainer.clear();
3123
+ this.editorContainer.addChild(this.editor);
3124
+ this.ui.setFocus(this.editor);
3125
+ try {
3126
+ fs.unlinkSync(tmpFile);
3127
+ }
3128
+ catch {
3129
+ // Ignore cleanup errors
3130
+ }
3131
+ };
3132
+ // Create a secret gist asynchronously
3133
+ let proc = null;
3134
+ loader.onAbort = () => {
3135
+ proc?.kill();
3136
+ restoreEditor();
3137
+ this.showStatus("Share cancelled");
3138
+ };
3139
+ try {
3140
+ const result = await new Promise((resolve) => {
3141
+ proc = spawn("gh", ["gist", "create", "--public=false", tmpFile]);
3142
+ let stdout = "";
3143
+ let stderr = "";
3144
+ proc.stdout?.on("data", (data) => {
3145
+ stdout += data.toString();
3146
+ });
3147
+ proc.stderr?.on("data", (data) => {
3148
+ stderr += data.toString();
3149
+ });
3150
+ proc.on("close", (code) => resolve({ stdout, stderr, code }));
3151
+ });
3152
+ if (loader.signal.aborted)
3153
+ return;
3154
+ restoreEditor();
3155
+ if (result.code !== 0) {
3156
+ const errorMsg = result.stderr?.trim() || "Unknown error";
3157
+ this.showError(`Failed to create gist: ${errorMsg}`);
3158
+ return;
3159
+ }
3160
+ // Extract gist ID from the URL returned by gh
3161
+ // gh returns something like: https://gist.github.com/username/GIST_ID
3162
+ const gistUrl = result.stdout?.trim();
3163
+ const gistId = gistUrl?.split("/").pop();
3164
+ if (!gistId) {
3165
+ this.showError("Failed to parse gist ID from gh output");
3166
+ return;
3167
+ }
3168
+ // Create the preview URL
3169
+ const previewUrl = getShareViewerUrl(gistId);
3170
+ this.showStatus(`Share URL: ${previewUrl}\nGist: ${gistUrl}`);
3171
+ }
3172
+ catch (error) {
3173
+ if (!loader.signal.aborted) {
3174
+ restoreEditor();
3175
+ this.showError(`Failed to create gist: ${error instanceof Error ? error.message : "Unknown error"}`);
3176
+ }
3177
+ }
3178
+ }
3179
+ handleCopyCommand() {
3180
+ const text = this.session.getLastAssistantText();
3181
+ if (!text) {
3182
+ this.showError("No agent messages to copy yet.");
3183
+ return;
3184
+ }
3185
+ try {
3186
+ copyToClipboard(text);
3187
+ this.showStatus("Copied last agent message to clipboard");
3188
+ }
3189
+ catch (error) {
3190
+ this.showError(error instanceof Error ? error.message : String(error));
3191
+ }
3192
+ }
3193
+ handleNameCommand(text) {
3194
+ const name = text.replace(/^\/name\s*/, "").trim();
3195
+ if (!name) {
3196
+ const currentName = this.sessionManager.getSessionName();
3197
+ if (currentName) {
3198
+ this.chatContainer.addChild(new Spacer(1));
3199
+ this.chatContainer.addChild(new Text(theme.fg("dim", `Session name: ${currentName}`), 1, 0));
3200
+ }
3201
+ else {
3202
+ this.showWarning("Usage: /name <name>");
3203
+ }
3204
+ this.ui.requestRender();
3205
+ return;
3206
+ }
3207
+ this.sessionManager.appendSessionInfo(name);
3208
+ this.updateTerminalTitle();
3209
+ this.chatContainer.addChild(new Spacer(1));
3210
+ this.chatContainer.addChild(new Text(theme.fg("dim", `Session name set: ${name}`), 1, 0));
3211
+ this.ui.requestRender();
3212
+ }
3213
+ handleSessionCommand() {
3214
+ const stats = this.session.getSessionStats();
3215
+ const sessionName = this.sessionManager.getSessionName();
3216
+ let info = `${theme.bold("Session Info")}\n\n`;
3217
+ if (sessionName) {
3218
+ info += `${theme.fg("dim", "Name:")} ${sessionName}\n`;
3219
+ }
3220
+ info += `${theme.fg("dim", "File:")} ${stats.sessionFile ?? "In-memory"}\n`;
3221
+ info += `${theme.fg("dim", "ID:")} ${stats.sessionId}\n\n`;
3222
+ info += `${theme.bold("Messages")}\n`;
3223
+ info += `${theme.fg("dim", "User:")} ${stats.userMessages}\n`;
3224
+ info += `${theme.fg("dim", "Assistant:")} ${stats.assistantMessages}\n`;
3225
+ info += `${theme.fg("dim", "Tool Calls:")} ${stats.toolCalls}\n`;
3226
+ info += `${theme.fg("dim", "Tool Results:")} ${stats.toolResults}\n`;
3227
+ info += `${theme.fg("dim", "Total:")} ${stats.totalMessages}\n\n`;
3228
+ info += `${theme.bold("Tokens")}\n`;
3229
+ info += `${theme.fg("dim", "Input:")} ${stats.tokens.input.toLocaleString()}\n`;
3230
+ info += `${theme.fg("dim", "Output:")} ${stats.tokens.output.toLocaleString()}\n`;
3231
+ if (stats.tokens.cacheRead > 0) {
3232
+ info += `${theme.fg("dim", "Cache Read:")} ${stats.tokens.cacheRead.toLocaleString()}\n`;
3233
+ }
3234
+ if (stats.tokens.cacheWrite > 0) {
3235
+ info += `${theme.fg("dim", "Cache Write:")} ${stats.tokens.cacheWrite.toLocaleString()}\n`;
3236
+ }
3237
+ info += `${theme.fg("dim", "Total:")} ${stats.tokens.total.toLocaleString()}\n`;
3238
+ if (stats.cost > 0) {
3239
+ info += `\n${theme.bold("Cost")}\n`;
3240
+ info += `${theme.fg("dim", "Total:")} ${stats.cost.toFixed(4)}`;
3241
+ }
3242
+ this.chatContainer.addChild(new Spacer(1));
3243
+ this.chatContainer.addChild(new Text(info, 1, 0));
3244
+ this.ui.requestRender();
3245
+ }
3246
+ handleChangelogCommand() {
3247
+ const changelogPath = getChangelogPath();
3248
+ const allEntries = parseChangelog(changelogPath);
3249
+ const changelogMarkdown = allEntries.length > 0
3250
+ ? allEntries
3251
+ .reverse()
3252
+ .map((e) => e.content)
3253
+ .join("\n\n")
3254
+ : "No changelog entries found.";
3255
+ this.chatContainer.addChild(new Spacer(1));
3256
+ this.chatContainer.addChild(new DynamicBorder());
3257
+ this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0));
3258
+ this.chatContainer.addChild(new Spacer(1));
3259
+ this.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings()));
3260
+ this.chatContainer.addChild(new DynamicBorder());
3261
+ this.ui.requestRender();
3262
+ }
3263
+ /**
3264
+ * Capitalize keybinding for display (e.g., "ctrl+c" -> "Ctrl+C").
3265
+ */
3266
+ capitalizeKey(key) {
3267
+ return key
3268
+ .split("/")
3269
+ .map((k) => k
3270
+ .split("+")
3271
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
3272
+ .join("+"))
3273
+ .join("/");
3274
+ }
3275
+ /**
3276
+ * Get capitalized display string for an app keybinding action.
3277
+ */
3278
+ getAppKeyDisplay(action) {
3279
+ return this.capitalizeKey(appKey(this.keybindings, action));
3280
+ }
3281
+ /**
3282
+ * Get capitalized display string for an editor keybinding action.
3283
+ */
3284
+ getEditorKeyDisplay(action) {
3285
+ return this.capitalizeKey(editorKey(action));
3286
+ }
3287
+ handleHotkeysCommand() {
3288
+ // Navigation keybindings
3289
+ const cursorWordLeft = this.getEditorKeyDisplay("cursorWordLeft");
3290
+ const cursorWordRight = this.getEditorKeyDisplay("cursorWordRight");
3291
+ const cursorLineStart = this.getEditorKeyDisplay("cursorLineStart");
3292
+ const cursorLineEnd = this.getEditorKeyDisplay("cursorLineEnd");
3293
+ const pageUp = this.getEditorKeyDisplay("pageUp");
3294
+ const pageDown = this.getEditorKeyDisplay("pageDown");
3295
+ // Editing keybindings
3296
+ const submit = this.getEditorKeyDisplay("submit");
3297
+ const newLine = this.getEditorKeyDisplay("newLine");
3298
+ const deleteWordBackward = this.getEditorKeyDisplay("deleteWordBackward");
3299
+ const deleteWordForward = this.getEditorKeyDisplay("deleteWordForward");
3300
+ const deleteToLineStart = this.getEditorKeyDisplay("deleteToLineStart");
3301
+ const deleteToLineEnd = this.getEditorKeyDisplay("deleteToLineEnd");
3302
+ const yank = this.getEditorKeyDisplay("yank");
3303
+ const yankPop = this.getEditorKeyDisplay("yankPop");
3304
+ const undo = this.getEditorKeyDisplay("undo");
3305
+ const tab = this.getEditorKeyDisplay("tab");
3306
+ // App keybindings
3307
+ const interrupt = this.getAppKeyDisplay("interrupt");
3308
+ const clear = this.getAppKeyDisplay("clear");
3309
+ const exit = this.getAppKeyDisplay("exit");
3310
+ const suspend = this.getAppKeyDisplay("suspend");
3311
+ const cycleThinkingLevel = this.getAppKeyDisplay("cycleThinkingLevel");
3312
+ const cycleModelForward = this.getAppKeyDisplay("cycleModelForward");
3313
+ const selectModel = this.getAppKeyDisplay("selectModel");
3314
+ const expandTools = this.getAppKeyDisplay("expandTools");
3315
+ const toggleThinking = this.getAppKeyDisplay("toggleThinking");
3316
+ const externalEditor = this.getAppKeyDisplay("externalEditor");
3317
+ const followUp = this.getAppKeyDisplay("followUp");
3318
+ const dequeue = this.getAppKeyDisplay("dequeue");
3319
+ let hotkeys = `
3320
+ **Navigation**
3321
+ | Key | Action |
3322
+ |-----|--------|
3323
+ | \`Arrow keys\` | Move cursor / browse history (Up when empty) |
3324
+ | \`${cursorWordLeft}\` / \`${cursorWordRight}\` | Move by word |
3325
+ | \`${cursorLineStart}\` | Start of line |
3326
+ | \`${cursorLineEnd}\` | End of line |
3327
+ | \`${pageUp}\` / \`${pageDown}\` | Scroll by page |
3328
+
3329
+ **Editing**
3330
+ | Key | Action |
3331
+ |-----|--------|
3332
+ | \`${submit}\` | Send message |
3333
+ | \`${newLine}\` | New line${process.platform === "win32" ? " (Ctrl+Enter on Windows Terminal)" : ""} |
3334
+ | \`${deleteWordBackward}\` | Delete word backwards |
3335
+ | \`${deleteWordForward}\` | Delete word forwards |
3336
+ | \`${deleteToLineStart}\` | Delete to start of line |
3337
+ | \`${deleteToLineEnd}\` | Delete to end of line |
3338
+ | \`${yank}\` | Paste the most-recently-deleted text |
3339
+ | \`${yankPop}\` | Cycle through the deleted text after pasting |
3340
+ | \`${undo}\` | Undo |
3341
+
3342
+ **Other**
3343
+ | Key | Action |
3344
+ |-----|--------|
3345
+ | \`${tab}\` | Path completion / accept autocomplete |
3346
+ | \`${interrupt}\` | Cancel autocomplete / abort streaming |
3347
+ | \`${clear}\` | Clear editor (first) / exit (second) |
3348
+ | \`${exit}\` | Exit (when editor is empty) |
3349
+ | \`${suspend}\` | Suspend to background |
3350
+ | \`${cycleThinkingLevel}\` | Cycle thinking level |
3351
+ | \`${cycleModelForward}\` | Cycle models |
3352
+ | \`${selectModel}\` | Open model selector |
3353
+ | \`${expandTools}\` | Toggle tool output expansion |
3354
+ | \`${toggleThinking}\` | Toggle thinking block visibility |
3355
+ | \`${externalEditor}\` | Edit message in external editor |
3356
+ | \`${followUp}\` | Queue follow-up message |
3357
+ | \`${dequeue}\` | Restore queued messages |
3358
+ | \`Ctrl+V\` | Paste image from clipboard |
3359
+ | \`/\` | Slash commands |
3360
+ | \`!\` | Run bash command |
3361
+ | \`!!\` | Run bash command (excluded from context) |
3362
+ `;
3363
+ // Add extension-registered shortcuts
3364
+ const extensionRunner = this.session.extensionRunner;
3365
+ if (extensionRunner) {
3366
+ const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
3367
+ if (shortcuts.size > 0) {
3368
+ hotkeys += `
3369
+ **Extensions**
3370
+ | Key | Action |
3371
+ |-----|--------|
3372
+ `;
3373
+ for (const [key, shortcut] of shortcuts) {
3374
+ const description = shortcut.description ?? shortcut.extensionPath;
3375
+ hotkeys += `| \`${key}\` | ${description} |\n`;
3376
+ }
3377
+ }
3378
+ }
3379
+ this.chatContainer.addChild(new Spacer(1));
3380
+ this.chatContainer.addChild(new DynamicBorder());
3381
+ this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "Keyboard Shortcuts")), 1, 0));
3382
+ this.chatContainer.addChild(new Spacer(1));
3383
+ this.chatContainer.addChild(new Markdown(hotkeys.trim(), 1, 1, this.getMarkdownThemeWithSettings()));
3384
+ this.chatContainer.addChild(new DynamicBorder());
3385
+ this.ui.requestRender();
3386
+ }
3387
+ async handleClearCommand() {
3388
+ // Stop loading animation
3389
+ if (this.loadingAnimation) {
3390
+ this.loadingAnimation.stop();
3391
+ this.loadingAnimation = undefined;
3392
+ }
3393
+ this.statusContainer.clear();
3394
+ // New session via session (emits extension session events)
3395
+ await this.session.newSession();
3396
+ // Clear UI state
3397
+ this.chatContainer.clear();
3398
+ this.pendingMessagesContainer.clear();
3399
+ this.compactionQueuedMessages = [];
3400
+ this.streamingComponent = undefined;
3401
+ this.streamingMessage = undefined;
3402
+ this.pendingTools.clear();
3403
+ this.chatContainer.addChild(new Spacer(1));
3404
+ this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ New session started")}`, 1, 1));
3405
+ this.ui.requestRender();
3406
+ }
3407
+ handleDebugCommand() {
3408
+ const width = this.ui.terminal.columns;
3409
+ const height = this.ui.terminal.rows;
3410
+ const allLines = this.ui.render(width);
3411
+ const debugLogPath = getDebugLogPath();
3412
+ const debugData = [
3413
+ `Debug output at ${new Date().toISOString()}`,
3414
+ `Terminal: ${width}x${height}`,
3415
+ `Total lines: ${allLines.length}`,
3416
+ "",
3417
+ "=== All rendered lines with visible widths ===",
3418
+ ...allLines.map((line, idx) => {
3419
+ const vw = visibleWidth(line);
3420
+ const escaped = JSON.stringify(line);
3421
+ return `[${idx}] (w=${vw}) ${escaped}`;
3422
+ }),
3423
+ "",
3424
+ "=== Agent messages (JSONL) ===",
3425
+ ...this.session.messages.map((msg) => JSON.stringify(msg)),
3426
+ "",
3427
+ ].join("\n");
3428
+ fs.mkdirSync(path.dirname(debugLogPath), { recursive: true });
3429
+ fs.writeFileSync(debugLogPath, debugData);
3430
+ this.chatContainer.addChild(new Spacer(1));
3431
+ this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ Debug log written")}\n${theme.fg("muted", debugLogPath)}`, 1, 1));
3432
+ this.ui.requestRender();
3433
+ }
3434
+ handleArminSaysHi() {
3435
+ this.chatContainer.addChild(new Spacer(1));
3436
+ this.chatContainer.addChild(new ArminComponent(this.ui));
3437
+ this.ui.requestRender();
3438
+ }
3439
+ async handleBashCommand(command, excludeFromContext = false) {
3440
+ const extensionRunner = this.session.extensionRunner;
3441
+ // Emit user_bash event to let extensions intercept
3442
+ const eventResult = extensionRunner
3443
+ ? await extensionRunner.emitUserBash({
3444
+ type: "user_bash",
3445
+ command,
3446
+ excludeFromContext,
3447
+ cwd: process.cwd(),
3448
+ })
3449
+ : undefined;
3450
+ // If extension returned a full result, use it directly
3451
+ if (eventResult?.result) {
3452
+ const result = eventResult.result;
3453
+ // Create UI component for display
3454
+ this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);
3455
+ if (this.session.isStreaming) {
3456
+ this.pendingMessagesContainer.addChild(this.bashComponent);
3457
+ this.pendingBashComponents.push(this.bashComponent);
3458
+ }
3459
+ else {
3460
+ this.chatContainer.addChild(this.bashComponent);
3461
+ }
3462
+ // Show output and complete
3463
+ if (result.output) {
3464
+ this.bashComponent.appendOutput(result.output);
3465
+ }
3466
+ this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated ? { truncated: true, content: result.output } : undefined, result.fullOutputPath);
3467
+ // Record the result in session
3468
+ this.session.recordBashResult(command, result, { excludeFromContext });
3469
+ this.bashComponent = undefined;
3470
+ this.ui.requestRender();
3471
+ return;
3472
+ }
3473
+ // Normal execution path (possibly with custom operations)
3474
+ const isDeferred = this.session.isStreaming;
3475
+ this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);
3476
+ if (isDeferred) {
3477
+ // Show in pending area when agent is streaming
3478
+ this.pendingMessagesContainer.addChild(this.bashComponent);
3479
+ this.pendingBashComponents.push(this.bashComponent);
3480
+ }
3481
+ else {
3482
+ // Show in chat immediately when agent is idle
3483
+ this.chatContainer.addChild(this.bashComponent);
3484
+ }
3485
+ this.ui.requestRender();
3486
+ try {
3487
+ const result = await this.session.executeBash(command, (chunk) => {
3488
+ if (this.bashComponent) {
3489
+ this.bashComponent.appendOutput(chunk);
3490
+ this.ui.requestRender();
3491
+ }
3492
+ }, { excludeFromContext, operations: eventResult?.operations });
3493
+ if (this.bashComponent) {
3494
+ this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated ? { truncated: true, content: result.output } : undefined, result.fullOutputPath);
3495
+ }
3496
+ }
3497
+ catch (error) {
3498
+ if (this.bashComponent) {
3499
+ this.bashComponent.setComplete(undefined, false);
3500
+ }
3501
+ this.showError(`Bash command failed: ${error instanceof Error ? error.message : "Unknown error"}`);
3502
+ }
3503
+ this.bashComponent = undefined;
3504
+ this.ui.requestRender();
3505
+ }
3506
+ async handleCompactCommand(customInstructions) {
3507
+ const entries = this.sessionManager.getEntries();
3508
+ const messageCount = entries.filter((e) => e.type === "message").length;
3509
+ if (messageCount < 2) {
3510
+ this.showWarning("Nothing to compact (no messages yet)");
3511
+ return;
3512
+ }
3513
+ await this.executeCompaction(customInstructions, false);
3514
+ }
3515
+ async executeCompaction(customInstructions, isAuto = false) {
3516
+ // Stop loading animation
3517
+ if (this.loadingAnimation) {
3518
+ this.loadingAnimation.stop();
3519
+ this.loadingAnimation = undefined;
3520
+ }
3521
+ this.statusContainer.clear();
3522
+ // Set up escape handler during compaction
3523
+ const originalOnEscape = this.defaultEditor.onEscape;
3524
+ this.defaultEditor.onEscape = () => {
3525
+ this.session.abortCompaction();
3526
+ };
3527
+ // Show compacting status
3528
+ this.chatContainer.addChild(new Spacer(1));
3529
+ const cancelHint = `(${appKey(this.keybindings, "interrupt")} to cancel)`;
3530
+ const label = isAuto ? `Auto-compacting context... ${cancelHint}` : `Compacting context... ${cancelHint}`;
3531
+ const compactingLoader = new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), label);
3532
+ this.statusContainer.addChild(compactingLoader);
3533
+ this.ui.requestRender();
3534
+ let result;
3535
+ try {
3536
+ result = await this.session.compact(customInstructions);
3537
+ // Rebuild UI
3538
+ this.rebuildChatFromMessages();
3539
+ // Add compaction component at bottom so user sees it without scrolling
3540
+ const msg = createCompactionSummaryMessage(result.summary, result.tokensBefore, new Date().toISOString());
3541
+ this.addMessageToChat(msg);
3542
+ this.footer.invalidate();
3543
+ }
3544
+ catch (error) {
3545
+ const message = error instanceof Error ? error.message : String(error);
3546
+ if (message === "Compaction cancelled" || (error instanceof Error && error.name === "AbortError")) {
3547
+ this.showError("Compaction cancelled");
3548
+ }
3549
+ else {
3550
+ this.showError(`Compaction failed: ${message}`);
3551
+ }
3552
+ }
3553
+ finally {
3554
+ compactingLoader.stop();
3555
+ this.statusContainer.clear();
3556
+ this.defaultEditor.onEscape = originalOnEscape;
3557
+ }
3558
+ void this.flushCompactionQueue({ willRetry: false });
3559
+ return result;
3560
+ }
3561
+ stop() {
3562
+ if (this.loadingAnimation) {
3563
+ this.loadingAnimation.stop();
3564
+ this.loadingAnimation = undefined;
3565
+ }
3566
+ this.footer.dispose();
3567
+ this.footerDataProvider.dispose();
3568
+ if (this.unsubscribe) {
3569
+ this.unsubscribe();
3570
+ }
3571
+ if (this.isInitialized) {
3572
+ this.ui.stop();
3573
+ this.isInitialized = false;
3574
+ }
3575
+ }
3576
+ }