@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,171 @@
1
+ import type http from 'node:http';
2
+ import { AgentLoop } from '../../agentLoop.js';
3
+ import type { createApprovalScope } from '../../approvalGrants.js';
4
+ import type { McpServer } from '../../acp/protocol.js';
5
+ import { CAUSYNE_BROWSER_MCP_NAME } from '../skybridgeBrowserMcp.js';
6
+ import type {
7
+ SessionActiveRun,
8
+ SkybridgeDecisionAnswer,
9
+ SkybridgeLoopFactory
10
+ } from './types.js';
11
+
12
+ const MAX_RUN_BUFFERED_FRAMES = 2400;
13
+ const MAX_RUN_BUFFERED_BYTES = 2 * 1024 * 1024;
14
+ const STREAM_HEARTBEAT_MS = 15_000;
15
+
16
+ export function createDefaultLoopFactory(
17
+ serverApprovalScope: ReturnType<typeof createApprovalScope>,
18
+ getBoundPort: () => number,
19
+ token: string
20
+ ): SkybridgeLoopFactory {
21
+ const buildSharedBrowserPeerMcp = (): McpServer[] => {
22
+ const port = getBoundPort();
23
+ if (!port) return [];
24
+ return [{
25
+ type: 'http',
26
+ name: CAUSYNE_BROWSER_MCP_NAME,
27
+ url: `http://127.0.0.1:${port}/api/mcp/browser`,
28
+ headers: [{ name: 'Authorization', value: `Bearer ${token}` }]
29
+ }];
30
+ };
31
+
32
+ return (sink, taskId, prompt, opts) => {
33
+ const loopOptions: {
34
+ workspaceRoot: string;
35
+ memorySessionId?: string | null;
36
+ provider?: string;
37
+ model?: string;
38
+ approvalScope?: ReturnType<typeof createApprovalScope>;
39
+ peerMcpServers?: McpServer[];
40
+ } = {
41
+ workspaceRoot: opts.workspaceRoot,
42
+ approvalScope: serverApprovalScope,
43
+ peerMcpServers: buildSharedBrowserPeerMcp()
44
+ };
45
+ if (opts.sessionId) loopOptions.memorySessionId = opts.sessionId;
46
+ if (opts.provider) loopOptions.provider = opts.provider;
47
+ if (opts.model) loopOptions.model = opts.model;
48
+
49
+ const loop = new AgentLoop(sink, taskId, prompt, loopOptions);
50
+ if (typeof opts.permissionPreset === 'string' && opts.permissionPreset) {
51
+ try {
52
+ loop.setPermissionPreset(opts.permissionPreset);
53
+ } catch {
54
+ // Fallback to mode normalization below.
55
+ }
56
+ } else if (opts.mode === 'A' || opts.mode === 'B' || opts.mode === 'C') {
57
+ try {
58
+ loop.setAutonomyMode(opts.mode);
59
+ } catch {
60
+ // Fallback when custom mode normalization differs.
61
+ }
62
+ }
63
+
64
+ const pendingDecisions = new Map<string, (answer: SkybridgeDecisionAnswer | null) => void>();
65
+ loop.waitForDecision = (request: any) => {
66
+ const reqId = typeof request?.id === 'string' && request.id ? request.id : `dec_${Date.now()}`;
67
+ return new Promise<SkybridgeDecisionAnswer | null>((resolve) => {
68
+ pendingDecisions.set(reqId, resolve);
69
+ });
70
+ };
71
+
72
+ return {
73
+ run: () => loop.run(),
74
+ abort: () => {
75
+ for (const [, resolve] of pendingDecisions) {
76
+ try { resolve(null); } catch { /* ignore */ }
77
+ }
78
+ pendingDecisions.clear();
79
+ loop.abort();
80
+ },
81
+ resolveApproval: (toolCallId: string, approved: boolean) => {
82
+ const resolver = loop.pendingApprovals.get(toolCallId);
83
+ if (resolver) resolver(approved);
84
+ },
85
+ resolveDecision: (requestId: string, answer: SkybridgeDecisionAnswer | null) => {
86
+ const resolver = pendingDecisions.get(requestId);
87
+ if (resolver) {
88
+ pendingDecisions.delete(requestId);
89
+ resolver(answer);
90
+ }
91
+ },
92
+ grantAlways: (toolName: string) => {
93
+ serverApprovalScope.grantAlways(toolName);
94
+ }
95
+ };
96
+ };
97
+ }
98
+
99
+ export function pushRunFrame(run: SessionActiveRun, raw: string): void {
100
+ const clean = raw.replace(/\r?\n/g, ' ');
101
+ const frameBytes = Buffer.byteLength(clean, 'utf8');
102
+ if (run.frames.length < MAX_RUN_BUFFERED_FRAMES && run.bufferedBytes + frameBytes <= MAX_RUN_BUFFERED_BYTES) {
103
+ run.frames.push(clean);
104
+ run.bufferedBytes += frameBytes;
105
+ }
106
+ for (const send of run.subscribers) {
107
+ try {
108
+ send(clean);
109
+ } catch {
110
+ // Isolate subscriber write failures so detached runs continue uninterrupted.
111
+ }
112
+ }
113
+ }
114
+
115
+ export function attachRunStream(
116
+ req: http.IncomingMessage,
117
+ res: http.ServerResponse,
118
+ run: SessionActiveRun,
119
+ replayBuffered: boolean
120
+ ): void {
121
+ req.setTimeout(0);
122
+ res.setTimeout(0);
123
+ try { req.socket?.setKeepAlive(true, STREAM_HEARTBEAT_MS); } catch { /* ignore */ }
124
+ res.statusCode = 200;
125
+ res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
126
+ res.setHeader('Transfer-Encoding', 'chunked');
127
+ res.setHeader('Cache-Control', 'no-store');
128
+ res.setHeader('X-Accel-Buffering', 'no');
129
+ res.flushHeaders?.();
130
+
131
+ const writeLine = (cleanFrame: string): void => {
132
+ if (res.writableEnded || res.destroyed) return;
133
+ res.write(`${cleanFrame}\n`);
134
+ };
135
+
136
+ const heartbeatTimer = setInterval(() => {
137
+ if (res.writableEnded || res.destroyed) return;
138
+ writeLine(JSON.stringify({ type: 'heartbeat', ts: Date.now() }));
139
+ }, STREAM_HEARTBEAT_MS);
140
+ heartbeatTimer.unref?.();
141
+
142
+ let detached = false;
143
+ const detach = (): void => {
144
+ if (detached) return;
145
+ detached = true;
146
+ clearInterval(heartbeatTimer);
147
+ run.subscribers.delete(writeLine);
148
+ run.doneSubscribers.delete(finishResponse);
149
+ };
150
+
151
+ const finishResponse = (): void => {
152
+ detach();
153
+ if (!res.writableEnded && !res.destroyed) res.end();
154
+ };
155
+
156
+ // Disconnecting a tab only unsubscribes this HTTP response; POST /api/stop cancels the run.
157
+ res.on('close', detach);
158
+
159
+ if (replayBuffered) {
160
+ for (const frame of run.frames) {
161
+ writeLine(frame);
162
+ }
163
+ }
164
+
165
+ if (run.status === 'running' || run.status === 'awaiting_client') {
166
+ run.subscribers.add(writeLine);
167
+ run.doneSubscribers.add(finishResponse);
168
+ } else {
169
+ finishResponse();
170
+ }
171
+ }
@@ -0,0 +1,355 @@
1
+ import { auditLog } from '../../auditLog.js';
2
+ import { causyneBrowser, expandSearchMacro } from '../../browser/causyneBrowser.js';
3
+ import { discoverLocalCdpTabs, importExplicitUserBrowserData, syncLocalCdpTabToCausyne } from '../skybridgeBrowserBridge.js';
4
+ import { handleBrowserMcpRpc } from '../skybridgeBrowserMcp.js';
5
+ import { readJsonBody, sendJson } from './security.js';
6
+ const ALLOWED_INPUT_KINDS = new Set([
7
+ 'click', 'dblclick', 'contextmenu', 'mousedown', 'mousemove', 'mouseup', 'wheel', 'type', 'key', 'paste'
8
+ ]);
9
+ export async function handleBrowserRoutes(req, res, parsedUrl, ctx) {
10
+ const pathname = parsedUrl.pathname;
11
+ const { workspaceRoot, version } = ctx;
12
+ if (req.method === 'GET' && pathname === '/api/mcp/browser') {
13
+ res.statusCode = 405;
14
+ res.setHeader('Allow', 'POST');
15
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
16
+ res.end(JSON.stringify({ error: 'Use POST for Streamable HTTP MCP JSON-RPC requests.' }));
17
+ return true;
18
+ }
19
+ if (req.method === 'POST' && pathname === '/api/mcp/browser') {
20
+ const body = await readJsonBody(req);
21
+ const reply = await handleBrowserMcpRpc(body, {
22
+ workspaceRoot,
23
+ version,
24
+ onActivity: (activity) => {
25
+ if (activity.phase === 'start') {
26
+ ctx.setBrowserControlOwner('agent');
27
+ ctx.setBrowserAgentActivity({
28
+ active: true,
29
+ tool: activity.tool,
30
+ detail: activity.detail,
31
+ updatedAt: Date.now()
32
+ });
33
+ }
34
+ else {
35
+ ctx.setBrowserAgentActivity({ active: false, tool: '', detail: '', updatedAt: Date.now() });
36
+ }
37
+ ctx.broadcastBrowserNotice({
38
+ type: 'agent_activity',
39
+ controlOwner: ctx.getBrowserControlOwner(),
40
+ agentActivity: ctx.getBrowserAgentActivity()
41
+ });
42
+ }
43
+ });
44
+ if (reply === null) {
45
+ res.statusCode = 202;
46
+ res.end();
47
+ return true;
48
+ }
49
+ sendJson(res, 200, reply);
50
+ return true;
51
+ }
52
+ if (req.method === 'GET' && pathname === '/api/browser/state') {
53
+ const ensure = parsedUrl.searchParams.get('ensure') === '1';
54
+ const browser = causyneBrowser({ workspace: workspaceRoot });
55
+ const frame = await browser.captureLiveFrame({ ensureStarted: ensure });
56
+ sendJson(res, 200, {
57
+ ok: true,
58
+ controlOwner: ctx.getBrowserControlOwner(),
59
+ agentActivity: ctx.getBrowserAgentActivity(),
60
+ computerUsePolicy: 'tiered-approval',
61
+ ...frame
62
+ });
63
+ return true;
64
+ }
65
+ if (req.method === 'GET' && pathname === '/api/browser/stream') {
66
+ const browser = causyneBrowser({ workspace: workspaceRoot });
67
+ res.statusCode = 200;
68
+ res.setHeader('Content-Type', 'application/x-ndjson; charset=utf-8');
69
+ res.setHeader('Transfer-Encoding', 'chunked');
70
+ res.setHeader('X-Accel-Buffering', 'no');
71
+ const writeStreamLine = (payload) => {
72
+ if (res.writableEnded || res.destroyed)
73
+ return;
74
+ try {
75
+ res.write(`${JSON.stringify(payload)}\n`);
76
+ }
77
+ catch {
78
+ // Stream closed mid-write.
79
+ }
80
+ };
81
+ const unsub = browser.subscribeLiveStream((ev) => {
82
+ writeStreamLine({
83
+ ...ev,
84
+ controlOwner: ctx.getBrowserControlOwner(),
85
+ agentActivity: ctx.getBrowserAgentActivity(),
86
+ computerUsePolicy: 'tiered-approval'
87
+ });
88
+ });
89
+ ctx.browserStreamClients.add(writeStreamLine);
90
+ writeStreamLine({
91
+ type: 'agent_activity',
92
+ controlOwner: ctx.getBrowserControlOwner(),
93
+ agentActivity: ctx.getBrowserAgentActivity(),
94
+ computerUsePolicy: 'tiered-approval'
95
+ });
96
+ const keepAlive = setInterval(() => {
97
+ writeStreamLine({ type: 'ping', ts: Date.now() });
98
+ }, 15_000);
99
+ keepAlive.unref?.();
100
+ const cleanup = () => {
101
+ clearInterval(keepAlive);
102
+ ctx.browserStreamClients.delete(writeStreamLine);
103
+ unsub();
104
+ };
105
+ req.on('close', cleanup);
106
+ res.on('close', cleanup);
107
+ return true;
108
+ }
109
+ if (req.method === 'POST' && pathname === '/api/browser/input') {
110
+ const body = await readJsonBody(req);
111
+ const kind = typeof body.kind === 'string' ? body.kind.trim() : '';
112
+ if (!ALLOWED_INPUT_KINDS.has(kind)) {
113
+ sendJson(res, 400, { error: 'Unsupported live browser input kind.' });
114
+ return true;
115
+ }
116
+ ctx.setBrowserControlOwner('human');
117
+ const browser = causyneBrowser({ workspace: workspaceRoot });
118
+ const result = await browser.dispatchLiveInput({
119
+ kind: kind,
120
+ x: typeof body.x === 'number' ? body.x : undefined,
121
+ y: typeof body.y === 'number' ? body.y : undefined,
122
+ deltaX: typeof body.deltaX === 'number' ? body.deltaX : undefined,
123
+ deltaY: typeof body.deltaY === 'number' ? body.deltaY : undefined,
124
+ text: typeof body.text === 'string' ? body.text : undefined,
125
+ key: typeof body.key === 'string' ? body.key : undefined,
126
+ button: body.button === 'right' || body.button === 'middle' ? body.button : 'left',
127
+ skipFrame: true
128
+ });
129
+ sendJson(res, 200, { ok: result.ok, controlOwner: ctx.getBrowserControlOwner() });
130
+ return true;
131
+ }
132
+ if (req.method === 'POST' && pathname === '/api/browser/action') {
133
+ const body = await readJsonBody(req);
134
+ const action = typeof body.action === 'string' ? body.action.trim() : '';
135
+ const browser = causyneBrowser({ workspace: workspaceRoot });
136
+ if (action === 'setMode') {
137
+ ctx.setBrowserControlOwner('human');
138
+ const rawPref = typeof body.enginePreference === 'string' ? body.enginePreference.trim() : '';
139
+ const enginePreference = rawPref === 'camoufox'
140
+ || rawPref === 'chromium'
141
+ || rawPref === 'auto'
142
+ ? rawPref
143
+ : undefined;
144
+ const frame = await browser.setDisplayMode({
145
+ visible: typeof body.visible === 'boolean' ? body.visible : undefined,
146
+ enginePreference,
147
+ ensureStarted: body.ensureStarted === true
148
+ });
149
+ auditLog.log({
150
+ event: 'skybridge_browser_mode_switch',
151
+ visible: frame.visible,
152
+ engine: frame.engine,
153
+ enginePreference: frame.enginePreference
154
+ });
155
+ ctx.broadcastBrowserNotice({
156
+ type: 'meta',
157
+ controlOwner: ctx.getBrowserControlOwner(),
158
+ agentActivity: ctx.getBrowserAgentActivity(),
159
+ ...frame
160
+ });
161
+ sendJson(res, 200, {
162
+ ok: true,
163
+ controlOwner: ctx.getBrowserControlOwner(),
164
+ agentActivity: ctx.getBrowserAgentActivity(),
165
+ ...frame
166
+ });
167
+ return true;
168
+ }
169
+ if (action === 'takeControl') {
170
+ ctx.setBrowserControlOwner('human');
171
+ ctx.setBrowserAgentActivity({ active: false, tool: '', detail: '', updatedAt: Date.now() });
172
+ const frame = await browser.captureLiveFrame({ ensureStarted: false });
173
+ ctx.broadcastBrowserNotice({
174
+ type: 'agent_activity',
175
+ controlOwner: ctx.getBrowserControlOwner(),
176
+ agentActivity: ctx.getBrowserAgentActivity()
177
+ });
178
+ sendJson(res, 200, {
179
+ ok: true,
180
+ controlOwner: ctx.getBrowserControlOwner(),
181
+ agentActivity: ctx.getBrowserAgentActivity(),
182
+ ...frame
183
+ });
184
+ return true;
185
+ }
186
+ if (action === 'handToAgent') {
187
+ ctx.setBrowserControlOwner('agent');
188
+ const frame = await browser.captureLiveFrame({ ensureStarted: false });
189
+ ctx.broadcastBrowserNotice({
190
+ type: 'agent_activity',
191
+ controlOwner: ctx.getBrowserControlOwner(),
192
+ agentActivity: ctx.getBrowserAgentActivity()
193
+ });
194
+ sendJson(res, 200, {
195
+ ok: true,
196
+ controlOwner: ctx.getBrowserControlOwner(),
197
+ agentActivity: ctx.getBrowserAgentActivity(),
198
+ ...frame
199
+ });
200
+ return true;
201
+ }
202
+ if (action === 'start') {
203
+ ctx.setBrowserControlOwner('human');
204
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
205
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
206
+ return true;
207
+ }
208
+ if (action === 'close') {
209
+ await browser.close();
210
+ const frame = await browser.captureLiveFrame({ ensureStarted: false });
211
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
212
+ return true;
213
+ }
214
+ if (action === 'goto' || action === 'newTab') {
215
+ ctx.setBrowserControlOwner('human');
216
+ let rawUrl = typeof body.url === 'string' ? body.url.trim() : '';
217
+ if (rawUrl.startsWith('@')) {
218
+ const idx = rawUrl.indexOf(' ');
219
+ const macro = idx === -1 ? rawUrl : rawUrl.slice(0, idx);
220
+ const q = idx === -1 ? '' : rawUrl.slice(idx + 1).trim();
221
+ const expanded = expandSearchMacro(macro, q);
222
+ if (!expanded) {
223
+ sendJson(res, 400, { error: 'Unsupported browser search macro.' });
224
+ return true;
225
+ }
226
+ rawUrl = expanded;
227
+ }
228
+ else if (rawUrl && !/^https?:\/\//i.test(rawUrl)) {
229
+ rawUrl = rawUrl.includes('.') || rawUrl.startsWith('localhost')
230
+ ? `https://${rawUrl}`
231
+ : (expandSearchMacro('@duckduckgo_search', rawUrl) || `https://duckduckgo.com/?q=${encodeURIComponent(rawUrl)}`);
232
+ }
233
+ await browser.run([action === 'newTab' ? { type: 'newTab', ...(rawUrl ? { url: rawUrl } : {}) } : { type: 'goto', url: rawUrl || 'about:blank' }], { workspace: workspaceRoot });
234
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
235
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
236
+ return true;
237
+ }
238
+ if (action === 'back' || action === 'forward' || action === 'reload') {
239
+ ctx.setBrowserControlOwner('human');
240
+ await browser.run([{ type: action }], { workspace: workspaceRoot });
241
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
242
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
243
+ return true;
244
+ }
245
+ if ((action === 'switchTab' || action === 'closeTab') && typeof body.tabId === 'string' && body.tabId.trim()) {
246
+ ctx.setBrowserControlOwner('human');
247
+ await browser.run([{ type: action, tabId: body.tabId.trim() }], { workspace: workspaceRoot });
248
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
249
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
250
+ return true;
251
+ }
252
+ if (action === 'viewport') {
253
+ const width = Math.max(320, Math.min(1920, Number(body.width) || 1280));
254
+ const height = Math.max(480, Math.min(1200, Number(body.height) || 800));
255
+ await browser.run([{ type: 'viewport', width, height }], { workspace: workspaceRoot });
256
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
257
+ sendJson(res, 200, { ok: true, controlOwner: ctx.getBrowserControlOwner(), ...frame });
258
+ return true;
259
+ }
260
+ if (action === 'snapshot') {
261
+ const snap = await browser.snapshot(0);
262
+ const frame = await browser.captureLiveFrame({ ensureStarted: true });
263
+ sendJson(res, 200, {
264
+ ok: true,
265
+ controlOwner: ctx.getBrowserControlOwner(),
266
+ snapshot: snap.text,
267
+ refsCount: snap.refsCount,
268
+ ...frame
269
+ });
270
+ return true;
271
+ }
272
+ if (ALLOWED_INPUT_KINDS.has(action)) {
273
+ ctx.setBrowserControlOwner('human');
274
+ const frame = await browser.interactAt({
275
+ kind: action,
276
+ x: typeof body.x === 'number' ? body.x : undefined,
277
+ y: typeof body.y === 'number' ? body.y : undefined,
278
+ deltaX: typeof body.deltaX === 'number' ? body.deltaX : undefined,
279
+ deltaY: typeof body.deltaY === 'number' ? body.deltaY : undefined,
280
+ text: typeof body.text === 'string' ? body.text : undefined,
281
+ key: typeof body.key === 'string' ? body.key : undefined,
282
+ button: body.button === 'right' || body.button === 'middle' ? body.button : 'left'
283
+ });
284
+ sendJson(res, 200, {
285
+ ok: true,
286
+ controlOwner: ctx.getBrowserControlOwner(),
287
+ agentActivity: ctx.getBrowserAgentActivity(),
288
+ ...frame
289
+ });
290
+ return true;
291
+ }
292
+ sendJson(res, 400, { error: 'Unsupported shared browser action.' });
293
+ return true;
294
+ }
295
+ if (req.method === 'GET' && pathname === '/api/browser/cdp/tabs') {
296
+ const portParam = parsedUrl.searchParams.get('port') || '9222';
297
+ const discovered = await discoverLocalCdpTabs(portParam);
298
+ sendJson(res, 200, {
299
+ ok: true,
300
+ port: discovered.port,
301
+ tabs: discovered.tabs.map((t) => ({ id: t.id, title: t.title, url: t.url }))
302
+ });
303
+ return true;
304
+ }
305
+ if (req.method === 'POST' && pathname === '/api/browser/cdp/sync') {
306
+ const body = await readJsonBody(req);
307
+ const targetId = typeof body.targetId === 'string' ? body.targetId.trim() : '';
308
+ if (!targetId) {
309
+ sendJson(res, 400, { error: 'targetId is required to sync a local browser tab.' });
310
+ return true;
311
+ }
312
+ const synced = await syncLocalCdpTabToCausyne({
313
+ workspaceRoot,
314
+ port: body.port ?? 9222,
315
+ targetId,
316
+ includeCookies: body.includeCookies === true
317
+ });
318
+ ctx.setBrowserControlOwner('human');
319
+ auditLog.log({
320
+ event: 'skybridge_browser_cdp_sync',
321
+ importedCookies: synced.importedCookies
322
+ });
323
+ sendJson(res, 200, {
324
+ ok: true,
325
+ controlOwner: ctx.getBrowserControlOwner(),
326
+ syncedUrl: synced.syncedUrl,
327
+ importedCookies: synced.importedCookies,
328
+ ...synced.frame
329
+ });
330
+ return true;
331
+ }
332
+ if (req.method === 'POST' && pathname === '/api/browser/import') {
333
+ const body = await readJsonBody(req);
334
+ const rawText = typeof body.rawText === 'string' ? body.rawText : '';
335
+ const summary = await importExplicitUserBrowserData({
336
+ workspaceRoot,
337
+ rawText,
338
+ openFirstUrl: body.openFirstUrl !== false
339
+ });
340
+ const frame = await causyneBrowser({ workspace: workspaceRoot }).captureLiveFrame({ ensureStarted: false });
341
+ auditLog.log({
342
+ event: 'skybridge_browser_import',
343
+ importedCookies: summary.importedCookies,
344
+ urlsCount: summary.importedUrls.length
345
+ });
346
+ sendJson(res, 200, {
347
+ ok: true,
348
+ controlOwner: ctx.getBrowserControlOwner(),
349
+ ...summary,
350
+ ...frame
351
+ });
352
+ return true;
353
+ }
354
+ return false;
355
+ }