@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,435 @@
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
+ let frame = await browser.captureLiveFrame({ ensureStarted: true });
230
+ const reqW = Number(body.width);
231
+ const reqH = Number(body.height);
232
+ if (frame.active && Number.isFinite(reqW) && Number.isFinite(reqH) && reqW >= 320 && reqH >= 240) {
233
+ const width = Math.max(320, Math.min(2560, Math.round(reqW)));
234
+ const height = Math.max(240, Math.min(1440, Math.round(reqH)));
235
+ try {
236
+ await browser.run([{ type: 'viewport', width, height }], { workspace: workspaceRoot });
237
+ frame = await browser.captureLiveFrame({ ensureStarted: false });
238
+ } catch {
239
+ // Keep started frame if viewport resize raced with close.
240
+ }
241
+ }
242
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
243
+ return true;
244
+ }
245
+ if (action === 'close') {
246
+ const frame = await browser.closeLiveSession();
247
+ ctx.broadcastBrowserNotice({
248
+ type: 'closed',
249
+ controlOwner: ctx.getBrowserControlOwner(),
250
+ ...frame
251
+ });
252
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
253
+ return true;
254
+ }
255
+ if (action === 'goto' || action === 'newTab') {
256
+ ctx.setBrowserControlOwner('human');
257
+ let rawUrl = typeof body.url === 'string' ? body.url.trim() : '';
258
+ if (rawUrl.startsWith('@')) {
259
+ const idx = rawUrl.indexOf(' ');
260
+ const macro = idx === -1 ? rawUrl : rawUrl.slice(0, idx);
261
+ const q = idx === -1 ? '' : rawUrl.slice(idx + 1).trim();
262
+ const expanded = expandSearchMacro(macro, q);
263
+ if (!expanded) {
264
+ sendJson(res, 400, { error: 'Unsupported browser search macro.' });
265
+ return true;
266
+ }
267
+ rawUrl = expanded;
268
+ } else if (rawUrl && !/^https?:\/\//i.test(rawUrl)) {
269
+ rawUrl = rawUrl.includes('.') || rawUrl.startsWith('localhost')
270
+ ? `https://${rawUrl}`
271
+ : (expandSearchMacro('@duckduckgo_search', rawUrl) || `https://duckduckgo.com/?q=${encodeURIComponent(rawUrl)}`);
272
+ }
273
+ const actions: Array<{ type: 'viewport'; width: number; height: number } | { type: 'newTab'; url?: string } | { type: 'goto'; url: string }> = [
274
+ action === 'newTab'
275
+ ? { type: 'newTab', ...(rawUrl ? { url: rawUrl } : {}) }
276
+ : { type: 'goto', url: rawUrl || 'about:blank' }
277
+ ];
278
+ const reqW = Number(body.width);
279
+ const reqH = Number(body.height);
280
+ if (Number.isFinite(reqW) && Number.isFinite(reqH) && reqW >= 320 && reqH >= 240) {
281
+ actions.push({
282
+ type: 'viewport',
283
+ width: Math.max(320, Math.min(2560, Math.round(reqW))),
284
+ height: Math.max(240, Math.min(1440, Math.round(reqH)))
285
+ });
286
+ }
287
+ await browser.run(actions, { workspace: workspaceRoot });
288
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
289
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
290
+ return true;
291
+ }
292
+ if (action === 'back' || action === 'forward' || action === 'reload') {
293
+ ctx.setBrowserControlOwner('human');
294
+ await browser.run([{ type: action }], { workspace: workspaceRoot });
295
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
296
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
297
+ return true;
298
+ }
299
+ if (action === 'switchTab' && typeof body.tabId === 'string' && body.tabId.trim()) {
300
+ ctx.setBrowserControlOwner('human');
301
+ await browser.run([{ type: 'switchTab', tabId: body.tabId.trim() }], { workspace: workspaceRoot });
302
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
303
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
304
+ return true;
305
+ }
306
+ if (action === 'closeTab' && typeof body.tabId === 'string' && body.tabId.trim()) {
307
+ ctx.setBrowserControlOwner('human');
308
+ const frame = await browser.closeLiveTab(body.tabId.trim());
309
+ if (!frame.active) {
310
+ ctx.broadcastBrowserNotice({
311
+ type: 'closed',
312
+ controlOwner: ctx.getBrowserControlOwner(),
313
+ ...frame
314
+ });
315
+ }
316
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
317
+ return true;
318
+ }
319
+ if (action === 'viewport') {
320
+ const pre = await browser.captureLiveFrame({ ensureStarted: false });
321
+ if (!pre.active) {
322
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...pre });
323
+ return true;
324
+ }
325
+ const width = Math.max(320, Math.min(2560, Math.round(Number(body.width) || 1280)));
326
+ const height = Math.max(240, Math.min(1440, Math.round(Number(body.height) || 800)));
327
+ try {
328
+ await browser.run([{ type: 'viewport', width, height }], { workspace: workspaceRoot });
329
+ } catch {
330
+ // Browser closed concurrently during resize; return current closed state cleanly.
331
+ }
332
+ const frame = await browser.captureLiveFrame({ ensureStarted: false });
333
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
334
+ return true;
335
+ }
336
+ if (action === 'snapshot') {
337
+ const snap = await browser.snapshot(0);
338
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
339
+ sendJson(res, 200, {
340
+ ok: true,
341
+ controlOwner: ctx.getBrowserControlOwner(),
342
+ snapshot: snap.text,
343
+ refsCount: snap.refsCount,
344
+ ...frame
345
+ });
346
+ return true;
347
+ }
348
+ if (ALLOWED_INPUT_KINDS.has(action)) {
349
+ ctx.setBrowserControlOwner('human');
350
+ const frame = await browser.interactAt({
351
+ kind: action as LiveBrowserInteraction['kind'],
352
+ x: typeof body.x === 'number' ? body.x : undefined,
353
+ y: typeof body.y === 'number' ? body.y : undefined,
354
+ deltaX: typeof body.deltaX === 'number' ? body.deltaX : undefined,
355
+ deltaY: typeof body.deltaY === 'number' ? body.deltaY : undefined,
356
+ text: typeof body.text === 'string' ? body.text : undefined,
357
+ key: typeof body.key === 'string' ? body.key : undefined,
358
+ button: body.button === 'right' || body.button === 'middle' ? body.button : 'left'
359
+ });
360
+ sendJson(res, 200, {
361
+ ok: true,
362
+ controlOwner: ctx.getBrowserControlOwner(),
363
+ agentActivity: ctx.getBrowserAgentActivity(),
364
+ ...frame
365
+ });
366
+ return true;
367
+ }
368
+ sendJson(res, 400, { error: 'Unsupported shared browser action.' });
369
+ return true;
370
+ }
371
+
372
+ if (req.method === 'GET' && pathname === '/api/browser/cdp/tabs') {
373
+ const portParam = parsedUrl.searchParams.get('port') || '9222';
374
+ const discovered = await discoverLocalCdpTabs(portParam);
375
+ sendJson(res, 200, {
376
+ ok: true,
377
+ port: discovered.port,
378
+ tabs: discovered.tabs.map((t) => ({ id: t.id, title: t.title, url: t.url }))
379
+ });
380
+ return true;
381
+ }
382
+
383
+ if (req.method === 'POST' && pathname === '/api/browser/cdp/sync') {
384
+ const body = await readJsonBody(req);
385
+ const targetId = typeof body.targetId === 'string' ? body.targetId.trim() : '';
386
+ if (!targetId) {
387
+ sendJson(res, 400, { error: 'targetId is required to sync a local browser tab.' });
388
+ return true;
389
+ }
390
+ const synced = await syncLocalCdpTabToCausyne({
391
+ workspaceRoot,
392
+ port: body.port ?? 9222,
393
+ targetId,
394
+ includeCookies: body.includeCookies === true
395
+ });
396
+ ctx.setBrowserControlOwner('human');
397
+ auditLog.log({
398
+ event: 'skybridge_browser_cdp_sync',
399
+ importedCookies: synced.importedCookies
400
+ });
401
+ sendJson(res, 200, {
402
+ ok: true,
403
+ controlOwner: ctx.getBrowserControlOwner(),
404
+ syncedUrl: synced.syncedUrl,
405
+ importedCookies: synced.importedCookies,
406
+ ...synced.frame
407
+ });
408
+ return true;
409
+ }
410
+
411
+ if (req.method === 'POST' && pathname === '/api/browser/import') {
412
+ const body = await readJsonBody(req);
413
+ const rawText = typeof body.rawText === 'string' ? body.rawText : '';
414
+ const summary = await importExplicitUserBrowserData({
415
+ workspaceRoot,
416
+ rawText,
417
+ openFirstUrl: body.openFirstUrl !== false
418
+ });
419
+ const frame = await causyneBrowser({ workspace: workspaceRoot }).captureLiveFrame({ ensureStarted: false });
420
+ auditLog.log({
421
+ event: 'skybridge_browser_import',
422
+ importedCookies: summary.importedCookies,
423
+ urlsCount: summary.importedUrls.length
424
+ });
425
+ sendJson(res, 200, {
426
+ ok: true,
427
+ controlOwner: ctx.getBrowserControlOwner(),
428
+ ...summary,
429
+ ...frame
430
+ });
431
+ return true;
432
+ }
433
+
434
+ return false;
435
+ }