@causyne/agent 1.20.124 → 1.20.128

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 (254) hide show
  1. package/bin/causyne.js +1 -1
  2. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  3. package/package.json +6 -4
  4. package/src/acp/protocol.ts +19 -1
  5. package/src/acp/server.js +282 -8
  6. package/src/acp/server.ts +284 -8
  7. package/src/agent/abortableDelay.js +2 -2
  8. package/src/agent/abortableDelay.ts +2 -2
  9. package/src/agent/errorClassifier.js +9 -1
  10. package/src/agent/errorClassifier.ts +8 -1
  11. package/src/agentLoop.js +142 -53
  12. package/src/agentLoop.ts +151 -50
  13. package/src/approvalPolicy.js +34 -10
  14. package/src/approvalPolicy.ts +42 -11
  15. package/src/browser/causyneBrowser.js +61 -3
  16. package/src/browser/causyneBrowser.ts +65 -3
  17. package/src/browser/urlPolicy.js +14 -1
  18. package/src/browser/urlPolicy.ts +12 -1
  19. package/src/cliMode.js +21 -9
  20. package/src/cliMode.ts +20 -8
  21. package/src/commands.js +365 -45
  22. package/src/commands.ts +403 -45
  23. package/src/config.js +19 -4
  24. package/src/config.ts +18 -4
  25. package/src/core/contextCompactor.js +54 -7
  26. package/src/core/contextCompactor.ts +63 -7
  27. package/src/core/goalLoop.js +257 -0
  28. package/src/core/goalLoop.ts +310 -0
  29. package/src/entrypoint.js +135 -3
  30. package/src/entrypoint.ts +136 -3
  31. package/src/game/causyneCoreBridge.js +686 -0
  32. package/src/game/causyneCoreBridge.ts +702 -0
  33. package/src/game/gameLauncher.js +287 -0
  34. package/src/game/gameLauncher.ts +352 -0
  35. package/src/game/gameProvisioner.js +425 -0
  36. package/src/game/gameProvisioner.ts +488 -0
  37. package/src/headlessCli.js +19 -12
  38. package/src/headlessCli.ts +22 -8
  39. package/src/infra/atomicWriter.js +40 -4
  40. package/src/infra/atomicWriter.ts +36 -4
  41. package/src/launchIntent.js +73 -3
  42. package/src/launchIntent.ts +76 -3
  43. package/src/lsp/lspClient.js +83 -12
  44. package/src/lsp/lspClient.ts +75 -12
  45. package/src/mcp/mcpRegistry.js +75 -8
  46. package/src/mcp/mcpRegistry.ts +70 -7
  47. package/src/memory/contextBudget.js +2 -0
  48. package/src/memory/contextBudget.ts +1 -0
  49. package/src/memory/episodicStore.js +40 -0
  50. package/src/memory/episodicStore.ts +46 -0
  51. package/src/memory.js +67 -0
  52. package/src/memory.ts +65 -0
  53. package/src/modelVariants.js +45 -0
  54. package/src/modelVariants.ts +54 -0
  55. package/src/outputRecovery.js +3 -2
  56. package/src/outputRecovery.ts +4 -2
  57. package/src/permissionPresets.js +327 -0
  58. package/src/permissionPresets.ts +361 -0
  59. package/src/personalization.js +365 -0
  60. package/src/personalization.ts +471 -0
  61. package/src/projectInstructions.js +30 -10
  62. package/src/projectInstructions.ts +31 -12
  63. package/src/providers/acp.js +3 -2
  64. package/src/providers/acp.ts +3 -2
  65. package/src/providers/antigravity.js +64 -9
  66. package/src/providers/antigravity.ts +75 -9
  67. package/src/providers/byokHttp.js +7 -1
  68. package/src/providers/byokHttp.ts +6 -1
  69. package/src/providers/byokStream.js +21 -8
  70. package/src/providers/byokStream.ts +17 -7
  71. package/src/providers/dashscope-byok.js +21 -5
  72. package/src/providers/dashscope-byok.ts +29 -11
  73. package/src/providers/moonshot.js +26 -7
  74. package/src/providers/moonshot.ts +34 -13
  75. package/src/providers/muse.js +6 -0
  76. package/src/providers/muse.ts +8 -0
  77. package/src/providers/ollama.js +39 -7
  78. package/src/providers/ollama.ts +36 -7
  79. package/src/providers/openai-compatible.js +16 -3
  80. package/src/providers/openai-compatible.ts +13 -3
  81. package/src/providers/openai.js +62 -4
  82. package/src/providers/openai.ts +50 -4
  83. package/src/providers/openrouter.js +19 -4
  84. package/src/providers/openrouter.ts +21 -4
  85. package/src/providers/qwen-byok.js +21 -5
  86. package/src/providers/qwen-byok.ts +29 -11
  87. package/src/providers/xai.js +26 -10
  88. package/src/providers/xai.ts +34 -16
  89. package/src/reporting.js +4 -2
  90. package/src/reporting.ts +4 -2
  91. package/src/sandbox.js +34 -0
  92. package/src/sandbox.ts +43 -0
  93. package/src/scheduler/scheduler.js +372 -0
  94. package/src/scheduler/scheduler.ts +433 -0
  95. package/src/sessionSearchIndex.js +267 -0
  96. package/src/sessionSearchIndex.ts +311 -0
  97. package/src/skillsManager.js +2 -3
  98. package/src/skillsManager.ts +2 -3
  99. package/src/toolPacks.js +6 -0
  100. package/src/toolPacks.ts +6 -0
  101. package/src/tools/applyPatch.js +1 -1
  102. package/src/tools/applyPatch.ts +1 -1
  103. package/src/tools/generateMediaViaApi.js +4 -3
  104. package/src/tools/generateMediaViaApi.ts +4 -3
  105. package/src/tools/memoryWrite.js +15 -1
  106. package/src/tools/memoryWrite.ts +16 -1
  107. package/src/tools/nativeEngine.js +2 -2
  108. package/src/tools/nativeEngine.ts +2 -2
  109. package/src/tools/openSourceToolProvisioner.js +2 -2
  110. package/src/tools/openSourceToolProvisioner.ts +2 -2
  111. package/src/tools/osSandbox.js +1 -1
  112. package/src/tools/osSandbox.ts +1 -1
  113. package/src/tools/payloadSanitizer.js +0 -1
  114. package/src/tools/payloadSanitizer.ts +0 -1
  115. package/src/tools/pdfReader.js +122 -20
  116. package/src/tools/pdfReader.ts +111 -20
  117. package/src/tools/presentDeliverable.js +103 -0
  118. package/src/tools/presentDeliverable.ts +127 -0
  119. package/src/tools/ptcRuntime.js +444 -0
  120. package/src/tools/ptcRuntime.ts +490 -0
  121. package/src/tools/ptyTerminal.js +1108 -0
  122. package/src/tools/ptyTerminal.ts +1245 -0
  123. package/src/tools/registry.js +21 -12
  124. package/src/tools/registry.ts +21 -12
  125. package/src/tools/toolOutputStore.js +26 -4
  126. package/src/tools/toolOutputStore.ts +22 -4
  127. package/src/tools/webFetch.js +158 -11
  128. package/src/tools/webFetch.ts +145 -11
  129. package/src/tools/webSearch.js +123 -36
  130. package/src/tools/webSearch.ts +124 -33
  131. package/src/tui/banner.js +5 -1
  132. package/src/tui/banner.ts +6 -1
  133. package/src/tui/chatRenderer.js +1 -2
  134. package/src/tui/chatRenderer.ts +1 -2
  135. package/src/tui/completion.js +1 -0
  136. package/src/tui/completion.ts +1 -0
  137. package/src/tui/composerControls.js +111 -27
  138. package/src/tui/composerControls.ts +124 -28
  139. package/src/tui/dialogs.js +3 -16
  140. package/src/tui/dialogs.ts +3 -16
  141. package/src/tui/home.js +1 -0
  142. package/src/tui/home.ts +1 -0
  143. package/src/tui/invocation.js +1 -2
  144. package/src/tui/invocation.ts +1 -2
  145. package/src/tui/modelPicker.js +22 -12
  146. package/src/tui/modelPicker.ts +22 -12
  147. package/src/tui/overlay.js +2 -5
  148. package/src/tui/overlay.ts +2 -5
  149. package/src/tui/prompt.js +6 -4
  150. package/src/tui/prompt.ts +6 -4
  151. package/src/tui/selectList.js +4 -12
  152. package/src/tui/selectList.ts +4 -12
  153. package/src/tui/setup.js +22 -9
  154. package/src/tui/setup.ts +26 -9
  155. package/src/tui/statusLine.ts +2 -0
  156. package/src/web/client/browserPanel.js +905 -0
  157. package/src/web/client/browserPanel.ts +872 -0
  158. package/src/web/client/chatStream.js +321 -0
  159. package/src/web/client/chatStream.ts +297 -0
  160. package/src/web/client/cliPanel.js +165 -0
  161. package/src/web/client/cliPanel.ts +171 -0
  162. package/src/web/client/composer.js +204 -0
  163. package/src/web/client/composer.ts +209 -0
  164. package/src/web/client/diffPanel.js +176 -0
  165. package/src/web/client/diffPanel.ts +203 -0
  166. package/src/web/client/dom.js +271 -0
  167. package/src/web/client/dom.ts +272 -0
  168. package/src/web/client/filesAndCanvas.js +233 -0
  169. package/src/web/client/filesAndCanvas.ts +240 -0
  170. package/src/web/client/gameLauncherUi.js +78 -0
  171. package/src/web/client/gameLauncherUi.ts +78 -0
  172. package/src/web/client/main.js +316 -0
  173. package/src/web/client/main.ts +391 -0
  174. package/src/web/client/markdown.js +364 -0
  175. package/src/web/client/markdown.ts +373 -0
  176. package/src/web/client/modelPicker.js +455 -0
  177. package/src/web/client/modelPicker.ts +451 -0
  178. package/src/web/client/permissionPresetsUi.js +307 -0
  179. package/src/web/client/permissionPresetsUi.ts +333 -0
  180. package/src/web/client/sessions.js +353 -0
  181. package/src/web/client/sessions.ts +372 -0
  182. package/src/web/client/settingsModal.js +824 -0
  183. package/src/web/client/settingsModal.ts +959 -0
  184. package/src/web/client/state.js +280 -0
  185. package/src/web/client/state.ts +259 -0
  186. package/src/web/client/streamSmoother.js +127 -0
  187. package/src/web/client/streamSmoother.ts +119 -0
  188. package/src/web/client/studioLayout.js +89 -0
  189. package/src/web/client/studioLayout.ts +103 -0
  190. package/src/web/client/studioShell.js +660 -0
  191. package/src/web/client/studioShell.ts +672 -0
  192. package/src/web/client/studioStart.js +77 -0
  193. package/src/web/client/studioStart.ts +89 -0
  194. package/src/web/client/terminalPanel.js +606 -0
  195. package/src/web/client/terminalPanel.ts +632 -0
  196. package/src/web/client/terminalTheme.js +249 -0
  197. package/src/web/client/terminalTheme.ts +258 -0
  198. package/src/web/client/turnView.js +934 -0
  199. package/src/web/client/turnView.ts +981 -0
  200. package/src/web/client/types.js +1 -0
  201. package/src/web/client/types.ts +322 -0
  202. package/src/web/client/validators.js +147 -0
  203. package/src/web/client/validators.ts +140 -0
  204. package/src/web/server/activeRuns.js +152 -0
  205. package/src/web/server/activeRuns.ts +171 -0
  206. package/src/web/server/routesBrowser.js +409 -0
  207. package/src/web/server/routesBrowser.ts +435 -0
  208. package/src/web/server/routesChat.js +304 -0
  209. package/src/web/server/routesChat.ts +347 -0
  210. package/src/web/server/routesCore.js +472 -0
  211. package/src/web/server/routesCore.ts +522 -0
  212. package/src/web/server/routesSettings.js +344 -0
  213. package/src/web/server/routesSettings.ts +397 -0
  214. package/src/web/server/routesTerminal.js +162 -0
  215. package/src/web/server/routesTerminal.ts +182 -0
  216. package/src/web/server/routesWorkspace.js +510 -0
  217. package/src/web/server/routesWorkspace.ts +546 -0
  218. package/src/web/server/security.js +98 -0
  219. package/src/web/server/security.ts +108 -0
  220. package/src/web/server/sessionTranscript.js +586 -0
  221. package/src/web/server/sessionTranscript.ts +566 -0
  222. package/src/web/server/staticAssets.js +104 -0
  223. package/src/web/server/staticAssets.ts +116 -0
  224. package/src/web/server/types.js +1 -0
  225. package/src/web/server/types.ts +135 -0
  226. package/src/web/server/workspaceFiles.js +368 -0
  227. package/src/web/server/workspaceFiles.ts +363 -0
  228. package/src/web/skybridgeServer.js +78 -2448
  229. package/src/web/skybridgeServer.ts +120 -2600
  230. package/src/web/skybridgeUi.js +20 -450
  231. package/src/web/skybridgeUi.ts +24 -455
  232. package/src/web/styles/agent.css +380 -0
  233. package/src/web/styles/composer.css +193 -0
  234. package/src/web/styles/overlays.css +935 -0
  235. package/src/web/styles/shell.css +387 -0
  236. package/src/web/styles/studio.css +951 -0
  237. package/src/web/styles/thread.css +221 -0
  238. package/src/web/styles/tokens.css +94 -0
  239. package/src/web/ui/brandMark.js +73 -0
  240. package/src/web/ui/brandMark.ts +82 -0
  241. package/src/web/ui/modalsTemplate.js +388 -0
  242. package/src/web/ui/modalsTemplate.ts +388 -0
  243. package/src/web/ui/sidebarTemplate.js +63 -0
  244. package/src/web/ui/sidebarTemplate.ts +64 -0
  245. package/src/web/ui/studioTemplate.js +256 -0
  246. package/src/web/ui/studioTemplate.ts +256 -0
  247. package/src/web/ui/workspaceTemplate.js +72 -0
  248. package/src/web/ui/workspaceTemplate.ts +73 -0
  249. package/src/worktreeManager.js +16 -1
  250. package/src/worktreeManager.ts +22 -1
  251. package/src/web/skybridgeClientScript.js +0 -3951
  252. package/src/web/skybridgeClientScript.ts +0 -3952
  253. package/src/web/skybridgeStyles.js +0 -827
  254. package/src/web/skybridgeStyles.ts +0 -828
@@ -0,0 +1,632 @@
1
+ import type { IDisposable, ITerminalInitOnlyOptions, ITerminalOptions, Terminal } from '@xterm/xterm';
2
+ import type { FitAddon } from '@xterm/addon-fit';
3
+ import { announceAlert, dom } from './dom.js';
4
+ import { apiUrl, authHeaders, state } from './state.js';
5
+ import { hydrateStartShellOptions } from './studioStart.js';
6
+ import { setStudioTabDynamicTitle } from './studioShell.js';
7
+ import { TerminalTheme, observeTerminalCursor } from './terminalTheme.js';
8
+ import type { AvailableShellPayload, TerminalSessionPayload } from './types.js';
9
+
10
+ interface TerminalStreamChunk {
11
+ type?: string;
12
+ sessionId?: string;
13
+ data?: string;
14
+ rawData?: string;
15
+ control?: 'user' | 'agent';
16
+ status?: 'running' | 'exited';
17
+ exitCode?: number | null;
18
+ cols?: number;
19
+ rows?: number;
20
+ }
21
+
22
+ type XtermCtor = new (options?: ITerminalOptions & ITerminalInitOnlyOptions) => Terminal;
23
+ type FitAddonCtor = new () => FitAddon;
24
+
25
+ interface XtermWindowGlobals {
26
+ Terminal?: XtermCtor;
27
+ FitAddon?: { FitAddon?: FitAddonCtor } | FitAddonCtor;
28
+ }
29
+
30
+ interface MountedTerminal {
31
+ sessionId: string;
32
+ hostEl: HTMLDivElement;
33
+ xterm: Terminal;
34
+ fitAddon: FitAddon;
35
+ palette: TerminalTheme;
36
+ cursorSub: IDisposable;
37
+ dataSub: IDisposable;
38
+ cleanupGestures: () => void;
39
+ lastSyncedCols: number;
40
+ lastSyncedRows: number;
41
+ resizeTimer: ReturnType<typeof setTimeout> | null;
42
+ pendingInput: Array<{ data: string; typed: boolean }>;
43
+ flushingInput: boolean;
44
+ }
45
+
46
+ const TYPED_INPUT_WINDOW_MS = 250;
47
+ const INPUT_GESTURES = ['keydown', 'beforeinput', 'paste', 'compositionend', 'drop', 'mousedown', 'touchstart'] as const;
48
+ const FOCUS_REPORTS = new Set(['\x1b[I', '\x1b[O']);
49
+ const TERMINAL_FONT_STACK = 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace';
50
+
51
+ const mountedTerminals = new Map<string, MountedTerminal>();
52
+ let viewportResizeObserver: ResizeObserver | null = null;
53
+ let themeObserver: MutationObserver | null = null;
54
+ let streamAbort: AbortController | null = null;
55
+ let streamedSessionId: string | null = null;
56
+
57
+ function resolveXtermConstructors(): { TerminalCtor: XtermCtor; FitCtor: FitAddonCtor } | null {
58
+ const g = window as unknown as XtermWindowGlobals;
59
+ const TerminalCtor = g.Terminal;
60
+ const FitCtor = typeof g.FitAddon === 'function' ? g.FitAddon : g.FitAddon?.FitAddon;
61
+ if (typeof TerminalCtor !== 'function' || typeof FitCtor !== 'function') return null;
62
+ return { TerminalCtor, FitCtor };
63
+ }
64
+
65
+ function stopTerminalStream(): void {
66
+ if (streamAbort) {
67
+ try { streamAbort.abort(); } catch { /* ignore */ }
68
+ streamAbort = null;
69
+ }
70
+ streamedSessionId = null;
71
+ }
72
+
73
+ function activeSession(): TerminalSessionPayload | null {
74
+ if (!state.activeTerminalId) return null;
75
+ return state.terminalSessions.find((s) => s.id === state.activeTerminalId) ?? null;
76
+ }
77
+
78
+ function readViewportThemeColors(): { background: string; foreground: string; isLight: boolean } {
79
+ const isLight = document.documentElement.getAttribute('data-theme') === 'light';
80
+ const fallbackBg = isLight ? '#f6f8f6' : '#0d100d';
81
+ const fallbackFg = isLight ? '#182018' : '#e6ece4';
82
+ if (!dom.termViewport) return { background: fallbackBg, foreground: fallbackFg, isLight };
83
+ const style = window.getComputedStyle(dom.termViewport);
84
+ return {
85
+ background: style.backgroundColor || fallbackBg,
86
+ foreground: style.color || fallbackFg,
87
+ isLight
88
+ };
89
+ }
90
+
91
+ function applyThemeToAllMounted(): void {
92
+ const { background, foreground, isLight } = readViewportThemeColors();
93
+ for (const inst of mountedTerminals.values()) {
94
+ inst.palette.update(background, foreground, isLight);
95
+ }
96
+ }
97
+
98
+ function estimateInitialDimensions(): { cols: number; rows: number } {
99
+ const curMounted = state.activeTerminalId ? mountedTerminals.get(state.activeTerminalId) : undefined;
100
+ if (curMounted) {
101
+ const proposed = curMounted.fitAddon.proposeDimensions();
102
+ if (proposed && Number.isFinite(proposed.cols) && Number.isFinite(proposed.rows)) {
103
+ return {
104
+ cols: Math.max(20, Math.min(400, proposed.cols)),
105
+ rows: Math.max(6, Math.min(160, proposed.rows))
106
+ };
107
+ }
108
+ }
109
+ const rect = dom.termViewport?.getBoundingClientRect();
110
+ if (rect && rect.width > 120 && rect.height > 80) {
111
+ const cols = Math.max(20, Math.min(400, Math.floor((rect.width - 28) / 7.8)));
112
+ const rows = Math.max(6, Math.min(160, Math.floor((rect.height - 16) / 18)));
113
+ return { cols, rows };
114
+ }
115
+ return { cols: 88, rows: 26 };
116
+ }
117
+
118
+ function syncTerminalChrome(): void {
119
+ const cur = activeSession();
120
+ const hasSession = Boolean(cur);
121
+ if (dom.termEmpty) dom.termEmpty.style.display = hasSession ? 'none' : 'flex';
122
+ if (dom.termViewport) dom.termViewport.style.display = hasSession ? 'flex' : 'none';
123
+ if (dom.termControlBanner) {
124
+ const showAgentBanner = Boolean(cur && cur.status === 'running' && cur.control === 'agent');
125
+ dom.termControlBanner.classList.toggle('visible', showAgentBanner);
126
+ if (dom.termControlText && showAgentBanner) {
127
+ dom.termControlText.textContent = `Causyne is driving ${cur?.name || 'terminal'}`;
128
+ }
129
+ }
130
+ if (dom.termStatus) {
131
+ if (!cur) {
132
+ dom.termStatus.textContent = 'No active terminal';
133
+ } else if (cur.status === 'exited') {
134
+ dom.termStatus.textContent = `${cur.name} · exited (${cur.exitCode ?? 0})`;
135
+ } else {
136
+ dom.termStatus.textContent = `${cur.name} · ${cur.transport.toUpperCase()} · ${cur.control === 'agent' ? 'agent control' : 'interactive'}`;
137
+ }
138
+ }
139
+ if (dom.termMeta) {
140
+ dom.termMeta.textContent = cur ? `${cur.shellLabel} · ${cur.cols}×${cur.rows}` : '';
141
+ }
142
+ setStudioTabDynamicTitle('terminal', cur ? cur.name : null);
143
+ }
144
+
145
+ function syncVisibleTerminalInstance(): void {
146
+ for (const [id, inst] of mountedTerminals) {
147
+ const isActive = id === state.activeTerminalId;
148
+ inst.hostEl.classList.toggle('active', isActive);
149
+ }
150
+ }
151
+
152
+ function scheduleRemoteResize(inst: MountedTerminal, cols: number, rows: number): void {
153
+ if (inst.lastSyncedCols === cols && inst.lastSyncedRows === rows) return;
154
+ const sess = state.terminalSessions.find((s) => s.id === inst.sessionId);
155
+ if (!sess || sess.status !== 'running') return;
156
+ if (inst.resizeTimer) clearTimeout(inst.resizeTimer);
157
+ inst.resizeTimer = setTimeout(() => {
158
+ inst.resizeTimer = null;
159
+ if (inst.lastSyncedCols === cols && inst.lastSyncedRows === rows) return;
160
+ inst.lastSyncedCols = cols;
161
+ inst.lastSyncedRows = rows;
162
+ sess.cols = cols;
163
+ sess.rows = rows;
164
+ if (state.activeTerminalId === inst.sessionId && dom.termMeta) {
165
+ dom.termMeta.textContent = `${sess.shellLabel} · ${cols}×${rows}`;
166
+ }
167
+ void fetch(apiUrl('/api/terminal/input'), {
168
+ method: 'POST',
169
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
170
+ body: JSON.stringify({ id: inst.sessionId, cols, rows })
171
+ }).catch(() => null);
172
+ }, 60);
173
+ }
174
+
175
+ function fitTerminalInstance(inst: MountedTerminal): void {
176
+ if (!dom.termViewport || !inst.hostEl.classList.contains('active')) return;
177
+ if (inst.hostEl.clientWidth < 40 || inst.hostEl.clientHeight < 30) return;
178
+ const dims = inst.fitAddon.proposeDimensions();
179
+ if (!dims || !Number.isFinite(dims.cols) || !Number.isFinite(dims.rows)) return;
180
+ const cols = Math.max(20, Math.min(400, dims.cols));
181
+ const rows = Math.max(6, Math.min(160, dims.rows));
182
+ if (inst.xterm.cols !== cols || inst.xterm.rows !== rows) {
183
+ inst.xterm.resize(cols, rows);
184
+ }
185
+ scheduleRemoteResize(inst, cols, rows);
186
+ }
187
+
188
+ export function fitActiveTerminal(): void {
189
+ if (!state.activeTerminalId) return;
190
+ const inst = mountedTerminals.get(state.activeTerminalId);
191
+ if (!inst) return;
192
+ requestAnimationFrame(() => {
193
+ fitTerminalInstance(inst);
194
+ });
195
+ }
196
+
197
+ export function focusActiveTerminal(): void {
198
+ if (!state.activeTerminalId) return;
199
+ const inst = mountedTerminals.get(state.activeTerminalId);
200
+ if (inst) inst.xterm.focus();
201
+ }
202
+
203
+ function flushInputQueue(inst: MountedTerminal): void {
204
+ if (inst.flushingInput || inst.pendingInput.length === 0) return;
205
+ inst.flushingInput = true;
206
+
207
+ void (async () => {
208
+ try {
209
+ while (inst.pendingInput.length > 0) {
210
+ const first = inst.pendingInput.shift()!;
211
+ let combined = first.data;
212
+ let typed = first.typed;
213
+ while (inst.pendingInput.length > 0 && inst.pendingInput[0]!.typed === typed) {
214
+ combined += inst.pendingInput.shift()!.data;
215
+ }
216
+ const res = await fetch(apiUrl('/api/terminal/input'), {
217
+ method: 'POST',
218
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
219
+ body: JSON.stringify({ id: inst.sessionId, data: combined, typed })
220
+ }).catch(() => null);
221
+ if (res && res.ok) {
222
+ const body = await res.json().catch(() => ({})) as { control?: 'user' | 'agent' };
223
+ const target = state.terminalSessions.find((s) => s.id === inst.sessionId);
224
+ if (target && body.control && target.control !== body.control) {
225
+ target.control = body.control;
226
+ syncTerminalChrome();
227
+ }
228
+ }
229
+ }
230
+ } finally {
231
+ inst.flushingInput = false;
232
+ }
233
+ })();
234
+ }
235
+
236
+ function enqueueTerminalInput(sessionId: string, data: string, typed: boolean): void {
237
+ const inst = mountedTerminals.get(sessionId);
238
+ if (!inst) return;
239
+ inst.pendingInput.push({ data, typed });
240
+ flushInputQueue(inst);
241
+ }
242
+
243
+ function disposeMountedTerminal(sessionId: string): void {
244
+ const inst = mountedTerminals.get(sessionId);
245
+ if (!inst) return;
246
+ if (inst.resizeTimer) clearTimeout(inst.resizeTimer);
247
+ inst.cleanupGestures();
248
+ inst.dataSub.dispose();
249
+ inst.cursorSub.dispose();
250
+ inst.palette.dispose();
251
+ inst.xterm.dispose();
252
+ inst.hostEl.remove();
253
+ mountedTerminals.delete(sessionId);
254
+ }
255
+
256
+ function ensureMountedTerminal(session: TerminalSessionPayload): MountedTerminal | null {
257
+ const existing = mountedTerminals.get(session.id);
258
+ if (existing) return existing;
259
+ if (!dom.termViewport) return null;
260
+ const ctors = resolveXtermConstructors();
261
+ if (!ctors) {
262
+ announceAlert('Terminal emulator assets failed to load.');
263
+ return null;
264
+ }
265
+
266
+ const hostEl = document.createElement('div');
267
+ hostEl.className = 'term-instance';
268
+ hostEl.dataset.sessionId = session.id;
269
+ if (session.id === state.activeTerminalId) hostEl.classList.add('active');
270
+ dom.termViewport.appendChild(hostEl);
271
+
272
+ const xterm = new ctors.TerminalCtor({
273
+ cols: Math.max(20, Math.min(400, session.cols || 88)),
274
+ rows: Math.max(6, Math.min(160, session.rows || 26)),
275
+ cursorBlink: true,
276
+ cursorStyle: 'block',
277
+ fontFamily: TERMINAL_FONT_STACK,
278
+ fontSize: 13,
279
+ lineHeight: 1.25,
280
+ minimumContrastRatio: 4.5,
281
+ scrollback: 5000,
282
+ convertEol: session.transport !== 'pty',
283
+ allowProposedApi: false
284
+ });
285
+ const fitAddon = new ctors.FitCtor();
286
+ xterm.loadAddon(fitAddon);
287
+ xterm.open(hostEl);
288
+ xterm.textarea?.setAttribute('aria-label', `${session.name} interactive terminal`);
289
+
290
+ const palette = new TerminalTheme(xterm);
291
+ const { background, foreground, isLight } = readViewportThemeColors();
292
+ palette.update(background, foreground, isLight);
293
+ const cursorSub = observeTerminalCursor(xterm, hostEl, () => palette.cursor);
294
+
295
+ // Copy on Ctrl+C / Cmd+C when text is selected instead of sending SIGINT; allow paste naturally
296
+ xterm.attachCustomKeyEventHandler((ev: KeyboardEvent) => {
297
+ const key = ev.key.toLowerCase();
298
+ if ((ev.metaKey || ev.ctrlKey) && key === 'c' && xterm.hasSelection()) {
299
+ if (ev.type === 'keydown' && navigator.clipboard?.writeText) {
300
+ void navigator.clipboard.writeText(xterm.getSelection()).catch(() => {});
301
+ }
302
+ return false;
303
+ }
304
+ if ((ev.metaKey || (ev.ctrlKey && ev.shiftKey)) && key === 'v') {
305
+ return false;
306
+ }
307
+ if (ev.ctrlKey && !ev.metaKey && !ev.altKey && ev.key === '`') {
308
+ return false;
309
+ }
310
+ return true;
311
+ });
312
+
313
+ let gestureAt = Number.NEGATIVE_INFINITY;
314
+ const markGesture = (): void => { gestureAt = performance.now(); };
315
+ for (const type of INPUT_GESTURES) {
316
+ hostEl.addEventListener(type, markGesture, { capture: true, passive: true });
317
+ }
318
+ const cleanupGestures = (): void => {
319
+ for (const type of INPUT_GESTURES) {
320
+ hostEl.removeEventListener(type, markGesture, { capture: true });
321
+ }
322
+ };
323
+
324
+ const dataSub = xterm.onData((data) => {
325
+ const isTyped = (performance.now() - gestureAt < TYPED_INPUT_WINDOW_MS) && !FOCUS_REPORTS.has(data);
326
+ enqueueTerminalInput(session.id, data, isTyped);
327
+ });
328
+
329
+ const inst: MountedTerminal = {
330
+ sessionId: session.id,
331
+ hostEl,
332
+ xterm,
333
+ fitAddon,
334
+ palette,
335
+ cursorSub,
336
+ dataSub,
337
+ cleanupGestures,
338
+ lastSyncedCols: session.cols,
339
+ lastSyncedRows: session.rows,
340
+ resizeTimer: null,
341
+ pendingInput: [],
342
+ flushingInput: false
343
+ };
344
+ mountedTerminals.set(session.id, inst);
345
+ return inst;
346
+ }
347
+
348
+ function renderTerminalTabs(): void {
349
+ if (!dom.termTabs || !dom.termNewBtn) return;
350
+ dom.termTabs.textContent = '';
351
+ for (const sess of state.terminalSessions) {
352
+ const pill = document.createElement('div');
353
+ pill.className = `btab${sess.id === state.activeTerminalId ? ' active' : ''}`;
354
+ pill.addEventListener('auxclick', (e) => {
355
+ if (e.button === 1) {
356
+ e.preventDefault();
357
+ void closeTerminalSession(sess.id);
358
+ }
359
+ });
360
+ const lbl = document.createElement('button');
361
+ lbl.type = 'button';
362
+ lbl.className = 'btab-label';
363
+ lbl.textContent = sess.status === 'exited' ? `${sess.name} (exited)` : sess.name;
364
+ lbl.addEventListener('click', () => { selectTerminalSession(sess.id); });
365
+ const cls = document.createElement('button');
366
+ cls.type = 'button';
367
+ cls.className = 'btab-close';
368
+ cls.textContent = '×';
369
+ cls.title = 'Close terminal';
370
+ cls.setAttribute('aria-label', `Close ${sess.name}`);
371
+ cls.addEventListener('click', () => { void closeTerminalSession(sess.id); });
372
+ pill.appendChild(lbl);
373
+ pill.appendChild(cls);
374
+ dom.termTabs.appendChild(pill);
375
+ }
376
+ dom.termTabs.appendChild(dom.termNewBtn);
377
+ syncTerminalChrome();
378
+ syncVisibleTerminalInstance();
379
+ }
380
+
381
+ function startTerminalStream(sessionId: string): void {
382
+ if (streamedSessionId === sessionId && streamAbort) return;
383
+ stopTerminalStream();
384
+ const sess = state.terminalSessions.find((s) => s.id === sessionId);
385
+ if (!sess) return;
386
+ const inst = ensureMountedTerminal(sess);
387
+ syncVisibleTerminalInstance();
388
+ if (inst) {
389
+ requestAnimationFrame(() => fitTerminalInstance(inst));
390
+ }
391
+
392
+ const ctrl = new AbortController();
393
+ streamAbort = ctrl;
394
+ streamedSessionId = sessionId;
395
+
396
+ void (async () => {
397
+ try {
398
+ const res = await fetch(
399
+ apiUrl(`/api/terminal/stream?id=${encodeURIComponent(sessionId)}`),
400
+ { headers: authHeaders(), signal: ctrl.signal }
401
+ );
402
+ if (!res.ok || !res.body) return;
403
+ const reader = res.body.getReader();
404
+ const dec = new TextDecoder();
405
+ let buf = '';
406
+ while (true) {
407
+ const step = await reader.read();
408
+ if (step.done) break;
409
+ buf += dec.decode(step.value, { stream: true });
410
+ let nl = buf.indexOf('\n');
411
+ while (nl !== -1) {
412
+ const line = buf.slice(0, nl).trim();
413
+ buf = buf.slice(nl + 1);
414
+ if (line) {
415
+ try {
416
+ const ev = JSON.parse(line) as TerminalStreamChunk;
417
+ const target = state.terminalSessions.find((s) => s.id === sessionId);
418
+ const mounted = mountedTerminals.get(sessionId);
419
+ if (ev.type === 'snapshot') {
420
+ if (target) {
421
+ if (ev.control) target.control = ev.control;
422
+ if (ev.status) target.status = ev.status;
423
+ if (ev.exitCode !== undefined) target.exitCode = ev.exitCode;
424
+ if (typeof ev.cols === 'number') target.cols = ev.cols;
425
+ if (typeof ev.rows === 'number') target.rows = ev.rows;
426
+ }
427
+ if (mounted) {
428
+ mounted.xterm.reset();
429
+ const payload = typeof ev.rawData === 'string' ? ev.rawData : (ev.data || '');
430
+ if (payload) mounted.xterm.write(payload);
431
+ requestAnimationFrame(() => fitTerminalInstance(mounted));
432
+ }
433
+ syncTerminalChrome();
434
+ } else if (ev.type === 'output') {
435
+ const payload = typeof ev.rawData === 'string' ? ev.rawData : (ev.data || '');
436
+ if (mounted && payload) {
437
+ mounted.xterm.write(payload);
438
+ }
439
+ } else if (ev.type === 'meta') {
440
+ if (target) {
441
+ if (typeof ev.cols === 'number') target.cols = ev.cols;
442
+ if (typeof ev.rows === 'number') target.rows = ev.rows;
443
+ if (ev.control) target.control = ev.control;
444
+ if (ev.status) target.status = ev.status;
445
+ }
446
+ syncTerminalChrome();
447
+ } else if (ev.type === 'control' && ev.control) {
448
+ if (target) target.control = ev.control;
449
+ syncTerminalChrome();
450
+ } else if (ev.type === 'exit') {
451
+ if (target) {
452
+ target.status = 'exited';
453
+ target.exitCode = ev.exitCode ?? 0;
454
+ }
455
+ if (mounted) {
456
+ mounted.xterm.write(`\r\n\x1b[2m[process exited with code ${ev.exitCode ?? 0}]\x1b[0m\r\n`);
457
+ }
458
+ renderTerminalTabs();
459
+ }
460
+ } catch {
461
+ // Ignore malformed stream line
462
+ }
463
+ }
464
+ nl = buf.indexOf('\n');
465
+ }
466
+ }
467
+ } catch {
468
+ // Aborted cleanly
469
+ } finally {
470
+ if (streamAbort === ctrl) {
471
+ streamAbort = null;
472
+ streamedSessionId = null;
473
+ }
474
+ }
475
+ })();
476
+ }
477
+
478
+ export function selectTerminalSession(sessionId: string): void {
479
+ state.activeTerminalId = sessionId;
480
+ const sess = activeSession();
481
+ if (sess) ensureMountedTerminal(sess);
482
+ renderTerminalTabs();
483
+ startTerminalStream(sessionId);
484
+ fitActiveTerminal();
485
+ focusActiveTerminal();
486
+ }
487
+
488
+ export async function loadTerminalSessions(): Promise<void> {
489
+ const res = await fetch(apiUrl('/api/terminal/sessions'), { headers: authHeaders() }).catch(() => null);
490
+ if (!res || !res.ok) return;
491
+ const data = await res.json() as {
492
+ sessions?: TerminalSessionPayload[];
493
+ shells?: AvailableShellPayload[];
494
+ };
495
+ if (Array.isArray(data.shells)) {
496
+ state.availableShells = data.shells;
497
+ hydrateStartShellOptions(data.shells);
498
+ }
499
+ const incoming = Array.isArray(data.sessions) ? data.sessions : [];
500
+ const validIds = new Set(incoming.map((s) => s.id));
501
+ for (const id of [...mountedTerminals.keys()]) {
502
+ if (!validIds.has(id)) disposeMountedTerminal(id);
503
+ }
504
+ state.terminalSessions = incoming;
505
+ if (state.activeTerminalId && !validIds.has(state.activeTerminalId)) {
506
+ state.activeTerminalId = null;
507
+ stopTerminalStream();
508
+ }
509
+ if (!state.activeTerminalId && state.terminalSessions.length > 0) {
510
+ state.activeTerminalId = state.terminalSessions[0]!.id;
511
+ }
512
+ const cur = activeSession();
513
+ if (cur) ensureMountedTerminal(cur);
514
+ renderTerminalTabs();
515
+ if (state.activeTerminalId) {
516
+ startTerminalStream(state.activeTerminalId);
517
+ fitActiveTerminal();
518
+ }
519
+ }
520
+
521
+ export async function openNewTerminalSession(shell?: string): Promise<void> {
522
+ const chosenShell = shell || dom.termShellSelect?.value || dom.startShellSelect?.value || undefined;
523
+ const { cols, rows } = estimateInitialDimensions();
524
+ const res = await fetch(apiUrl('/api/terminal/sessions'), {
525
+ method: 'POST',
526
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
527
+ body: JSON.stringify({ shell: chosenShell, cols, rows })
528
+ }).catch(() => null);
529
+ if (!res) { announceAlert('Failed to open workspace terminal.'); return; }
530
+ const data = await res.json().catch(() => ({ error: `HTTP ${res.status}` })) as {
531
+ ok?: boolean;
532
+ session?: TerminalSessionPayload;
533
+ error?: string;
534
+ };
535
+ if (!res.ok || !data.session) {
536
+ announceAlert(data.error || 'Failed to open workspace terminal.');
537
+ return;
538
+ }
539
+ state.terminalSessions.push(data.session);
540
+ selectTerminalSession(data.session.id);
541
+ }
542
+
543
+ export async function closeTerminalSession(sessionId: string): Promise<void> {
544
+ await fetch(apiUrl(`/api/terminal/sessions/${encodeURIComponent(sessionId)}`), {
545
+ method: 'DELETE',
546
+ headers: authHeaders()
547
+ }).catch(() => null);
548
+ disposeMountedTerminal(sessionId);
549
+ state.terminalSessions = state.terminalSessions.filter((s) => s.id !== sessionId);
550
+ if (state.activeTerminalId === sessionId) {
551
+ stopTerminalStream();
552
+ state.activeTerminalId = state.terminalSessions[0]?.id ?? null;
553
+ }
554
+ renderTerminalTabs();
555
+ if (state.activeTerminalId) {
556
+ startTerminalStream(state.activeTerminalId);
557
+ fitActiveTerminal();
558
+ }
559
+ }
560
+
561
+ export async function closeAllTerminalSessions(): Promise<void> {
562
+ const ids = state.terminalSessions.map((s) => s.id);
563
+ stopTerminalStream();
564
+ for (const id of ids) {
565
+ disposeMountedTerminal(id);
566
+ await fetch(apiUrl(`/api/terminal/sessions/${encodeURIComponent(id)}`), {
567
+ method: 'DELETE',
568
+ headers: authHeaders()
569
+ }).catch(() => null);
570
+ }
571
+ state.terminalSessions = [];
572
+ state.activeTerminalId = null;
573
+ renderTerminalTabs();
574
+ }
575
+
576
+ async function sendTerminalSignal(signal: 'SIGINT' | 'SIGTERM' | 'SIGTSTP'): Promise<void> {
577
+ const id = state.activeTerminalId;
578
+ if (!id) return;
579
+ await fetch(apiUrl('/api/terminal/signal'), {
580
+ method: 'POST',
581
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
582
+ body: JSON.stringify({ id, signal })
583
+ }).catch(() => null);
584
+ }
585
+
586
+ export function deactivateTerminalPanel(): void {
587
+ stopTerminalStream();
588
+ }
589
+
590
+ export function bindTerminalPanelEvents(): void {
591
+ dom.termNewBtn?.addEventListener('click', () => { void openNewTerminalSession(); });
592
+ dom.termEmptyStartBtn?.addEventListener('click', () => { void openNewTerminalSession(); });
593
+ dom.termSigintBtn?.addEventListener('click', () => {
594
+ void sendTerminalSignal('SIGINT');
595
+ focusActiveTerminal();
596
+ });
597
+ dom.termClearBtn?.addEventListener('click', () => {
598
+ if (!state.activeTerminalId) return;
599
+ const inst = mountedTerminals.get(state.activeTerminalId);
600
+ if (inst) {
601
+ inst.xterm.clear();
602
+ inst.xterm.focus();
603
+ }
604
+ });
605
+ dom.termTakeControlBtn?.addEventListener('click', () => {
606
+ if (!state.activeTerminalId) return;
607
+ enqueueTerminalInput(state.activeTerminalId, '', true);
608
+ focusActiveTerminal();
609
+ });
610
+
611
+ if (dom.termViewport && typeof ResizeObserver !== 'undefined') {
612
+ viewportResizeObserver = new ResizeObserver(() => {
613
+ if (!state.activeTerminalId) return;
614
+ const inst = mountedTerminals.get(state.activeTerminalId);
615
+ if (inst) fitTerminalInstance(inst);
616
+ });
617
+ viewportResizeObserver.observe(dom.termViewport);
618
+ }
619
+
620
+ if (typeof MutationObserver !== 'undefined') {
621
+ themeObserver = new MutationObserver(() => {
622
+ applyThemeToAllMounted();
623
+ });
624
+ themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
625
+ }
626
+
627
+ window.addEventListener('beforeunload', () => {
628
+ stopTerminalStream();
629
+ viewportResizeObserver?.disconnect();
630
+ themeObserver?.disconnect();
631
+ });
632
+ }