u-foo 4.0.3 → 4.0.10
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.
- package/README.md +239 -19
- package/README.zh-CN.md +3 -3
- package/bin/ucode.js +10 -2
- package/bin/ufoo.js +3 -0
- package/dist/tui/darwin-arm64/ufoo-tui +0 -0
- package/dist/tui/darwin-x64/ufoo-tui +0 -0
- package/dist/tui/linux-arm64/ufoo-tui +0 -0
- package/dist/tui/linux-x64/ufoo-tui +0 -0
- package/{OBSERVABILITY.md → docs/OBSERVABILITY.md} +3 -3
- package/docs/README.md +27 -0
- package/extensions/ufoo-browser/LICENSE +152 -0
- package/extensions/ufoo-browser/NOTICE +10 -0
- package/extensions/ufoo-browser/README.md +30 -0
- package/extensions/ufoo-browser/background.js +409 -0
- package/extensions/ufoo-browser/icons/icon-128.png +0 -0
- package/extensions/ufoo-browser/icons/icon-16.png +0 -0
- package/extensions/ufoo-browser/icons/icon-256.png +0 -0
- package/extensions/ufoo-browser/icons/icon-32.png +0 -0
- package/extensions/ufoo-browser/icons/icon-48.png +0 -0
- package/extensions/ufoo-browser/icons/logo.png +0 -0
- package/extensions/ufoo-browser/icons/toolbar-16.png +0 -0
- package/extensions/ufoo-browser/icons/toolbar-32.png +0 -0
- package/extensions/ufoo-browser/icons/toolbar-logo.png +0 -0
- package/extensions/ufoo-browser/manifest.json +30 -0
- package/extensions/ufoo-browser/popup.css +71 -0
- package/extensions/ufoo-browser/popup.html +44 -0
- package/extensions/ufoo-browser/popup.js +153 -0
- package/package.json +7 -5
- package/scripts/postinstall.js +6 -0
- package/src/agents/capabilities/browser/index.js +49 -0
- package/src/agents/capabilities/coding/backgroundHooks.js +94 -0
- package/src/agents/capabilities/coding/index.js +30 -1
- package/src/agents/capabilities/index.js +5 -2
- package/src/agents/capabilities/planning/index.js +44 -5
- package/src/agents/capabilities/turnRecall/index.js +341 -0
- package/src/agents/controller/controllerToolExecutor.js +2 -2
- package/src/agents/internal/internalRunner.js +30 -8
- package/src/agents/internal/taskControl.js +107 -0
- package/src/agents/profiles/coding.js +1 -1
- package/src/agents/profiles/main.js +1 -1
- package/src/agents/prompts/mainAgent.js +1 -0
- package/src/agents/prompts/native/toolDescriptions/bash.js +7 -1
- package/src/agents/providers/claudeSessionFiles.js +1 -1
- package/src/agents/providers/codexThreadProvider.js +6 -1
- package/src/agents/providers/credentials/agy.js +171 -0
- package/src/agents/providers/directAuthStatus.js +20 -2
- package/src/agents/providers/modelsCatalog.js +26 -5
- package/src/agents/providers/nativeTransport.js +145 -73
- package/src/agents/providers/providerId.js +17 -0
- package/src/agents/providers/runtimeConfig.js +67 -20
- package/src/agents/providers/transports/antigravityTransport.js +242 -0
- package/src/agents/providers/transports/index.js +1 -0
- package/src/agents/providers/transports/openaiChatTransport.js +3 -2
- package/src/agents/providers/transports/openaiResponsesTransport.js +2 -1
- package/src/agents/providers/transports/responsesProtocol.js +119 -18
- package/src/agents/providers/transports/transportContract.js +1 -0
- package/src/agents/providers/upstreamRuntime.js +3 -1
- package/src/agents/runtime/context/contextBudget.js +1 -19
- package/src/agents/runtime/context/contextWindow.js +5 -0
- package/src/agents/runtime/context/replayHistory.js +16 -10
- package/src/agents/runtime/context/runtimeStore.js +0 -1
- package/src/agents/runtime/context/sessionJournal.js +1 -1
- package/src/agents/runtime/context/slidingWindowManager.js +792 -0
- package/src/agents/runtime/context/topicSelector.js +338 -0
- package/src/agents/runtime/context/turnAnalyzer.js +767 -0
- package/src/agents/runtime/context/turnIndexStore.js +515 -0
- package/src/agents/runtime/core/agentLoop.js +140 -35
- package/src/agents/runtime/core/executionBudget.js +2 -1
- package/src/agents/runtime/core/toolErrorGuard.js +39 -0
- package/src/agents/runtime/createAgentRuntime.js +80 -7
- package/src/agents/runtime/index.js +5 -0
- package/src/agents/runtime/protocol/materialize.js +1 -1
- package/src/agents/runtime/tasks/hooks.js +137 -0
- package/src/app/chat/ChatController.js +8 -4
- package/src/app/chat/daemonMessageRouter.js +3 -1
- package/src/app/chat/inputSubmitHandler.js +2 -2
- package/src/app/chat/transport.js +1 -1
- package/src/app/cli/browserCommands.js +340 -0
- package/src/app/cli/busCoreCommands.js +63 -3
- package/src/app/cli/features/doctor.js +21 -0
- package/src/app/cli/metricsCommands.js +1 -1
- package/src/app/cli/run.js +81 -1
- package/src/app/cli/setupCommands.js +200 -0
- package/src/code/UcodeController.js +31 -1
- package/src/code/agent.js +76 -25
- package/src/code/busConsumer.js +13 -12
- package/src/code/commands.js +0 -1
- package/src/code/context/assembler.js +11 -88
- package/src/code/context/planGraphService.js +121 -6
- package/src/code/context/planProjection.js +10 -2
- package/src/code/context/reducers.js +172 -4
- package/src/code/context/stateCommit.js +0 -32
- package/src/code/context/transcript.js +7 -4
- package/src/code/internalThread.js +9 -1
- package/src/code/launcher/ucode.js +4 -2
- package/src/code/modelCommand.js +6 -5
- package/src/code/nativeRunner.js +232 -62
- package/src/code/repl.js +27 -1
- package/src/code/runtime/agentWakeup.js +20 -3
- package/src/code/runtime/backgroundWakeHost.js +45 -0
- package/src/code/runtime/taskFocusContext.js +7 -0
- package/src/code/runtime/taskLoop.js +24 -1
- package/src/code/sessionStore.js +14 -10
- package/src/code/taskDecomposer.js +16 -7
- package/src/code/tools/backgroundProcess.js +23 -0
- package/src/code/tools/bash.js +764 -12
- package/src/code/tools/executor.js +13 -4
- package/src/code/tools/planGraph.js +1 -0
- package/src/code/tools/specs.js +62 -4
- package/src/code/tools/taskRun.js +38 -0
- package/src/config.js +92 -6
- package/src/coordination/bus/index.js +2 -2
- package/src/coordination/bus/message.js +10 -1
- package/src/coordination/bus/nickname.js +3 -1
- package/src/coordination/bus/subscriber.js +25 -10
- package/src/coordination/bus/utils.js +4 -0
- package/src/coordination/bus/wakeEndpoint.js +198 -0
- package/src/coordination/history/agentPerformance.js +18 -18
- package/src/coordination/history/agentTrace.js +7 -3
- package/src/coordination/state/paths.js +4 -0
- package/src/coordination/state/workspaceAccess.js +3 -1
- package/src/orchestration/groups/modelConfig.js +66 -0
- package/src/orchestration/groups/validateTemplate.js +2 -0
- package/src/runtime/browser/broker.js +1027 -0
- package/src/runtime/browser/brokerClient.js +108 -0
- package/src/runtime/browser/componentInstaller.js +275 -0
- package/src/runtime/browser/installState.js +329 -0
- package/src/runtime/browser/manifest.js +145 -0
- package/src/runtime/browser/native-host-runner.js +198 -0
- package/src/runtime/browser/nativeHost.js +213 -0
- package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
- package/src/runtime/browser/paths.js +134 -0
- package/src/runtime/browser/playwrightSession.js +614 -0
- package/src/runtime/daemon/agentHost.js +175 -28
- package/src/runtime/daemon/busBridge.js +2 -1
- package/src/runtime/daemon/deliveryScheduler.js +70 -2
- package/src/runtime/daemon/globalDaemon.js +20 -0
- package/src/runtime/daemon/groupOrchestrator.js +20 -1
- package/src/runtime/daemon/index.js +6 -4
- package/src/runtime/daemon/ops.js +14 -8
- package/src/tools/handlers/listAgents.js +1 -1
- package/src/tools/handlers/readBusSummary.js +1 -1
- package/src/tools/handlers/routeAgent.js +122 -5
- package/src/tools/schemaFixtures.js +1 -1
- package/src/ui/agentSurface.js +60 -6
- package/src/ui/format/index.js +34 -2
- package/src/ui/format/markdownRenderer.js +4 -2
- package/src/ui/rustChatHost.js +22 -7
- package/src/ui/rustMultiSession.js +14 -2
- package/src/ui/rustUcodeHost.js +249 -80
- package/src/ui/ucodeAgentSession.js +88 -0
- package/templates/groups/build-lane.json +57 -3
- package/templates/groups/build-ultra.json +114 -6
- package/templates/groups/design-system.json +57 -3
- package/templates/groups/product-discovery.json +57 -3
- package/templates/groups/ui-plan-review.json +57 -3
- package/templates/groups/ui-polish.json +57 -3
- package/templates/groups/verify-ship.json +57 -3
- package/src/agents/runtime/context/checkpointStore.js +0 -38
- package/src/agents/runtime/context/compaction.js +0 -151
|
@@ -0,0 +1,1027 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { randomUUID } = require("crypto");
|
|
4
|
+
const fs = require("fs");
|
|
5
|
+
const http = require("http");
|
|
6
|
+
const net = require("net");
|
|
7
|
+
const path = require("path");
|
|
8
|
+
const { WebSocketServer, WebSocket } = require("ws");
|
|
9
|
+
const { loadGlobalBrowserConfig } = require("../../config");
|
|
10
|
+
const { writeFileAtomic } = require("../../coordination/bus/utils");
|
|
11
|
+
const {
|
|
12
|
+
privateDir,
|
|
13
|
+
brokerSocketPath,
|
|
14
|
+
brokerInfoPath,
|
|
15
|
+
} = require("./paths");
|
|
16
|
+
const {
|
|
17
|
+
getReleaseManifest,
|
|
18
|
+
isExtensionCompatible,
|
|
19
|
+
resolveAllowedExtensionIds,
|
|
20
|
+
} = require("./manifest");
|
|
21
|
+
|
|
22
|
+
const TOKEN_TTL_MS = 60 * 1000;
|
|
23
|
+
const EXTENSION_RPC_TIMEOUT_MS = 15 * 1000;
|
|
24
|
+
const MAX_EXTENSION_TOKENS = 32;
|
|
25
|
+
|
|
26
|
+
function isSupportedTab(tab) {
|
|
27
|
+
if (!tab || tab.id === undefined || tab.id === null) return false;
|
|
28
|
+
if (tab.incognito === true) return false;
|
|
29
|
+
const rawUrl = String(tab.url || tab.pendingUrl || "").trim().toLowerCase();
|
|
30
|
+
if (!rawUrl) return true;
|
|
31
|
+
if (
|
|
32
|
+
rawUrl.startsWith("chrome://")
|
|
33
|
+
|| rawUrl.startsWith("chrome-extension://")
|
|
34
|
+
|| rawUrl.startsWith("devtools://")
|
|
35
|
+
|| rawUrl.startsWith("edge://")
|
|
36
|
+
|| rawUrl.startsWith("view-source:chrome-extension://")
|
|
37
|
+
) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function parseExtensionOrigin(originHeader = "") {
|
|
44
|
+
const raw = String(originHeader || "").trim();
|
|
45
|
+
const match = raw.match(/^chrome-extension:\/\/([a-p]{32})$/);
|
|
46
|
+
return match ? match[1] : "";
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseBearerToken(authHeader = "") {
|
|
50
|
+
const raw = String(authHeader || "").trim();
|
|
51
|
+
const match = raw.match(/^Bearer\s+([^\s]+)$/i);
|
|
52
|
+
return match ? match[1] : "";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
class BrowserBroker {
|
|
56
|
+
constructor(options = {}) {
|
|
57
|
+
this.env = options.env || process.env;
|
|
58
|
+
this.hostVersion = options.hostVersion || "";
|
|
59
|
+
this.loadConfig = options.loadConfig || loadGlobalBrowserConfig;
|
|
60
|
+
this.background = options.background !== false;
|
|
61
|
+
this.devAllowed = options.devAllowed !== false;
|
|
62
|
+
this.socketPath = options.socketPath || brokerSocketPath(this.env);
|
|
63
|
+
this.infoPath = options.infoPath || brokerInfoPath(this.env);
|
|
64
|
+
|
|
65
|
+
this.ipcServer = null;
|
|
66
|
+
this.httpServer = null;
|
|
67
|
+
this.wss = null;
|
|
68
|
+
this.port = 0;
|
|
69
|
+
this.started = false;
|
|
70
|
+
this.closed = false;
|
|
71
|
+
|
|
72
|
+
this.extensionWs = null;
|
|
73
|
+
this.connectedExtension = null;
|
|
74
|
+
this.protocolMismatch = false;
|
|
75
|
+
this.protocolError = "";
|
|
76
|
+
this.paused = false;
|
|
77
|
+
|
|
78
|
+
this.pendingExtensionTokens = new Map();
|
|
79
|
+
this.extensionRpcCallbacks = new Map();
|
|
80
|
+
this.nextRpcId = 1;
|
|
81
|
+
this.nextTabSeq = 1;
|
|
82
|
+
|
|
83
|
+
this.knownTabs = new Map(); // tabId -> tab metadata
|
|
84
|
+
this.attachedTabs = new Map(); // tabId -> { tabId, relaySessionId, targetInfo, childSessions: Set, ownerSessionId }
|
|
85
|
+
this.tabOwners = new Map(); // tabId -> agentSessionId
|
|
86
|
+
this.sessions = new Map(); // agentSessionId -> { sessionId, token, projectName, agentName, workspaceRoot, ws, autoAttach, invalidated }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
allowedExtensionIds() {
|
|
90
|
+
return resolveAllowedExtensionIds({ dev: this.devAllowed, env: this.env });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
isBrowserEnabled() {
|
|
94
|
+
try {
|
|
95
|
+
const cfg = this.loadConfig();
|
|
96
|
+
return cfg.enabled === true;
|
|
97
|
+
} catch {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async start() {
|
|
103
|
+
if (this.started) return this.info();
|
|
104
|
+
fs.mkdirSync(path.dirname(this.socketPath), { recursive: true, mode: 0o700 });
|
|
105
|
+
fs.mkdirSync(privateDir(this.env), { recursive: true, mode: 0o700 });
|
|
106
|
+
if (fs.existsSync(this.socketPath)) {
|
|
107
|
+
try { fs.rmSync(this.socketPath, { force: true }); } catch { /* ignore */ }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
this.httpServer = http.createServer((_req, res) => {
|
|
111
|
+
res.statusCode = 404;
|
|
112
|
+
res.end("Not found");
|
|
113
|
+
});
|
|
114
|
+
this.wss = new WebSocketServer({ noServer: true });
|
|
115
|
+
this.httpServer.on("upgrade", (req, socket, head) => {
|
|
116
|
+
this._handleUpgrade(req, socket, head);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
await new Promise((resolve, reject) => {
|
|
120
|
+
this.httpServer.once("error", reject);
|
|
121
|
+
this.httpServer.listen(0, "127.0.0.1", () => {
|
|
122
|
+
this.httpServer.removeListener("error", reject);
|
|
123
|
+
const addr = this.httpServer.address();
|
|
124
|
+
this.port = addr && typeof addr === "object" ? addr.port : 0;
|
|
125
|
+
resolve();
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
this.ipcServer = net.createServer((socket) => this._handleIpcSocket(socket));
|
|
130
|
+
await new Promise((resolve, reject) => {
|
|
131
|
+
this.ipcServer.once("error", reject);
|
|
132
|
+
this.ipcServer.listen(this.socketPath, () => {
|
|
133
|
+
this.ipcServer.removeListener("error", reject);
|
|
134
|
+
try { fs.chmodSync(this.socketPath, 0o600); } catch { /* ignore */ }
|
|
135
|
+
resolve();
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
this.started = true;
|
|
140
|
+
writeFileAtomic(this.infoPath, JSON.stringify({
|
|
141
|
+
pid: process.pid,
|
|
142
|
+
port: this.port,
|
|
143
|
+
socketPath: this.socketPath,
|
|
144
|
+
startedAt: new Date().toISOString(),
|
|
145
|
+
}, null, 2), { mode: 0o600 });
|
|
146
|
+
return this.info();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
info() {
|
|
150
|
+
return {
|
|
151
|
+
ok: true,
|
|
152
|
+
pid: process.pid,
|
|
153
|
+
port: this.port,
|
|
154
|
+
socketPath: this.socketPath,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
status() {
|
|
159
|
+
const tabOwners = [];
|
|
160
|
+
for (const [tabId, sessionId] of this.tabOwners.entries()) {
|
|
161
|
+
const session = this.sessions.get(sessionId);
|
|
162
|
+
const tab = this.knownTabs.get(tabId) || {};
|
|
163
|
+
tabOwners.push({
|
|
164
|
+
tabId,
|
|
165
|
+
sessionId,
|
|
166
|
+
projectName: session?.projectName || "",
|
|
167
|
+
agentName: session?.agentName || "",
|
|
168
|
+
title: tab.title || "",
|
|
169
|
+
url: tab.url || "",
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
ok: true,
|
|
174
|
+
pid: process.pid,
|
|
175
|
+
port: this.port,
|
|
176
|
+
enabled: this.isBrowserEnabled(),
|
|
177
|
+
extensionConnected: Boolean(this.extensionWs && this.extensionWs.readyState === WebSocket.OPEN),
|
|
178
|
+
connectedExtension: this.connectedExtension,
|
|
179
|
+
protocolMismatch: this.protocolMismatch,
|
|
180
|
+
protocolError: this.protocolError,
|
|
181
|
+
paused: this.paused,
|
|
182
|
+
sessionCount: this.sessions.size,
|
|
183
|
+
tabOwners,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async stop() {
|
|
188
|
+
if (this.closed) return;
|
|
189
|
+
this.closed = true;
|
|
190
|
+
this.started = false;
|
|
191
|
+
this._revokeAllSessions("Broker stopped");
|
|
192
|
+
this._closeExtension("Broker stopped");
|
|
193
|
+
await Promise.all([
|
|
194
|
+
new Promise((resolve) => {
|
|
195
|
+
if (!this.ipcServer) return resolve();
|
|
196
|
+
try { this.ipcServer.close(() => resolve()); } catch { resolve(); }
|
|
197
|
+
}),
|
|
198
|
+
new Promise((resolve) => {
|
|
199
|
+
if (!this.wss) return resolve();
|
|
200
|
+
try { this.wss.close(() => resolve()); } catch { resolve(); }
|
|
201
|
+
}),
|
|
202
|
+
new Promise((resolve) => {
|
|
203
|
+
if (!this.httpServer) return resolve();
|
|
204
|
+
try { this.httpServer.close(() => resolve()); } catch { resolve(); }
|
|
205
|
+
}),
|
|
206
|
+
]);
|
|
207
|
+
try { fs.rmSync(this.socketPath, { force: true }); } catch { /* ignore */ }
|
|
208
|
+
try { fs.rmSync(this.infoPath, { force: true }); } catch { /* ignore */ }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
_handleIpcSocket(socket) {
|
|
212
|
+
let buffer = "";
|
|
213
|
+
socket.on("data", (chunk) => {
|
|
214
|
+
buffer += chunk.toString("utf8");
|
|
215
|
+
const lines = buffer.split(/\r?\n/);
|
|
216
|
+
buffer = lines.pop() || "";
|
|
217
|
+
for (const line of lines) {
|
|
218
|
+
if (!line.trim()) continue;
|
|
219
|
+
let req;
|
|
220
|
+
try {
|
|
221
|
+
req = JSON.parse(line);
|
|
222
|
+
} catch {
|
|
223
|
+
socket.write(`${JSON.stringify({ ok: false, code: "invalid_json", error: "Malformed IPC JSON" })}\n`);
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
Promise.resolve(this.handleRpc(req.op, req.params || {})).then(
|
|
227
|
+
(res) => {
|
|
228
|
+
if (!socket.destroyed) socket.write(`${JSON.stringify(res)}\n`);
|
|
229
|
+
},
|
|
230
|
+
(err) => {
|
|
231
|
+
if (!socket.destroyed) {
|
|
232
|
+
socket.write(`${JSON.stringify({
|
|
233
|
+
ok: false,
|
|
234
|
+
code: err?.code || "broker_error",
|
|
235
|
+
error: err?.message || String(err),
|
|
236
|
+
})}\n`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async handleRpc(op, params = {}) {
|
|
245
|
+
switch (op) {
|
|
246
|
+
case "ping":
|
|
247
|
+
return { ok: true, pid: process.pid, port: this.port, protocolVersion: getReleaseManifest(this.env).protocolVersion };
|
|
248
|
+
case "status":
|
|
249
|
+
return this.status();
|
|
250
|
+
case "native_hello":
|
|
251
|
+
return this._handleNativeHello(params);
|
|
252
|
+
case "register_session":
|
|
253
|
+
return this._registerSession(params);
|
|
254
|
+
case "unregister_session":
|
|
255
|
+
return this._unregisterSession(params.sessionId);
|
|
256
|
+
case "list_tabs":
|
|
257
|
+
return this._listTabs();
|
|
258
|
+
case "claim_tab":
|
|
259
|
+
return this._claimTab(params.sessionId, params.tabId);
|
|
260
|
+
case "create_tab":
|
|
261
|
+
return this._createTab(params.sessionId, params.url);
|
|
262
|
+
case "close_tab":
|
|
263
|
+
return this._closeTab(params.sessionId, params.tabId);
|
|
264
|
+
case "release_tab":
|
|
265
|
+
return this._releaseTab(params.sessionId, params.tabId);
|
|
266
|
+
case "session_tab_status":
|
|
267
|
+
return this._sessionTabStatus(params.sessionId);
|
|
268
|
+
case "config_changed":
|
|
269
|
+
return this._handleConfigChanged();
|
|
270
|
+
case "revoke_all":
|
|
271
|
+
this._revokeAllSessions("Revoked by operator");
|
|
272
|
+
this._closeExtension("Revoked by operator");
|
|
273
|
+
return { ok: true };
|
|
274
|
+
default:
|
|
275
|
+
return { ok: false, code: "unknown_broker_op", error: `Unknown broker operation: ${op}` };
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
_handleNativeHello({ extensionId = "", extensionVersion = "", protocolVersion = 0 } = {}) {
|
|
280
|
+
if (!this.isBrowserEnabled()) {
|
|
281
|
+
return { ok: false, code: "disabled", error: "ufoo Browser is disabled" };
|
|
282
|
+
}
|
|
283
|
+
const allowed = this.allowedExtensionIds();
|
|
284
|
+
if (!extensionId || !allowed.includes(extensionId)) {
|
|
285
|
+
return { ok: false, code: "extension_not_allowed", error: "Extension ID is not authorized for this host" };
|
|
286
|
+
}
|
|
287
|
+
const manifest = getReleaseManifest(this.env);
|
|
288
|
+
const compat = isExtensionCompatible({ extensionVersion, protocolVersion }, manifest);
|
|
289
|
+
if (!compat.ok) {
|
|
290
|
+
this.protocolMismatch = true;
|
|
291
|
+
this.protocolError = compat.reason;
|
|
292
|
+
return { ok: false, code: "protocol_mismatch", error: compat.reason };
|
|
293
|
+
}
|
|
294
|
+
this.protocolMismatch = false;
|
|
295
|
+
this.protocolError = "";
|
|
296
|
+
|
|
297
|
+
const now = Date.now();
|
|
298
|
+
for (const [tok, entry] of this.pendingExtensionTokens.entries()) {
|
|
299
|
+
if (entry.expiresAt <= now) this.pendingExtensionTokens.delete(tok);
|
|
300
|
+
}
|
|
301
|
+
if (this.pendingExtensionTokens.size >= MAX_EXTENSION_TOKENS) {
|
|
302
|
+
const oldest = this.pendingExtensionTokens.keys().next().value;
|
|
303
|
+
if (oldest) this.pendingExtensionTokens.delete(oldest);
|
|
304
|
+
}
|
|
305
|
+
const token = randomUUID();
|
|
306
|
+
this.pendingExtensionTokens.set(token, {
|
|
307
|
+
extensionId,
|
|
308
|
+
extensionVersion,
|
|
309
|
+
expiresAt: now + TOKEN_TTL_MS,
|
|
310
|
+
});
|
|
311
|
+
return {
|
|
312
|
+
ok: true,
|
|
313
|
+
wsUrl: `ws://127.0.0.1:${this.port}/extension?token=${encodeURIComponent(token)}`,
|
|
314
|
+
token,
|
|
315
|
+
protocolVersion: manifest.protocolVersion,
|
|
316
|
+
hostVersion: this.hostVersion,
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
_handleUpgrade(req, socket, head) {
|
|
321
|
+
let url;
|
|
322
|
+
try {
|
|
323
|
+
url = new URL(req.url || "/", `http://127.0.0.1:${this.port}`);
|
|
324
|
+
} catch {
|
|
325
|
+
socket.write("HTTP/1.1 400 Bad Request\r\n\r\n");
|
|
326
|
+
socket.destroy();
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (url.pathname === "/extension") {
|
|
331
|
+
const originExtId = parseExtensionOrigin(req.headers.origin);
|
|
332
|
+
const allowed = this.allowedExtensionIds();
|
|
333
|
+
if (!originExtId || !allowed.includes(originExtId)) {
|
|
334
|
+
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
335
|
+
socket.destroy();
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
const token = url.searchParams.get("token") || parseBearerToken(req.headers.authorization);
|
|
339
|
+
const tokenEntry = token ? this.pendingExtensionTokens.get(token) : null;
|
|
340
|
+
if (!tokenEntry || tokenEntry.expiresAt < Date.now() || tokenEntry.extensionId !== originExtId) {
|
|
341
|
+
if (token) this.pendingExtensionTokens.delete(token);
|
|
342
|
+
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
|
|
343
|
+
socket.destroy();
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
this.pendingExtensionTokens.delete(token);
|
|
347
|
+
if (!this.isBrowserEnabled()) {
|
|
348
|
+
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
349
|
+
socket.destroy();
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
this.wss.handleUpgrade(req, socket, head, (ws) => {
|
|
353
|
+
this._attachExtensionWs(ws, { extensionId: originExtId, extensionVersion: tokenEntry.extensionVersion });
|
|
354
|
+
});
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (url.pathname.startsWith("/cdp/")) {
|
|
359
|
+
// Reject browser-originated WebSocket upgrades (CSWSH defense).
|
|
360
|
+
if (req.headers.origin) {
|
|
361
|
+
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
362
|
+
socket.destroy();
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
const sessionId = decodeURIComponent(url.pathname.slice("/cdp/".length));
|
|
366
|
+
const session = this.sessions.get(sessionId);
|
|
367
|
+
const bearer = parseBearerToken(req.headers.authorization);
|
|
368
|
+
if (!session || session.invalidated || !bearer || bearer !== session.token) {
|
|
369
|
+
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
|
|
370
|
+
socket.destroy();
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
if (this.paused || !this.extensionWs || this.extensionWs.readyState !== WebSocket.OPEN) {
|
|
374
|
+
socket.write("HTTP/1.1 503 Service Unavailable\r\n\r\n");
|
|
375
|
+
socket.destroy();
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
this.wss.handleUpgrade(req, socket, head, (ws) => {
|
|
379
|
+
this._attachCdpWs(session, ws);
|
|
380
|
+
});
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
|
|
385
|
+
socket.destroy();
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
_attachExtensionWs(ws, meta) {
|
|
389
|
+
if (this.extensionWs && this.extensionWs !== ws) {
|
|
390
|
+
this._closeExtension("Superseded by newer extension connection");
|
|
391
|
+
}
|
|
392
|
+
this.extensionWs = ws;
|
|
393
|
+
this.connectedExtension = {
|
|
394
|
+
extensionId: meta.extensionId,
|
|
395
|
+
extensionVersion: meta.extensionVersion || "",
|
|
396
|
+
connectedAt: new Date().toISOString(),
|
|
397
|
+
};
|
|
398
|
+
this.protocolMismatch = false;
|
|
399
|
+
this.protocolError = "";
|
|
400
|
+
|
|
401
|
+
ws.on("message", (raw) => {
|
|
402
|
+
let msg;
|
|
403
|
+
try {
|
|
404
|
+
msg = JSON.parse(raw.toString("utf8"));
|
|
405
|
+
} catch {
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
this._onExtensionMessage(ws, msg);
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
ws.on("close", () => {
|
|
412
|
+
if (this.extensionWs !== ws) return;
|
|
413
|
+
this.extensionWs = null;
|
|
414
|
+
this.connectedExtension = null;
|
|
415
|
+
for (const cb of this.extensionRpcCallbacks.values()) {
|
|
416
|
+
clearTimeout(cb.timer);
|
|
417
|
+
cb.reject(new Error("Extension disconnected"));
|
|
418
|
+
}
|
|
419
|
+
this.extensionRpcCallbacks.clear();
|
|
420
|
+
this.knownTabs.clear();
|
|
421
|
+
this.attachedTabs.clear();
|
|
422
|
+
this.tabOwners.clear();
|
|
423
|
+
this._invalidateAllSessions("Chrome extension disconnected");
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
ws.on("error", () => {});
|
|
427
|
+
this._syncExtensionState();
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
_closeExtension(reason) {
|
|
431
|
+
this.pendingExtensionTokens.clear();
|
|
432
|
+
if (this.extensionWs) {
|
|
433
|
+
try {
|
|
434
|
+
if (this.extensionWs.readyState === WebSocket.OPEN) {
|
|
435
|
+
this.extensionWs.close(1000, reason);
|
|
436
|
+
}
|
|
437
|
+
} catch { /* ignore */ }
|
|
438
|
+
}
|
|
439
|
+
this.extensionWs = null;
|
|
440
|
+
this.connectedExtension = null;
|
|
441
|
+
this.knownTabs.clear();
|
|
442
|
+
this.attachedTabs.clear();
|
|
443
|
+
this.tabOwners.clear();
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
_sendExtensionRpc(method, params = []) {
|
|
447
|
+
if (!this.extensionWs || this.extensionWs.readyState !== WebSocket.OPEN) {
|
|
448
|
+
return Promise.reject(Object.assign(new Error("Chrome extension is not connected"), { code: "waiting_for_browser" }));
|
|
449
|
+
}
|
|
450
|
+
const id = this.nextRpcId++;
|
|
451
|
+
return new Promise((resolve, reject) => {
|
|
452
|
+
const timer = setTimeout(() => {
|
|
453
|
+
this.extensionRpcCallbacks.delete(id);
|
|
454
|
+
reject(new Error(`Extension RPC timed out: ${method}`));
|
|
455
|
+
}, EXTENSION_RPC_TIMEOUT_MS);
|
|
456
|
+
timer.unref?.();
|
|
457
|
+
this.extensionRpcCallbacks.set(id, { resolve, reject, timer });
|
|
458
|
+
this.extensionWs.send(JSON.stringify({ id, method, params }));
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
_sendExtensionNotification(method, params = {}) {
|
|
463
|
+
if (!this.extensionWs || this.extensionWs.readyState !== WebSocket.OPEN) return;
|
|
464
|
+
try {
|
|
465
|
+
this.extensionWs.send(JSON.stringify({ method, params }));
|
|
466
|
+
} catch { /* ignore */ }
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
_syncExtensionState() {
|
|
470
|
+
const tabOwners = [];
|
|
471
|
+
for (const [tabId, sessionId] of this.tabOwners.entries()) {
|
|
472
|
+
const session = this.sessions.get(sessionId);
|
|
473
|
+
const tab = this.knownTabs.get(tabId) || {};
|
|
474
|
+
tabOwners.push({
|
|
475
|
+
tabId,
|
|
476
|
+
sessionId,
|
|
477
|
+
projectName: session?.projectName || "",
|
|
478
|
+
agentName: session?.agentName || "",
|
|
479
|
+
title: tab.title || "",
|
|
480
|
+
url: tab.url || "",
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
this._sendExtensionNotification("host.state_sync", {
|
|
484
|
+
paused: this.paused,
|
|
485
|
+
enabled: this.isBrowserEnabled(),
|
|
486
|
+
sessionCount: this.sessions.size,
|
|
487
|
+
tabOwners,
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
_onExtensionMessage(ws, msg) {
|
|
492
|
+
if (!msg || typeof msg !== "object") return;
|
|
493
|
+
if (msg.id) {
|
|
494
|
+
const cb = this.extensionRpcCallbacks.get(msg.id);
|
|
495
|
+
if (!cb) return;
|
|
496
|
+
this.extensionRpcCallbacks.delete(msg.id);
|
|
497
|
+
clearTimeout(cb.timer);
|
|
498
|
+
if (msg.error) cb.reject(new Error(typeof msg.error === "string" ? msg.error : msg.error.message || "Extension error"));
|
|
499
|
+
else cb.resolve(msg.result);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
switch (msg.method) {
|
|
504
|
+
case "extension.initialized": {
|
|
505
|
+
const info = msg.params || {};
|
|
506
|
+
const compat = isExtensionCompatible({
|
|
507
|
+
extensionVersion: info.extensionVersion || this.connectedExtension?.extensionVersion || "",
|
|
508
|
+
protocolVersion: info.protocolVersion,
|
|
509
|
+
}, getReleaseManifest(this.env));
|
|
510
|
+
if (!compat.ok) {
|
|
511
|
+
this.protocolMismatch = true;
|
|
512
|
+
this.protocolError = compat.reason;
|
|
513
|
+
this._sendExtensionNotification("host.protocol_mismatch", { reason: compat.reason });
|
|
514
|
+
try { ws.close(1008, compat.reason); } catch { /* ignore */ }
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
if (this.connectedExtension) {
|
|
518
|
+
this.connectedExtension.extensionVersion = String(info.extensionVersion || this.connectedExtension.extensionVersion || "");
|
|
519
|
+
}
|
|
520
|
+
if (Array.isArray(info.tabs)) {
|
|
521
|
+
this.knownTabs.clear();
|
|
522
|
+
for (const tab of info.tabs) {
|
|
523
|
+
if (isSupportedTab(tab)) this.knownTabs.set(tab.id, tab);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
this._syncExtensionState();
|
|
527
|
+
break;
|
|
528
|
+
}
|
|
529
|
+
case "extension.pause_all":
|
|
530
|
+
this._pauseAll();
|
|
531
|
+
break;
|
|
532
|
+
case "extension.resume_all":
|
|
533
|
+
this.paused = false;
|
|
534
|
+
this._syncExtensionState();
|
|
535
|
+
break;
|
|
536
|
+
case "extension.release_tab": {
|
|
537
|
+
const tabId = Number(msg.params?.tabId);
|
|
538
|
+
if (Number.isInteger(tabId)) {
|
|
539
|
+
void this._forceReleaseTab(tabId, "Released by user in extension");
|
|
540
|
+
}
|
|
541
|
+
break;
|
|
542
|
+
}
|
|
543
|
+
case "chrome.tabs.onCreated": {
|
|
544
|
+
const [tab] = Array.isArray(msg.params) ? msg.params : [];
|
|
545
|
+
if (isSupportedTab(tab)) this.knownTabs.set(tab.id, tab);
|
|
546
|
+
break;
|
|
547
|
+
}
|
|
548
|
+
case "chrome.tabs.onUpdated": {
|
|
549
|
+
const [tabId, changeInfo, tab] = Array.isArray(msg.params) ? msg.params : [];
|
|
550
|
+
if (tab && isSupportedTab(tab)) {
|
|
551
|
+
this.knownTabs.set(tabId, tab);
|
|
552
|
+
} else if (changeInfo && this.knownTabs.has(tabId)) {
|
|
553
|
+
const updated = { ...this.knownTabs.get(tabId), ...changeInfo };
|
|
554
|
+
if (isSupportedTab(updated)) this.knownTabs.set(tabId, updated);
|
|
555
|
+
else {
|
|
556
|
+
this.knownTabs.delete(tabId);
|
|
557
|
+
void this._forceReleaseTab(tabId, "Tab navigated to unsupported page");
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
this._syncExtensionState();
|
|
561
|
+
break;
|
|
562
|
+
}
|
|
563
|
+
case "chrome.tabs.onRemoved": {
|
|
564
|
+
const [tabId] = Array.isArray(msg.params) ? msg.params : [];
|
|
565
|
+
this.knownTabs.delete(tabId);
|
|
566
|
+
void this._forceReleaseTab(tabId, "Tab closed");
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
569
|
+
case "chrome.debugger.onEvent": {
|
|
570
|
+
const [source, method, params] = Array.isArray(msg.params) ? msg.params : [];
|
|
571
|
+
this._onDebuggerEvent(source, method, params);
|
|
572
|
+
break;
|
|
573
|
+
}
|
|
574
|
+
case "chrome.debugger.onDetach": {
|
|
575
|
+
const [source] = Array.isArray(msg.params) ? msg.params : [];
|
|
576
|
+
if (source && source.tabId !== undefined) {
|
|
577
|
+
void this._forceReleaseTab(source.tabId, "Debugger detached");
|
|
578
|
+
}
|
|
579
|
+
break;
|
|
580
|
+
}
|
|
581
|
+
default:
|
|
582
|
+
break;
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
_pauseAll() {
|
|
587
|
+
this.paused = true;
|
|
588
|
+
for (const tabId of [...this.attachedTabs.keys()]) {
|
|
589
|
+
this._sendExtensionRpc("chrome.debugger.detach", [{ tabId }]).catch(() => {});
|
|
590
|
+
}
|
|
591
|
+
for (const [tabId, attached] of this.attachedTabs.entries()) {
|
|
592
|
+
const owner = this.sessions.get(attached.ownerSessionId);
|
|
593
|
+
this._emitTargetDetached(owner, attached);
|
|
594
|
+
this.tabOwners.delete(tabId);
|
|
595
|
+
}
|
|
596
|
+
this.attachedTabs.clear();
|
|
597
|
+
this.tabOwners.clear();
|
|
598
|
+
this._invalidateAllSessions("Browser control paused by user");
|
|
599
|
+
this._syncExtensionState();
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
_invalidateAllSessions(reason) {
|
|
603
|
+
for (const session of this.sessions.values()) {
|
|
604
|
+
session.invalidated = true;
|
|
605
|
+
session.token = "";
|
|
606
|
+
if (session.ws && session.ws.readyState === WebSocket.OPEN) {
|
|
607
|
+
try { session.ws.close(1000, reason); } catch { /* ignore */ }
|
|
608
|
+
}
|
|
609
|
+
session.ws = null;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
_revokeAllSessions(reason) {
|
|
614
|
+
this._invalidateAllSessions(reason);
|
|
615
|
+
this.sessions.clear();
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
_handleConfigChanged() {
|
|
619
|
+
if (!this.isBrowserEnabled()) {
|
|
620
|
+
this._pauseAll();
|
|
621
|
+
this._sendExtensionNotification("host.disabled", {});
|
|
622
|
+
this._closeExtension("Browser capability disabled");
|
|
623
|
+
return { ok: true, enabled: false };
|
|
624
|
+
}
|
|
625
|
+
this._syncExtensionState();
|
|
626
|
+
return { ok: true, enabled: true };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
_emitTargetAttached(session, attached) {
|
|
630
|
+
if (!session || !session.ws || session.ws.readyState !== WebSocket.OPEN || !session.autoAttach) return;
|
|
631
|
+
session.ws.send(JSON.stringify({
|
|
632
|
+
method: "Target.attachedToTarget",
|
|
633
|
+
params: {
|
|
634
|
+
sessionId: attached.relaySessionId,
|
|
635
|
+
targetInfo: { ...attached.targetInfo, attached: true },
|
|
636
|
+
waitingForDebugger: false,
|
|
637
|
+
},
|
|
638
|
+
}));
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
_emitTargetDetached(session, attached) {
|
|
642
|
+
if (!session || !session.ws || session.ws.readyState !== WebSocket.OPEN) return;
|
|
643
|
+
try {
|
|
644
|
+
session.ws.send(JSON.stringify({
|
|
645
|
+
method: "Target.detachedFromTarget",
|
|
646
|
+
params: {
|
|
647
|
+
sessionId: attached.relaySessionId,
|
|
648
|
+
targetId: attached.targetInfo?.targetId,
|
|
649
|
+
},
|
|
650
|
+
}));
|
|
651
|
+
} catch { /* ignore */ }
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
async _forceReleaseTab(tabId, reason = "") {
|
|
655
|
+
void reason;
|
|
656
|
+
const ownerSessionId = this.tabOwners.get(tabId);
|
|
657
|
+
this.tabOwners.delete(tabId);
|
|
658
|
+
const attached = this.attachedTabs.get(tabId);
|
|
659
|
+
if (attached) {
|
|
660
|
+
this.attachedTabs.delete(tabId);
|
|
661
|
+
const owner = this.sessions.get(ownerSessionId || attached.ownerSessionId);
|
|
662
|
+
this._emitTargetDetached(owner, attached);
|
|
663
|
+
if (owner) owner.releasedSinceLastClaim = true;
|
|
664
|
+
await this._sendExtensionRpc("chrome.debugger.detach", [{ tabId }]).catch(() => {});
|
|
665
|
+
}
|
|
666
|
+
this._syncExtensionState();
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
_registerSession({ sessionId = "", projectName = "", agentName = "", workspaceRoot = "" } = {}) {
|
|
670
|
+
if (!sessionId) return { ok: false, code: "browser_context_required", error: "sessionId is required" };
|
|
671
|
+
if (!this.isBrowserEnabled()) return { ok: false, code: "browser_disabled", error: "ufoo Browser is disabled" };
|
|
672
|
+
if (this.protocolMismatch) return { ok: false, code: "protocol_mismatch", error: this.protocolError || "Protocol mismatch" };
|
|
673
|
+
if (this.paused) return { ok: false, code: "browser_paused", error: "Browser control is paused in Ufoo extension" };
|
|
674
|
+
if (!this.extensionWs || this.extensionWs.readyState !== WebSocket.OPEN) {
|
|
675
|
+
return { ok: false, code: "waiting_for_browser", error: "Chrome with Ufoo extension is not connected" };
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const existing = this.sessions.get(sessionId);
|
|
679
|
+
if (existing && !existing.invalidated) {
|
|
680
|
+
if (projectName) existing.projectName = String(projectName);
|
|
681
|
+
if (agentName) existing.agentName = String(agentName);
|
|
682
|
+
return {
|
|
683
|
+
ok: true,
|
|
684
|
+
sessionId,
|
|
685
|
+
wsEndpoint: `ws://127.0.0.1:${this.port}/cdp/${encodeURIComponent(sessionId)}`,
|
|
686
|
+
sessionToken: existing.token,
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
const token = randomUUID();
|
|
691
|
+
const record = {
|
|
692
|
+
sessionId,
|
|
693
|
+
token,
|
|
694
|
+
projectName: String(projectName || (workspaceRoot ? path.basename(workspaceRoot) : "") || "ufoo"),
|
|
695
|
+
agentName: String(agentName || "agent"),
|
|
696
|
+
workspaceRoot: String(workspaceRoot || ""),
|
|
697
|
+
ws: null,
|
|
698
|
+
autoAttach: false,
|
|
699
|
+
invalidated: false,
|
|
700
|
+
releasedSinceLastClaim: false,
|
|
701
|
+
};
|
|
702
|
+
this.sessions.set(sessionId, record);
|
|
703
|
+
this._syncExtensionState();
|
|
704
|
+
return {
|
|
705
|
+
ok: true,
|
|
706
|
+
sessionId,
|
|
707
|
+
wsEndpoint: `ws://127.0.0.1:${this.port}/cdp/${encodeURIComponent(sessionId)}`,
|
|
708
|
+
sessionToken: token,
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
async _unregisterSession(sessionId = "") {
|
|
713
|
+
const session = this.sessions.get(sessionId);
|
|
714
|
+
if (!session) return { ok: true };
|
|
715
|
+
const ownedTabs = [...this.tabOwners.entries()]
|
|
716
|
+
.filter(([, ownerId]) => ownerId === sessionId)
|
|
717
|
+
.map(([tabId]) => tabId);
|
|
718
|
+
for (const tabId of ownedTabs) {
|
|
719
|
+
await this._forceReleaseTab(tabId, "Session unregistered");
|
|
720
|
+
}
|
|
721
|
+
if (session.ws && session.ws.readyState === WebSocket.OPEN) {
|
|
722
|
+
try { session.ws.close(1000, "Session disconnected"); } catch { /* ignore */ }
|
|
723
|
+
}
|
|
724
|
+
this.sessions.delete(sessionId);
|
|
725
|
+
this._syncExtensionState();
|
|
726
|
+
return { ok: true };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
async _listTabs() {
|
|
730
|
+
if (this.protocolMismatch) return { ok: false, code: "protocol_mismatch", error: this.protocolError };
|
|
731
|
+
if (!this.extensionWs || this.extensionWs.readyState !== WebSocket.OPEN) {
|
|
732
|
+
return { ok: false, code: "waiting_for_browser", error: "Chrome with Ufoo extension is not connected" };
|
|
733
|
+
}
|
|
734
|
+
const rawTabs = await this._sendExtensionRpc("ufoo.listTabs", []);
|
|
735
|
+
const list = Array.isArray(rawTabs) ? rawTabs : [];
|
|
736
|
+
this.knownTabs.clear();
|
|
737
|
+
const tabs = [];
|
|
738
|
+
for (const tab of list) {
|
|
739
|
+
if (!isSupportedTab(tab)) continue;
|
|
740
|
+
this.knownTabs.set(tab.id, tab);
|
|
741
|
+
const ownerId = this.tabOwners.get(tab.id);
|
|
742
|
+
const ownerSession = ownerId ? this.sessions.get(ownerId) : null;
|
|
743
|
+
tabs.push({
|
|
744
|
+
tabId: tab.id,
|
|
745
|
+
windowId: tab.windowId,
|
|
746
|
+
active: Boolean(tab.active),
|
|
747
|
+
title: String(tab.title || ""),
|
|
748
|
+
url: String(tab.url || ""),
|
|
749
|
+
owner: ownerSession
|
|
750
|
+
? { sessionId: ownerId, projectName: ownerSession.projectName, agentName: ownerSession.agentName }
|
|
751
|
+
: null,
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
return { ok: true, paused: this.paused, tabs };
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
async _ensureTabAttached(tabId, ownerSessionId) {
|
|
758
|
+
const existing = this.attachedTabs.get(tabId);
|
|
759
|
+
if (existing && existing.ownerSessionId === ownerSessionId) return existing;
|
|
760
|
+
await this._sendExtensionRpc("chrome.debugger.attach", [{ tabId }, "1.3"]);
|
|
761
|
+
const infoRes = await this._sendExtensionRpc("chrome.debugger.sendCommand", [{ tabId }, "Target.getTargetInfo"]);
|
|
762
|
+
const targetInfo = infoRes?.targetInfo || { targetId: `tab-${tabId}`, type: "page", url: this.knownTabs.get(tabId)?.url || "", title: this.knownTabs.get(tabId)?.title || "" };
|
|
763
|
+
const relaySessionId = `pw-tab-${this.nextTabSeq++}`;
|
|
764
|
+
const attached = {
|
|
765
|
+
tabId,
|
|
766
|
+
relaySessionId,
|
|
767
|
+
targetInfo,
|
|
768
|
+
childSessions: new Set(),
|
|
769
|
+
ownerSessionId,
|
|
770
|
+
};
|
|
771
|
+
this.attachedTabs.set(tabId, attached);
|
|
772
|
+
const owner = this.sessions.get(ownerSessionId);
|
|
773
|
+
this._emitTargetAttached(owner, attached);
|
|
774
|
+
return attached;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
async _claimTab(sessionId = "", rawTabId) {
|
|
778
|
+
const session = this.sessions.get(sessionId);
|
|
779
|
+
if (!session || session.invalidated) {
|
|
780
|
+
return { ok: false, code: "browser_reconnect_required", error: "Browser session is not registered or was invalidated" };
|
|
781
|
+
}
|
|
782
|
+
if (this.paused) {
|
|
783
|
+
return { ok: false, code: "browser_paused", error: "Browser control is paused in Ufoo extension" };
|
|
784
|
+
}
|
|
785
|
+
if (!this.extensionWs || this.extensionWs.readyState !== WebSocket.OPEN) {
|
|
786
|
+
return { ok: false, code: "waiting_for_browser", error: "Chrome with Ufoo extension is not connected" };
|
|
787
|
+
}
|
|
788
|
+
const tabId = Number(rawTabId);
|
|
789
|
+
if (!Number.isInteger(tabId) || tabId <= 0) {
|
|
790
|
+
return { ok: false, code: "invalid_tab_id", error: "A valid positive integer tabId is required" };
|
|
791
|
+
}
|
|
792
|
+
// Refresh tab list if unknown
|
|
793
|
+
if (!this.knownTabs.has(tabId)) {
|
|
794
|
+
await this._listTabs();
|
|
795
|
+
}
|
|
796
|
+
const tab = this.knownTabs.get(tabId);
|
|
797
|
+
if (!tab || !isSupportedTab(tab)) {
|
|
798
|
+
return { ok: false, code: "unsupported_tab", error: `Tab ${tabId} was not found or is an unsupported/incognito Chrome page` };
|
|
799
|
+
}
|
|
800
|
+
const currentOwnerId = this.tabOwners.get(tabId);
|
|
801
|
+
if (currentOwnerId && currentOwnerId !== sessionId) {
|
|
802
|
+
const ownerSession = this.sessions.get(currentOwnerId);
|
|
803
|
+
return {
|
|
804
|
+
ok: false,
|
|
805
|
+
code: "browser_tab_busy",
|
|
806
|
+
error: `Tab ${tabId} is currently in use by ${ownerSession?.projectName || "another project"} (${ownerSession?.agentName || "agent"})`,
|
|
807
|
+
owner: {
|
|
808
|
+
projectName: ownerSession?.projectName || "unknown",
|
|
809
|
+
agentName: ownerSession?.agentName || "agent",
|
|
810
|
+
},
|
|
811
|
+
};
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
this.tabOwners.set(tabId, sessionId);
|
|
815
|
+
session.releasedSinceLastClaim = false;
|
|
816
|
+
try {
|
|
817
|
+
const attached = await this._ensureTabAttached(tabId, sessionId);
|
|
818
|
+
this._syncExtensionState();
|
|
819
|
+
return {
|
|
820
|
+
ok: true,
|
|
821
|
+
tabId,
|
|
822
|
+
relaySessionId: attached.relaySessionId,
|
|
823
|
+
targetId: attached.targetInfo?.targetId || "",
|
|
824
|
+
title: tab.title || "",
|
|
825
|
+
url: tab.url || "",
|
|
826
|
+
};
|
|
827
|
+
} catch (error) {
|
|
828
|
+
this.tabOwners.delete(tabId);
|
|
829
|
+
this.attachedTabs.delete(tabId);
|
|
830
|
+
this._syncExtensionState();
|
|
831
|
+
return { ok: false, code: "tab_attach_failed", error: error?.message || "Failed to attach debugger to tab" };
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
async _createTab(sessionId = "", url = "") {
|
|
836
|
+
const session = this.sessions.get(sessionId);
|
|
837
|
+
if (!session || session.invalidated) {
|
|
838
|
+
return { ok: false, code: "browser_reconnect_required", error: "Browser session is not registered or was invalidated" };
|
|
839
|
+
}
|
|
840
|
+
if (this.paused) {
|
|
841
|
+
return { ok: false, code: "browser_paused", error: "Browser control is paused in Ufoo extension" };
|
|
842
|
+
}
|
|
843
|
+
const created = await this._sendExtensionRpc("chrome.tabs.create", [{
|
|
844
|
+
url: url || "about:blank",
|
|
845
|
+
active: !this.background,
|
|
846
|
+
}]);
|
|
847
|
+
if (!created || created.id === undefined) {
|
|
848
|
+
return { ok: false, code: "tab_create_failed", error: "Failed to create browser tab" };
|
|
849
|
+
}
|
|
850
|
+
if (!isSupportedTab(created)) {
|
|
851
|
+
await this._sendExtensionRpc("chrome.tabs.remove", [created.id]).catch(() => {});
|
|
852
|
+
return { ok: false, code: "unsupported_tab", error: "Cannot control internal or incognito Chrome pages" };
|
|
853
|
+
}
|
|
854
|
+
this.knownTabs.set(created.id, created);
|
|
855
|
+
return this._claimTab(sessionId, created.id);
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
async _closeTab(sessionId = "", tabId) {
|
|
859
|
+
const numId = Number(tabId);
|
|
860
|
+
if (!Number.isInteger(numId)) return { ok: false, code: "invalid_tab_id", error: "tabId is required" };
|
|
861
|
+
if (this.tabOwners.get(numId) !== sessionId) {
|
|
862
|
+
return { ok: false, code: "tab_not_owned", error: "Session does not own this tab" };
|
|
863
|
+
}
|
|
864
|
+
await this._forceReleaseTab(numId, "Closed by owning session");
|
|
865
|
+
await this._sendExtensionRpc("chrome.tabs.remove", [numId]).catch(() => {});
|
|
866
|
+
this.knownTabs.delete(numId);
|
|
867
|
+
return { ok: true, closedTabId: numId };
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
async _releaseTab(sessionId = "", tabId) {
|
|
871
|
+
const numId = Number(tabId);
|
|
872
|
+
if (!Number.isInteger(numId)) return { ok: false, code: "invalid_tab_id", error: "tabId is required" };
|
|
873
|
+
if (this.tabOwners.get(numId) !== sessionId) {
|
|
874
|
+
return { ok: true, released: false };
|
|
875
|
+
}
|
|
876
|
+
await this._forceReleaseTab(numId, "Released by session");
|
|
877
|
+
return { ok: true, released: true };
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
_sessionTabStatus(sessionId = "") {
|
|
881
|
+
const session = this.sessions.get(sessionId);
|
|
882
|
+
const ownedTabs = [];
|
|
883
|
+
for (const [tabId, ownerId] of this.tabOwners.entries()) {
|
|
884
|
+
if (ownerId !== sessionId) continue;
|
|
885
|
+
const tab = this.knownTabs.get(tabId) || {};
|
|
886
|
+
const attached = this.attachedTabs.get(tabId);
|
|
887
|
+
ownedTabs.push({
|
|
888
|
+
tabId,
|
|
889
|
+
targetId: attached?.targetInfo?.targetId || "",
|
|
890
|
+
title: tab.title || "",
|
|
891
|
+
url: tab.url || "",
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
return {
|
|
895
|
+
ok: true,
|
|
896
|
+
paused: this.paused,
|
|
897
|
+
invalidated: Boolean(!session || session.invalidated),
|
|
898
|
+
releasedSinceLastClaim: Boolean(session && session.releasedSinceLastClaim),
|
|
899
|
+
ownedTabs,
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
_attachCdpWs(session, ws) {
|
|
904
|
+
session.ws = ws;
|
|
905
|
+
session.autoAttach = false;
|
|
906
|
+
ws.on("message", async (raw) => {
|
|
907
|
+
let msg;
|
|
908
|
+
try {
|
|
909
|
+
msg = JSON.parse(raw.toString("utf8"));
|
|
910
|
+
} catch {
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
const { id, sessionId: cdpSessionId, method, params } = msg;
|
|
914
|
+
try {
|
|
915
|
+
const result = await this._handleCdpCommand(session, method, params, cdpSessionId);
|
|
916
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
917
|
+
ws.send(JSON.stringify({ id, sessionId: cdpSessionId, result }));
|
|
918
|
+
}
|
|
919
|
+
} catch (error) {
|
|
920
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
921
|
+
ws.send(JSON.stringify({ id, sessionId: cdpSessionId, error: { message: error?.message || String(error) } }));
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
});
|
|
925
|
+
ws.on("close", () => {
|
|
926
|
+
if (session.ws === ws) session.ws = null;
|
|
927
|
+
});
|
|
928
|
+
ws.on("error", () => {});
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
_ownedAttachedTabs(agentSessionId) {
|
|
932
|
+
const list = [];
|
|
933
|
+
for (const attached of this.attachedTabs.values()) {
|
|
934
|
+
if (attached.ownerSessionId === agentSessionId) list.push(attached);
|
|
935
|
+
}
|
|
936
|
+
return list;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
_debuggerTargetForSession(agentSessionId, method, cdpSessionId) {
|
|
940
|
+
const owned = this._ownedAttachedTabs(agentSessionId);
|
|
941
|
+
if (!cdpSessionId) {
|
|
942
|
+
if (owned.length === 0) {
|
|
943
|
+
throw new Error(`No claimed tab for session to execute ${method}`);
|
|
944
|
+
}
|
|
945
|
+
return { tabId: owned[0].tabId };
|
|
946
|
+
}
|
|
947
|
+
const direct = owned.find((item) => item.relaySessionId === cdpSessionId);
|
|
948
|
+
if (direct) return { tabId: direct.tabId };
|
|
949
|
+
const parent = owned.find((item) => item.childSessions.has(cdpSessionId));
|
|
950
|
+
if (parent) return { tabId: parent.tabId, sessionId: cdpSessionId };
|
|
951
|
+
throw new Error(`Session does not own CDP target ${cdpSessionId}`);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
async _handleCdpCommand(session, method, params, cdpSessionId) {
|
|
955
|
+
if (this.paused || session.invalidated) {
|
|
956
|
+
throw new Error("Browser control is paused or session was invalidated");
|
|
957
|
+
}
|
|
958
|
+
switch (method) {
|
|
959
|
+
case "Browser.getVersion":
|
|
960
|
+
return {
|
|
961
|
+
protocolVersion: "1.3",
|
|
962
|
+
product: "Chrome/Extension-Bridge",
|
|
963
|
+
userAgent: "ufoo-browser-relay/1.0.0",
|
|
964
|
+
};
|
|
965
|
+
case "Browser.setDownloadBehavior":
|
|
966
|
+
return {};
|
|
967
|
+
case "Target.setAutoAttach": {
|
|
968
|
+
if (cdpSessionId) break;
|
|
969
|
+
session.autoAttach = true;
|
|
970
|
+
for (const attached of this._ownedAttachedTabs(session.sessionId)) {
|
|
971
|
+
this._emitTargetAttached(session, attached);
|
|
972
|
+
}
|
|
973
|
+
return {};
|
|
974
|
+
}
|
|
975
|
+
case "Target.createTarget": {
|
|
976
|
+
const created = await this._createTab(session.sessionId, params?.url);
|
|
977
|
+
if (!created.ok) throw new Error(created.error || "Failed to create target");
|
|
978
|
+
return { targetId: created.targetId };
|
|
979
|
+
}
|
|
980
|
+
case "Target.closeTarget": {
|
|
981
|
+
const targetId = params?.targetId;
|
|
982
|
+
const owned = this._ownedAttachedTabs(session.sessionId)
|
|
983
|
+
.find((item) => item.targetInfo?.targetId === targetId);
|
|
984
|
+
if (!owned) return { success: false };
|
|
985
|
+
await this._closeTab(session.sessionId, owned.tabId);
|
|
986
|
+
return { success: true };
|
|
987
|
+
}
|
|
988
|
+
case "Target.getTargetInfo": {
|
|
989
|
+
const owned = this._ownedAttachedTabs(session.sessionId)
|
|
990
|
+
.find((item) => item.relaySessionId === cdpSessionId);
|
|
991
|
+
return owned ? owned.targetInfo : undefined;
|
|
992
|
+
}
|
|
993
|
+
case "Page.bringToFront":
|
|
994
|
+
case "Target.activateTarget":
|
|
995
|
+
if (this.background) return {};
|
|
996
|
+
break;
|
|
997
|
+
default:
|
|
998
|
+
break;
|
|
999
|
+
}
|
|
1000
|
+
const target = this._debuggerTargetForSession(session.sessionId, method, cdpSessionId);
|
|
1001
|
+
return this._sendExtensionRpc("chrome.debugger.sendCommand", [target, method, params]);
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
_onDebuggerEvent(source, method, params) {
|
|
1005
|
+
if (!source || source.tabId === undefined) return;
|
|
1006
|
+
const attached = this.attachedTabs.get(source.tabId);
|
|
1007
|
+
if (!attached) return;
|
|
1008
|
+
const owner = this.sessions.get(attached.ownerSessionId);
|
|
1009
|
+
if (!owner || !owner.ws || owner.ws.readyState !== WebSocket.OPEN) return;
|
|
1010
|
+
|
|
1011
|
+
const childSessionId = params?.sessionId;
|
|
1012
|
+
if (method === "Target.attachedToTarget" && childSessionId) {
|
|
1013
|
+
attached.childSessions.add(childSessionId);
|
|
1014
|
+
} else if (method === "Target.detachedFromTarget" && childSessionId) {
|
|
1015
|
+
attached.childSessions.delete(childSessionId);
|
|
1016
|
+
}
|
|
1017
|
+
const outSessionId = source.sessionId || attached.relaySessionId;
|
|
1018
|
+
owner.ws.send(JSON.stringify({ sessionId: outSessionId, method, params }));
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
module.exports = {
|
|
1023
|
+
BrowserBroker,
|
|
1024
|
+
isSupportedTab,
|
|
1025
|
+
parseExtensionOrigin,
|
|
1026
|
+
parseBearerToken,
|
|
1027
|
+
};
|