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.
Files changed (160) hide show
  1. package/README.md +239 -19
  2. package/README.zh-CN.md +3 -3
  3. package/bin/ucode.js +10 -2
  4. package/bin/ufoo.js +3 -0
  5. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  6. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  7. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  8. package/dist/tui/linux-x64/ufoo-tui +0 -0
  9. package/{OBSERVABILITY.md → docs/OBSERVABILITY.md} +3 -3
  10. package/docs/README.md +27 -0
  11. package/extensions/ufoo-browser/LICENSE +152 -0
  12. package/extensions/ufoo-browser/NOTICE +10 -0
  13. package/extensions/ufoo-browser/README.md +30 -0
  14. package/extensions/ufoo-browser/background.js +409 -0
  15. package/extensions/ufoo-browser/icons/icon-128.png +0 -0
  16. package/extensions/ufoo-browser/icons/icon-16.png +0 -0
  17. package/extensions/ufoo-browser/icons/icon-256.png +0 -0
  18. package/extensions/ufoo-browser/icons/icon-32.png +0 -0
  19. package/extensions/ufoo-browser/icons/icon-48.png +0 -0
  20. package/extensions/ufoo-browser/icons/logo.png +0 -0
  21. package/extensions/ufoo-browser/icons/toolbar-16.png +0 -0
  22. package/extensions/ufoo-browser/icons/toolbar-32.png +0 -0
  23. package/extensions/ufoo-browser/icons/toolbar-logo.png +0 -0
  24. package/extensions/ufoo-browser/manifest.json +30 -0
  25. package/extensions/ufoo-browser/popup.css +71 -0
  26. package/extensions/ufoo-browser/popup.html +44 -0
  27. package/extensions/ufoo-browser/popup.js +153 -0
  28. package/package.json +7 -5
  29. package/scripts/postinstall.js +6 -0
  30. package/src/agents/capabilities/browser/index.js +49 -0
  31. package/src/agents/capabilities/coding/backgroundHooks.js +94 -0
  32. package/src/agents/capabilities/coding/index.js +30 -1
  33. package/src/agents/capabilities/index.js +5 -2
  34. package/src/agents/capabilities/planning/index.js +44 -5
  35. package/src/agents/capabilities/turnRecall/index.js +341 -0
  36. package/src/agents/controller/controllerToolExecutor.js +2 -2
  37. package/src/agents/internal/internalRunner.js +30 -8
  38. package/src/agents/internal/taskControl.js +107 -0
  39. package/src/agents/profiles/coding.js +1 -1
  40. package/src/agents/profiles/main.js +1 -1
  41. package/src/agents/prompts/mainAgent.js +1 -0
  42. package/src/agents/prompts/native/toolDescriptions/bash.js +7 -1
  43. package/src/agents/providers/claudeSessionFiles.js +1 -1
  44. package/src/agents/providers/codexThreadProvider.js +6 -1
  45. package/src/agents/providers/credentials/agy.js +171 -0
  46. package/src/agents/providers/directAuthStatus.js +20 -2
  47. package/src/agents/providers/modelsCatalog.js +26 -5
  48. package/src/agents/providers/nativeTransport.js +145 -73
  49. package/src/agents/providers/providerId.js +17 -0
  50. package/src/agents/providers/runtimeConfig.js +67 -20
  51. package/src/agents/providers/transports/antigravityTransport.js +242 -0
  52. package/src/agents/providers/transports/index.js +1 -0
  53. package/src/agents/providers/transports/openaiChatTransport.js +3 -2
  54. package/src/agents/providers/transports/openaiResponsesTransport.js +2 -1
  55. package/src/agents/providers/transports/responsesProtocol.js +119 -18
  56. package/src/agents/providers/transports/transportContract.js +1 -0
  57. package/src/agents/providers/upstreamRuntime.js +3 -1
  58. package/src/agents/runtime/context/contextBudget.js +1 -19
  59. package/src/agents/runtime/context/contextWindow.js +5 -0
  60. package/src/agents/runtime/context/replayHistory.js +16 -10
  61. package/src/agents/runtime/context/runtimeStore.js +0 -1
  62. package/src/agents/runtime/context/sessionJournal.js +1 -1
  63. package/src/agents/runtime/context/slidingWindowManager.js +792 -0
  64. package/src/agents/runtime/context/topicSelector.js +338 -0
  65. package/src/agents/runtime/context/turnAnalyzer.js +767 -0
  66. package/src/agents/runtime/context/turnIndexStore.js +515 -0
  67. package/src/agents/runtime/core/agentLoop.js +140 -35
  68. package/src/agents/runtime/core/executionBudget.js +2 -1
  69. package/src/agents/runtime/core/toolErrorGuard.js +39 -0
  70. package/src/agents/runtime/createAgentRuntime.js +80 -7
  71. package/src/agents/runtime/index.js +5 -0
  72. package/src/agents/runtime/protocol/materialize.js +1 -1
  73. package/src/agents/runtime/tasks/hooks.js +137 -0
  74. package/src/app/chat/ChatController.js +8 -4
  75. package/src/app/chat/daemonMessageRouter.js +3 -1
  76. package/src/app/chat/inputSubmitHandler.js +2 -2
  77. package/src/app/chat/transport.js +1 -1
  78. package/src/app/cli/browserCommands.js +340 -0
  79. package/src/app/cli/busCoreCommands.js +63 -3
  80. package/src/app/cli/features/doctor.js +21 -0
  81. package/src/app/cli/metricsCommands.js +1 -1
  82. package/src/app/cli/run.js +81 -1
  83. package/src/app/cli/setupCommands.js +200 -0
  84. package/src/code/UcodeController.js +31 -1
  85. package/src/code/agent.js +76 -25
  86. package/src/code/busConsumer.js +13 -12
  87. package/src/code/commands.js +0 -1
  88. package/src/code/context/assembler.js +11 -88
  89. package/src/code/context/planGraphService.js +121 -6
  90. package/src/code/context/planProjection.js +10 -2
  91. package/src/code/context/reducers.js +172 -4
  92. package/src/code/context/stateCommit.js +0 -32
  93. package/src/code/context/transcript.js +7 -4
  94. package/src/code/internalThread.js +9 -1
  95. package/src/code/launcher/ucode.js +4 -2
  96. package/src/code/modelCommand.js +6 -5
  97. package/src/code/nativeRunner.js +232 -62
  98. package/src/code/repl.js +27 -1
  99. package/src/code/runtime/agentWakeup.js +20 -3
  100. package/src/code/runtime/backgroundWakeHost.js +45 -0
  101. package/src/code/runtime/taskFocusContext.js +7 -0
  102. package/src/code/runtime/taskLoop.js +24 -1
  103. package/src/code/sessionStore.js +14 -10
  104. package/src/code/taskDecomposer.js +16 -7
  105. package/src/code/tools/backgroundProcess.js +23 -0
  106. package/src/code/tools/bash.js +764 -12
  107. package/src/code/tools/executor.js +13 -4
  108. package/src/code/tools/planGraph.js +1 -0
  109. package/src/code/tools/specs.js +62 -4
  110. package/src/code/tools/taskRun.js +38 -0
  111. package/src/config.js +92 -6
  112. package/src/coordination/bus/index.js +2 -2
  113. package/src/coordination/bus/message.js +10 -1
  114. package/src/coordination/bus/nickname.js +3 -1
  115. package/src/coordination/bus/subscriber.js +25 -10
  116. package/src/coordination/bus/utils.js +4 -0
  117. package/src/coordination/bus/wakeEndpoint.js +198 -0
  118. package/src/coordination/history/agentPerformance.js +18 -18
  119. package/src/coordination/history/agentTrace.js +7 -3
  120. package/src/coordination/state/paths.js +4 -0
  121. package/src/coordination/state/workspaceAccess.js +3 -1
  122. package/src/orchestration/groups/modelConfig.js +66 -0
  123. package/src/orchestration/groups/validateTemplate.js +2 -0
  124. package/src/runtime/browser/broker.js +1027 -0
  125. package/src/runtime/browser/brokerClient.js +108 -0
  126. package/src/runtime/browser/componentInstaller.js +275 -0
  127. package/src/runtime/browser/installState.js +329 -0
  128. package/src/runtime/browser/manifest.js +145 -0
  129. package/src/runtime/browser/native-host-runner.js +198 -0
  130. package/src/runtime/browser/nativeHost.js +213 -0
  131. package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
  132. package/src/runtime/browser/paths.js +134 -0
  133. package/src/runtime/browser/playwrightSession.js +614 -0
  134. package/src/runtime/daemon/agentHost.js +175 -28
  135. package/src/runtime/daemon/busBridge.js +2 -1
  136. package/src/runtime/daemon/deliveryScheduler.js +70 -2
  137. package/src/runtime/daemon/globalDaemon.js +20 -0
  138. package/src/runtime/daemon/groupOrchestrator.js +20 -1
  139. package/src/runtime/daemon/index.js +6 -4
  140. package/src/runtime/daemon/ops.js +14 -8
  141. package/src/tools/handlers/listAgents.js +1 -1
  142. package/src/tools/handlers/readBusSummary.js +1 -1
  143. package/src/tools/handlers/routeAgent.js +122 -5
  144. package/src/tools/schemaFixtures.js +1 -1
  145. package/src/ui/agentSurface.js +60 -6
  146. package/src/ui/format/index.js +34 -2
  147. package/src/ui/format/markdownRenderer.js +4 -2
  148. package/src/ui/rustChatHost.js +22 -7
  149. package/src/ui/rustMultiSession.js +14 -2
  150. package/src/ui/rustUcodeHost.js +249 -80
  151. package/src/ui/ucodeAgentSession.js +88 -0
  152. package/templates/groups/build-lane.json +57 -3
  153. package/templates/groups/build-ultra.json +114 -6
  154. package/templates/groups/design-system.json +57 -3
  155. package/templates/groups/product-discovery.json +57 -3
  156. package/templates/groups/ui-plan-review.json +57 -3
  157. package/templates/groups/ui-polish.json +57 -3
  158. package/templates/groups/verify-ship.json +57 -3
  159. package/src/agents/runtime/context/checkpointStore.js +0 -38
  160. package/src/agents/runtime/context/compaction.js +0 -151
@@ -0,0 +1,614 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const os = require("os");
5
+ const path = require("path");
6
+ const { createHash, randomUUID } = require("crypto");
7
+ const { Client } = require("@modelcontextprotocol/sdk/client/index.js");
8
+ const { StdioClientTransport, getDefaultEnvironment } = require("@modelcontextprotocol/sdk/client/stdio.js");
9
+ const { AjvJsonSchemaValidator } = require("@modelcontextprotocol/sdk/validation/ajv-provider.js");
10
+ const lockfile = require("proper-lockfile");
11
+ const { loadGlobalBrowserConfig } = require("../../config");
12
+ const {
13
+ resolveMcpCliEntrypoint,
14
+ acquireRuntimeLease,
15
+ computeBrowserSetupStatus,
16
+ } = require("./installState");
17
+ const {
18
+ requestBroker,
19
+ ensureBrokerRunning,
20
+ } = require("./brokerClient");
21
+
22
+ // Deliberately exclude browser_install/browser_close and arbitrary Node execution.
23
+ // Disconnecting the MCP client must never close the user's browser.
24
+ const ALLOWED_TOOLS = new Set([
25
+ "browser_tabs", "browser_navigate", "browser_navigate_back", "browser_snapshot", "browser_find",
26
+ "browser_click", "browser_type", "browser_press_key", "browser_hover", "browser_drag",
27
+ "browser_select_option", "browser_fill_form", "browser_handle_dialog", "browser_wait_for",
28
+ "browser_take_screenshot", "browser_evaluate", "browser_file_upload", "browser_drop",
29
+ "browser_console_messages", "browser_network_requests",
30
+ "browser_mouse_move_xy", "browser_mouse_click_xy", "browser_mouse_drag_xy", "browser_mouse_wheel",
31
+ ]);
32
+ const READ_TOOLS = new Set(["browser_snapshot", "browser_find", "browser_take_screenshot", "browser_console_messages", "browser_network_requests", "browser_wait_for"]);
33
+ const hash = (text) => createHash("sha256").update(text).digest("hex").slice(0, 24);
34
+ const failure = (code, error, extra = {}) => ({ ok: false, code, error, ...extra });
35
+ const setup = "Enable browser support with `ufoo setup --browser=install` (or `ufoo browser install`) and install the Ufoo Chrome extension. For explicit CDP, set UFOO_BROWSER_CDP_ENDPOINT. Never fall back to launching another browser.";
36
+
37
+ function readConnectionConfig(env = process.env, { loadBrowserConfig = null } = {}) {
38
+ const endpoint = String(env.UFOO_BROWSER_CDP_ENDPOINT || "").trim();
39
+ if (endpoint && !["chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", "msedge-canary"].includes(endpoint)) {
40
+ const url = new URL(endpoint);
41
+ if (!["http:", "https:", "ws:", "wss:"].includes(url.protocol)) throw new Error("Invalid browser CDP endpoint protocol");
42
+ }
43
+ if (endpoint) {
44
+ return {
45
+ mode: "cdp",
46
+ endpoint,
47
+ headers: [],
48
+ profile: String(env.UFOO_BROWSER_PROFILE || "").trim(),
49
+ };
50
+ }
51
+ const hostCfg = typeof loadBrowserConfig === "function" ? loadBrowserConfig() : null;
52
+ if (hostCfg && hostCfg.backend === "ufoo-extension") {
53
+ return {
54
+ mode: "ufoo-extension",
55
+ endpoint: "",
56
+ headers: [],
57
+ profile: String(env.UFOO_BROWSER_PROFILE || hostCfg.profile || "").trim(),
58
+ };
59
+ }
60
+ return {
61
+ mode: "extension",
62
+ endpoint: "",
63
+ headers: [],
64
+ profile: String(env.UFOO_BROWSER_PROFILE || "").trim(),
65
+ };
66
+ }
67
+
68
+ async function acquireCdpLease() {
69
+ // One CDP owner per OS user, across processes and workspaces. Endpoint aliases
70
+ // can refer to the same Chrome; a conservative global lease avoids that race.
71
+ const dir = path.join(os.tmpdir(), `ufoo-browser-${process.getuid?.() ?? os.userInfo().username}`);
72
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
73
+ try {
74
+ return await lockfile.lock(path.join(dir, "cdp"), { realpath: false, stale: 30000, update: 10000, retries: 0 });
75
+ } catch (error) {
76
+ if (error.code === "ELOCKED") throw Object.assign(new Error("Another ufoo/ucode session owns the CDP browser. Disconnect it first, or use extension mode for independently owned tabs."), { code: "browser_busy" });
77
+ throw error;
78
+ }
79
+ }
80
+
81
+ function browserProcessEnvironment(env = process.env) {
82
+ const childEnv = getDefaultEnvironment();
83
+ for (const key of ["TMPDIR", "TMP", "TEMP", "DISPLAY", "WAYLAND_DISPLAY", "XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "PLAYWRIGHT_MCP_EXTENSION_TOKEN"]) {
84
+ if (env[key]) childEnv[key] = env[key];
85
+ }
86
+ return childEnv;
87
+ }
88
+
89
+ function createMcpConnection({ root, outputDir, config, name, env, cliPath = "", allowBundledFallback = true, nodeVersion = process.versions.node }) {
90
+ if (Number(nodeVersion.split(".")[0]) < 20) {
91
+ throw Object.assign(new Error("Browser automation requires Node.js 20 or newer. Upgrade Node.js and restart ufoo/ucode; core features still support Node.js 18.17+."), { code: "browser_node_unsupported" });
92
+ }
93
+ const resolved = cliPath
94
+ ? { entryPath: cliPath, version: "" }
95
+ : resolveMcpCliEntrypoint({ env, allowBundledFallback });
96
+ if (!resolved || !resolved.entryPath) {
97
+ throw Object.assign(new Error("Playwright MCP optional runtime is not installed. Run `ufoo browser install` first."), { code: "not_installed" });
98
+ }
99
+ const args = [resolved.entryPath, "--no-webmcp", "--caps", "vision", "--codegen", "none", "--image-responses", "allow",
100
+ "--output-dir", outputDir, "--file-paths", "absolute", "--timeout-action", "10000", "--timeout-navigation", "45000"];
101
+ if (config.mode === "cdp" || config.mode === "ufoo-extension") {
102
+ args.push("--cdp-endpoint", config.endpoint);
103
+ if (Array.isArray(config.headers)) {
104
+ for (const header of config.headers) args.push("--cdp-header", header);
105
+ }
106
+ } else {
107
+ args.push("--extension");
108
+ if (config.profile) args.push("--profile-dir-name", config.profile);
109
+ }
110
+ const childEnv = browserProcessEnvironment(env);
111
+ const transport = new StdioClientTransport({ command: process.execPath, args, env: childEnv, cwd: root, stderr: "pipe" });
112
+ // Drain diagnostics without leaking extension tokens or URLs into transcripts.
113
+ transport.stderr?.on("data", () => {});
114
+ const client = new Client({ name, version: "1.0.0" });
115
+ return { client, transport };
116
+ }
117
+
118
+ function isReadCall(tool, args = {}) {
119
+ return READ_TOOLS.has(tool) || (tool === "browser_tabs" && args.action === "list");
120
+ }
121
+
122
+ function formatTabListText(tabs = [], currentSessionId = "", paused = false) {
123
+ const lines = [];
124
+ if (paused) lines.push("[Browser control is currently PAUSED in Ufoo extension]");
125
+ if (!tabs.length) {
126
+ lines.push("No open Chrome tabs found (use browser_tabs action=new to open a tab).");
127
+ return lines.join("\n");
128
+ }
129
+ lines.push("Chrome tabs (select with browser_tabs action=select and tabId):");
130
+ tabs.forEach((tab, idx) => {
131
+ const ownerTag = !tab.owner
132
+ ? "available"
133
+ : tab.owner.sessionId === currentSessionId
134
+ ? "owned-by-this-session"
135
+ : `busy (${tab.owner.projectName}/${tab.owner.agentName})`;
136
+ const activeTag = tab.active ? " [active]" : "";
137
+ lines.push(`- index=${idx} tabId=${tab.tabId}${activeTag} [${ownerTag}] ${tab.title || "(untitled)"} — ${tab.url || "about:blank"}`);
138
+ });
139
+ return lines.join("\n");
140
+ }
141
+
142
+ function augmentTabsSchema(tool) {
143
+ if (!tool || tool.name !== "browser_tabs") return tool;
144
+ const schema = tool.inputSchema ? JSON.parse(JSON.stringify(tool.inputSchema)) : { type: "object", properties: {} };
145
+ schema.properties = schema.properties || {};
146
+ schema.properties.tabId = { type: "integer", description: "Stable Chrome tabId returned by browser_tabs action=list (preferred over index in ufoo-extension mode)" };
147
+ return { ...tool, inputSchema: schema };
148
+ }
149
+
150
+ function createBrowserSessions({
151
+ env = process.env,
152
+ createConnection = createMcpConnection,
153
+ acquireLease = acquireCdpLease,
154
+ idleMs = 600000,
155
+ hostControlled = false,
156
+ loadBrowserConfig = loadGlobalBrowserConfig,
157
+ broker = { request: requestBroker, ensureRunning: ensureBrokerRunning },
158
+ } = {}) {
159
+ const sessions = new Map();
160
+ const validator = new AjvJsonSchemaValidator();
161
+
162
+ function identity(context) {
163
+ if (!context.sessionId) throw new Error("Browser operations require a sessionId");
164
+ const root = fs.realpathSync(context.workspaceRoot || process.cwd());
165
+ const id = hash(`${root}\0${context.artifactNamespace || "ucode"}\0${context.sessionId}`);
166
+ return {
167
+ root,
168
+ id,
169
+ projectName: String(context.projectName || path.basename(root) || "ufoo"),
170
+ agentName: String(context.agentName || context.artifactNamespace || "agent"),
171
+ };
172
+ }
173
+
174
+ function get(context) {
175
+ const { root, id, projectName, agentName } = identity(context);
176
+ if (!sessions.has(id)) {
177
+ sessions.set(id, {
178
+ id,
179
+ root,
180
+ projectName,
181
+ agentName,
182
+ outputDir: path.join(root, ".ufoo", "browser", id),
183
+ queue: Promise.resolve(),
184
+ client: null,
185
+ transport: null,
186
+ release: null,
187
+ runtimeRelease: null,
188
+ tools: new Map(),
189
+ state: "disconnected",
190
+ reconnectRequired: false,
191
+ lastListedTabs: [],
192
+ brokerRegistered: false,
193
+ sessionToken: "",
194
+ toolsOnlyClient: false,
195
+ });
196
+ } else {
197
+ const entry = sessions.get(id);
198
+ entry.projectName = projectName;
199
+ entry.agentName = agentName;
200
+ }
201
+ return sessions.get(id);
202
+ }
203
+
204
+ async function close(entry, { unregisterBroker = true, preserveTools = false } = {}) {
205
+ clearTimeout(entry.timer);
206
+ const { client, transport, release, runtimeRelease, brokerRegistered, config } = entry;
207
+ entry.client = null;
208
+ entry.transport = null;
209
+ entry.release = null;
210
+ entry.runtimeRelease = null;
211
+ if (unregisterBroker) {
212
+ entry.brokerRegistered = false;
213
+ entry.sessionToken = "";
214
+ }
215
+ entry.toolsOnlyClient = false;
216
+ if (!preserveTools) entry.tools.clear();
217
+ entry.state = "disconnected";
218
+ try {
219
+ await client?.close();
220
+ } finally {
221
+ try {
222
+ await transport?.close();
223
+ } finally {
224
+ if (release) await release();
225
+ if (runtimeRelease) runtimeRelease();
226
+ if (unregisterBroker && brokerRegistered && config?.mode === "ufoo-extension") {
227
+ await broker.request("unregister_session", { sessionId: entry.id }, { env }).catch(() => {});
228
+ }
229
+ }
230
+ }
231
+ }
232
+
233
+ function effectiveConfig() {
234
+ return readConnectionConfig(env, { loadBrowserConfig: hostControlled ? loadBrowserConfig : null });
235
+ }
236
+
237
+ function checkHostAvailability(cfg) {
238
+ if (!hostControlled) return { allowed: true };
239
+ if (cfg.mode === "cdp") return { allowed: true };
240
+ const browserCfg = loadBrowserConfig();
241
+ if (!browserCfg.enabled) {
242
+ return {
243
+ allowed: false,
244
+ code: "browser_disabled",
245
+ error: "ufoo Browser is disabled or not configured. Run `ufoo setup --browser=install` or `ufoo browser enable` to enable it.",
246
+ };
247
+ }
248
+ const resolvedCli = resolveMcpCliEntrypoint({ env, allowBundledFallback: false });
249
+ if (!resolvedCli) {
250
+ return {
251
+ allowed: false,
252
+ code: "not_installed",
253
+ error: "ufoo Browser optional runtime component is not installed. Run `ufoo browser install` first.",
254
+ };
255
+ }
256
+ return { allowed: true, cli: resolvedCli };
257
+ }
258
+
259
+ function status(entry) {
260
+ const cfg = entry.config || effectiveConfig();
261
+ const base = {
262
+ ok: true,
263
+ state: entry.state,
264
+ mode: cfg.mode,
265
+ reconnectRequired: entry.reconnectRequired,
266
+ setup,
267
+ };
268
+ if (!hostControlled) return base;
269
+ const hostStatus = computeBrowserSetupStatus({ env });
270
+ return {
271
+ ...base,
272
+ enabled: hostStatus.enabled,
273
+ availability: hostStatus.state,
274
+ setupChoice: hostStatus.setupChoice,
275
+ runtimeInstalled: hostStatus.runtimeInstalled,
276
+ extensionInstalled: hostStatus.extensionInstalled,
277
+ };
278
+ }
279
+
280
+ async function ensureBrokerSession(entry, { requireExtension = true } = {}) {
281
+ const ensured = await broker.ensureRunning({ env });
282
+ if (!ensured.ok) {
283
+ throw Object.assign(new Error(ensured.error || "Browser broker unavailable"), { code: ensured.code || "browser_connection_failed" });
284
+ }
285
+ if (!requireExtension) return null;
286
+ const reg = await broker.request("register_session", {
287
+ sessionId: entry.id,
288
+ projectName: entry.projectName,
289
+ agentName: entry.agentName,
290
+ workspaceRoot: entry.root,
291
+ }, { env });
292
+ if (!reg || !reg.ok) {
293
+ throw Object.assign(new Error(reg?.error || "Chrome extension is not ready"), { code: reg?.code || "waiting_for_browser" });
294
+ }
295
+ entry.brokerRegistered = true;
296
+ if (entry.client && entry.sessionToken && reg.sessionToken && entry.sessionToken !== reg.sessionToken) {
297
+ await close(entry, { unregisterBroker: false });
298
+ }
299
+ entry.sessionToken = reg.sessionToken || "";
300
+ return reg;
301
+ }
302
+
303
+ async function start(entry, signal, { skipRelayConnect = false } = {}) {
304
+ if (entry.client) {
305
+ if (skipRelayConnect || !entry.toolsOnlyClient) return;
306
+ await close(entry, { unregisterBroker: false });
307
+ }
308
+ entry.config = effectiveConfig();
309
+ const avail = checkHostAvailability(entry.config);
310
+ if (!avail.allowed) {
311
+ throw Object.assign(new Error(avail.error), { code: avail.code });
312
+ }
313
+ if (entry.config.mode === "cdp") {
314
+ entry.release = await acquireLease();
315
+ } else if (entry.config.mode === "ufoo-extension") {
316
+ if (skipRelayConnect) {
317
+ // Tool schema inspection only: pass a loopback dummy endpoint without touching Chrome.
318
+ entry.config = { ...entry.config, endpoint: "ws://127.0.0.1:1/unused", headers: [] };
319
+ } else {
320
+ const reg = await ensureBrokerSession(entry, { requireExtension: true });
321
+ entry.config = {
322
+ ...entry.config,
323
+ endpoint: reg.wsEndpoint,
324
+ headers: [`Authorization: Bearer ${reg.sessionToken}`],
325
+ };
326
+ }
327
+ }
328
+
329
+ if (avail.cli && avail.cli.version) {
330
+ entry.runtimeRelease = acquireRuntimeLease(avail.cli.version, env);
331
+ }
332
+ fs.mkdirSync(entry.outputDir, { recursive: true, mode: 0o700 });
333
+ const { client, transport } = createConnection({
334
+ root: entry.root,
335
+ outputDir: entry.outputDir,
336
+ config: entry.config,
337
+ name: `ufoo-${entry.id}`,
338
+ env,
339
+ cliPath: avail.cli?.entryPath || "",
340
+ allowBundledFallback: !hostControlled,
341
+ });
342
+ entry.client = client;
343
+ entry.transport = transport;
344
+ entry.toolsOnlyClient = Boolean(skipRelayConnect);
345
+ client.onclose = () => {
346
+ if (entry.client !== client) return;
347
+ entry.state = "disconnected";
348
+ entry.reconnectRequired = !entry.toolsOnlyClient;
349
+ entry.queue = entry.queue.then(() => close(entry)).catch(() => {});
350
+ };
351
+ await client.connect(transport, { signal, timeout: 15000 });
352
+ let cursor;
353
+ do {
354
+ const page = await client.listTools(cursor ? { cursor } : {}, { signal, timeout: 15000 });
355
+ for (const tool of page.tools) {
356
+ if (ALLOWED_TOOLS.has(tool.name)) {
357
+ const normalizedTool = entry.config.mode === "ufoo-extension" ? augmentTabsSchema(tool) : tool;
358
+ entry.tools.set(normalizedTool.name, { ...normalizedTool, validate: validator.getValidator(normalizedTool.inputSchema) });
359
+ }
360
+ }
361
+ cursor = page.nextCursor;
362
+ } while (cursor);
363
+ entry.state = "ready";
364
+ }
365
+
366
+ function normalizeResult(entry, result) {
367
+ const text = (result.content || []).filter((item) => item.type === "text").map((item) => item.text).join("\n");
368
+ const output = { ok: !result.isError };
369
+ if (result.isError) { output.code = "browser_action_failed"; output.error = text.slice(0, 1500); }
370
+ if (text.length > 6000) {
371
+ output.outputPath = path.join(entry.outputDir, `${randomUUID()}.txt`);
372
+ fs.writeFileSync(output.outputPath, text, { mode: 0o600 });
373
+ output.truncated = true;
374
+ }
375
+ const image = (result.content || []).find((item) => item.type === "image");
376
+ if (image && !result.isError) {
377
+ const extension = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp" }[image.mimeType];
378
+ if (extension) {
379
+ const bytes = Buffer.from(image.data, "base64");
380
+ const file = path.join(entry.outputDir, `${randomUUID()}.${extension}`);
381
+ fs.writeFileSync(file, bytes, { mode: 0o600 });
382
+ Object.assign(output, { path: file, mediaType: image.mimeType, bytes: bytes.length, base64: image.data });
383
+ }
384
+ }
385
+ // Put artifact references before potentially escaped/large page text so
386
+ // transport clipping still leaves a way to retrieve the original output.
387
+ output.text = text.slice(0, 6000) + (output.truncated ? "\n[Truncated; use read on outputPath for the remaining content.]" : "");
388
+ return output;
389
+ }
390
+
391
+ async function handleBrokerManagedTabs(entry, args = {}, context = {}) {
392
+ const action = String(args.action || "list");
393
+ if (action === "list") {
394
+ await ensureBrokerSession(entry, { requireExtension: false });
395
+ const res = await broker.request("list_tabs", {}, { env });
396
+ if (!res || !res.ok) return failure(res?.code || "waiting_for_browser", res?.error || "Chrome extension is not connected");
397
+ entry.lastListedTabs = res.tabs || [];
398
+ entry.state = res.paused ? "disconnected" : "ready";
399
+ return {
400
+ ok: true,
401
+ paused: Boolean(res.paused),
402
+ tabs: entry.lastListedTabs,
403
+ text: formatTabListText(entry.lastListedTabs, entry.id, Boolean(res.paused)),
404
+ };
405
+ }
406
+
407
+ if (action === "select") {
408
+ let targetTabId = Number(args.tabId);
409
+ if (!Number.isInteger(targetTabId) && Number.isInteger(args.index)) {
410
+ const listed = entry.lastListedTabs[args.index];
411
+ if (listed) targetTabId = listed.tabId;
412
+ }
413
+ if (!Number.isInteger(targetTabId) || targetTabId <= 0) {
414
+ return failure("invalid_browser_arguments", "Specify a valid tabId (or index from browser_tabs action=list)");
415
+ }
416
+ await ensureBrokerSession(entry, { requireExtension: true });
417
+ const claim = await broker.request("claim_tab", { sessionId: entry.id, tabId: targetTabId }, { env });
418
+ if (!claim || !claim.ok) {
419
+ return failure(claim?.code || "browser_tab_busy", claim?.error || "Unable to claim tab", claim?.owner ? { owner: claim.owner } : {});
420
+ }
421
+ await start(entry, context.signal);
422
+ // Ensure Playwright MCP initializes its BrowserContext and selects the claimed tab.
423
+ const listCheck = await entry.client.callTool({ name: "browser_tabs", arguments: { action: "list" } }, undefined, { signal: context.signal, timeout: 15000 });
424
+ if (listCheck?.isError) return normalizeResult(entry, listCheck);
425
+ const tabStatus = await broker.request("session_tab_status", { sessionId: entry.id }, { env });
426
+ const owned = Array.isArray(tabStatus?.ownedTabs) ? tabStatus.ownedTabs : [];
427
+ const ownedIdx = owned.findIndex((item) => item.tabId === targetTabId);
428
+ if (ownedIdx >= 0) {
429
+ const selCheck = await entry.client.callTool({ name: "browser_tabs", arguments: { action: "select", index: ownedIdx } }, undefined, { signal: context.signal, timeout: 15000 });
430
+ if (selCheck?.isError) return normalizeResult(entry, selCheck);
431
+ }
432
+ entry.state = "connected";
433
+ return {
434
+ ok: true,
435
+ tabId: targetTabId,
436
+ title: claim.title || "",
437
+ url: claim.url || "",
438
+ text: `Selected tabId=${targetTabId}: ${claim.title || "(untitled)"} — ${claim.url || ""}`,
439
+ };
440
+ }
441
+
442
+ if (action === "new") {
443
+ if (context.executionState?.planMode) return failure("plan_mode", "Browser actions that change state require plan mode to be off");
444
+ await ensureBrokerSession(entry, { requireExtension: true });
445
+ const created = await broker.request("create_tab", { sessionId: entry.id, url: args.url || "" }, { env });
446
+ if (!created || !created.ok) return failure(created?.code || "browser_action_failed", created?.error || "Failed to create tab");
447
+ await start(entry, context.signal);
448
+ const listCheck = await entry.client.callTool({ name: "browser_tabs", arguments: { action: "list" } }, undefined, { signal: context.signal, timeout: 15000 });
449
+ if (listCheck?.isError) return normalizeResult(entry, listCheck);
450
+ const tabStatus = await broker.request("session_tab_status", { sessionId: entry.id }, { env });
451
+ const owned = Array.isArray(tabStatus?.ownedTabs) ? tabStatus.ownedTabs : [];
452
+ const ownedIdx = owned.findIndex((item) => item.tabId === created.tabId);
453
+ if (ownedIdx >= 0) {
454
+ const selCheck = await entry.client.callTool({ name: "browser_tabs", arguments: { action: "select", index: ownedIdx } }, undefined, { signal: context.signal, timeout: 15000 });
455
+ if (selCheck?.isError) return normalizeResult(entry, selCheck);
456
+ }
457
+ entry.state = "connected";
458
+ return {
459
+ ok: true,
460
+ tabId: created.tabId,
461
+ title: created.title || "",
462
+ url: created.url || args.url || "about:blank",
463
+ text: `Opened new owned tabId=${created.tabId} (${created.url || args.url || "about:blank"})`,
464
+ };
465
+ }
466
+
467
+ if (action === "close") {
468
+ if (context.executionState?.planMode) return failure("plan_mode", "Browser actions that change state require plan mode to be off");
469
+ const tabStatus = await broker.request("session_tab_status", { sessionId: entry.id }, { env });
470
+ const owned = Array.isArray(tabStatus?.ownedTabs) ? tabStatus.ownedTabs : [];
471
+ let targetTabId = Number(args.tabId);
472
+ if (!Number.isInteger(targetTabId)) {
473
+ const idx = Number.isInteger(args.index) ? args.index : 0;
474
+ targetTabId = owned[idx]?.tabId;
475
+ }
476
+ if (!Number.isInteger(targetTabId)) {
477
+ return failure("tab_not_owned", "No owned tab to close");
478
+ }
479
+ const closed = await broker.request("close_tab", { sessionId: entry.id, tabId: targetTabId }, { env });
480
+ if (!closed || !closed.ok) return failure(closed?.code || "browser_action_failed", closed?.error || "Failed to close tab");
481
+ return { ok: true, closedTabId: targetTabId, text: `Closed tabId=${targetTabId} (no replacement tab created)` };
482
+ }
483
+
484
+ return failure("invalid_browser_arguments", `Unsupported browser_tabs action: ${action}`);
485
+ }
486
+
487
+ async function execute(input = {}, context = {}) {
488
+ let entry;
489
+ try { entry = get(context); } catch (error) { return failure("browser_context_required", error.message); }
490
+ if (input.operation === "status") return status(entry);
491
+
492
+ const run = async () => {
493
+ clearTimeout(entry.timer);
494
+ if (context.signal?.aborted) return failure("cancelled", "Browser operation cancelled before execution");
495
+ const operation = input.operation;
496
+ if (operation === "disconnect") { await close(entry); entry.reconnectRequired = false; return status(entry); }
497
+ if (!["connect", "tools", "call"].includes(operation)) return failure("invalid_browser_operation", "Use status, connect, tools, call or disconnect");
498
+
499
+ const cfg = effectiveConfig();
500
+ const avail = checkHostAvailability(cfg);
501
+ if (!avail.allowed) {
502
+ return failure(avail.code, avail.error);
503
+ }
504
+
505
+ const tool = operation === "connect" ? "browser_tabs" : input.tool;
506
+ const args = operation === "connect" ? { action: "list" } : (input.arguments || {});
507
+ if (operation === "call" && !ALLOWED_TOOLS.has(tool)) return failure("unsupported_browser_tool", "Use browser tools to discover supported operations");
508
+ if (operation === "call" && context.executionState?.planMode && !isReadCall(tool, args)) return failure("plan_mode", "Browser actions that change state require plan mode to be off");
509
+ if (args.isolatedContext && args.isolatedContext !== "default") return failure("existing_browser_only", "Use the existing browser context; isolated contexts are disabled");
510
+ if (entry.reconnectRequired && operation !== "connect") {
511
+ return failure("browser_reconnect_required", "The browser connection was lost. Explicitly connect and inspect the current page before deciding whether to repeat any action.");
512
+ }
513
+
514
+ let dispatched = false;
515
+ try {
516
+ if (operation === "connect" && entry.reconnectRequired) {
517
+ await close(entry);
518
+ entry.reconnectRequired = false;
519
+ }
520
+
521
+ if (operation === "tools") {
522
+ if (cfg.mode === "ufoo-extension") {
523
+ if (entry.tools.size === 0) {
524
+ const hadClient = Boolean(entry.client);
525
+ await start(entry, context.signal, { skipRelayConnect: !hadClient });
526
+ if (!hadClient) {
527
+ await close(entry, { unregisterBroker: false, preserveTools: true });
528
+ }
529
+ }
530
+ } else {
531
+ await start(entry, context.signal, { skipRelayConnect: false });
532
+ }
533
+ if (!tool) return { ok: true, tools: [...entry.tools.values()].map((item) => ({ name: item.name, description: item.description })) };
534
+ const found = entry.tools.get(tool);
535
+ return found ? { ok: true, name: found.name, description: found.description, inputSchema: found.inputSchema } : failure("unsupported_browser_tool", "Tool is unavailable in this Playwright version");
536
+ }
537
+
538
+ if (cfg.mode === "ufoo-extension" && tool === "browser_tabs") {
539
+ return await handleBrokerManagedTabs(entry, args, context);
540
+ }
541
+
542
+ if (cfg.mode === "ufoo-extension") {
543
+ const tabStatus = await broker.request("session_tab_status", { sessionId: entry.id }, { env });
544
+ if (tabStatus?.paused) {
545
+ await close(entry);
546
+ return failure("browser_paused", "Browser control is paused in Ufoo extension");
547
+ }
548
+ if (tabStatus?.invalidated || tabStatus?.releasedSinceLastClaim) {
549
+ await close(entry);
550
+ entry.reconnectRequired = true;
551
+ return failure("browser_reconnect_required", "Tab control was released or interrupted. Reconnect and re-verify the page before acting.");
552
+ }
553
+ if (!Array.isArray(tabStatus?.ownedTabs) || tabStatus.ownedTabs.length === 0) {
554
+ return failure("tab_selection_required", "No tab is claimed for this session. Call browser_tabs with action=list and action=select (with tabId) or action=new first.");
555
+ }
556
+ }
557
+
558
+ await start(entry, context.signal);
559
+ const definition = entry.tools.get(tool);
560
+ if (!definition) return failure("unsupported_browser_tool", "Tool is unavailable in this Playwright version");
561
+ const checked = definition.validate(args);
562
+ if (!checked.valid) return failure("invalid_browser_arguments", checked.errorMessage);
563
+ entry.state = entry.state === "connected" ? "connected" : "connecting";
564
+ dispatched = true;
565
+ const result = await entry.client.callTool({ name: tool, arguments: args }, undefined, { signal: context.signal, timeout: 60000, resetTimeoutOnProgress: false });
566
+ entry.state = result.isError && entry.state === "connecting" ? "ready" : "connected";
567
+ return normalizeResult(entry, result);
568
+ } catch (error) {
569
+ await close(entry).catch(() => {});
570
+ entry.reconnectRequired = dispatched;
571
+ const uncertain = dispatched && !isReadCall(tool, args);
572
+ if (!uncertain && ["browser_node_unsupported", "browser_disabled", "not_installed", "waiting_for_browser", "protocol_mismatch", "browser_paused", "browser_busy"].includes(error?.code)) {
573
+ return failure(error.code, error.message);
574
+ }
575
+ return failure(
576
+ uncertain ? "browser_action_uncertain" : (error.code === "browser_busy" ? "browser_busy" : "browser_connection_failed"),
577
+ `${uncertain ? "Action outcome is unknown; do not retry automatically. Reconnect and inspect the page. " : "Could not complete the browser operation. "}${error.code === "browser_busy" ? error.message : setup}`
578
+ );
579
+ }
580
+ };
581
+
582
+ const result = entry.queue.then(run, run).finally(() => {
583
+ if (entry.client) {
584
+ entry.timer = setTimeout(() => {
585
+ entry.reconnectRequired = true;
586
+ entry.queue = entry.queue.then(() => close(entry)).catch(() => {});
587
+ }, idleMs);
588
+ entry.timer.unref?.();
589
+ }
590
+ });
591
+ entry.queue = result.catch(() => {});
592
+ return result;
593
+ }
594
+
595
+ async function disconnect(context) { return execute({ operation: "disconnect" }, context); }
596
+ async function closeAll() { await Promise.all([...sessions.values()].map((entry) => entry.queue.then(() => close(entry)))); sessions.clear(); }
597
+ return { execute, disconnect, closeAll };
598
+ }
599
+
600
+ let shared;
601
+ function getBrowserSessions() {
602
+ return shared ||= createBrowserSessions({ hostControlled: true });
603
+ }
604
+
605
+ module.exports = {
606
+ createBrowserSessions,
607
+ getBrowserSessions,
608
+ createMcpConnection,
609
+ readConnectionConfig,
610
+ browserProcessEnvironment,
611
+ acquireCdpLease,
612
+ ALLOWED_TOOLS,
613
+ isReadCall,
614
+ };