@causyne/agent 1.20.124 → 1.20.127

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 (235) hide show
  1. package/bin/causyne.js +1 -1
  2. package/package.json +4 -4
  3. package/src/acp/protocol.ts +19 -1
  4. package/src/acp/server.js +282 -8
  5. package/src/acp/server.ts +284 -8
  6. package/src/agent/abortableDelay.js +2 -2
  7. package/src/agent/abortableDelay.ts +2 -2
  8. package/src/agent/errorClassifier.js +9 -1
  9. package/src/agent/errorClassifier.ts +8 -1
  10. package/src/agentLoop.js +83 -27
  11. package/src/agentLoop.ts +92 -26
  12. package/src/approvalPolicy.js +34 -10
  13. package/src/approvalPolicy.ts +42 -11
  14. package/src/browser/causyneBrowser.js +30 -3
  15. package/src/browser/causyneBrowser.ts +33 -3
  16. package/src/browser/urlPolicy.js +14 -1
  17. package/src/browser/urlPolicy.ts +12 -1
  18. package/src/cliMode.js +21 -9
  19. package/src/cliMode.ts +20 -8
  20. package/src/commands.js +188 -32
  21. package/src/commands.ts +209 -32
  22. package/src/config.js +19 -4
  23. package/src/config.ts +18 -4
  24. package/src/core/contextCompactor.js +54 -7
  25. package/src/core/contextCompactor.ts +63 -7
  26. package/src/core/goalLoop.js +257 -0
  27. package/src/core/goalLoop.ts +310 -0
  28. package/src/entrypoint.js +135 -3
  29. package/src/entrypoint.ts +136 -3
  30. package/src/game/causyneCoreBridge.js +686 -0
  31. package/src/game/causyneCoreBridge.ts +702 -0
  32. package/src/game/gameLauncher.js +287 -0
  33. package/src/game/gameLauncher.ts +352 -0
  34. package/src/game/gameProvisioner.js +425 -0
  35. package/src/game/gameProvisioner.ts +488 -0
  36. package/src/headlessCli.js +19 -12
  37. package/src/headlessCli.ts +22 -8
  38. package/src/infra/atomicWriter.js +40 -4
  39. package/src/infra/atomicWriter.ts +36 -4
  40. package/src/launchIntent.js +73 -3
  41. package/src/launchIntent.ts +76 -3
  42. package/src/lsp/lspClient.js +83 -12
  43. package/src/lsp/lspClient.ts +75 -12
  44. package/src/mcp/mcpRegistry.js +75 -8
  45. package/src/mcp/mcpRegistry.ts +70 -7
  46. package/src/memory/contextBudget.js +2 -0
  47. package/src/memory/contextBudget.ts +1 -0
  48. package/src/modelVariants.js +45 -0
  49. package/src/modelVariants.ts +54 -0
  50. package/src/outputRecovery.js +3 -2
  51. package/src/outputRecovery.ts +4 -2
  52. package/src/permissionPresets.js +327 -0
  53. package/src/permissionPresets.ts +361 -0
  54. package/src/providers/antigravity.js +62 -9
  55. package/src/providers/antigravity.ts +73 -9
  56. package/src/providers/byokHttp.js +7 -1
  57. package/src/providers/byokHttp.ts +6 -1
  58. package/src/providers/byokStream.js +21 -8
  59. package/src/providers/byokStream.ts +17 -7
  60. package/src/providers/dashscope-byok.js +21 -5
  61. package/src/providers/dashscope-byok.ts +29 -11
  62. package/src/providers/moonshot.js +26 -7
  63. package/src/providers/moonshot.ts +34 -13
  64. package/src/providers/muse.js +6 -0
  65. package/src/providers/muse.ts +8 -0
  66. package/src/providers/ollama.js +39 -7
  67. package/src/providers/ollama.ts +36 -7
  68. package/src/providers/openai-compatible.js +16 -3
  69. package/src/providers/openai-compatible.ts +13 -3
  70. package/src/providers/openai.js +62 -4
  71. package/src/providers/openai.ts +50 -4
  72. package/src/providers/openrouter.js +19 -4
  73. package/src/providers/openrouter.ts +21 -4
  74. package/src/providers/qwen-byok.js +21 -5
  75. package/src/providers/qwen-byok.ts +29 -11
  76. package/src/providers/xai.js +26 -10
  77. package/src/providers/xai.ts +34 -16
  78. package/src/reporting.js +4 -2
  79. package/src/reporting.ts +4 -2
  80. package/src/sandbox.js +34 -0
  81. package/src/sandbox.ts +43 -0
  82. package/src/scheduler/scheduler.js +372 -0
  83. package/src/scheduler/scheduler.ts +433 -0
  84. package/src/sessionSearchIndex.js +267 -0
  85. package/src/sessionSearchIndex.ts +311 -0
  86. package/src/skillsManager.js +2 -3
  87. package/src/skillsManager.ts +2 -3
  88. package/src/toolPacks.js +6 -0
  89. package/src/toolPacks.ts +6 -0
  90. package/src/tools/applyPatch.js +1 -1
  91. package/src/tools/applyPatch.ts +1 -1
  92. package/src/tools/generateMediaViaApi.js +4 -3
  93. package/src/tools/generateMediaViaApi.ts +4 -3
  94. package/src/tools/nativeEngine.js +2 -2
  95. package/src/tools/nativeEngine.ts +2 -2
  96. package/src/tools/openSourceToolProvisioner.js +2 -2
  97. package/src/tools/openSourceToolProvisioner.ts +2 -2
  98. package/src/tools/payloadSanitizer.js +0 -1
  99. package/src/tools/payloadSanitizer.ts +0 -1
  100. package/src/tools/pdfReader.js +122 -20
  101. package/src/tools/pdfReader.ts +111 -20
  102. package/src/tools/presentDeliverable.js +103 -0
  103. package/src/tools/presentDeliverable.ts +127 -0
  104. package/src/tools/ptcRuntime.js +444 -0
  105. package/src/tools/ptcRuntime.ts +490 -0
  106. package/src/tools/ptyTerminal.js +1096 -0
  107. package/src/tools/ptyTerminal.ts +1231 -0
  108. package/src/tools/registry.js +21 -12
  109. package/src/tools/registry.ts +21 -12
  110. package/src/tools/toolOutputStore.js +26 -4
  111. package/src/tools/toolOutputStore.ts +22 -4
  112. package/src/tools/webFetch.js +158 -11
  113. package/src/tools/webFetch.ts +145 -11
  114. package/src/tools/webSearch.js +123 -36
  115. package/src/tools/webSearch.ts +124 -33
  116. package/src/tui/banner.js +5 -1
  117. package/src/tui/banner.ts +6 -1
  118. package/src/tui/chatRenderer.js +1 -2
  119. package/src/tui/chatRenderer.ts +1 -2
  120. package/src/tui/completion.js +1 -0
  121. package/src/tui/completion.ts +1 -0
  122. package/src/tui/composerControls.js +111 -27
  123. package/src/tui/composerControls.ts +124 -28
  124. package/src/tui/dialogs.js +3 -16
  125. package/src/tui/dialogs.ts +3 -16
  126. package/src/tui/home.js +1 -0
  127. package/src/tui/home.ts +1 -0
  128. package/src/tui/invocation.js +1 -2
  129. package/src/tui/invocation.ts +1 -2
  130. package/src/tui/modelPicker.js +22 -12
  131. package/src/tui/modelPicker.ts +22 -12
  132. package/src/tui/overlay.js +2 -5
  133. package/src/tui/overlay.ts +2 -5
  134. package/src/tui/prompt.js +6 -4
  135. package/src/tui/prompt.ts +6 -4
  136. package/src/tui/selectList.js +4 -12
  137. package/src/tui/selectList.ts +4 -12
  138. package/src/tui/setup.js +22 -9
  139. package/src/tui/setup.ts +26 -9
  140. package/src/tui/statusLine.ts +2 -0
  141. package/src/web/client/browserPanel.js +702 -0
  142. package/src/web/client/browserPanel.ts +663 -0
  143. package/src/web/client/chatStream.js +309 -0
  144. package/src/web/client/chatStream.ts +289 -0
  145. package/src/web/client/cliPanel.js +165 -0
  146. package/src/web/client/cliPanel.ts +171 -0
  147. package/src/web/client/composer.js +204 -0
  148. package/src/web/client/composer.ts +209 -0
  149. package/src/web/client/diffPanel.js +176 -0
  150. package/src/web/client/diffPanel.ts +203 -0
  151. package/src/web/client/dom.js +220 -0
  152. package/src/web/client/dom.ts +221 -0
  153. package/src/web/client/filesAndCanvas.js +231 -0
  154. package/src/web/client/filesAndCanvas.ts +238 -0
  155. package/src/web/client/gameLauncherUi.js +78 -0
  156. package/src/web/client/gameLauncherUi.ts +78 -0
  157. package/src/web/client/main.js +301 -0
  158. package/src/web/client/main.ts +368 -0
  159. package/src/web/client/markdown.js +364 -0
  160. package/src/web/client/markdown.ts +373 -0
  161. package/src/web/client/modelPicker.js +455 -0
  162. package/src/web/client/modelPicker.ts +451 -0
  163. package/src/web/client/permissionPresetsUi.js +307 -0
  164. package/src/web/client/permissionPresetsUi.ts +333 -0
  165. package/src/web/client/sessions.js +353 -0
  166. package/src/web/client/sessions.ts +372 -0
  167. package/src/web/client/settingsModal.js +191 -0
  168. package/src/web/client/settingsModal.ts +176 -0
  169. package/src/web/client/state.js +250 -0
  170. package/src/web/client/state.ts +233 -0
  171. package/src/web/client/streamSmoother.js +127 -0
  172. package/src/web/client/streamSmoother.ts +119 -0
  173. package/src/web/client/studioLayout.js +54 -0
  174. package/src/web/client/studioLayout.ts +60 -0
  175. package/src/web/client/studioShell.js +327 -0
  176. package/src/web/client/studioShell.ts +340 -0
  177. package/src/web/client/studioStart.js +77 -0
  178. package/src/web/client/studioStart.ts +89 -0
  179. package/src/web/client/terminalPanel.js +357 -0
  180. package/src/web/client/terminalPanel.ts +345 -0
  181. package/src/web/client/turnView.js +934 -0
  182. package/src/web/client/turnView.ts +981 -0
  183. package/src/web/client/types.js +1 -0
  184. package/src/web/client/types.ts +319 -0
  185. package/src/web/client/validators.js +106 -0
  186. package/src/web/client/validators.ts +96 -0
  187. package/src/web/server/activeRuns.js +152 -0
  188. package/src/web/server/activeRuns.ts +171 -0
  189. package/src/web/server/routesBrowser.js +355 -0
  190. package/src/web/server/routesBrowser.ts +386 -0
  191. package/src/web/server/routesChat.js +304 -0
  192. package/src/web/server/routesChat.ts +347 -0
  193. package/src/web/server/routesCore.js +472 -0
  194. package/src/web/server/routesCore.ts +522 -0
  195. package/src/web/server/routesTerminal.js +162 -0
  196. package/src/web/server/routesTerminal.ts +182 -0
  197. package/src/web/server/routesWorkspace.js +510 -0
  198. package/src/web/server/routesWorkspace.ts +546 -0
  199. package/src/web/server/security.js +98 -0
  200. package/src/web/server/security.ts +108 -0
  201. package/src/web/server/sessionTranscript.js +586 -0
  202. package/src/web/server/sessionTranscript.ts +566 -0
  203. package/src/web/server/staticAssets.js +80 -0
  204. package/src/web/server/staticAssets.ts +91 -0
  205. package/src/web/server/types.js +1 -0
  206. package/src/web/server/types.ts +135 -0
  207. package/src/web/server/workspaceFiles.js +368 -0
  208. package/src/web/server/workspaceFiles.ts +363 -0
  209. package/src/web/skybridgeServer.js +76 -2449
  210. package/src/web/skybridgeServer.ts +118 -2600
  211. package/src/web/skybridgeUi.js +16 -450
  212. package/src/web/skybridgeUi.ts +16 -454
  213. package/src/web/styles/agent.css +380 -0
  214. package/src/web/styles/composer.css +193 -0
  215. package/src/web/styles/overlays.css +436 -0
  216. package/src/web/styles/shell.css +387 -0
  217. package/src/web/styles/studio.css +723 -0
  218. package/src/web/styles/thread.css +221 -0
  219. package/src/web/styles/tokens.css +94 -0
  220. package/src/web/ui/brandMark.js +73 -0
  221. package/src/web/ui/brandMark.ts +82 -0
  222. package/src/web/ui/modalsTemplate.js +139 -0
  223. package/src/web/ui/modalsTemplate.ts +139 -0
  224. package/src/web/ui/sidebarTemplate.js +63 -0
  225. package/src/web/ui/sidebarTemplate.ts +64 -0
  226. package/src/web/ui/studioTemplate.js +258 -0
  227. package/src/web/ui/studioTemplate.ts +258 -0
  228. package/src/web/ui/workspaceTemplate.js +72 -0
  229. package/src/web/ui/workspaceTemplate.ts +73 -0
  230. package/src/worktreeManager.js +16 -1
  231. package/src/worktreeManager.ts +22 -1
  232. package/src/web/skybridgeClientScript.js +0 -3951
  233. package/src/web/skybridgeClientScript.ts +0 -3952
  234. package/src/web/skybridgeStyles.js +0 -827
  235. package/src/web/skybridgeStyles.ts +0 -828
@@ -0,0 +1,386 @@
1
+ import type http from 'node:http';
2
+ import { auditLog } from '../../auditLog.js';
3
+ import {
4
+ causyneBrowser,
5
+ expandSearchMacro,
6
+ type BrowserEnginePreference,
7
+ type LiveBrowserInteraction
8
+ } from '../../browser/causyneBrowser.js';
9
+ import {
10
+ discoverLocalCdpTabs,
11
+ importExplicitUserBrowserData,
12
+ syncLocalCdpTabToCausyne
13
+ } from '../skybridgeBrowserBridge.js';
14
+ import {
15
+ handleBrowserMcpRpc,
16
+ type JsonRpcMessage
17
+ } from '../skybridgeBrowserMcp.js';
18
+ import { readJsonBody, sendJson } from './security.js';
19
+ import type { SkybridgeContext } from './types.js';
20
+
21
+ const ALLOWED_INPUT_KINDS = new Set([
22
+ 'click', 'dblclick', 'contextmenu', 'mousedown', 'mousemove', 'mouseup', 'wheel', 'type', 'key', 'paste'
23
+ ]);
24
+
25
+ export async function handleBrowserRoutes(
26
+ req: http.IncomingMessage,
27
+ res: http.ServerResponse,
28
+ parsedUrl: URL,
29
+ ctx: SkybridgeContext
30
+ ): Promise<boolean> {
31
+ const pathname = parsedUrl.pathname;
32
+ const { workspaceRoot, version } = ctx;
33
+
34
+ if (req.method === 'GET' && pathname === '/api/mcp/browser') {
35
+ res.statusCode = 405;
36
+ res.setHeader('Allow', 'POST');
37
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
38
+ res.end(JSON.stringify({ error: 'Use POST for Streamable HTTP MCP JSON-RPC requests.' }));
39
+ return true;
40
+ }
41
+
42
+ if (req.method === 'POST' && pathname === '/api/mcp/browser') {
43
+ const body = await readJsonBody(req) as JsonRpcMessage;
44
+ const reply = await handleBrowserMcpRpc(body, {
45
+ workspaceRoot,
46
+ version,
47
+ onActivity: (activity) => {
48
+ if (activity.phase === 'start') {
49
+ ctx.setBrowserControlOwner('agent');
50
+ ctx.setBrowserAgentActivity({
51
+ active: true,
52
+ tool: activity.tool,
53
+ detail: activity.detail,
54
+ updatedAt: Date.now()
55
+ });
56
+ } else {
57
+ ctx.setBrowserAgentActivity({ active: false, tool: '', detail: '', updatedAt: Date.now() });
58
+ }
59
+ ctx.broadcastBrowserNotice({
60
+ type: 'agent_activity',
61
+ controlOwner: ctx.getBrowserControlOwner(),
62
+ agentActivity: ctx.getBrowserAgentActivity()
63
+ });
64
+ }
65
+ });
66
+ if (reply === null) {
67
+ res.statusCode = 202;
68
+ res.end();
69
+ return true;
70
+ }
71
+ sendJson(res, 200, reply);
72
+ return true;
73
+ }
74
+
75
+ if (req.method === 'GET' && pathname === '/api/browser/state') {
76
+ const ensure = parsedUrl.searchParams.get('ensure') === '1';
77
+ const browser = causyneBrowser({ workspace: workspaceRoot });
78
+ const frame = await browser.captureLiveFrame({ ensureStarted: ensure });
79
+ sendJson(res, 200, {
80
+ ok: true,
81
+ controlOwner: ctx.getBrowserControlOwner(),
82
+ agentActivity: ctx.getBrowserAgentActivity(),
83
+ computerUsePolicy: 'tiered-approval',
84
+ ...frame
85
+ });
86
+ return true;
87
+ }
88
+
89
+ if (req.method === 'GET' && pathname === '/api/browser/stream') {
90
+ const browser = causyneBrowser({ workspace: workspaceRoot });
91
+ res.statusCode = 200;
92
+ res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
93
+ res.setHeader('Transfer-Encoding', 'chunked');
94
+ res.setHeader('X-Accel-Buffering', 'no');
95
+ const writeStreamLine = (payload: Record<string, unknown>): void => {
96
+ if (res.writableEnded || res.destroyed) return;
97
+ try {
98
+ res.write(`${JSON.stringify(payload)}\n`);
99
+ } catch {
100
+ // Stream closed mid-write.
101
+ }
102
+ };
103
+ const unsub = browser.subscribeLiveStream((ev) => {
104
+ writeStreamLine({
105
+ ...ev,
106
+ controlOwner: ctx.getBrowserControlOwner(),
107
+ agentActivity: ctx.getBrowserAgentActivity(),
108
+ computerUsePolicy: 'tiered-approval'
109
+ });
110
+ });
111
+ ctx.browserStreamClients.add(writeStreamLine);
112
+ writeStreamLine({
113
+ type: 'agent_activity',
114
+ controlOwner: ctx.getBrowserControlOwner(),
115
+ agentActivity: ctx.getBrowserAgentActivity(),
116
+ computerUsePolicy: 'tiered-approval'
117
+ });
118
+ const keepAlive = setInterval(() => {
119
+ writeStreamLine({ type: 'ping', ts: Date.now() });
120
+ }, 15_000);
121
+ keepAlive.unref?.();
122
+ const cleanup = (): void => {
123
+ clearInterval(keepAlive);
124
+ ctx.browserStreamClients.delete(writeStreamLine);
125
+ unsub();
126
+ };
127
+ req.on('close', cleanup);
128
+ res.on('close', cleanup);
129
+ return true;
130
+ }
131
+
132
+ if (req.method === 'POST' && pathname === '/api/browser/input') {
133
+ const body = await readJsonBody(req);
134
+ const kind = typeof body.kind === 'string' ? body.kind.trim() : '';
135
+ if (!ALLOWED_INPUT_KINDS.has(kind)) {
136
+ sendJson(res, 400, { error: 'Unsupported live browser input kind.' });
137
+ return true;
138
+ }
139
+ ctx.setBrowserControlOwner('human');
140
+ const browser = causyneBrowser({ workspace: workspaceRoot });
141
+ const result = await browser.dispatchLiveInput({
142
+ kind: kind as LiveBrowserInteraction['kind'],
143
+ x: typeof body.x === 'number' ? body.x : undefined,
144
+ y: typeof body.y === 'number' ? body.y : undefined,
145
+ deltaX: typeof body.deltaX === 'number' ? body.deltaX : undefined,
146
+ deltaY: typeof body.deltaY === 'number' ? body.deltaY : undefined,
147
+ text: typeof body.text === 'string' ? body.text : undefined,
148
+ key: typeof body.key === 'string' ? body.key : undefined,
149
+ button: body.button === 'right' || body.button === 'middle' ? body.button : 'left',
150
+ skipFrame: true
151
+ });
152
+ sendJson(res, 200, { ok: result.ok, controlOwner: ctx.getBrowserControlOwner() });
153
+ return true;
154
+ }
155
+
156
+ if (req.method === 'POST' && pathname === '/api/browser/action') {
157
+ const body = await readJsonBody(req);
158
+ const action = typeof body.action === 'string' ? body.action.trim() : '';
159
+ const browser = causyneBrowser({ workspace: workspaceRoot });
160
+
161
+ if (action === 'setMode') {
162
+ ctx.setBrowserControlOwner('human');
163
+ const rawPref = typeof body.enginePreference === 'string' ? body.enginePreference.trim() : '';
164
+ const enginePreference: BrowserEnginePreference | undefined = rawPref === 'camoufox'
165
+ || rawPref === 'chromium'
166
+ || rawPref === 'auto'
167
+ ? rawPref
168
+ : undefined;
169
+ const frame = await browser.setDisplayMode({
170
+ visible: typeof body.visible === 'boolean' ? body.visible : undefined,
171
+ enginePreference,
172
+ ensureStarted: body.ensureStarted === true
173
+ });
174
+ auditLog.log({
175
+ event: 'skybridge_browser_mode_switch',
176
+ visible: frame.visible,
177
+ engine: frame.engine,
178
+ enginePreference: frame.enginePreference
179
+ });
180
+ ctx.broadcastBrowserNotice({
181
+ type: 'meta',
182
+ controlOwner: ctx.getBrowserControlOwner(),
183
+ agentActivity: ctx.getBrowserAgentActivity(),
184
+ ...frame
185
+ });
186
+ sendJson(res, 200, {
187
+ ok: true,
188
+ controlOwner: ctx.getBrowserControlOwner(),
189
+ agentActivity: ctx.getBrowserAgentActivity(),
190
+ ...frame
191
+ });
192
+ return true;
193
+ }
194
+ if (action === 'takeControl') {
195
+ ctx.setBrowserControlOwner('human');
196
+ ctx.setBrowserAgentActivity({ active: false, tool: '', detail: '', updatedAt: Date.now() });
197
+ const frame = await browser.captureLiveFrame({ ensureStarted: false });
198
+ ctx.broadcastBrowserNotice({
199
+ type: 'agent_activity',
200
+ controlOwner: ctx.getBrowserControlOwner(),
201
+ agentActivity: ctx.getBrowserAgentActivity()
202
+ });
203
+ sendJson(res, 200, {
204
+ ok: true,
205
+ controlOwner: ctx.getBrowserControlOwner(),
206
+ agentActivity: ctx.getBrowserAgentActivity(),
207
+ ...frame
208
+ });
209
+ return true;
210
+ }
211
+ if (action === 'handToAgent') {
212
+ ctx.setBrowserControlOwner('agent');
213
+ const frame = await browser.captureLiveFrame({ ensureStarted: false });
214
+ ctx.broadcastBrowserNotice({
215
+ type: 'agent_activity',
216
+ controlOwner: ctx.getBrowserControlOwner(),
217
+ agentActivity: ctx.getBrowserAgentActivity()
218
+ });
219
+ sendJson(res, 200, {
220
+ ok: true,
221
+ controlOwner: ctx.getBrowserControlOwner(),
222
+ agentActivity: ctx.getBrowserAgentActivity(),
223
+ ...frame
224
+ });
225
+ return true;
226
+ }
227
+ if (action === 'start') {
228
+ ctx.setBrowserControlOwner('human');
229
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
230
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
231
+ return true;
232
+ }
233
+ if (action === 'close') {
234
+ await browser.close();
235
+ const frame = await browser.captureLiveFrame({ ensureStarted: false });
236
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
237
+ return true;
238
+ }
239
+ if (action === 'goto' || action === 'newTab') {
240
+ ctx.setBrowserControlOwner('human');
241
+ let rawUrl = typeof body.url === 'string' ? body.url.trim() : '';
242
+ if (rawUrl.startsWith('@')) {
243
+ const idx = rawUrl.indexOf(' ');
244
+ const macro = idx === -1 ? rawUrl : rawUrl.slice(0, idx);
245
+ const q = idx === -1 ? '' : rawUrl.slice(idx + 1).trim();
246
+ const expanded = expandSearchMacro(macro, q);
247
+ if (!expanded) {
248
+ sendJson(res, 400, { error: 'Unsupported browser search macro.' });
249
+ return true;
250
+ }
251
+ rawUrl = expanded;
252
+ } else if (rawUrl && !/^https?:\/\//i.test(rawUrl)) {
253
+ rawUrl = rawUrl.includes('.') || rawUrl.startsWith('localhost')
254
+ ? `https://${rawUrl}`
255
+ : (expandSearchMacro('@duckduckgo_search', rawUrl) || `https://duckduckgo.com/?q=${encodeURIComponent(rawUrl)}`);
256
+ }
257
+ await browser.run(
258
+ [action === 'newTab' ? { type: 'newTab', ...(rawUrl ? { url: rawUrl } : {}) } : { type: 'goto', url: rawUrl || 'about:blank' }],
259
+ { workspace: workspaceRoot }
260
+ );
261
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
262
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
263
+ return true;
264
+ }
265
+ if (action === 'back' || action === 'forward' || action === 'reload') {
266
+ ctx.setBrowserControlOwner('human');
267
+ await browser.run([{ type: action }], { workspace: workspaceRoot });
268
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
269
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
270
+ return true;
271
+ }
272
+ if ((action === 'switchTab' || action === 'closeTab') && typeof body.tabId === 'string' && body.tabId.trim()) {
273
+ ctx.setBrowserControlOwner('human');
274
+ await browser.run([{ type: action, tabId: body.tabId.trim() }], { workspace: workspaceRoot });
275
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
276
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
277
+ return true;
278
+ }
279
+ if (action === 'viewport') {
280
+ const width = Math.max(320, Math.min(1920, Number(body.width) || 1280));
281
+ const height = Math.max(480, Math.min(1200, Number(body.height) || 800));
282
+ await browser.run([{ type: 'viewport', width, height }], { workspace: workspaceRoot });
283
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
284
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
285
+ return true;
286
+ }
287
+ if (action === 'snapshot') {
288
+ const snap = await browser.snapshot(0);
289
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
290
+ sendJson(res, 200, {
291
+ ok: true,
292
+ controlOwner: ctx.getBrowserControlOwner(),
293
+ snapshot: snap.text,
294
+ refsCount: snap.refsCount,
295
+ ...frame
296
+ });
297
+ return true;
298
+ }
299
+ if (ALLOWED_INPUT_KINDS.has(action)) {
300
+ ctx.setBrowserControlOwner('human');
301
+ const frame = await browser.interactAt({
302
+ kind: action as LiveBrowserInteraction['kind'],
303
+ x: typeof body.x === 'number' ? body.x : undefined,
304
+ y: typeof body.y === 'number' ? body.y : undefined,
305
+ deltaX: typeof body.deltaX === 'number' ? body.deltaX : undefined,
306
+ deltaY: typeof body.deltaY === 'number' ? body.deltaY : undefined,
307
+ text: typeof body.text === 'string' ? body.text : undefined,
308
+ key: typeof body.key === 'string' ? body.key : undefined,
309
+ button: body.button === 'right' || body.button === 'middle' ? body.button : 'left'
310
+ });
311
+ sendJson(res, 200, {
312
+ ok: true,
313
+ controlOwner: ctx.getBrowserControlOwner(),
314
+ agentActivity: ctx.getBrowserAgentActivity(),
315
+ ...frame
316
+ });
317
+ return true;
318
+ }
319
+ sendJson(res, 400, { error: 'Unsupported shared browser action.' });
320
+ return true;
321
+ }
322
+
323
+ if (req.method === 'GET' && pathname === '/api/browser/cdp/tabs') {
324
+ const portParam = parsedUrl.searchParams.get('port') || '9222';
325
+ const discovered = await discoverLocalCdpTabs(portParam);
326
+ sendJson(res, 200, {
327
+ ok: true,
328
+ port: discovered.port,
329
+ tabs: discovered.tabs.map((t) => ({ id: t.id, title: t.title, url: t.url }))
330
+ });
331
+ return true;
332
+ }
333
+
334
+ if (req.method === 'POST' && pathname === '/api/browser/cdp/sync') {
335
+ const body = await readJsonBody(req);
336
+ const targetId = typeof body.targetId === 'string' ? body.targetId.trim() : '';
337
+ if (!targetId) {
338
+ sendJson(res, 400, { error: 'targetId is required to sync a local browser tab.' });
339
+ return true;
340
+ }
341
+ const synced = await syncLocalCdpTabToCausyne({
342
+ workspaceRoot,
343
+ port: body.port ?? 9222,
344
+ targetId,
345
+ includeCookies: body.includeCookies === true
346
+ });
347
+ ctx.setBrowserControlOwner('human');
348
+ auditLog.log({
349
+ event: 'skybridge_browser_cdp_sync',
350
+ importedCookies: synced.importedCookies
351
+ });
352
+ sendJson(res, 200, {
353
+ ok: true,
354
+ controlOwner: ctx.getBrowserControlOwner(),
355
+ syncedUrl: synced.syncedUrl,
356
+ importedCookies: synced.importedCookies,
357
+ ...synced.frame
358
+ });
359
+ return true;
360
+ }
361
+
362
+ if (req.method === 'POST' && pathname === '/api/browser/import') {
363
+ const body = await readJsonBody(req);
364
+ const rawText = typeof body.rawText === 'string' ? body.rawText : '';
365
+ const summary = await importExplicitUserBrowserData({
366
+ workspaceRoot,
367
+ rawText,
368
+ openFirstUrl: body.openFirstUrl !== false
369
+ });
370
+ const frame = await causyneBrowser({ workspace: workspaceRoot }).captureLiveFrame({ ensureStarted: false });
371
+ auditLog.log({
372
+ event: 'skybridge_browser_import',
373
+ importedCookies: summary.importedCookies,
374
+ urlsCount: summary.importedUrls.length
375
+ });
376
+ sendJson(res, 200, {
377
+ ok: true,
378
+ controlOwner: ctx.getBrowserControlOwner(),
379
+ ...summary,
380
+ ...frame
381
+ });
382
+ return true;
383
+ }
384
+
385
+ return false;
386
+ }
@@ -0,0 +1,304 @@
1
+ import { createSession, getSession, saveSessionMessages } from '../../sessionJournal.js';
2
+ import { auditLog } from '../../auditLog.js';
3
+ import { redactProviderSecrets } from '../../providers/byokHttp.js';
4
+ import { DAILY_LIMIT_SUPPORT_MESSAGE, EntitlementAccessError } from '../../licensing/entitlements.js';
5
+ import { getSessionPermissionPreset, normalizePermissionPreset, presetToAutonomyMode, setSessionPermissionPreset } from '../../permissionPresets.js';
6
+ import { SAFE_MODEL_RE, SAFE_PROVIDER_RE, SAFE_SESSION_ID_RE, readJsonBody, sendJson } from './security.js';
7
+ import { buildWorkspacePromptWithAttachments, workspaceMatchesSession } from './workspaceFiles.js';
8
+ import { MUTATING_FILE_TOOLS } from './sessionTranscript.js';
9
+ export async function handleChatRoutes(req, res, parsedUrl, ctx) {
10
+ const pathname = parsedUrl.pathname;
11
+ const { workspaceRoot } = ctx;
12
+ if (req.method === 'POST' && pathname === '/api/approve') {
13
+ const body = await readJsonBody(req);
14
+ const toolCallId = typeof body.toolCallId === 'string' ? body.toolCallId.trim() : '';
15
+ const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
16
+ ? body.sessionId.trim()
17
+ : '';
18
+ const approved = body.approved === true;
19
+ const remember = body.remember === true;
20
+ const toolName = typeof body.tool === 'string' ? body.tool.trim().slice(0, 80) : '';
21
+ const targetRun = ctx.findActiveRun(sessionId || null);
22
+ if (!toolCallId || !targetRun?.loop.resolveApproval) {
23
+ sendJson(res, 400, { error: 'No active pending approval matches that toolCallId.' });
24
+ return true;
25
+ }
26
+ if (approved && remember && toolName && targetRun.loop.grantAlways) {
27
+ targetRun.loop.grantAlways(toolName);
28
+ auditLog.log({ event: 'skybridge_approval_grant_always', tool: toolName });
29
+ }
30
+ targetRun.status = 'running';
31
+ targetRun.loop.resolveApproval(toolCallId, approved);
32
+ sendJson(res, 200, { ok: true, toolCallId, approved, remembered: Boolean(approved && remember && toolName) });
33
+ return true;
34
+ }
35
+ if (req.method === 'POST' && pathname === '/api/decision') {
36
+ const body = await readJsonBody(req);
37
+ const requestId = typeof body.requestId === 'string' ? body.requestId.trim() : '';
38
+ const sessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
39
+ ? body.sessionId.trim()
40
+ : '';
41
+ const label = typeof body.label === 'string' ? body.label.trim().slice(0, 400) : '';
42
+ const optionId = typeof body.optionId === 'string' ? body.optionId.trim().slice(0, 120) : null;
43
+ const custom = body.custom === true;
44
+ const targetRun = ctx.findActiveRun(sessionId || null);
45
+ if (!requestId || !targetRun?.loop.resolveDecision) {
46
+ sendJson(res, 400, { error: 'No active pending decision matches that requestId.' });
47
+ return true;
48
+ }
49
+ targetRun.status = 'running';
50
+ targetRun.loop.resolveDecision(requestId, label ? { optionId, label, custom } : null);
51
+ sendJson(res, 200, { ok: true, requestId, label });
52
+ return true;
53
+ }
54
+ if (req.method === 'POST' && pathname === '/api/stop') {
55
+ let stopSessionId = '';
56
+ try {
57
+ const body = await readJsonBody(req);
58
+ if (typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())) {
59
+ stopSessionId = body.sessionId.trim();
60
+ }
61
+ }
62
+ catch {
63
+ // Empty body is valid for /api/stop.
64
+ }
65
+ if (stopSessionId) {
66
+ const run = ctx.activeRuns.get(stopSessionId);
67
+ if (run) {
68
+ run.userStopped = true;
69
+ run.loop.abort?.();
70
+ }
71
+ }
72
+ else {
73
+ for (const run of ctx.activeRuns.values()) {
74
+ run.userStopped = true;
75
+ run.loop.abort?.();
76
+ }
77
+ }
78
+ sendJson(res, 200, { ok: true });
79
+ return true;
80
+ }
81
+ if (req.method === 'POST' && pathname === '/api/chat') {
82
+ const body = await readJsonBody(req);
83
+ const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';
84
+ const requestedSessionId = typeof body.sessionId === 'string' && SAFE_SESSION_ID_RE.test(body.sessionId.trim())
85
+ ? body.sessionId.trim()
86
+ : '';
87
+ const explicitPreset = normalizePermissionPreset(body.permissionPreset)
88
+ ?? normalizePermissionPreset(body.mode);
89
+ const resolvedPreset = explicitPreset ?? getSessionPermissionPreset(requestedSessionId || null);
90
+ const mode = presetToAutonomyMode(resolvedPreset);
91
+ const providerOverride = typeof body.provider === 'string' && SAFE_PROVIDER_RE.test(body.provider.trim())
92
+ ? body.provider.trim()
93
+ : undefined;
94
+ const modelOverride = typeof body.model === 'string' && SAFE_MODEL_RE.test(body.model.trim())
95
+ ? body.model.trim()
96
+ : undefined;
97
+ if (!prompt) {
98
+ sendJson(res, 400, { error: 'Prompt text is required.' });
99
+ return true;
100
+ }
101
+ let boundSession = requestedSessionId ? getSession(requestedSessionId) : null;
102
+ if (boundSession && !workspaceMatchesSession(boundSession.workspace, workspaceRoot)) {
103
+ boundSession = null;
104
+ }
105
+ if (!boundSession && !ctx.hasCustomFactory) {
106
+ boundSession = createSession(workspaceRoot, prompt.slice(0, 60), false);
107
+ }
108
+ if (boundSession && explicitPreset) {
109
+ setSessionPermissionPreset(boundSession.id, resolvedPreset);
110
+ }
111
+ const runKey = boundSession?.id || '__ephemeral__';
112
+ const existingRun = ctx.activeRuns.get(runKey);
113
+ if (existingRun && (existingRun.status === 'running' || existingRun.status === 'awaiting_client')) {
114
+ sendJson(res, 409, {
115
+ error: 'This conversation already has a task running. Stop it or wait for completion.'
116
+ });
117
+ return true;
118
+ }
119
+ const { effectivePrompt, attachedPaths } = buildWorkspacePromptWithAttachments(workspaceRoot, prompt, body.attachments);
120
+ const taskId = ctx.nextTaskId();
121
+ let collectedAssistantText = '';
122
+ let runRef = null;
123
+ const emitFrame = (raw) => {
124
+ const clean = raw.replace(/\r?\n/g, ' ');
125
+ try {
126
+ const parsed = JSON.parse(clean);
127
+ if (parsed.type === 'agent_chunk' && typeof parsed.delta === 'string') {
128
+ collectedAssistantText += parsed.delta;
129
+ }
130
+ else if (parsed.type === 'agent_message' && typeof parsed.content === 'string' && !collectedAssistantText) {
131
+ collectedAssistantText = parsed.content;
132
+ }
133
+ if (runRef && (parsed.type === 'approval_request' || parsed.type === 'decision_request')) {
134
+ runRef.status = 'awaiting_client';
135
+ }
136
+ const toolLower = typeof parsed.tool === 'string' ? parsed.tool.toLowerCase() : '';
137
+ const actionLower = typeof parsed.actionName === 'string' ? parsed.actionName.toLowerCase() : '';
138
+ if (boundSession?.id) {
139
+ if (parsed.type === 'code_progress' && typeof parsed.path === 'string') {
140
+ ctx.recordSessionTouchedFile(boundSession.id, parsed.path);
141
+ }
142
+ else if ((parsed.type === 'step_complete' || parsed.type === 'tool_result')
143
+ && MUTATING_FILE_TOOLS.has(toolLower)
144
+ && parsed.args) {
145
+ for (const key of ['path', 'filePath', 'file_path', 'targetFile', 'filename', 'file', 'destination']) {
146
+ ctx.recordSessionTouchedFile(boundSession.id, parsed.args[key]);
147
+ }
148
+ }
149
+ else if (parsed.type === 'notice' && MUTATING_FILE_TOOLS.has(actionLower) && parsed.detail) {
150
+ ctx.recordSessionTouchedFile(boundSession.id, parsed.detail);
151
+ }
152
+ }
153
+ const isBrowserTool = toolLower.includes('browser');
154
+ const isComputerTool = toolLower.includes('computer_use') || toolLower.includes('desktop_act');
155
+ if ((parsed.type === 'step_start' || parsed.type === 'tool_start') && (isBrowserTool || isComputerTool)) {
156
+ if (isBrowserTool)
157
+ ctx.setBrowserControlOwner('agent');
158
+ const detail = isBrowserTool && Array.isArray(parsed.args?.actions) && parsed.args.actions[0]
159
+ ? String(parsed.args.actions[0].type || 'browser.act')
160
+ : String(parsed.args?.action || parsed.tool || '');
161
+ ctx.setBrowserAgentActivity({
162
+ active: true,
163
+ tool: parsed.tool || 'browser.act',
164
+ detail: detail.slice(0, 80),
165
+ updatedAt: Date.now()
166
+ });
167
+ ctx.broadcastBrowserNotice({
168
+ type: 'agent_activity',
169
+ controlOwner: ctx.getBrowserControlOwner(),
170
+ agentActivity: ctx.getBrowserAgentActivity()
171
+ });
172
+ }
173
+ else if ((parsed.type === 'step_complete' || parsed.type === 'step_error' || parsed.type === 'tool_complete')
174
+ && (isBrowserTool || isComputerTool)) {
175
+ ctx.setBrowserAgentActivity({ active: false, tool: '', detail: '', updatedAt: Date.now() });
176
+ ctx.broadcastBrowserNotice({
177
+ type: 'agent_activity',
178
+ controlOwner: ctx.getBrowserControlOwner(),
179
+ agentActivity: ctx.getBrowserAgentActivity()
180
+ });
181
+ }
182
+ }
183
+ catch {
184
+ // pass raw frame through untouched
185
+ }
186
+ if (runRef)
187
+ ctx.pushRunFrame(runRef, clean);
188
+ };
189
+ const wrappedSink = { readyState: 1, send: emitFrame };
190
+ const loop = ctx.loopFactory(wrappedSink, taskId, effectivePrompt, {
191
+ workspaceRoot,
192
+ mode,
193
+ permissionPreset: resolvedPreset,
194
+ sessionId: boundSession?.id,
195
+ provider: providerOverride,
196
+ model: modelOverride
197
+ });
198
+ const run = {
199
+ key: runKey,
200
+ sessionId: boundSession?.id || null,
201
+ taskId,
202
+ prompt,
203
+ startedAt: Date.now(),
204
+ status: 'running',
205
+ userStopped: false,
206
+ loop,
207
+ frames: [],
208
+ bufferedBytes: 0,
209
+ subscribers: new Set(),
210
+ doneSubscribers: new Set()
211
+ };
212
+ runRef = run;
213
+ ctx.activeRuns.set(runKey, run);
214
+ if (boundSession) {
215
+ ctx.pushRunFrame(run, JSON.stringify({
216
+ type: 'session_bound',
217
+ sessionId: boundSession.id,
218
+ title: boundSession.title,
219
+ attachments: attachedPaths
220
+ }));
221
+ }
222
+ ctx.attachRunStream(req, res, run, true);
223
+ void (async () => {
224
+ try {
225
+ await loop.run();
226
+ if (boundSession && ctx.hasCustomFactory && collectedAssistantText.trim()) {
227
+ const latest = getSession(boundSession.id);
228
+ if (latest) {
229
+ const nextMessages = [
230
+ ...latest.messages,
231
+ { role: 'user', content: prompt },
232
+ { role: 'assistant', content: collectedAssistantText.trim() }
233
+ ];
234
+ saveSessionMessages(boundSession.id, nextMessages);
235
+ }
236
+ }
237
+ const refreshed = boundSession ? getSession(boundSession.id) : null;
238
+ if (run.userStopped) {
239
+ run.status = 'stopped';
240
+ ctx.pushRunFrame(run, JSON.stringify({
241
+ type: 'stopped',
242
+ taskId,
243
+ sessionId: boundSession?.id || null,
244
+ title: refreshed?.title || boundSession?.title || null,
245
+ userStopped: true
246
+ }));
247
+ }
248
+ else {
249
+ run.status = 'completed';
250
+ ctx.pushRunFrame(run, JSON.stringify({
251
+ type: 'done',
252
+ taskId,
253
+ sessionId: boundSession?.id || null,
254
+ title: refreshed?.title || boundSession?.title || null
255
+ }));
256
+ }
257
+ }
258
+ catch (err) {
259
+ run.status = run.userStopped ? 'stopped' : 'errored';
260
+ if (run.userStopped) {
261
+ ctx.pushRunFrame(run, JSON.stringify({
262
+ type: 'stopped',
263
+ taskId,
264
+ sessionId: boundSession?.id || null,
265
+ userStopped: true
266
+ }));
267
+ }
268
+ else if (err instanceof EntitlementAccessError && err.code === 'DAILY_LIMIT_REACHED') {
269
+ ctx.pushRunFrame(run, JSON.stringify({
270
+ type: 'error',
271
+ code: 'DAILY_LIMIT_REACHED',
272
+ message: err.message || DAILY_LIMIT_SUPPORT_MESSAGE
273
+ }));
274
+ }
275
+ else {
276
+ auditLog.log({
277
+ event: 'skybridge_chat_error',
278
+ taskId,
279
+ detail: redactProviderSecrets(err instanceof Error ? err.message : String(err)).slice(0, 300)
280
+ });
281
+ ctx.pushRunFrame(run, JSON.stringify({
282
+ type: 'error',
283
+ message: 'Task failed. Inspect local audit log or run `/doctor --report` for sanitized details.'
284
+ }));
285
+ }
286
+ }
287
+ finally {
288
+ for (const doneCb of [...run.doneSubscribers]) {
289
+ try {
290
+ doneCb();
291
+ }
292
+ catch { /* ignore */ }
293
+ }
294
+ run.subscribers.clear();
295
+ run.doneSubscribers.clear();
296
+ if (ctx.activeRuns.get(runKey) === run) {
297
+ ctx.activeRuns.delete(runKey);
298
+ }
299
+ }
300
+ })();
301
+ return true;
302
+ }
303
+ return false;
304
+ }