@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,981 @@
1
+ import { announceAlert, cloneCausyneMark, copyText, dom } from './dom.js';
2
+ import {
3
+ apiUrl,
4
+ authHeaders,
5
+ scrollToBottom,
6
+ setLiveness,
7
+ setStageMode,
8
+ state,
9
+ updateComposerMetrics
10
+ } from './state.js';
11
+ import {
12
+ artifactBadgeFor,
13
+ extractLoopbackUrls,
14
+ isHtmlOrSvgPath
15
+ } from './validators.js';
16
+ import { renderMarkdownInto } from './markdown.js';
17
+ import { createStreamSmoother } from './streamSmoother.js';
18
+ import type {
19
+ AssistantTurnHandle,
20
+ DecisionRequestPayload,
21
+ RestoredBlock,
22
+ StreamEventPayload
23
+ } from './types.js';
24
+
25
+ export interface TurnViewCallbacks {
26
+ openFile(relPath: string): Promise<void>;
27
+ openInCanvas(suggestedPath: string, content: string, preferPreview: boolean): void;
28
+ openBrowserUrl(rawUrl: string): void;
29
+ openBrowserArtifact(title: string, htmlOrSvg: string): void;
30
+ openSettingsForUpgrade(): void;
31
+ submitPrompt(promptText: string, attachList: string[]): Promise<void>;
32
+ }
33
+
34
+ let callbacks: TurnViewCallbacks = {
35
+ openFile: async () => {},
36
+ openInCanvas: () => {},
37
+ openBrowserUrl: () => {},
38
+ openBrowserArtifact: () => {},
39
+ openSettingsForUpgrade: () => {},
40
+ submitPrompt: async () => {}
41
+ };
42
+
43
+ export function configureTurnViewCallbacks(cbs: TurnViewCallbacks): void {
44
+ callbacks = cbs;
45
+ }
46
+
47
+ interface CollapsibleCardHandle {
48
+ root: HTMLDivElement;
49
+ inner: HTMLDivElement;
50
+ labelEl: HTMLSpanElement;
51
+ dot: HTMLSpanElement;
52
+ setOpen(next: boolean, byUser: boolean): void;
53
+ wasUserToggled(): boolean;
54
+ setActive(active: boolean): void;
55
+ }
56
+
57
+ function createBrandAvatar(): HTMLDivElement {
58
+ const wrap = document.createElement('div');
59
+ wrap.className = 'assistant-avatar';
60
+ const mark = cloneCausyneMark('');
61
+ if (mark) wrap.appendChild(mark);
62
+ return wrap;
63
+ }
64
+
65
+ function summarizeToolTarget(args?: Record<string, unknown>): string {
66
+ if (!args || typeof args !== 'object') return '';
67
+ const raw = args.path || args.filePath || args.file || args.command || args.query || args.url || '';
68
+ return typeof raw === 'string' ? raw.slice(0, 90) : '';
69
+ }
70
+
71
+ function formatThoughtDuration(ms: number): string {
72
+ const secs = Math.round(ms / 1000);
73
+ if (secs < 1) return 'Thought briefly';
74
+ if (secs < 60) return `Thought for ${secs}s`;
75
+ const mins = Math.floor(secs / 60);
76
+ const rem = secs % 60;
77
+ return rem > 0 ? `Thought for ${mins}m ${rem}s` : `Thought for ${mins}m`;
78
+ }
79
+
80
+ function classifyStepKind(toolName?: string): string {
81
+ const t = String(toolName || '').toLowerCase();
82
+ if (t === 'fs_read' || t === 'read_file' || t === 'view_file' || t === 'view_image') return 'read';
83
+ if (t === 'fs_write' || t === 'write_file' || t === 'create_file' || t === 'write_to_file') return 'write';
84
+ if (t === 'fs_edit' || t === 'edit_file' || t === 'multi_edit' || t === 'apply_patch') return 'edit';
85
+ if (t === 'fs_list' || t === 'fs_search' || t === 'grep' || t === 'glob') return 'search';
86
+ if (t === 'sysrun' || t === 'bash' || t === 'shell' || t === 'run_command') return 'cmd';
87
+ if (t.includes('browser') || t === 'screenshot') return 'browser';
88
+ if (t.includes('web_search') || t.includes('web_fetch')) return 'web';
89
+ if (t === 'tool_search') return 'discover';
90
+ if (t === 'update_plan') return 'plan';
91
+ return 'other';
92
+ }
93
+
94
+ export function summarizeTimelineSteps(
95
+ stepKinds: string[],
96
+ totalCount: number,
97
+ isRunning: boolean,
98
+ elapsedMs: number,
99
+ restored: boolean
100
+ ): string {
101
+ if (totalCount === 0) return isRunning ? 'Working...' : 'Completed';
102
+ const counts = new Map<string, number>();
103
+ for (const k of stepKinds) counts.set(k, (counts.get(k) || 0) + 1);
104
+ const parts: string[] = [];
105
+ const add = (key: string, sg: string, pl: string): void => {
106
+ const n = counts.get(key) || 0;
107
+ if (n > 0) parts.push(n === 1 ? sg : pl.replace('{n}', String(n)));
108
+ };
109
+ add('read', 'Read a file', 'Read {n} files');
110
+ add('write', 'Created a file', 'Created {n} files');
111
+ add('edit', 'Edited a file', 'Edited {n} files');
112
+ add('search', 'Searched files', 'Searched files');
113
+ add('cmd', 'Ran a command', 'Ran {n} commands');
114
+ add('browser', 'Used browser', 'Used browser ({n})');
115
+ add('web', 'Searched the web', 'Searched the web');
116
+ const prefix = parts.length > 0
117
+ ? parts.slice(0, 3).join(', ')
118
+ : (isRunning
119
+ ? `Working · ${totalCount}${totalCount === 1 ? ' step' : ' steps'}`
120
+ : `${totalCount}${totalCount === 1 ? ' step' : ' steps'}`);
121
+ if (isRunning) return `${prefix}...`;
122
+ if (!restored && typeof elapsedMs === 'number' && elapsedMs >= 1000) {
123
+ return `${prefix} · ${Math.round(elapsedMs / 1000)}s`;
124
+ }
125
+ return prefix;
126
+ }
127
+
128
+ export function createCollapsibleCard(
129
+ initialLabel: string,
130
+ openByDefault: boolean,
131
+ dotKind: string
132
+ ): CollapsibleCardHandle {
133
+ const root = document.createElement('div');
134
+ root.className = `collapsible-card${openByDefault ? ' is-open' : ''}`;
135
+ const trigger = document.createElement('button');
136
+ trigger.type = 'button';
137
+ trigger.className = 'collapsible-trigger';
138
+ trigger.setAttribute('aria-expanded', openByDefault ? 'true' : 'false');
139
+ const left = document.createElement('span');
140
+ left.className = 'collapsible-trigger-left';
141
+ const dot = document.createElement('span');
142
+ dot.className = `status-dot${dotKind ? ` ${dotKind}` : ''}`;
143
+ const labelEl = document.createElement('span');
144
+ labelEl.className = 'collapsible-label';
145
+ labelEl.textContent = initialLabel;
146
+ left.appendChild(dot);
147
+ left.appendChild(labelEl);
148
+
149
+ const chev = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
150
+ chev.setAttribute('viewBox', '0 0 24 24');
151
+ chev.setAttribute('class', 'collapsible-chevron');
152
+ const pl = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
153
+ pl.setAttribute('points', '9 6 15 12 9 18');
154
+ chev.appendChild(pl);
155
+ trigger.appendChild(left);
156
+ trigger.appendChild(chev);
157
+
158
+ const body = document.createElement('div');
159
+ body.className = 'collapsible-body';
160
+ const inner = document.createElement('div');
161
+ inner.className = 'collapsible-inner';
162
+ body.appendChild(inner);
163
+ root.appendChild(trigger);
164
+ root.appendChild(body);
165
+
166
+ let userToggled = false;
167
+ const setOpen = (next: boolean, byUser: boolean): void => {
168
+ if (byUser) userToggled = true;
169
+ root.classList.toggle('is-open', Boolean(next));
170
+ trigger.setAttribute('aria-expanded', next ? 'true' : 'false');
171
+ };
172
+ trigger.addEventListener('click', () => setOpen(!root.classList.contains('is-open'), true));
173
+
174
+ return {
175
+ root,
176
+ inner,
177
+ labelEl,
178
+ dot,
179
+ setOpen,
180
+ wasUserToggled: () => userToggled,
181
+ setActive(active: boolean) { root.classList.toggle('is-active', Boolean(active)); }
182
+ };
183
+ }
184
+
185
+ let threadSpacerEl: HTMLDivElement | null = null;
186
+ let lastLiveUserTurnEl: HTMLDivElement | null = null;
187
+
188
+ function ensureThreadSpacer(): HTMLDivElement {
189
+ if (!threadSpacerEl || !threadSpacerEl.isConnected) {
190
+ threadSpacerEl = document.createElement('div');
191
+ threadSpacerEl.id = 'thread-spacer';
192
+ threadSpacerEl.className = 'thread-spacer';
193
+ threadSpacerEl.setAttribute('aria-hidden', 'true');
194
+ threadSpacerEl.style.height = '0px';
195
+ dom.threadEl.appendChild(threadSpacerEl);
196
+ } else if (dom.threadEl.lastElementChild !== threadSpacerEl) {
197
+ dom.threadEl.appendChild(threadSpacerEl);
198
+ }
199
+ return threadSpacerEl;
200
+ }
201
+
202
+ export function resetThreadSpacer(): void {
203
+ lastLiveUserTurnEl = null;
204
+ if (threadSpacerEl) threadSpacerEl.style.height = '0px';
205
+ }
206
+
207
+ function updateThreadSpacer(): void {
208
+ if (!threadSpacerEl || !lastLiveUserTurnEl || !lastLiveUserTurnEl.isConnected || !dom.threadWrapEl) return;
209
+ const userRect = lastLiveUserTurnEl.getBoundingClientRect();
210
+ const spacerRect = threadSpacerEl.getBoundingClientRect();
211
+ const contentBelowUser = Math.max(0, spacerRect.top - userRect.top);
212
+ const targetExtra = Math.max(0, dom.threadWrapEl.clientHeight - contentBelowUser - 36);
213
+ threadSpacerEl.style.height = `${Math.round(targetExtra)}px`;
214
+ }
215
+
216
+ export function appendUserTurn(prompt: string, attachments: string[], animate = false): void {
217
+ setStageMode(true);
218
+ const turn = document.createElement('div');
219
+ turn.className = `turn user${animate ? ' turn-enter' : ''}`;
220
+ if (attachments && attachments.length > 0) {
221
+ const line = document.createElement('div');
222
+ line.className = 'attach-line';
223
+ for (const p of attachments) {
224
+ const tag = document.createElement('span');
225
+ tag.className = 'attach-tag';
226
+ tag.textContent = `@${p}`;
227
+ line.appendChild(tag);
228
+ }
229
+ turn.appendChild(line);
230
+ }
231
+ const bubble = document.createElement('div');
232
+ bubble.className = 'user-bubble';
233
+ bubble.textContent = prompt;
234
+ turn.appendChild(bubble);
235
+
236
+ const uActs = document.createElement('div');
237
+ uActs.className = 'user-actions';
238
+ const cp = document.createElement('button');
239
+ cp.type = 'button';
240
+ cp.className = 'msg-action-btn';
241
+ cp.textContent = 'Copy';
242
+ cp.addEventListener('click', () => copyText(prompt, cp));
243
+ const ed = document.createElement('button');
244
+ ed.type = 'button';
245
+ ed.className = 'msg-action-btn';
246
+ ed.textContent = 'Edit';
247
+ ed.addEventListener('click', () => {
248
+ dom.promptInput.value = prompt;
249
+ updateComposerMetrics();
250
+ dom.promptInput.focus();
251
+ });
252
+ uActs.appendChild(cp);
253
+ uActs.appendChild(ed);
254
+ turn.appendChild(uActs);
255
+
256
+ if (threadSpacerEl && threadSpacerEl.parentElement === dom.threadEl) {
257
+ dom.threadEl.insertBefore(turn, threadSpacerEl);
258
+ } else {
259
+ dom.threadEl.appendChild(turn);
260
+ }
261
+ if (animate) {
262
+ lastLiveUserTurnEl = turn;
263
+ ensureThreadSpacer();
264
+ updateThreadSpacer();
265
+ window.requestAnimationFrame(() => {
266
+ updateThreadSpacer();
267
+ scrollToBottom(true, true);
268
+ });
269
+ } else {
270
+ scrollToBottom(true);
271
+ }
272
+ }
273
+
274
+ export function createAssistantTurn(
275
+ promptForRetry: string,
276
+ opts?: { restored?: boolean }
277
+ ): AssistantTurnHandle {
278
+ const isRestored = Boolean(opts?.restored);
279
+ setStageMode(true);
280
+ const turn = document.createElement('div');
281
+ turn.className = `turn assistant${isRestored ? '' : ' turn-enter'}`;
282
+ const row = document.createElement('div');
283
+ row.className = `assistant-row${isRestored ? '' : ' is-streaming'}`;
284
+ row.appendChild(createBrandAvatar());
285
+
286
+ const col = document.createElement('div');
287
+ col.className = 'assistant-col';
288
+ const eventsSlot = document.createElement('div');
289
+ eventsSlot.style.display = 'flex';
290
+ eventsSlot.style.flexDirection = 'column';
291
+ eventsSlot.style.gap = '8px';
292
+ const artifactsSlot = document.createElement('div');
293
+ artifactsSlot.style.display = 'flex';
294
+ artifactsSlot.style.flexDirection = 'column';
295
+ artifactsSlot.style.gap = '8px';
296
+ const prose = document.createElement('div');
297
+ prose.className = 'assistant-prose';
298
+ const urlPreviewSlot = document.createElement('div');
299
+ urlPreviewSlot.className = 'preview-url-bar';
300
+ const errorSlot = document.createElement('div');
301
+ errorSlot.style.display = 'flex';
302
+ errorSlot.style.flexDirection = 'column';
303
+ errorSlot.style.gap = '8px';
304
+ const liveRow = document.createElement('div');
305
+ liveRow.className = `turn-live-row${isRestored ? '' : ' is-active'}`;
306
+ const liveMark = document.createElement('span');
307
+ liveMark.className = 'turn-live-mark';
308
+ const liveSvg = cloneCausyneMark('');
309
+ if (liveSvg) liveMark.appendChild(liveSvg);
310
+ const liveLabel = document.createElement('span');
311
+ liveLabel.className = 'turn-live-label';
312
+ liveLabel.textContent = 'Thinking...';
313
+ liveRow.appendChild(liveMark);
314
+ liveRow.appendChild(liveLabel);
315
+
316
+ const actionsRow = document.createElement('div');
317
+ actionsRow.className = 'msg-actions';
318
+ actionsRow.style.display = 'none';
319
+
320
+ col.appendChild(eventsSlot);
321
+ col.appendChild(artifactsSlot);
322
+ col.appendChild(prose);
323
+ col.appendChild(urlPreviewSlot);
324
+ col.appendChild(errorSlot);
325
+ col.appendChild(liveRow);
326
+ col.appendChild(actionsRow);
327
+ row.appendChild(col);
328
+ turn.appendChild(row);
329
+
330
+ if (threadSpacerEl && threadSpacerEl.parentElement === dom.threadEl) {
331
+ dom.threadEl.insertBefore(turn, threadSpacerEl);
332
+ } else {
333
+ dom.threadEl.appendChild(turn);
334
+ }
335
+
336
+ let rawText = '';
337
+ let reasoningText = '';
338
+ let interruptedShown = false;
339
+ let reasonCard: CollapsibleCardHandle | null = null;
340
+ let reasonBody: HTMLDivElement | null = null;
341
+ let reasonStartedAt = 0;
342
+ let reasonCollapsedOnProse = false;
343
+ let planCard: HTMLDivElement | null = null;
344
+ let timelineCard: CollapsibleCardHandle | null = null;
345
+ let timelineStepsEl: HTMLDivElement | null = null;
346
+ let timelineStartedAt = 0;
347
+ let stepCount = 0;
348
+ let runningSteps = 0;
349
+ const stepKinds: string[] = [];
350
+ const toolCards = new Map<string, { card: HTMLDivElement; status: HTMLSpanElement; dot: HTMLSpanElement; startedAt: number }>();
351
+ const codeCards = new Map<string, {
352
+ card: HTMLDivElement;
353
+ ic: HTMLDivElement;
354
+ title: HTMLDivElement;
355
+ sub: HTMLDivElement;
356
+ btns: HTMLDivElement;
357
+ pre: HTMLPreElement;
358
+ code: string;
359
+ path: string;
360
+ }>();
361
+
362
+ function renderText(textToRender: string, isStreaming: boolean): void {
363
+ renderMarkdownInto(prose, textToRender, isStreaming);
364
+ if (isStreaming && prose.lastElementChild) {
365
+ prose.lastElementChild.classList.add('stream-fade');
366
+ }
367
+ updateThreadSpacer();
368
+ scrollToBottom(false);
369
+ }
370
+
371
+ const proseSmoother = createStreamSmoother((visibleText, isStreaming) => {
372
+ renderText(visibleText, isStreaming);
373
+ });
374
+
375
+ const reasonSmoother = createStreamSmoother((visibleReasoning, isStreaming) => {
376
+ if (!reasonBody) return;
377
+ reasonBody.textContent = visibleReasoning;
378
+ reasonBody.scrollTop = reasonBody.scrollHeight;
379
+ if (reasonCard && isStreaming) {
380
+ const sec = Math.max(1, Math.round((Date.now() - reasonStartedAt) / 1000));
381
+ reasonCard.labelEl.textContent = `Thinking · ${sec}s`;
382
+ }
383
+ scrollToBottom(false);
384
+ });
385
+
386
+ function ensureTimeline(): void {
387
+ if (timelineCard) return;
388
+ timelineStartedAt = Date.now();
389
+ const card = createCollapsibleCard('Working...', !isRestored, isRestored ? 'done' : 'running');
390
+ if (!isRestored) card.setActive(true);
391
+ const stepsWrap = document.createElement('div');
392
+ stepsWrap.className = 'timeline-steps';
393
+ card.inner.appendChild(stepsWrap);
394
+ eventsSlot.appendChild(card.root);
395
+ timelineCard = card;
396
+ timelineStepsEl = stepsWrap;
397
+ }
398
+
399
+ function refreshTimelineHeader(done: boolean): void {
400
+ if (!timelineCard) return;
401
+ const running = !done && runningSteps > 0;
402
+ const elapsed = Date.now() - timelineStartedAt;
403
+ timelineCard.labelEl.textContent = summarizeTimelineSteps(stepKinds, stepCount, running, elapsed, isRestored);
404
+ timelineCard.setActive(running);
405
+ timelineCard.dot.className = `status-dot ${running ? 'running' : 'done'}`;
406
+ }
407
+
408
+ function collapseThinkingOnProse(): void {
409
+ if (!reasonCard || reasonCollapsedOnProse || isRestored) return;
410
+ reasonCollapsedOnProse = true;
411
+ reasonSmoother.flush();
412
+ reasonCard.setActive(false);
413
+ reasonCard.dot.className = 'status-dot done';
414
+ reasonCard.labelEl.textContent = formatThoughtDuration(Date.now() - reasonStartedAt);
415
+ if (!reasonCard.wasUserToggled()) reasonCard.setOpen(false, false);
416
+ }
417
+
418
+ function syncLoopbackButtons(): void {
419
+ urlPreviewSlot.textContent = '';
420
+ for (const u of extractLoopbackUrls(rawText)) {
421
+ const btn = document.createElement('button');
422
+ btn.type = 'button';
423
+ btn.className = 'preview-url-btn';
424
+ btn.textContent = `Open ${u} in Live Browser`;
425
+ btn.addEventListener('click', () => callbacks.openBrowserUrl(u));
426
+ urlPreviewSlot.appendChild(btn);
427
+ }
428
+ }
429
+
430
+ function buildStepRow(
431
+ toolName: string,
432
+ targetText: string,
433
+ statusText: string,
434
+ failed: boolean,
435
+ outputText: string
436
+ ): { card: HTMLDivElement; statusEl: HTMLSpanElement; dotEl: HTMLSpanElement } {
437
+ const card = document.createElement('div');
438
+ card.className = 'tool-card';
439
+ const head = document.createElement('div');
440
+ head.className = 'tool-card-head';
441
+ const hLeft = document.createElement('span');
442
+ hLeft.className = 'tool-head-left';
443
+ const sDot = document.createElement('span');
444
+ sDot.className = `status-dot ${statusText === 'running...' ? 'running' : failed ? 'failed' : 'done'}`;
445
+ const name = document.createElement('span');
446
+ name.className = 'tool-badge';
447
+ name.textContent = toolName;
448
+ const target = document.createElement('span');
449
+ target.className = 'tool-target';
450
+ target.textContent = targetText;
451
+ hLeft.appendChild(sDot);
452
+ hLeft.appendChild(name);
453
+ hLeft.appendChild(target);
454
+ const st = document.createElement('span');
455
+ st.className = 'tool-state';
456
+ st.textContent = statusText;
457
+ if (failed) st.style.color = 'var(--err)';
458
+ head.appendChild(hLeft);
459
+ head.appendChild(st);
460
+ card.appendChild(head);
461
+ if (outputText) {
462
+ const out = document.createElement('div');
463
+ out.className = 'tool-out';
464
+ out.textContent = String(outputText).slice(0, 480);
465
+ card.appendChild(out);
466
+ }
467
+ return { card, statusEl: st, dotEl: sDot };
468
+ }
469
+
470
+ return {
471
+ setActivity(active: boolean, label: string): void {
472
+ if (isRestored) return;
473
+ liveRow.classList.toggle('is-active', Boolean(active));
474
+ if (label) liveLabel.textContent = label;
475
+ },
476
+ appendText(delta: string): void {
477
+ collapseThinkingOnProse();
478
+ rawText += delta;
479
+ proseSmoother.push(delta);
480
+ },
481
+ setText(full: string, streaming: boolean): void {
482
+ if (full) collapseThinkingOnProse();
483
+ rawText = full;
484
+ proseSmoother.setFull(full, Boolean(streaming));
485
+ },
486
+ updateReasoning(ev: StreamEventPayload): void {
487
+ if (!reasonCard) {
488
+ reasonStartedAt = Date.now();
489
+ const openInit = Boolean(ev.streaming && !isRestored);
490
+ reasonCard = createCollapsibleCard(
491
+ isRestored ? 'Thought process' : 'Thinking...',
492
+ openInit,
493
+ ev.streaming ? 'thinking' : 'done'
494
+ );
495
+ reasonCard.setActive(Boolean(ev.streaming && !isRestored));
496
+ reasonBody = document.createElement('div');
497
+ reasonBody.className = 'reason-body';
498
+ reasonCard.inner.appendChild(reasonBody);
499
+ eventsSlot.prepend(reasonCard.root);
500
+ }
501
+ if (typeof ev.content === 'string' && ev.content.length >= reasoningText.length) {
502
+ reasoningText = ev.content;
503
+ reasonSmoother.setFull(reasoningText, Boolean(ev.streaming && !isRestored));
504
+ } else if (typeof ev.delta === 'string') {
505
+ reasoningText += ev.delta;
506
+ reasonSmoother.push(ev.delta);
507
+ }
508
+ if (isRestored) {
509
+ reasonCard.labelEl.textContent = 'Thought process';
510
+ reasonCard.setActive(false);
511
+ reasonCard.dot.className = 'status-dot done';
512
+ } else if (!ev.streaming) {
513
+ const ms = typeof ev.elapsedMs === 'number' ? ev.elapsedMs : (Date.now() - reasonStartedAt);
514
+ reasonCard.labelEl.textContent = formatThoughtDuration(ms);
515
+ reasonCard.setActive(false);
516
+ reasonCard.dot.className = 'status-dot done';
517
+ }
518
+ scrollToBottom(false);
519
+ },
520
+ renderRestoredBlocks(blocks: RestoredBlock[]): void {
521
+ const allTextParts: string[] = [];
522
+ prose.style.display = 'none';
523
+ for (const blk of blocks) {
524
+ if (blk.kind === 'reasoning' && blk.content) {
525
+ const rc = createCollapsibleCard('Thought process', false, 'done');
526
+ const rb = document.createElement('div');
527
+ rb.className = 'reason-body';
528
+ rb.textContent = blk.content;
529
+ rc.inner.appendChild(rb);
530
+ eventsSlot.appendChild(rc.root);
531
+ } else if (blk.kind === 'steps' && Array.isArray(blk.steps) && blk.steps.length > 0) {
532
+ const kinds = blk.steps.map((s) => classifyStepKind(s.tool));
533
+ const label = summarizeTimelineSteps(kinds, blk.steps.length, false, 0, true);
534
+ const tc = createCollapsibleCard(
535
+ label,
536
+ false,
537
+ blk.steps.some((s) => s.status === 'failed') ? 'failed' : 'done'
538
+ );
539
+ const sw = document.createElement('div');
540
+ sw.className = 'timeline-steps';
541
+ for (const st of blk.steps) {
542
+ const rowObj = buildStepRow(
543
+ st.tool || 'step',
544
+ st.target || '',
545
+ st.status === 'failed' ? 'failed' : 'done',
546
+ st.status === 'failed',
547
+ st.output || ''
548
+ );
549
+ sw.appendChild(rowObj.card);
550
+ }
551
+ tc.inner.appendChild(sw);
552
+ eventsSlot.appendChild(tc.root);
553
+ } else if (blk.kind === 'text' && blk.content) {
554
+ allTextParts.push(blk.content);
555
+ const seg = document.createElement('div');
556
+ seg.className = 'assistant-prose';
557
+ renderMarkdownInto(seg, blk.content, false);
558
+ eventsSlot.appendChild(seg);
559
+ }
560
+ }
561
+ rawText = allTextParts.join('\n\n');
562
+ },
563
+ updatePlan(ev: StreamEventPayload): void {
564
+ const items = Array.isArray(ev.plan) ? ev.plan : [];
565
+ if (items.length === 0) return;
566
+ if (!planCard) {
567
+ planCard = document.createElement('div');
568
+ planCard.className = 'plan-card';
569
+ eventsSlot.appendChild(planCard);
570
+ }
571
+ planCard.textContent = '';
572
+ const doneCount = items.filter((s) => s.status === 'completed').length;
573
+ const head = document.createElement('div');
574
+ head.className = 'plan-head';
575
+ const left = document.createElement('span');
576
+ left.textContent = ev.explanation || 'Execution Plan';
577
+ const right = document.createElement('span');
578
+ right.textContent = `${doneCount}/${items.length}`;
579
+ head.appendChild(left);
580
+ head.appendChild(right);
581
+ planCard.appendChild(head);
582
+ for (const s of items) {
583
+ const line = document.createElement('div');
584
+ const st = String(s.status || 'pending');
585
+ line.className = `plan-step${st === 'completed' ? ' done' : st === 'in_progress' ? ' active' : ''}`;
586
+ const ic = document.createElement('span');
587
+ ic.className = 'step-icon';
588
+ ic.textContent = st === 'completed' ? '✓' : st === 'in_progress' ? '●' : '○';
589
+ const txt = document.createElement('span');
590
+ txt.textContent = s.text || s.step || '';
591
+ line.appendChild(ic);
592
+ line.appendChild(txt);
593
+ planCard.appendChild(line);
594
+ }
595
+ scrollToBottom(false);
596
+ },
597
+ addStepStart(ev: StreamEventPayload): void {
598
+ ensureTimeline();
599
+ stepCount += 1;
600
+ runningSteps += 1;
601
+ stepKinds.push(classifyStepKind(ev.tool));
602
+ const targetStr = summarizeToolTarget(ev.args);
603
+ const built = buildStepRow(ev.tool || 'tool', targetStr, 'running...', false, '');
604
+ timelineStepsEl?.appendChild(built.card);
605
+ const key = ev.toolCallId || (`${ev.tool || 'tool'}:${stepCount}`);
606
+ toolCards.set(key, { card: built.card, status: built.statusEl, dot: built.dotEl, startedAt: Date.now() });
607
+ refreshTimelineHeader(false);
608
+ setLiveness(true, (ev.tool || 'Running') + (targetStr ? ` · ${targetStr}` : ''));
609
+ scrollToBottom(false);
610
+ },
611
+ addStepEnd(ev: StreamEventPayload, failed: boolean): void {
612
+ ensureTimeline();
613
+ if (runningSteps > 0) runningSteps -= 1;
614
+ const key = ev.toolCallId || '';
615
+ const entry = key ? toolCards.get(key) : null;
616
+ const resObj = ev.result && typeof ev.result === 'object' ? ev.result : null;
617
+ const rawOut = ev.error || ev.summary || (typeof ev.output === 'string' ? ev.output : '')
618
+ || (resObj && typeof resObj.output === 'string' ? resObj.output : '')
619
+ || (resObj && typeof resObj.message === 'string' ? resObj.message : '');
620
+ if (!entry) {
621
+ stepCount += 1;
622
+ stepKinds.push(classifyStepKind(ev.tool));
623
+ const built = buildStepRow(ev.tool || 'tool', '', failed ? 'failed' : 'done', failed, rawOut);
624
+ timelineStepsEl?.appendChild(built.card);
625
+ } else {
626
+ const elapsed = Math.max(1, Date.now() - entry.startedAt);
627
+ entry.status.textContent = `${failed ? 'failed · ' : 'done · '}${elapsed}ms`;
628
+ entry.dot.className = `status-dot ${failed ? 'failed' : 'done'}`;
629
+ if (failed) entry.status.style.color = 'var(--err)';
630
+ if (rawOut) {
631
+ const out = document.createElement('div');
632
+ out.className = 'tool-out';
633
+ out.textContent = String(rawOut).slice(0, 480);
634
+ entry.card.appendChild(out);
635
+ }
636
+ }
637
+ refreshTimelineHeader(false);
638
+ scrollToBottom(false);
639
+ },
640
+ addNativeStep(ev: StreamEventPayload, failed: boolean): void {
641
+ const actionName = String(ev.actionName || '').trim();
642
+ const detail = String(ev.detail || '').trim();
643
+ const msg = String(ev.message || '').trim();
644
+ if (actionName === 'true' || actionName === ':' || detail === 'true' || detail === ':') return;
645
+ if (!actionName && (!msg || /(?:^|\s)(?:true|:)$/.test(msg))) return;
646
+ ensureTimeline();
647
+ stepCount += 1;
648
+ const cleanAction = actionName.replace(/^causyne[-_]browser[_:]/i, '');
649
+ stepKinds.push(classifyStepKind(cleanAction));
650
+ const cleanMsg = msg.replace(/^acp\/[a-z0-9._-]+\s+/i, '').replace(/^causyne[-_]browser[_:]/i, '');
651
+ const built = buildStepRow(
652
+ cleanAction || 'step',
653
+ detail || (cleanMsg && cleanMsg !== cleanAction ? cleanMsg : ''),
654
+ failed ? 'failed' : 'done',
655
+ failed,
656
+ ''
657
+ );
658
+ timelineStepsEl?.appendChild(built.card);
659
+ refreshTimelineHeader(false);
660
+ scrollToBottom(false);
661
+ },
662
+ upsertCodeProgress(ev: StreamEventPayload): void {
663
+ const key = ev.id || ev.path || (`code-${codeCards.size}`);
664
+ let slot = codeCards.get(key);
665
+ if (!slot) {
666
+ const card = document.createElement('div');
667
+ card.className = 'artifact-card streaming';
668
+ const top = document.createElement('div');
669
+ top.className = 'artifact-top';
670
+ const meta = document.createElement('div');
671
+ meta.className = 'artifact-meta';
672
+ const ic = document.createElement('div');
673
+ ic.className = 'artifact-icon';
674
+ const textBox = document.createElement('div');
675
+ textBox.style.minWidth = '0';
676
+ const title = document.createElement('div');
677
+ title.className = 'artifact-title';
678
+ const sub = document.createElement('div');
679
+ sub.className = 'artifact-sub';
680
+ textBox.appendChild(title);
681
+ textBox.appendChild(sub);
682
+ meta.appendChild(ic);
683
+ meta.appendChild(textBox);
684
+ const btns = document.createElement('div');
685
+ btns.className = 'artifact-btns';
686
+ top.appendChild(meta);
687
+ top.appendChild(btns);
688
+ const pre = document.createElement('pre');
689
+ pre.className = 'artifact-stream-pre';
690
+ card.appendChild(top);
691
+ card.appendChild(pre);
692
+ artifactsSlot.appendChild(card);
693
+ slot = { card, ic, title, sub, btns, pre, code: '', path: '' };
694
+ codeCards.set(key, slot);
695
+ }
696
+ const relPath = ev.path || slot.path || 'workspace-file';
697
+ slot.path = relPath;
698
+ if (typeof ev.code === 'string') slot.code = ev.code;
699
+ const badge = artifactBadgeFor(relPath, '');
700
+ slot.ic.textContent = badge.tag;
701
+ slot.title.textContent = relPath;
702
+ const lines = slot.code ? slot.code.split('\n').length : 0;
703
+ const phase = ev.phase || 'working';
704
+ slot.card.classList.toggle('streaming', phase === 'draft' || phase === 'working');
705
+ slot.sub.textContent = `${ev.operation || 'Updating'} · ${badge.label}${lines > 0 ? ` · ${lines} lines` : ''} · ${phase}`;
706
+ if (slot.code) {
707
+ slot.pre.style.display = 'block';
708
+ slot.pre.textContent = slot.code.split('\n').slice(-10).join('\n');
709
+ } else {
710
+ slot.pre.style.display = 'none';
711
+ }
712
+ slot.btns.textContent = '';
713
+ if (phase === 'done') {
714
+ slot.pre.style.display = 'none';
715
+ const openBtn = document.createElement('button');
716
+ openBtn.type = 'button';
717
+ openBtn.className = 'btn-ghost';
718
+ openBtn.textContent = 'Open';
719
+ const capturedCode = slot.code;
720
+ openBtn.addEventListener('click', () => {
721
+ if (capturedCode) callbacks.openInCanvas(relPath, capturedCode, relPath.endsWith('.md') || isHtmlOrSvgPath(relPath));
722
+ else void callbacks.openFile(relPath);
723
+ });
724
+ slot.btns.appendChild(openBtn);
725
+ if (isHtmlOrSvgPath(relPath) && capturedCode) {
726
+ const liveBtn = document.createElement('button');
727
+ liveBtn.type = 'button';
728
+ liveBtn.className = 'btn-primary';
729
+ liveBtn.textContent = 'Preview';
730
+ liveBtn.addEventListener('click', () => callbacks.openBrowserArtifact(relPath, capturedCode));
731
+ slot.btns.appendChild(liveBtn);
732
+ }
733
+ }
734
+ scrollToBottom(false);
735
+ },
736
+ addApproval(ev: StreamEventPayload): void {
737
+ const box = document.createElement('div');
738
+ box.className = 'approval-card';
739
+ const top = document.createElement('div');
740
+ top.className = 'approval-top';
741
+ const text = document.createElement('span');
742
+ text.className = 'approval-text';
743
+ text.textContent = `Allow ${ev.tool || 'tool'}?`;
744
+ const btns = document.createElement('div');
745
+ btns.className = 'approval-actions';
746
+ const yes = document.createElement('button');
747
+ yes.type = 'button'; yes.className = 'btn-primary'; yes.textContent = 'Allow';
748
+ const always = document.createElement('button');
749
+ always.type = 'button'; always.className = 'btn-ghost'; always.textContent = 'Always allow';
750
+ const no = document.createElement('button');
751
+ no.type = 'button'; no.className = 'btn-danger'; no.textContent = 'Deny';
752
+
753
+ const decide = async (approved: boolean, remember: boolean): Promise<void> => {
754
+ yes.disabled = true; always.disabled = true; no.disabled = true;
755
+ await fetch(apiUrl('/api/approve'), {
756
+ method: 'POST',
757
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
758
+ body: JSON.stringify({
759
+ sessionId: state.sessionId || undefined,
760
+ toolCallId: ev.toolCallId,
761
+ approved,
762
+ remember: Boolean(remember),
763
+ tool: ev.tool || ''
764
+ })
765
+ });
766
+ text.textContent = (approved ? (remember ? 'Always allowed ' : 'Allowed ') : 'Denied ') + (ev.tool || 'tool');
767
+ btns.textContent = '';
768
+ const badge = document.createElement('span');
769
+ badge.className = 'pop-sub';
770
+ badge.textContent = approved ? (remember ? 'Always allowed' : 'Allowed') : 'Denied';
771
+ if (!approved) badge.style.color = 'var(--err)';
772
+ btns.appendChild(badge);
773
+ };
774
+ yes.addEventListener('click', () => { void decide(true, false); });
775
+ always.addEventListener('click', () => { void decide(true, true); });
776
+ no.addEventListener('click', () => { void decide(false, false); });
777
+ btns.appendChild(yes); btns.appendChild(always); btns.appendChild(no);
778
+ top.appendChild(text); top.appendChild(btns);
779
+ box.appendChild(top);
780
+ if (ev.args && typeof ev.args === 'object' && Object.keys(ev.args).length > 0) {
781
+ const pre = document.createElement('pre');
782
+ pre.className = 'approval-args';
783
+ try { pre.textContent = JSON.stringify(ev.args, null, 2).slice(0, 600); } catch { /* ignore */ }
784
+ box.appendChild(pre);
785
+ }
786
+ eventsSlot.appendChild(box);
787
+ setLiveness(true, `Waiting for approval · ${ev.tool || 'tool'}`);
788
+ scrollToBottom(true);
789
+ },
790
+ addDecision(reqObj: DecisionRequestPayload): void {
791
+ if (!reqObj || typeof reqObj !== 'object') return;
792
+ const box = document.createElement('div');
793
+ box.className = 'decision-card';
794
+ const q = document.createElement('div');
795
+ q.className = 'decision-q';
796
+ q.textContent = reqObj.question || 'Choose how to proceed:';
797
+ box.appendChild(q);
798
+ const optsWrap = document.createElement('div');
799
+ optsWrap.className = 'decision-options';
800
+ const optButtons: HTMLButtonElement[] = [];
801
+ let resolved = false;
802
+ const customInput = document.createElement('input');
803
+ const customBtn = document.createElement('button');
804
+
805
+ const submitChoice = async (optionId: string | null, label: string, custom: boolean): Promise<void> => {
806
+ if (resolved || !label) return;
807
+ resolved = true;
808
+ for (const b of optButtons) b.disabled = true;
809
+ customInput.disabled = true;
810
+ customBtn.disabled = true;
811
+ await fetch(apiUrl('/api/decision'), {
812
+ method: 'POST',
813
+ headers: authHeaders({ 'Content-Type': 'application/json' }),
814
+ body: JSON.stringify({
815
+ sessionId: state.sessionId || undefined,
816
+ requestId: reqObj.id || '',
817
+ optionId: optionId || null,
818
+ label,
819
+ custom: Boolean(custom)
820
+ })
821
+ }).catch(() => {});
822
+ optsWrap.textContent = '';
823
+ const chosen = document.createElement('span');
824
+ chosen.className = 'pop-sub';
825
+ chosen.textContent = `Selected: ${label}`;
826
+ optsWrap.appendChild(chosen);
827
+ };
828
+
829
+ const options = Array.isArray(reqObj.options) ? reqObj.options : [];
830
+ for (const opt of options) {
831
+ const btn = document.createElement('button');
832
+ btn.type = 'button';
833
+ btn.className = 'decision-opt-btn';
834
+ const lbl = document.createElement('span');
835
+ lbl.className = 'decision-opt-label';
836
+ lbl.textContent = opt.label || opt.id || 'Option';
837
+ btn.appendChild(lbl);
838
+ if (opt.description) {
839
+ const desc = document.createElement('span');
840
+ desc.className = 'decision-opt-desc';
841
+ desc.textContent = opt.description;
842
+ btn.appendChild(desc);
843
+ }
844
+ btn.addEventListener('click', () => {
845
+ void submitChoice(opt.id || null, opt.label || opt.id || '', false);
846
+ });
847
+ optButtons.push(btn);
848
+ optsWrap.appendChild(btn);
849
+ }
850
+
851
+ const customRow = document.createElement('div');
852
+ customRow.className = 'decision-custom-row';
853
+ customInput.type = 'text';
854
+ customInput.className = 'decision-custom-input';
855
+ customInput.placeholder = 'Or type a custom answer...';
856
+ customBtn.type = 'button';
857
+ customBtn.className = 'btn-ghost';
858
+ customBtn.textContent = 'Send';
859
+ customBtn.addEventListener('click', () => { void submitChoice(null, (customInput.value || '').trim(), true); });
860
+ customInput.addEventListener('keydown', (e) => {
861
+ if (e.key === 'Enter') { e.preventDefault(); void submitChoice(null, (customInput.value || '').trim(), true); }
862
+ });
863
+ customRow.appendChild(customInput);
864
+ customRow.appendChild(customBtn);
865
+ box.appendChild(optsWrap);
866
+ box.appendChild(customRow);
867
+ eventsSlot.appendChild(box);
868
+ setLiveness(true, 'Waiting for your decision...');
869
+ updateThreadSpacer();
870
+ scrollToBottom(true);
871
+ },
872
+ addNotice(msg: string): void {
873
+ const card = document.createElement('div');
874
+ card.className = 'tool-card';
875
+ card.textContent = msg;
876
+ eventsSlot.appendChild(card);
877
+ updateThreadSpacer();
878
+ scrollToBottom(false);
879
+ },
880
+ addError(msg: string, retryText?: string, code?: string): void {
881
+ const err = document.createElement('div');
882
+ err.className = code === 'DAILY_LIMIT_REACHED' ? 'msg-upgrade' : 'msg-error';
883
+ const txt = document.createElement('span');
884
+ txt.textContent = msg;
885
+ err.appendChild(txt);
886
+ if (code === 'DAILY_LIMIT_REACHED') {
887
+ const acts = document.createElement('div');
888
+ acts.className = 'msg-upgrade-actions';
889
+ const upgBtn = document.createElement('button');
890
+ upgBtn.type = 'button';
891
+ upgBtn.className = 'btn-primary';
892
+ upgBtn.textContent = 'Upgrade to Pro';
893
+ upgBtn.addEventListener('click', () => callbacks.openSettingsForUpgrade());
894
+ acts.appendChild(upgBtn);
895
+ err.appendChild(acts);
896
+ } else {
897
+ const targetRetry = retryText || promptForRetry;
898
+ if (targetRetry) {
899
+ const btn = document.createElement('button');
900
+ btn.type = 'button';
901
+ btn.className = 'btn-ghost';
902
+ btn.textContent = 'Retry';
903
+ btn.addEventListener('click', () => {
904
+ err.remove();
905
+ void callbacks.submitPrompt(targetRetry, []);
906
+ });
907
+ err.appendChild(btn);
908
+ }
909
+ }
910
+ errorSlot.appendChild(err);
911
+ announceAlert(msg);
912
+ updateThreadSpacer();
913
+ scrollToBottom(true);
914
+ },
915
+ addInterrupted(msg: string, retryText?: string): void {
916
+ if (interruptedShown) return;
917
+ interruptedShown = true;
918
+ const box = document.createElement('div');
919
+ box.className = 'msg-interrupted';
920
+ const txt = document.createElement('span');
921
+ txt.textContent = msg || 'Causyne\u2019s response was interrupted.';
922
+ box.appendChild(txt);
923
+ const targetRetry = retryText || promptForRetry;
924
+ if (targetRetry) {
925
+ const acts = document.createElement('div');
926
+ acts.className = 'msg-interrupted-actions';
927
+ const contBtn = document.createElement('button');
928
+ contBtn.type = 'button';
929
+ contBtn.className = 'btn-primary';
930
+ contBtn.textContent = 'Continue';
931
+ contBtn.addEventListener('click', () => {
932
+ box.remove();
933
+ void callbacks.submitPrompt(targetRetry, []);
934
+ });
935
+ acts.appendChild(contBtn);
936
+ box.appendChild(acts);
937
+ }
938
+ errorSlot.appendChild(box);
939
+ updateThreadSpacer();
940
+ scrollToBottom(false);
941
+ },
942
+ finish(): void {
943
+ row.classList.remove('is-streaming');
944
+ liveRow.classList.remove('is-active');
945
+ reasonSmoother.flush();
946
+ if (prose.style.display !== 'none') proseSmoother.flush();
947
+ if (reasonCard && !isRestored) {
948
+ reasonCard.setActive(false);
949
+ reasonCard.dot.className = 'status-dot done';
950
+ reasonCard.labelEl.textContent = formatThoughtDuration(Date.now() - reasonStartedAt);
951
+ if (!reasonCard.wasUserToggled()) reasonCard.setOpen(false, false);
952
+ }
953
+ syncLoopbackButtons();
954
+ refreshTimelineHeader(true);
955
+ if (timelineCard && stepCount > 0 && !timelineCard.wasUserToggled()) timelineCard.setOpen(false, false);
956
+ if (!rawText.trim()) return;
957
+ actionsRow.textContent = '';
958
+ actionsRow.style.display = 'flex';
959
+ const copyBtn = document.createElement('button');
960
+ copyBtn.type = 'button';
961
+ copyBtn.className = 'msg-action-btn';
962
+ copyBtn.textContent = 'Copy';
963
+ copyBtn.addEventListener('click', () => copyText(rawText, copyBtn));
964
+ const canvasBtn = document.createElement('button');
965
+ canvasBtn.type = 'button';
966
+ canvasBtn.className = 'msg-action-btn';
967
+ canvasBtn.textContent = 'Open in Canvas';
968
+ canvasBtn.addEventListener('click', () => callbacks.openInCanvas('response.idoc.md', rawText, true));
969
+ actionsRow.appendChild(copyBtn);
970
+ actionsRow.appendChild(canvasBtn);
971
+ if (promptForRetry) {
972
+ const retryBtn = document.createElement('button');
973
+ retryBtn.type = 'button';
974
+ retryBtn.className = 'msg-action-btn';
975
+ retryBtn.textContent = 'Regenerate';
976
+ retryBtn.addEventListener('click', () => { void callbacks.submitPrompt(promptForRetry, []); });
977
+ actionsRow.appendChild(retryBtn);
978
+ }
979
+ }
980
+ };
981
+ }