u-foo 4.0.5 → 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 (149) hide show
  1. package/README.md +224 -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 +5 -3
  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 +36 -20
  49. package/src/agents/providers/providerId.js +17 -0
  50. package/src/agents/providers/runtimeConfig.js +26 -19
  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 -2
  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 +95 -32
  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/features/doctor.js +21 -0
  80. package/src/app/cli/metricsCommands.js +1 -1
  81. package/src/app/cli/run.js +80 -1
  82. package/src/app/cli/setupCommands.js +200 -0
  83. package/src/code/UcodeController.js +31 -1
  84. package/src/code/agent.js +41 -7
  85. package/src/code/busConsumer.js +13 -12
  86. package/src/code/commands.js +0 -1
  87. package/src/code/context/assembler.js +11 -88
  88. package/src/code/context/planGraphService.js +83 -9
  89. package/src/code/context/planProjection.js +10 -2
  90. package/src/code/context/reducers.js +172 -4
  91. package/src/code/context/stateCommit.js +0 -32
  92. package/src/code/context/transcript.js +7 -4
  93. package/src/code/internalThread.js +9 -1
  94. package/src/code/launcher/ucode.js +4 -2
  95. package/src/code/nativeRunner.js +221 -10
  96. package/src/code/repl.js +27 -1
  97. package/src/code/runtime/agentWakeup.js +20 -3
  98. package/src/code/runtime/backgroundWakeHost.js +45 -0
  99. package/src/code/runtime/taskFocusContext.js +7 -0
  100. package/src/code/runtime/taskLoop.js +24 -1
  101. package/src/code/sessionStore.js +14 -10
  102. package/src/code/taskDecomposer.js +13 -7
  103. package/src/code/tools/backgroundProcess.js +23 -0
  104. package/src/code/tools/bash.js +764 -12
  105. package/src/code/tools/executor.js +12 -4
  106. package/src/code/tools/specs.js +60 -3
  107. package/src/code/tools/taskRun.js +38 -0
  108. package/src/config.js +92 -6
  109. package/src/coordination/bus/subscriber.js +1 -1
  110. package/src/coordination/history/agentPerformance.js +18 -18
  111. package/src/coordination/history/agentTrace.js +7 -3
  112. package/src/coordination/state/workspaceAccess.js +3 -1
  113. package/src/orchestration/groups/modelConfig.js +66 -0
  114. package/src/orchestration/groups/validateTemplate.js +2 -0
  115. package/src/runtime/browser/broker.js +1027 -0
  116. package/src/runtime/browser/brokerClient.js +108 -0
  117. package/src/runtime/browser/componentInstaller.js +275 -0
  118. package/src/runtime/browser/installState.js +329 -0
  119. package/src/runtime/browser/manifest.js +145 -0
  120. package/src/runtime/browser/native-host-runner.js +198 -0
  121. package/src/runtime/browser/nativeHost.js +213 -0
  122. package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
  123. package/src/runtime/browser/paths.js +134 -0
  124. package/src/runtime/browser/playwrightSession.js +614 -0
  125. package/src/runtime/daemon/agentHost.js +175 -30
  126. package/src/runtime/daemon/busBridge.js +2 -1
  127. package/src/runtime/daemon/globalDaemon.js +20 -0
  128. package/src/runtime/daemon/groupOrchestrator.js +20 -1
  129. package/src/runtime/daemon/index.js +5 -4
  130. package/src/runtime/daemon/ops.js +14 -8
  131. package/src/tools/handlers/listAgents.js +1 -1
  132. package/src/tools/handlers/readBusSummary.js +1 -1
  133. package/src/tools/handlers/routeAgent.js +122 -5
  134. package/src/tools/schemaFixtures.js +1 -1
  135. package/src/ui/agentSurface.js +26 -3
  136. package/src/ui/format/index.js +34 -2
  137. package/src/ui/rustChatHost.js +22 -7
  138. package/src/ui/rustMultiSession.js +14 -2
  139. package/src/ui/rustUcodeHost.js +246 -77
  140. package/src/ui/ucodeAgentSession.js +88 -0
  141. package/templates/groups/build-lane.json +57 -3
  142. package/templates/groups/build-ultra.json +114 -6
  143. package/templates/groups/design-system.json +57 -3
  144. package/templates/groups/product-discovery.json +57 -3
  145. package/templates/groups/ui-plan-review.json +57 -3
  146. package/templates/groups/ui-polish.json +57 -3
  147. package/templates/groups/verify-ship.json +57 -3
  148. package/src/agents/runtime/context/checkpointStore.js +0 -52
  149. package/src/agents/runtime/context/compaction.js +0 -171
@@ -0,0 +1,329 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { randomUUID } = require("crypto");
6
+ const { loadGlobalBrowserConfig } = require("../../config");
7
+ const { writeFileAtomic } = require("../../coordination/bus/utils");
8
+ const { withFileLock } = require("../../coordination/state/fileLock");
9
+ const {
10
+ browserHomeDir,
11
+ installStatePath,
12
+ activeRuntimePath,
13
+ runtimeLeasesDir,
14
+ chromeNativeMessagingHostsDirs,
15
+ chromeUserDataDirs,
16
+ } = require("./paths");
17
+ const {
18
+ getReleaseManifest,
19
+ isSupportedPlatform,
20
+ NATIVE_HOST_NAME,
21
+ DEV_NATIVE_HOST_NAME,
22
+ } = require("./manifest");
23
+
24
+ function readJsonSafe(filePath, fallback = null) {
25
+ try {
26
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
27
+ return parsed && typeof parsed === "object" ? parsed : fallback;
28
+ } catch {
29
+ return fallback;
30
+ }
31
+ }
32
+
33
+ function readInstallState(env = process.env) {
34
+ const filePath = installStatePath(env);
35
+ const raw = readJsonSafe(filePath, null);
36
+ return {
37
+ schemaVersion: 1,
38
+ state: "not_installed",
39
+ mode: "release",
40
+ runtimeInstalled: false,
41
+ runtimeVersion: "",
42
+ nativeHostRegistered: false,
43
+ devHostRegistered: false,
44
+ lastError: "",
45
+ updatedAt: "",
46
+ ...(raw || {}),
47
+ };
48
+ }
49
+
50
+ function writeInstallState(patch = {}, env = process.env) {
51
+ const target = installStatePath(env);
52
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
53
+ return withFileLock(target, () => {
54
+ const current = readInstallState(env);
55
+ const next = {
56
+ ...current,
57
+ ...(typeof patch === "function" ? patch(current) : patch),
58
+ schemaVersion: 1,
59
+ updatedAt: new Date().toISOString(),
60
+ };
61
+ writeFileAtomic(target, JSON.stringify(next, null, 2), { mode: 0o600 });
62
+ return next;
63
+ });
64
+ }
65
+
66
+ function readActiveRuntime(env = process.env) {
67
+ const raw = readJsonSafe(activeRuntimePath(env), null);
68
+ if (!raw || typeof raw.entryPath !== "string" || !raw.entryPath.trim()) return null;
69
+ if (!fs.existsSync(raw.entryPath)) return null;
70
+ return raw;
71
+ }
72
+
73
+ function writeActiveRuntimeAtomic(record, env = process.env) {
74
+ const target = activeRuntimePath(env);
75
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
76
+ writeFileAtomic(target, JSON.stringify(record, null, 2), { mode: 0o600 });
77
+ return record;
78
+ }
79
+
80
+ /**
81
+ * Resolve the @playwright/mcp cli.js entrypoint.
82
+ * Production paths resolve strictly from ~/.ufoo/browser/active.json (or UFOO_BROWSER_MCP_CLI).
83
+ * Repo devDependencies fallback is only allowed when `allowBundledFallback` is true (unit/integration tests).
84
+ */
85
+ function resolveMcpCliEntrypoint({ env = process.env, allowBundledFallback = false } = {}) {
86
+ const override = String(env.UFOO_BROWSER_MCP_CLI || "").trim();
87
+ if (override && fs.existsSync(override)) {
88
+ return { entryPath: override, version: "override", source: "env" };
89
+ }
90
+ const active = readActiveRuntime(env);
91
+ if (active) {
92
+ return { entryPath: active.entryPath, version: active.version || "", source: "optional-runtime" };
93
+ }
94
+ if (allowBundledFallback) {
95
+ try {
96
+ const pkgPath = require.resolve("@playwright/mcp/package.json");
97
+ const pkg = readJsonSafe(pkgPath, {});
98
+ const cli = path.join(path.dirname(pkgPath), "cli.js");
99
+ if (fs.existsSync(cli)) {
100
+ return { entryPath: cli, version: pkg.version || "", source: "bundled-fallback" };
101
+ }
102
+ } catch {
103
+ // Not available in node_modules
104
+ }
105
+ }
106
+ return null;
107
+ }
108
+
109
+ /**
110
+ * Acquire a lightweight runtime-version lease so concurrent updates don't delete an in-use runtime.
111
+ */
112
+ function acquireRuntimeLease(version = "", env = process.env) {
113
+ if (!version) return () => {};
114
+ const dir = runtimeLeasesDir(env);
115
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
116
+ const safeVersion = String(version).replace(/[^a-zA-Z0-9._-]/g, "_");
117
+ const file = path.join(dir, `${safeVersion}.${process.pid}.${randomUUID()}.lease`);
118
+ fs.writeFileSync(file, JSON.stringify({ pid: process.pid, version, createdAt: new Date().toISOString() }), { mode: 0o600 });
119
+ return () => {
120
+ try { fs.rmSync(file, { force: true }); } catch { /* ignore */ }
121
+ };
122
+ }
123
+
124
+ function listLeasedRuntimeVersions(env = process.env) {
125
+ const dir = runtimeLeasesDir(env);
126
+ const versions = new Set();
127
+ if (!fs.existsSync(dir)) return versions;
128
+ for (const name of fs.readdirSync(dir)) {
129
+ if (!name.endsWith(".lease")) continue;
130
+ const file = path.join(dir, name);
131
+ const data = readJsonSafe(file, null);
132
+ const pid = Number(data?.pid);
133
+ let alive = false;
134
+ if (Number.isInteger(pid) && pid > 0) {
135
+ try {
136
+ process.kill(pid, 0);
137
+ alive = true;
138
+ } catch (err) {
139
+ alive = err && err.code === "EPERM";
140
+ }
141
+ }
142
+ if (alive && data?.version) {
143
+ versions.add(String(data.version));
144
+ } else {
145
+ try { fs.rmSync(file, { force: true }); } catch { /* ignore */ }
146
+ }
147
+ }
148
+ return versions;
149
+ }
150
+
151
+ function isExtensionPresentInProfileDir(profileDir, extensionId) {
152
+ if (!extensionId) return false;
153
+ if (fs.existsSync(path.join(profileDir, "Extensions", extensionId))) return true;
154
+ for (const fileName of ["Preferences", "Secure Preferences"]) {
155
+ const prefs = readJsonSafe(path.join(profileDir, fileName), null);
156
+ const record = prefs?.extensions?.settings?.[extensionId];
157
+ if (record && typeof record === "object" && Object.keys(record).length > 0) {
158
+ return true;
159
+ }
160
+ }
161
+ return false;
162
+ }
163
+
164
+ /**
165
+ * Read-only detection of Chrome installation and whether ufoo extensions appear in Chrome profiles.
166
+ * Never writes to Chrome profile directories or preferences.
167
+ */
168
+ function detectChromeEnvironment({ env = process.env, platform = process.platform } = {}) {
169
+ const effectivePlatform = String(env.UFOO_BROWSER_PLATFORM || platform || "").trim();
170
+ const manifest = getReleaseManifest(env);
171
+ const chromeBinaryOverride = String(env.UFOO_BROWSER_CHROME_BIN || "").trim();
172
+ const candidateBins = chromeBinaryOverride
173
+ ? [chromeBinaryOverride]
174
+ : effectivePlatform === "darwin"
175
+ ? [
176
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
177
+ path.join(require("os").homedir(), "Applications", "Google Chrome.app", "Contents", "MacOS", "Google Chrome"),
178
+ "/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta",
179
+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
180
+ ]
181
+ : [];
182
+ const chromePath = candidateBins.find((candidate) => fs.existsSync(candidate)) || "";
183
+ const userDataDirs = chromeUserDataDirs(env, effectivePlatform).filter((dir) => fs.existsSync(dir));
184
+ const chromeInstalled = Boolean(chromePath) || userDataDirs.length > 0;
185
+
186
+ let releaseExtensionInstalled = false;
187
+ let devExtensionInstalled = false;
188
+ const matchedProfiles = [];
189
+
190
+ for (const userDataDir of userDataDirs) {
191
+ let entries = [];
192
+ try {
193
+ entries = fs.readdirSync(userDataDir);
194
+ } catch {
195
+ entries = [];
196
+ }
197
+ const profiles = entries.filter((name) => name === "Default" || /^Profile \d+$/.test(name));
198
+ for (const profile of profiles) {
199
+ const profileDir = path.join(userDataDir, profile);
200
+ const hasRelease = manifest.releaseExtensionId
201
+ ? isExtensionPresentInProfileDir(profileDir, manifest.releaseExtensionId)
202
+ : false;
203
+ const hasDev = isExtensionPresentInProfileDir(profileDir, manifest.devExtensionId);
204
+ if (hasRelease) releaseExtensionInstalled = true;
205
+ if (hasDev) devExtensionInstalled = true;
206
+ if (hasRelease || hasDev) matchedProfiles.push({ userDataDir, profile, hasRelease, hasDev });
207
+ }
208
+ }
209
+
210
+ return {
211
+ platform: effectivePlatform,
212
+ platformSupported: isSupportedPlatform(effectivePlatform, env),
213
+ chromeInstalled,
214
+ chromePath,
215
+ userDataDirs,
216
+ releaseExtensionInstalled,
217
+ devExtensionInstalled,
218
+ extensionInstalled: releaseExtensionInstalled || devExtensionInstalled,
219
+ matchedProfiles,
220
+ };
221
+ }
222
+
223
+ function readNativeHostRegistrations(env = process.env, platform = process.platform) {
224
+ const dirs = chromeNativeMessagingHostsDirs(env, platform);
225
+ const releaseFiles = [];
226
+ const devFiles = [];
227
+ for (const dir of dirs) {
228
+ const rel = path.join(dir, `${NATIVE_HOST_NAME}.json`);
229
+ const dev = path.join(dir, `${DEV_NATIVE_HOST_NAME}.json`);
230
+ if (fs.existsSync(rel)) releaseFiles.push(rel);
231
+ if (fs.existsSync(dev)) devFiles.push(dev);
232
+ }
233
+ return { releaseFiles, devFiles };
234
+ }
235
+
236
+ /**
237
+ * Compute unified browser installation/connection status from disk config, install state, and optional live broker state.
238
+ */
239
+ function computeBrowserSetupStatus({ env = process.env, brokerStatus = null } = {}) {
240
+ const config = loadGlobalBrowserConfig();
241
+ const install = readInstallState(env);
242
+ const active = readActiveRuntime(env);
243
+ const manifest = getReleaseManifest(env);
244
+ const chrome = detectChromeEnvironment({ env });
245
+ const hosts = readNativeHostRegistrations(env, chrome.platform);
246
+ const runtimeInstalled = Boolean(active && active.entryPath);
247
+ const nativeHostRegistered = hosts.releaseFiles.length > 0 || hosts.devFiles.length > 0;
248
+ const extensionConnected = Boolean(brokerStatus && brokerStatus.extensionConnected);
249
+ const protocolMismatch = Boolean(brokerStatus && brokerStatus.protocolMismatch);
250
+ const paused = Boolean(brokerStatus && brokerStatus.paused);
251
+
252
+ let state = "not_installed";
253
+ if (!chrome.platformSupported && !env.UFOO_BROWSER_CDP_ENDPOINT && config.backend === "ufoo-extension") {
254
+ state = "unsupported_platform";
255
+ } else if (install.state === "installing") {
256
+ state = "installing";
257
+ } else if (protocolMismatch) {
258
+ state = "protocol_mismatch";
259
+ } else if (!runtimeInstalled && config.setupChoice !== "install") {
260
+ state = "not_installed";
261
+ } else if (config.setupChoice === "install" && !runtimeInstalled) {
262
+ state = install.state === "installing" ? "installing" : "not_installed";
263
+ } else if (!config.enabled) {
264
+ state = "disabled";
265
+ } else if (config.backend === "cdp" || env.UFOO_BROWSER_CDP_ENDPOINT) {
266
+ state = "ready";
267
+ } else if (config.backend === "playwright-extension") {
268
+ state = runtimeInstalled ? "waiting_for_browser" : "not_installed";
269
+ } else if (extensionConnected) {
270
+ state = paused ? "waiting_for_browser" : "ready";
271
+ } else if (!nativeHostRegistered) {
272
+ state = "pending_browser_install";
273
+ } else if (install.mode === "dev") {
274
+ state = chrome.devExtensionInstalled ? "waiting_for_browser" : "pending_browser_install";
275
+ } else if (!manifest.storePublished) {
276
+ state = chrome.devExtensionInstalled ? "waiting_for_browser" : "pending_browser_install";
277
+ } else {
278
+ state = chrome.releaseExtensionInstalled ? "waiting_for_browser" : "pending_browser_install";
279
+ }
280
+
281
+ return {
282
+ state,
283
+ setupChoice: config.setupChoice,
284
+ enabled: config.enabled,
285
+ backend: config.backend,
286
+ schemaVersion: config.schemaVersion,
287
+ browserHome: browserHomeDir(env),
288
+ runtimeInstalled,
289
+ runtimeVersion: active?.version || install.runtimeVersion || "",
290
+ activeEntryPath: active?.entryPath || "",
291
+ nativeHostRegistered,
292
+ releaseHostRegistered: hosts.releaseFiles.length > 0,
293
+ devHostRegistered: hosts.devFiles.length > 0,
294
+ chromeInstalled: chrome.chromeInstalled,
295
+ platform: chrome.platform,
296
+ platformSupported: chrome.platformSupported,
297
+ extensionInstalled: chrome.extensionInstalled,
298
+ releaseExtensionInstalled: chrome.releaseExtensionInstalled,
299
+ devExtensionInstalled: chrome.devExtensionInstalled,
300
+ storePublished: manifest.storePublished,
301
+ storeUrl: manifest.storeUrl,
302
+ releaseExtensionId: manifest.releaseExtensionId,
303
+ devExtensionId: manifest.devExtensionId,
304
+ devExtensionDir: manifest.devExtensionDir,
305
+ protocolVersion: manifest.protocolVersion,
306
+ protocolCompatible: !protocolMismatch,
307
+ extensionConnected,
308
+ paused,
309
+ brokerRunning: Boolean(brokerStatus && brokerStatus.ok),
310
+ connectedExtension: brokerStatus?.connectedExtension || null,
311
+ activeTabs: brokerStatus?.tabOwners || [],
312
+ installMode: install.mode || "release",
313
+ lastError: install.lastError || brokerStatus?.protocolError || "",
314
+ };
315
+ }
316
+
317
+ module.exports = {
318
+ readJsonSafe,
319
+ readInstallState,
320
+ writeInstallState,
321
+ readActiveRuntime,
322
+ writeActiveRuntimeAtomic,
323
+ resolveMcpCliEntrypoint,
324
+ acquireRuntimeLease,
325
+ listLeasedRuntimeVersions,
326
+ detectChromeEnvironment,
327
+ readNativeHostRegistrations,
328
+ computeBrowserSetupStatus,
329
+ };
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+
3
+ const crypto = require("crypto");
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+
7
+ const RUNTIME_COMPONENT_NAME = "@playwright/mcp";
8
+ const RUNTIME_COMPONENT_VERSION = "0.0.85";
9
+ const PROTOCOL_VERSION = 1;
10
+ const CDP_RELAY_PROTOCOL_VERSION = 2;
11
+ const COMPATIBLE_EXTENSION_MIN_VERSION = "0.1.0";
12
+ const COMPATIBLE_EXTENSION_MAX_MAJOR = 1;
13
+
14
+ const NATIVE_HOST_NAME = "com.ufoo.browser";
15
+ const DEV_NATIVE_HOST_NAME = "com.ufoo.browser.dev";
16
+
17
+ // Deterministic key and extension ID for unpacked developer loading of extensions/ufoo-browser.
18
+ const DEV_EXTENSION_ID = "hepkcmckfedpfpijhdpbfccnddjpdceh";
19
+ const SUPPORTED_PLATFORMS = new Set(["darwin"]);
20
+
21
+ /**
22
+ * Compute Chrome's deterministic 32-char a-p extension ID from an SPKI DER base64 public key.
23
+ */
24
+ function computeExtensionIdFromPublicKey(base64Key = "") {
25
+ const raw = String(base64Key || "").trim();
26
+ if (!raw) return "";
27
+ const der = Buffer.from(raw, "base64");
28
+ const digest = crypto.createHash("sha256").update(der).digest();
29
+ let id = "";
30
+ for (let i = 0; i < 16; i += 1) {
31
+ const byte = digest[i];
32
+ id += String.fromCharCode(97 + (byte >> 4)) + String.fromCharCode(97 + (byte & 0x0f));
33
+ }
34
+ return id;
35
+ }
36
+
37
+ function getRepoExtensionDir() {
38
+ return path.resolve(__dirname, "..", "..", "..", "extensions", "ufoo-browser");
39
+ }
40
+
41
+ function getReleaseManifest(env = process.env) {
42
+ const releaseExtensionId = String(env.UFOO_BROWSER_STORE_EXTENSION_ID || "").trim();
43
+ const storeUrl = String(env.UFOO_BROWSER_STORE_URL || "").trim()
44
+ || (releaseExtensionId ? `https://chromewebstore.google.com/detail/ufoo-browser/${releaseExtensionId}` : "");
45
+ const componentTarballUrl = String(env.UFOO_BROWSER_COMPONENT_TARBALL || "").trim();
46
+ const componentTarballSha256 = String(env.UFOO_BROWSER_COMPONENT_SHA256 || "").trim().toLowerCase();
47
+ const devDir = getRepoExtensionDir();
48
+ return {
49
+ schemaVersion: 1,
50
+ runtimeComponentName: RUNTIME_COMPONENT_NAME,
51
+ runtimeComponentVersion: RUNTIME_COMPONENT_VERSION,
52
+ componentTarballUrl,
53
+ componentTarballSha256,
54
+ protocolVersion: PROTOCOL_VERSION,
55
+ cdpRelayProtocolVersion: CDP_RELAY_PROTOCOL_VERSION,
56
+ compatibleExtensionMinVersion: COMPATIBLE_EXTENSION_MIN_VERSION,
57
+ compatibleExtensionMaxMajor: COMPATIBLE_EXTENSION_MAX_MAJOR,
58
+ nativeHostName: NATIVE_HOST_NAME,
59
+ devNativeHostName: DEV_NATIVE_HOST_NAME,
60
+ releaseExtensionId,
61
+ storeUrl,
62
+ storePublished: Boolean(releaseExtensionId && storeUrl),
63
+ devExtensionId: DEV_EXTENSION_ID,
64
+ devExtensionDir: fs.existsSync(devDir) ? devDir : "",
65
+ };
66
+ }
67
+
68
+ function parseSemverTuple(version = "") {
69
+ const match = String(version || "").trim().match(/^(\d+)\.(\d+)\.(\d+)/);
70
+ if (!match) return null;
71
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
72
+ }
73
+
74
+ function compareSemver(left = "", right = "") {
75
+ const a = parseSemverTuple(left);
76
+ const b = parseSemverTuple(right);
77
+ if (!a || !b) return NaN;
78
+ for (let i = 0; i < 3; i += 1) {
79
+ if (a[i] !== b[i]) return a[i] - b[i];
80
+ }
81
+ return 0;
82
+ }
83
+
84
+ /**
85
+ * Validate extension version and protocol version against the host compatibility range.
86
+ */
87
+ function isExtensionCompatible({ extensionVersion = "", protocolVersion = 0 } = {}, manifest = getReleaseManifest()) {
88
+ const proto = Number(protocolVersion);
89
+ if (!Number.isInteger(proto) || proto !== manifest.protocolVersion) {
90
+ return {
91
+ ok: false,
92
+ reason: `protocol_version_mismatch (expected ${manifest.protocolVersion}, got ${protocolVersion || "none"})`,
93
+ };
94
+ }
95
+ const parsed = parseSemverTuple(extensionVersion);
96
+ if (!parsed) {
97
+ return { ok: false, reason: `invalid_extension_version (${extensionVersion || "empty"})` };
98
+ }
99
+ if (parsed[0] > manifest.compatibleExtensionMaxMajor) {
100
+ return {
101
+ ok: false,
102
+ reason: `extension_major_too_new (${extensionVersion} > ${manifest.compatibleExtensionMaxMajor}.x)`,
103
+ };
104
+ }
105
+ if (compareSemver(extensionVersion, manifest.compatibleExtensionMinVersion) < 0) {
106
+ return {
107
+ ok: false,
108
+ reason: `extension_version_too_old (${extensionVersion} < ${manifest.compatibleExtensionMinVersion})`,
109
+ };
110
+ }
111
+ return { ok: true, reason: "" };
112
+ }
113
+
114
+ function isSupportedPlatform(platform = process.platform, env = process.env) {
115
+ const effective = String(env.UFOO_BROWSER_PLATFORM || platform || "").trim();
116
+ return SUPPORTED_PLATFORMS.has(effective);
117
+ }
118
+
119
+ function resolveAllowedExtensionIds({ dev = true, env = process.env } = {}) {
120
+ const manifest = getReleaseManifest(env);
121
+ const ids = [];
122
+ if (manifest.releaseExtensionId) ids.push(manifest.releaseExtensionId);
123
+ if (dev && manifest.devExtensionId) ids.push(manifest.devExtensionId);
124
+ return [...new Set(ids)];
125
+ }
126
+
127
+ module.exports = {
128
+ RUNTIME_COMPONENT_NAME,
129
+ RUNTIME_COMPONENT_VERSION,
130
+ PROTOCOL_VERSION,
131
+ CDP_RELAY_PROTOCOL_VERSION,
132
+ COMPATIBLE_EXTENSION_MIN_VERSION,
133
+ COMPATIBLE_EXTENSION_MAX_MAJOR,
134
+ NATIVE_HOST_NAME,
135
+ DEV_NATIVE_HOST_NAME,
136
+ DEV_EXTENSION_ID,
137
+ SUPPORTED_PLATFORMS,
138
+ computeExtensionIdFromPublicKey,
139
+ getRepoExtensionDir,
140
+ getReleaseManifest,
141
+ compareSemver,
142
+ isExtensionCompatible,
143
+ isSupportedPlatform,
144
+ resolveAllowedExtensionIds,
145
+ };
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ /**
5
+ * Standalone zero-dependency Chrome Native Messaging Host for ufoo Browser.
6
+ * Copied into ~/.ufoo/browser/native-host/native-host-runner.js so Chrome can
7
+ * launch it from an immutable user path without depending on npm package versions
8
+ * or shell PATH.
9
+ */
10
+
11
+ const crypto = require("crypto");
12
+ const fs = require("fs");
13
+ const net = require("net");
14
+ const os = require("os");
15
+ const path = require("path");
16
+
17
+ const MAX_NATIVE_BYTES = 1024 * 1024;
18
+
19
+ function browserHomeDir() {
20
+ const override = String(process.env.UFOO_BROWSER_HOME || "").trim();
21
+ if (override) return path.resolve(override);
22
+ return path.join(os.homedir(), ".ufoo", "browser");
23
+ }
24
+
25
+ function globalConfigPath() {
26
+ const override = String(process.env.UFOO_GLOBAL_CONFIG_PATH || "").trim();
27
+ if (override) return path.resolve(override);
28
+ return path.join(os.homedir(), ".ufoo", "config.json");
29
+ }
30
+
31
+ function readJsonSafe(filePath) {
32
+ try {
33
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
38
+
39
+ function writeNativeMessage(payload) {
40
+ const json = Buffer.from(JSON.stringify(payload), "utf8");
41
+ if (json.length > MAX_NATIVE_BYTES) return;
42
+ const header = Buffer.allocUnsafe(4);
43
+ header.writeUInt32LE(json.length, 0);
44
+ process.stdout.write(Buffer.concat([header, json]));
45
+ }
46
+
47
+ function createNativeReader(onMessage) {
48
+ let buf = Buffer.alloc(0);
49
+ return (chunk) => {
50
+ buf = Buffer.concat([buf, chunk]);
51
+ while (buf.length >= 4) {
52
+ const len = buf.readUInt32LE(0);
53
+ if (len === 0 || len > MAX_NATIVE_BYTES) {
54
+ buf = Buffer.alloc(0);
55
+ return;
56
+ }
57
+ if (buf.length < 4 + len) return;
58
+ const body = buf.slice(4, 4 + len).toString("utf8");
59
+ buf = buf.slice(4 + len);
60
+ try {
61
+ onMessage(JSON.parse(body));
62
+ } catch {
63
+ // Ignore malformed frame
64
+ }
65
+ }
66
+ };
67
+ }
68
+
69
+ function checkLocalInstallState() {
70
+ const home = browserHomeDir();
71
+ const installFile = path.join(home, "install.json");
72
+ if (!fs.existsSync(installFile)) {
73
+ return { installed: false, enabled: false, reason: "native_not_installed" };
74
+ }
75
+ const config = readJsonSafe(globalConfigPath());
76
+ const browserCfg = config && typeof config.browser === "object" ? config.browser : {};
77
+ if (browserCfg.enabled === false) {
78
+ return { installed: true, enabled: false, reason: "disabled" };
79
+ }
80
+ return { installed: true, enabled: true, reason: "ok" };
81
+ }
82
+
83
+ function requestBroker(sockPath, payload) {
84
+ return new Promise((resolve) => {
85
+ const socket = net.createConnection(sockPath);
86
+ let buffer = "";
87
+ let done = false;
88
+ const finish = (value) => {
89
+ if (done) return;
90
+ done = true;
91
+ clearTimeout(timer);
92
+ try { socket.destroy(); } catch { /* ignore */ }
93
+ resolve(value);
94
+ };
95
+ const timer = setTimeout(() => finish({ ok: false, code: "waiting_for_ufoo", error: "ufoo broker timed out" }), 4000);
96
+ socket.on("connect", () => {
97
+ socket.write(`${JSON.stringify(payload)}\n`);
98
+ });
99
+ socket.on("data", (chunk) => {
100
+ buffer += chunk.toString("utf8");
101
+ const idx = buffer.indexOf("\n");
102
+ if (idx === -1) return;
103
+ const line = buffer.slice(0, idx).trim();
104
+ try {
105
+ finish(JSON.parse(line));
106
+ } catch {
107
+ finish({ ok: false, code: "broker_bad_response", error: "Invalid broker response" });
108
+ }
109
+ });
110
+ socket.on("error", (err) => {
111
+ finish({ ok: false, code: "waiting_for_ufoo", error: err && err.message ? err.message : "Broker unavailable" });
112
+ });
113
+ });
114
+ }
115
+
116
+ function resolveBrokerSocketPath() {
117
+ const priv = path.join(browserHomeDir(), "private");
118
+ const candidate = path.join(priv, "broker.sock");
119
+ if (Buffer.byteLength(candidate) <= 96) return candidate;
120
+ const tag = crypto.createHash("sha256").update(priv).digest("hex").slice(0, 16);
121
+ return path.join("/tmp", `ufoo-bb-${tag}.sock`);
122
+ }
123
+
124
+ async function handleIncomingNativeMessage(msg) {
125
+ if (!msg || typeof msg !== "object") return;
126
+ const local = checkLocalInstallState();
127
+ if (!local.installed) {
128
+ writeNativeMessage({ type: "status", state: "native_not_installed", id: msg.id || null });
129
+ return;
130
+ }
131
+ if (!local.enabled) {
132
+ writeNativeMessage({ type: "status", state: "disabled", id: msg.id || null });
133
+ return;
134
+ }
135
+
136
+ const sockPath = resolveBrokerSocketPath();
137
+ if (!fs.existsSync(sockPath)) {
138
+ writeNativeMessage({ type: "status", state: "waiting_for_ufoo", id: msg.id || null });
139
+ return;
140
+ }
141
+
142
+ if (msg.type === "hello") {
143
+ const res = await requestBroker(sockPath, {
144
+ op: "native_hello",
145
+ params: {
146
+ extensionId: String(msg.extensionId || ""),
147
+ extensionVersion: String(msg.extensionVersion || ""),
148
+ protocolVersion: Number(msg.protocolVersion || 0),
149
+ },
150
+ });
151
+ if (!res || !res.ok) {
152
+ writeNativeMessage({
153
+ type: "status",
154
+ state: res?.code || "waiting_for_ufoo",
155
+ error: res?.error || "",
156
+ id: msg.id || null,
157
+ });
158
+ return;
159
+ }
160
+ writeNativeMessage({
161
+ type: "connect_info",
162
+ id: msg.id || null,
163
+ wsUrl: res.wsUrl,
164
+ token: res.token,
165
+ protocolVersion: res.protocolVersion,
166
+ hostVersion: res.hostVersion || "",
167
+ });
168
+ return;
169
+ }
170
+
171
+ if (msg.type === "ping") {
172
+ const res = await requestBroker(sockPath, { op: "ping", params: {} });
173
+ writeNativeMessage({
174
+ type: "pong",
175
+ id: msg.id || null,
176
+ brokerRunning: Boolean(res && res.ok),
177
+ });
178
+ }
179
+ }
180
+
181
+ function main() {
182
+ const push = createNativeReader((msg) => {
183
+ void handleIncomingNativeMessage(msg);
184
+ });
185
+ process.stdin.on("data", push);
186
+ process.stdin.on("end", () => process.exit(0));
187
+ process.stdin.on("error", () => process.exit(0));
188
+ }
189
+
190
+ if (require.main === module) {
191
+ main();
192
+ }
193
+
194
+ module.exports = {
195
+ checkLocalInstallState,
196
+ handleIncomingNativeMessage,
197
+ createNativeReader,
198
+ };