diff --git a/PRIVACY.md b/PRIVACY.md index eade258..30f2d6d 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -64,7 +64,7 @@ The optional JEV executor is disabled by default. A CLI task must include `--enable-fast-agent`. The optional `browser_task` MCP tool must first be enabled for the server, and each call must include `cloudConsent: true`. `--dry-run` validates local task configuration without opening a browser -connection, reading an API key or making network requests. +connection or making network requests; no API key is required. An enabled task sends a bounded, allowlisted model payload to BeatAPI: @@ -79,8 +79,19 @@ An enabled task sends a bounded, allowlisted model payload to BeatAPI: The default endpoint is `https://api.beatapi.io`; a trusted local operator may set `BEATAPI_BASE_URL`. The destination matters: the configured endpoint receives the BeatAPI authorization key in the request header. Only the Node -process reads `BEATAPI_API_KEY`; the key is not sent across the extension bridge -or included in the model state or trace. Per-task MCP arguments cannot override +process reads `BEATAPI_API_KEY`. Alternatively, the extension FAST setup sends a +human-entered key over its local loopback bridge connection. The Node bridge +stores it in `~/.beat-browser/fast-settings.json` with owner-only (`0600`) +permissions. This file contains plaintext credentials, not keychain-encrypted +credentials. The key is not saved in Chrome storage, returned to the extension +or an agent, logged, or included in model state or traces. The extension password +field retains an unsaved draft only until it is saved or the extension page is +closed. UI setup always targets `https://api.beatapi.io`. **Test connection** and +**Test & enable** make a real synthetic decision request and may consume credits; +they do not read any browser page. Disabling preserves the local key; **Remove +saved key** removes it and disables FAST, without changing environment secrets. +Settings are shared by local processes using the same BeatBrowser home. +Per-task MCP arguments cannot override credentials, endpoint or model. The fast path does not collect cookie or storage dumps, browser authorization diff --git a/README.md b/README.md index 4d36ed0..dc215ae 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Connect Codex, Claude Code and other compatible agents directly to the Chrome you already use. Keep your website logins, run tasks in background windows, and take over when needed. BeatBrowser is a free, MIT-licensed Chrome extension and local bridge. -[Get started](#quick-start) · [Cloud agents](#cloud-agents-your-chrome) · [Examples](#what-you-can-do) · [Compare](#compare-browser-integrations) · [JavaScript SDK](docs/JAVASCRIPT.md) · [Website](https://beatapi.io/browser) +[Get started](#quick-start) · [FAST mode](#fast-mode) · [Cloud agents](#cloud-agents-your-chrome) · [Examples](#what-you-can-do) · [Compare](#compare-browser-integrations) · [JavaScript SDK](docs/JAVASCRIPT.md) · [Website](https://beatapi.io/browser) Normal local browser tools are **free**, with **no BeatBrowser account or API key**. Your agent uses its own model access. @@ -27,6 +27,7 @@ Normal local browser tools are **free**, with **no BeatBrowser account or API ke | **Choose your agent** | Codex, Claude Code, WorkBuddy and more. | | **Own the toolchain** | Extension, bridge, MCP, CLI and SDK source. | | **Work in the background** | Task windows with pause and takeover. | +| **Optional FAST execution** | Your agent supplies the goal and inputs; JEV chooses bounded browser actions. Requires a BeatAPI key. | | **Cloud access preview** | Self-hosted access to your local Chrome. | The extension, local bridge, MCP server, CLI and Node SDK are public under [MIT](LICENSE). Task windows share their Chrome profile's cookies and storage. @@ -109,6 +110,37 @@ page title, report the result, and pause for my review. Open the extension → **Workspace** to inspect the task. The agent supplies the reasoning; BeatBrowser supplies the browser tools. + + +## FAST mode: let JEV execute a bounded browser task + +In normal mode, your agent calls browser tools step by step. **FAST mode** lets a local agent hand a goal, exact inputs and success assertions to `browser_task`. JEV chooses among bounded actions such as clicking, typing, selecting and scrolling, and the executor checks the result. Use it for interaction tasks with clear boundaries; the outer agent still handles planning and exceptions. + +FAST is **off by default** and requires a **BeatAPI key**. Connection tests and live model calls may consume credits. Normal browser tools remain free and need no key. + +**To enable:** + +1. In the extension popup or workspace, open **Settings → FAST → Configure**. +2. Enter a BeatAPI key and JEV model (default `jev-1.13`), confirm model calls, and choose **Test & enable**. +3. Ask your local agent to use `browser_task` with a concrete goal, inputs and success assertions. Each task still requires cloud-processing consent. **Turn off FAST** stops FAST execution. + +Only the local Node bridge saves the key in an owner-only file; Chrome storage does not retain it. **The new settings entry is currently on the source branch and has not shipped in a new npm package or extension download.** Both the CLI/MCP package and extension must contain it. Existing `1.4.1` installations use [environment configuration](docs/JEV_FAST_AGENT.md#prerequisites-and-configuration). + +FAST currently supports top-frame light DOM, excluding iframes and shadow DOM, and stops on uncertainty. [Full configuration and execution boundaries](docs/JEV_FAST_AGENT.md) · [Dated test results](TEST_RESULTS.md) + +
+Check task arguments locally without a key + +```sh +beat-browser run --dry-run \ + --url https://example.com \ + --goal 'Check that the Example Domain page is ready' +``` + +Dry-run only validates arguments; it makes no model call and opens no browser connection. + +
+ ## Cloud agents, your Chrome **Run the agent in the cloud. Keep the browser on your computer.** @@ -229,21 +261,6 @@ npm run check:package Bug reports and pull requests are welcome. Include the CLI/extension versions, reproduction steps and sanitized output. Do not include tokens, cookies or private page data. Unit and isolated Chromium checks do not certify every agent client or macOS foreground-focus behavior. -
-Optional BeatAPI execution — Fast JEV - -The optional Fast JEV executor lets a BeatAPI model choose from a bounded set of browser actions. It uses the same connection, is **off by default**, and requires a BeatAPI key and explicit task consent. Normal browser tools do not require it. - -```sh -beat-browser run --dry-run \ - --url https://example.com \ - --goal 'Check that the Example Domain page is ready' -``` - -Dry-run makes no model call and opens no browser connection. Fast JEV targets top-frame light DOM, not iframes or shadow DOM; it stops on uncertainty instead of replaying an uncertain submission. [Configuration and consent](docs/JEV_FAST_AGENT.md) - -
- ## License Released under the [MIT License](LICENSE). diff --git a/README.zh-CN.md b/README.zh-CN.md index 0632d10..34b2fb3 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -14,7 +14,7 @@ 保留现有浏览器、登录态与使用习惯,让 Codex、Claude Code 等兼容 Agent 直接在 Chrome 里完成网页任务。任务使用独立后台窗口,你随时查看、暂停或接管。BeatBrowser 是免费、MIT 开源的 Chrome 扩展与本地桥接工具。 -[快速开始](#快速开始) · [云端 Agent](#云端-agent你的-chrome) · [使用示例](#可以用来做什么) · [能力对比](#浏览器接入方式对比) · [JavaScript SDK](docs/JAVASCRIPT.md) · [项目官网](https://beatapi.io/browser) +[快速开始](#快速开始) · [FAST 模式](#fast模式) · [云端 Agent](#云端-agent你的-chrome) · [使用示例](#可以用来做什么) · [能力对比](#浏览器接入方式对比) · [JavaScript SDK](docs/JAVASCRIPT.md) · [项目官网](https://beatapi.io/browser) 普通本地浏览器工具**免费**,**不需要 BeatBrowser 账号或 API Key**;Agent 使用自己的模型服务。 @@ -27,6 +27,7 @@ | **Agent 自由选择** | 接入 Codex、Claude Code、WorkBuddy 等。 | | **工具链源码公开** | 扩展、桥接、MCP、CLI、SDK 均可检查和修改。 | | **后台任务工作区** | 独立任务窗口,可暂停、继续或接管。 | +| **可选 FAST 执行** | Agent 给定目标与输入,JEV 选择有限的浏览器动作;需要 BeatAPI Key。 | | **云端接入预览** | 自建认证入口,连接你本地的 Chrome。 | 扩展、桥接服务、MCP、CLI 和 Node SDK 源码按 [MIT](LICENSE) 公开。同一 Chrome 配置下的任务共享 Cookie 与存储。 @@ -106,6 +107,37 @@ beat-browser doctor --json 点击扩展 → **工作区** 查看任务。Agent 负责推理,BeatBrowser 提供浏览器工具。 + + +## FAST 模式:让 JEV 执行明确的浏览器任务 + +普通模式由你的 Agent 逐步调用浏览器工具。**FAST 模式**允许本地 Agent 把目标、准确输入和成功条件交给 `browser_task`,由 JEV 在点击、输入、选择和滚动等有限动作中决定下一步,执行后检查结果。它适合步骤边界明确的交互任务;规划和异常处理仍由外层 Agent 负责。 + +FAST **默认关闭**,需要 **BeatAPI Key**;测试连接和实际模型调用可能消耗额度。普通浏览器工具仍免费,无需 Key。 + +**开启方式:** + +1. 在扩展弹窗或工作区打开 **设置 → FAST → 配置**。 +2. 填入 BeatAPI Key 和 JEV 模型(默认 `jev-1.13`),勾选允许模型调用,点击 **测试并开启**。 +3. 让本地 Agent 使用 `browser_task`,提供具体目标、输入和成功条件;每次任务仍需云端处理授权。**关闭 FAST** 可停止 FAST 执行。 + +Key 由本机 Node 桥接以受限权限文件保存,不写入 Chrome 存储。**新版设置入口目前在源码分支中,尚未随新的 npm 包或扩展下载发布**;需要同时使用包含该入口的 CLI/MCP 与扩展,现有 `1.4.1` 安装仍按[环境变量方式](docs/JEV_FAST_AGENT.md#prerequisites-and-configuration)配置。 + +FAST 当前支持页面顶层的普通 DOM,不支持 iframe 或 shadow DOM;遇到不确定状态会停止。[完整配置与执行边界](docs/JEV_FAST_AGENT.md) · [注明日期的测试记录](TEST_RESULTS.md) + +
+无需 Key 的本地参数检查 + +```sh +beat-browser run --dry-run \ + --url https://example.com \ + --goal 'Check that the Example Domain page is ready' +``` + +Dry-run 只检查参数,不调用模型、不连接浏览器。 + +
+ ## 云端 Agent,你的 Chrome **Agent 在云端,浏览器留在你的电脑。** @@ -225,21 +257,6 @@ npm run check:package 欢迎提交问题与 PR,请附上 CLI/扩展版本、复现步骤和脱敏输出,不要包含令牌、Cookie 或私有页面数据。单元测试和隔离 Chromium 检查不代表已验收每个 Agent 客户端或 macOS 原生焦点行为。 -
-可选 BeatAPI 执行能力 — Fast JEV - -Fast JEV 让 BeatAPI 模型从有限的浏览器动作中选择下一步,复用相同连接,**默认关闭**。真实调用需要 BeatAPI Key 和明确任务授权,普通浏览器工具不需要。 - -```sh -beat-browser run --dry-run \ - --url https://example.com \ - --goal 'Check that the Example Domain page is ready' -``` - -Dry-run 不调用模型、不连接浏览器。Fast JEV 面向顶层 light DOM,不支持 iframe 或 shadow DOM;遇到不确定状态会停止,不自动重发结果不明的提交。[配置与授权](docs/JEV_FAST_AGENT.md) - -
- ## 许可证 本项目采用 [MIT 许可证](LICENSE)。 diff --git a/TEST_RESULTS.md b/TEST_RESULTS.md index 39a422a..43c0ad3 100644 --- a/TEST_RESULTS.md +++ b/TEST_RESULTS.md @@ -1,5 +1,61 @@ # Test results +### GitHub source submission validation, 2026-10-26 + +- Re-ran all 292 tests: zero failures, cancellations or skips. Syntax checks + passed for 78 JavaScript files; the narrow source-pattern security scan found + no findings in 128 files. Clean package installation (134 files), 24 normal + MCP tools, and local extension packaging passed. +- Re-ran isolated Chrome for Testing acceptance with synthetic provider responses. + Popup/sidebar setup, consent, test without saving, enable/disable/remove, + credential boundaries, Chinese layout and collapsed Settings passed. The real + browser runner performed one click and passed its outcome assertion with + `status: completed`, `verified: true`. +- This recheck made no real BeatAPI model calls and does not revalidate the + dated live-provider observations below. Source submission does not publish + a new npm version, GitHub Release or extension download. + +### Source preview: extension FAST entry, 2026-10-25 + +- The revised popup/sidebar keep tasks first and nest FAST inside the collapsed + Settings section. Expanding Settings shows a compact FAST row; only Configure + reveals API key/model/consent fields. Isolated Chromium acceptance confirmed + this initial state, configuration expansion, and unsaved-key clearing when + Settings is closed. Default, Settings-row and expanded-form screenshots were + regenerated without making additional live model calls for the layout change. +- 292 tests passed with zero failures/skips. Eight new integration tests cover + ephemeral connection testing, private key persistence, consent, fixed BeatAPI + routing, failure preservation, permission/symlink rejection, opt-out precedence, + live MCP tool discovery, revocation, and credential-free bridge replies/audits. +- `node scripts/check-fast-browser.mjs` with `BEAT_TEST_CHROME` uses an isolated + Chrome for Testing profile, temporary bridge and synthetic model responses. + Actual popup and sidebar controls passed: consent gating, invalid-key response, + test-without-saving, enable/disable/remove, saved-state recovery, Chinese UI and + 340px layout. Keys were absent from Chrome local/session storage, and an injected + content script could not change FAST settings. +- The real extension/bridge runner completed a local fixture task with one JEV + decision and one actual browser click, followed by a passing page assertion. + The provider response was synthetic: this does not establish current real JEV + availability, billing, latency, or decision quality. +- Syntax: 78 JavaScript files. Narrow source-pattern scan: no findings. Clean + 134-file package installation, stable launcher and 24 normal MCP tools passed. +- A subsequent explicit live run used the operator-authorized credential through + process memory. The non-billable `GET /v1/usage` check returned HTTP 200. + Exactly two `POST /v1/systemone` calls to BeatAPI with `jev-1.13` returned 200: + the popup's **Test & enable** request (1,773 ms response-header latency) and + the actual browser runner decision (614 ms response-header latency). The + runner performed one real click and passed its page assertion with + `status: completed`, `verified: true`. These are two observed requests, + not a general latency or reliability benchmark. The popup/sidebar and + enable/disable/remove controls passed with this real provider configuration. +- The live run used a disposable browser profile and owner-only temporary settings; + the key was removed from those settings and the test profile was deleted. + It was not written to the repository, result report or Chrome storage. The + authorized existing secret-store entry was unchanged. No exact billing charge + was audited. Signed-in websites, complex workflows and native macOS focus + behavior remain unverified. This is an unreleased development branch; the + active extension was not replaced. + ### 1.4 release validation, 2026-10-18 - 1.4.0 includes the optional remote adapter and current WorkBuddy configuration detection. The 284-test suite, syntax, source-pattern security scan, comparison assets, clean package installation, MCP discovery and extension packaging passed. diff --git a/docs/JEV_FAST_AGENT.md b/docs/JEV_FAST_AGENT.md index d4917df..c0224f5 100644 --- a/docs/JEV_FAST_AGENT.md +++ b/docs/JEV_FAST_AGENT.md @@ -6,7 +6,7 @@ and success assertions. The executor observes the current page, asks BeatAPI JEV to choose from a finite action set, validates that choice, rechecks the live target, performs one supported action and verifies the result. -It is off by default. The 23 ordinary manual MCP tools, local bridge, +It is off by default. The ordinary manual MCP tools, local bridge, installation flow and existing `ask` mechanism remain available without a BeatAPI API key. Fast mode is intended for constrained interaction loops; the outer agent retains planning, task authorization and handling of exceptions. @@ -20,6 +20,55 @@ page and update the note after the run. ## Prerequisites and configuration +### Extension FAST entry + +The popup and workspace keep tasks first. Open **Settings**, then choose +**Configure** on its FAST row to reveal the API key, JEV model and consent +options. Settings and the configuration form are collapsed on initial load; +FAST remains disabled by default. Closing Settings also closes the form and +clears its unsaved key. Enter a BeatAPI API key and JEV model, and confirm model calls. **Test connection** +makes one synthetic JEV decision request without reading a browser page or saving +the draft. **Test & enable** repeats that check and enables FAST only after a +valid JEV response. Tests can consume model credits. The default model remains +`jev-1.13`; the model field accepts another published JEV model ID. + +The Node bridge must be running from a package containing this entry; an older +bridge needs a package update and agent restart. The key is sent once over the +local extension-to-bridge WebSocket and stored in `~/.beat-browser/fast-settings.json` +with owner-only permissions (`0600`). This is a local plaintext credential file, +not an OS keychain. It is never saved in Chrome storage, returned in settings +responses, exposed to an agent, or included in audit/model/trace data. UI setup +always uses `https://api.beatapi.io` even if the process has another base URL. +The password field keeps an unsaved draft only while that extension page is open. + +Enabling FAST adds `browser_task` to a local MCP server's current tool list and +sends a tool-list-changed notification. Clients that cache the list may need a +reconnect. Each task still requires `cloudConsent: true`; the switch itself +does not start a task or authorize a website action. Turning FAST off prevents +new calls, stops running MCP tasks, and prevents a further runner operation +after revocation. Removing a saved key also switches FAST off. Disabling keeps +the saved key for later use; removing it does not erase a separately configured +process-environment key. Settings apply to local processes sharing this user's +BeatBrowser home, across Chrome profiles. Remote servers explicitly keep FAST +disabled. + +Existing process-environment configuration still works when no saved settings +file exists. A saved disabled configuration overrides startup opt-in until the +user enables FAST again. `BEAT_BROWSER_FAST_AGENT=0` is an explicit opt-out that +also overrides saved configuration. CLI live runs still require their explicit +`--enable-fast-agent` flag and can reuse the saved key. Dry runs remain offline. + +For isolated test processes only, `BEAT_BROWSER_FAST_CONFIG_FILE` selects a +different trusted local settings path; it is never a per-task argument. + +`BEAT_TEST_CHROME=/path/to/chrome node scripts/check-fast-browser.mjs` exercises +the popup, sidebar and real browser actions with synthetic provider responses in +a disposable profile. Explicit `--live` additionally requires `BEATAPI_API_KEY` +in process memory and uses real BeatAPI calls. It skips redundant/negative live +model tests to limit billed calls. Reports and screenshots contain no key, and +temporary credential settings are removed when the run exits. See `TEST_RESULTS.md` +for the dated live run and its narrow acceptance scope. + Use the repository's supported Node.js version, install its existing dependencies, and load the BeatBrowser Chrome extension. No new runtime dependency is needed for fast mode. `beat-browser doctor --json` can diagnose diff --git a/extension/background.js b/extension/background.js index bd918dc..4f7a3d1 100644 --- a/extension/background.js +++ b/extension/background.js @@ -21,6 +21,20 @@ import { validateScript, condText, repeatMax, EXEC_BUDGET } from './script.js'; const fastRuns = new Map(); const fastTabWatches = new Map(); const fastCanceledRuns = new Set(); +const fastSettingsRequests = new Map(); + +async function fastSettingsRequest(params) { + if (!(await connected())) throw new Error('FAST_BRIDGE_REQUIRED'); + const id = crypto.randomUUID(); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { fastSettingsRequests.delete(id); reject(new Error('FAST_BRIDGE_TIMEOUT')); }, 20000); + fastSettingsRequests.set(id, { resolve, reject, timer }); + // No persistent outbox: a credential setup request must never be replayed. + void toBridge({ type: 'fast_settings', id, params }).catch(() => { + clearTimeout(timer); fastSettingsRequests.delete(id); reject(new Error('FAST_BRIDGE_REQUIRED')); + }); + }); +} // @@ -251,6 +265,14 @@ const emit = (event, extra = {}) => toBridge({ type: 'event', event, ...extra }) const NO_SLOT_CMDS = new Set(['tabs', 'spaces', 'download', 'reload', 'status']); async function onMessage(msg) { + if (msg.type === 'fast_settings_result') { + const pending = fastSettingsRequests.get(msg.id); + if (!pending) return; + clearTimeout(pending.timer); fastSettingsRequests.delete(msg.id); + if (msg.error) pending.reject(new Error(msg.error)); + else pending.resolve(msg.data); + return; + } if (msg.type === 'event') return onBridgeEvent(msg); if (msg.type !== 'cmd') return; try { @@ -2414,6 +2436,13 @@ chrome.tabs.onUpdated.addListener((tabId, info) => { }); chrome.runtime.onMessage.addListener((m, _s, sendResponse) => { + if (m?.__hcPopup === 'fastSettings') { + if (_s.id !== chrome.runtime.id || !['popup.html', 'panel.html'].some(file => _s.url === chrome.runtime.getURL(file))) { + sendResponse({ error: 'FAST_UI_REQUIRED' }); return false; + } + fastSettingsRequest(m.params).then(sendResponse).catch(error => sendResponse({ error: error.message })); + return true; + } if (m?.__hcPopup === 'spaces' || m?.__hcPopup === 'workspacePages') { if (_s.id !== chrome.runtime.id || !['popup.html', 'panel.html'].some(path => _s.url === chrome.runtime.getURL(path))) { sendResponse({error:'TaskSpace controls are available only in the extension workspace.'}); diff --git a/extension/fast-settings.js b/extension/fast-settings.js new file mode 100644 index 0000000..b1607a5 --- /dev/null +++ b/extension/fast-settings.js @@ -0,0 +1,119 @@ +// [INPUT] Human settings actions in the extension popup/workspace. +// [OUTPUT] Local-bridge setup requests and credential-free FAST status. +// [POS] Extension UI. [PROTOCOL] Never persist, prefill or echo API keys. +export function mountFastSettings({ t }) { + const root = document.createElement('section'); + root.className = 'fast-card'; + root.innerHTML = ` +
FAST +
+ +

`; + const settings = document.querySelector('details.adv'); + settings.querySelector('.sess').before(root); + const el = id => root.querySelector(`#fast-${id}`); + let current = null, busy = false, message = '', failed = false; + const errors = { + FAST_PROCESS_DISABLED: 'Remove the local FAST opt-out and restart your agent.', + FAST_BRIDGE_REQUIRED: 'Open your agent and reconnect to set up FAST.', + FAST_BRIDGE_TIMEOUT: 'Update the local BeatBrowser package and restart your agent.', + INVALID_SETTINGS: 'Enter a valid BeatAPI key and JEV model.', + MISSING_API_KEY: 'Enter a valid BeatAPI key and JEV model.', + INVALID_API_KEY: 'Enter a valid BeatAPI key and JEV model.', + PROVIDER_HTTP_ERROR: 'BeatAPI rejected the test. Check the key, balance and model.', + INVALID_DECISION: 'The model did not return a valid JEV decision.', + INVALID_RESPONSE: 'The model did not return a valid JEV decision.', + NETWORK_ERROR: 'BeatAPI timed out. Try the connection test again.', + TIMEOUT: 'BeatAPI timed out. Try the connection test again.', + }; + function render() { + el('disable').hidden = current?.enabled !== true; + el('status').textContent = t(current ? current.enabled ? 'On' : 'Off' : 'Unavailable'); + el('status').dataset.on = String(current?.enabled === true); + el('key').placeholder = t(current?.configured ? 'Key configured · leave blank to keep' : 'Paste your BeatAPI key'); + el('forget').hidden = !current?.savedKey; + el('message').textContent = t(message); + el('message').dataset.error = String(failed); + root.querySelectorAll('button').forEach(button => { button.disabled = busy; }); + el('consent').disabled = busy; + el('key').disabled = busy; + el('model').disabled = busy; + } + async function request(params) { + const result = await chrome.runtime.sendMessage({ __hcPopup: 'fastSettings', params }); + if (!result) throw new Error('FAST_BRIDGE_TIMEOUT'); + if (result.error) throw new Error(result.error); + return result; + } + async function refresh() { + if (busy) return; + try { + current = await request({ action: 'status' }); + if (el('form').hidden) el('model').value = current.model; + if (message === errors.FAST_BRIDGE_REQUIRED || message === errors.FAST_BRIDGE_TIMEOUT) message = ''; + } catch (error) { + current = null; + if (!message) { message = errors[error.message] || 'FAST settings unavailable. Reconnect and try again.'; failed = true; } + } + render(); + } + function configure() { + el('form').hidden = !el('form').hidden; + el('configure').setAttribute('aria-expanded', String(!el('form').hidden)); + if (!el('form').hidden) { el('model').value = current?.model || 'jev-1.13'; el('key').focus(); } + else { el('key').value = ''; el('consent').checked = false; } + } + async function perform(action) { + if (busy) return; + if (['test', 'enable'].includes(action) && !el('consent').checked) { + message = 'Confirm model calls before testing or enabling FAST.'; failed = true; render(); return; + } + busy = true; failed = false; message = ['test', 'enable'].includes(action) ? 'Testing JEV…' : 'Saving…'; render(); + const params = { action }; + if (['test', 'enable'].includes(action)) { + params.apiKey = el('key').value.trim(); params.model = el('model').value.trim(); params.cloudConsent = true; + } + // Keep a tested draft only in this password field until saved or closed. + try { + const result = await request(params); + current = result; + message = action === 'enable' ? 'FAST enabled. Your agent can now use browser_task.' + : action === 'test' ? 'JEV connection verified. FAST has not been changed.' + : action === 'forget' ? 'Saved key removed. FAST is off.' : 'FAST is off. Running FAST tasks are being stopped.'; + if (action !== 'test') el('key').value = ''; + if (action === 'enable' || action === 'forget') { + el('form').hidden = true; el('consent').checked = false; + el('configure').setAttribute('aria-expanded', 'false'); + } + } catch (error) { + message = errors[error.message] || 'FAST settings unavailable. Reconnect and try again.'; failed = true; + } finally { params.apiKey = undefined; busy = false; render(); } + } + el('configure').onclick = configure; + el('disable').onclick = () => perform('disable'); + el('test').onclick = () => perform('test'); + el('forget').onclick = () => perform('forget'); + el('form').onsubmit = event => { event.preventDefault(); void perform('enable'); }; + const timer = setInterval(refresh, 5000); + settings.addEventListener('toggle', () => { + if (!settings.open && !el('form').hidden) configure(); + }); + window.addEventListener('pagehide', () => { clearInterval(timer); el('key').value = ''; }); + void refresh(); + return { render }; +} diff --git a/extension/popup.js b/extension/popup.js index 5dccd2b..474e1ee 100644 --- a/extension/popup.js +++ b/extension/popup.js @@ -1,4 +1,5 @@ import {taskPresentation, activityLabel} from './workspace-state.js'; +import { mountFastSettings } from './fast-settings.js'; const ui = globalThis.BeatBrowserUI; let language = await ui.read(); const t = (key, params) => ui.text(key, language, params); @@ -11,6 +12,8 @@ function applyLanguage() { document.querySelectorAll('[data-i18n-aria]').forEach(el => { el.setAttribute('aria-label', t(el.dataset.i18nAria)); }); } applyLanguage(); +const fastSettingsUI = mountFastSettings({ t }); +applyLanguage(); languageSelect.querySelectorAll('button').forEach(button => { button.onclick = async () => { try { await chrome.storage.local.set({uiLanguage:button.dataset.language}); } @@ -303,7 +306,7 @@ async function refreshSpaces() { refreshSpaces().catch(()=>{document.getElementById('spaces-message').textContent=t('Task spaces unavailable');}); chrome.storage.onChanged.addListener((changes,area)=>{ if(area==='local' && changes.uiLanguage) { - language=ui.resolve(changes.uiLanguage.newValue);applyLanguage();showMessage('');refreshConnection();refreshMark();refreshSpaces().catch(()=>{}); + language=ui.resolve(changes.uiLanguage.newValue);applyLanguage();fastSettingsUI.render();showMessage('');refreshConnection();refreshMark();refreshSpaces().catch(()=>{}); } if(area==='session' && changes.beatTaskSpaces) refreshSpaces().catch(()=>{}); }); diff --git a/extension/ui-language.js b/extension/ui-language.js index 419d7e3..1ba93d2 100644 --- a/extension/ui-language.js +++ b/extension/ui-language.js @@ -5,6 +5,38 @@ (() => { if (globalThis.BeatBrowserUI) return; const chinese = { + "Turn off FAST": "关闭 FAST", + "Remove the local FAST opt-out and restart your agent.": "请移除本地 FAST 禁用配置,再重启 Agent。", + "On": "已开启", + "Off": "已关闭", + "Unavailable": "不可用", + "Browser actions powered by JEV": "由 JEV 驱动浏览器操作", + "Configure": "配置", + "BeatAPI API Key": "BeatAPI API Key", + "Stored only by the local bridge on this computer.": "仅由这台电脑的本地桥接保存。", + "Get a BeatAPI key": "获取 BeatAPI Key", + "JEV model": "JEV 模型", + "Allow BeatAPI model calls. FAST tasks send limited page context; calls may use credits.": "允许调用 BeatAPI 模型。FAST 任务会发送有限的页面上下文,调用可能消耗额度。", + "Your agent starts each FAST task. Turning this on does not operate any page.": "每次 FAST 任务由 Agent 发起,开启开关不会操作页面。", + "Test connection": "测试连接", + "Test & enable": "测试并开启", + "Remove saved key": "移除已保存的 Key", + "Key configured · leave blank to keep": "已配置 Key · 留空保留", + "Paste your BeatAPI key": "粘贴 BeatAPI Key", + "Open your agent and reconnect to set up FAST.": "请打开 Agent 并重连,再配置 FAST。", + "Update the local BeatBrowser package and restart your agent.": "请更新本地 BeatBrowser 包并重启 Agent。", + "Enter a valid BeatAPI key and JEV model.": "请填写有效的 BeatAPI Key 和 JEV 模型。", + "BeatAPI rejected the test. Check the key, balance and model.": "BeatAPI 未通过测试,请检查 Key、余额和模型。", + "The model did not return a valid JEV decision.": "模型未返回有效的 JEV 决策。", + "BeatAPI timed out. Try the connection test again.": "BeatAPI 响应超时,请重新测试连接。", + "FAST settings unavailable. Reconnect and try again.": "FAST 配置暂不可用,请重连后重试。", + "Confirm model calls before testing or enabling FAST.": "请先勾选允许模型调用,再测试或开启 FAST。", + "Testing JEV…": "正在测试 JEV…", + "Saving…": "正在保存…", + "FAST enabled. Your agent can now use browser_task.": "FAST 已开启,Agent 现在可以使用 browser_task。", + "JEV connection verified. FAST has not been changed.": "JEV 连接已验证,FAST 开关状态未改变。", + "Saved key removed. FAST is off.": "已移除保存的 Key,FAST 已关闭。", + "FAST is off. Running FAST tasks are being stopped.": "FAST 已关闭,正在停止运行中的 FAST 任务。", "Browser pages": "浏览器页面", "Linked pages in this Chrome profile": "当前 Chrome 配置的关联页面", "{windows} windows · {pages} pages": "{windows} 个窗口 · {pages} 个页面", diff --git a/extension/workspace.css b/extension/workspace.css index 3e1f385..ce59cd4 100644 --- a/extension/workspace.css +++ b/extension/workspace.css @@ -45,6 +45,22 @@ button:focus-visible,summary:focus-visible,input:focus-visible,a:focus-visible { .workspace-open span[aria-hidden] { color:#d6d9e6; font-size:14px; line-height:1; } .meta { font-size:11px; color:var(--muted); margin:7px 0; overflow-wrap:anywhere; } .meta:empty,.task-summary:empty { display:none; } +.fast-card { margin-top:16px; padding-top:14px; border-top:1px solid var(--line); } +.fast-heading { display:flex; align-items:center; gap:8px; } +.fast-word { font:500 13px var(--mono); letter-spacing:1px; } +.fast-heading .count[data-on='true'] { color:var(--ok); background:#eaf4ee; } +#fast-configure { margin-left:auto; padding:0; background:none; border:0; color:var(--accent); font-size:11px; } +#fast-form { padding-top:4px; margin-top:8px; } +#fast-form>label { display:block; font-size:11px; font-weight:550; margin:10px 0 5px; } +#fast-form>input { display:block; width:100%; min-width:0; padding:8px; color:var(--ink); background:var(--soft); border:1px solid var(--line); border-radius:5px; font:11px var(--mono); } +#fast-form a { color:var(--accent); font-size:10px; } +#fast-form .fast-consent { display:flex; align-items:flex-start; gap:7px; font-weight:400; color:var(--muted); } +.fast-consent input { margin:4px 0 0; flex:none; accent-color:var(--accent); } +.fast-actions { display:flex; flex-wrap:wrap; gap:6px; margin-top:12px; } +.fast-actions button { border:1px solid var(--line); padding:7px 10px; background:var(--soft); color:var(--ink); border-radius:6px; font-size:11px; } +#fast-enable { background:var(--ink); border-color:var(--ink); color:#fff; } +.fast-forget { border:0; background:none; color:var(--muted); font-size:10px; padding:10px 0 0; } +#fast-message[data-error='true'] { color:var(--danger); } .spaces { margin-top:18px; } .section-heading { display:flex; align-items:center; gap:7px; margin-bottom:10px; } .spaces h2 { font-size:12px; font-weight:650; margin:0; } diff --git a/scripts/check-fast-browser.mjs b/scripts/check-fast-browser.mjs new file mode 100644 index 0000000..e666653 --- /dev/null +++ b/scripts/check-fast-browser.mjs @@ -0,0 +1,222 @@ +// [INPUT] Disposable Chromium profile; synthetic responses or explicit --live opt-in. +// [OUTPUT] Real popup, bridge and browser-executor acceptance with screenshots. +// [POS] Local acceptance. [PROTOCOL] Live calls require --live and a process key. +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import http from 'node:http'; +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { createHash } from 'node:crypto'; +import WebSocket from 'ws'; +import { browserTestArgs } from './browser-test-launch.mjs'; +import { startBridge } from '../src/bridge.js'; +import { createFastSettings } from '../src/fast-agent/settings.js'; +import { createBeatAPIClient } from '../src/fast-agent/client.js'; +import { runTask } from '../src/fast-agent/runner.js'; + +const binary = process.env.BEAT_TEST_CHROME; +if (!binary) throw Error('Set BEAT_TEST_CHROME to Chrome for Testing.'); +const live = process.argv.includes('--live'); +if (live && !process.env.BEATAPI_API_KEY) throw Error('Live acceptance requires a process-level BeatAPI key.'); +const root = path.resolve(import.meta.dirname, '..'); +const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'beat-spaces-fast-')); +const key = live ? process.env.BEATAPI_API_KEY : ['synthetic', 'browser', 'test'].join('-'); +let providerCalls = 0; +const providerChecks = []; +const fetchImpl = async (_url, options) => { + providerCalls++; + if (live) { + assert.equal(_url, 'https://api.beatapi.io/v1/systemone'); + const started = Date.now(); + const response = await fetch(_url, options); + providerChecks.push({ status: response.status, latencyMs: Date.now() - started }); + return response; + } + if (options.headers.Authorization !== `Bearer ${key}`) return new Response('{}', { status: 401 }); + assert(!options.body.includes(key)); + const { questions } = JSON.parse(options.body); + const answers = Object.fromEntries(Object.entries(questions).map(([head, question]) => { + const ids = Object.keys(question.criteria); + const choice = head === 'operation' && ids.includes('CLICK') ? 'CLICK' : ids[0]; + return [head, { type: 'choice', choice, confidence: 1, + probabilities: Object.fromEntries(ids.map(id => [id, id === choice ? 1 : 0])) }]; + })); + return Response.json({ answers }); +}; +const settings = createFastSettings({ filename: path.join(tmp, 'fast.json'), env: {}, + createClient: config => createBeatAPIClient({ ...config, fetchImpl }) }); +const bridge = startBridge({ port: 0, writeInfo: false, fastSettings: settings, auditFn: () => {} }); +await bridge.ready; +const port = bridge.wss.address().port; +const extension = path.join(tmp, 'extension'); +fs.cpSync(path.join(root, 'extension'), extension, { recursive: true }); +for (const file of ['background.js', 'offscreen.js']) { + const filename = path.join(extension, file); + fs.writeFileSync(filename, fs.readFileSync(filename, 'utf8') + .replace('const PORTS = [18899, 18900, 18901, 18902, 18903];', `const PORTS = [${port}];`)); +} +const manifest = JSON.parse(fs.readFileSync(path.join(extension, 'manifest.json'))); +const id = [...createHash('sha256').update(Buffer.from(manifest.key, 'base64')).digest('hex').slice(0, 32)] + .map(char => String.fromCharCode(97 + parseInt(char, 16))).join(''); +const fixture = http.createServer((_req, res) => { + res.setHeader('Content-Type', 'text/html'); + res.end('FAST fixture

FAST browser test

Ready'); +}); +fixture.listen(0, '127.0.0.1'); await once(fixture, 'listening'); +const url = `http://127.0.0.1:${fixture.address().port}`; +const browserEnv = { ...process.env }; +delete browserEnv.BEATAPI_API_KEY; +const browser = spawn(binary, browserTestArgs({ temporaryDirectory: tmp, extensionDirectory: extension, url }), + { stdio: 'ignore', env: browserEnv }); +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); +const until = async check => { + const end = Date.now() + 15000; + while (!await check()) { if (Date.now() > end) throw Error('Isolated FAST acceptance timed out'); await sleep(100); } +}; +let cdp, agent; +const pending = new Map(); +let seq = 0; +try { + const devtools = path.join(tmp, 'profile', 'DevToolsActivePort'); + await until(() => fs.existsSync(devtools)); + const [debugPort, route] = fs.readFileSync(devtools, 'utf8').trim().split('\n'); + cdp = new WebSocket(`ws://127.0.0.1:${debugPort}${route}`); await once(cdp, 'open'); + cdp.on('message', raw => { + const message = JSON.parse(raw), waiter = pending.get(message.id); + if (!waiter) return; + pending.delete(message.id); clearTimeout(waiter.timer); + message.error ? waiter.reject(Error(message.error.message)) : waiter.resolve(message.result); + }); + const command = (method, params = {}, sessionId) => new Promise((resolve, reject) => { + const id = ++seq; + const timer = setTimeout(() => { pending.delete(id); reject(Error(`CDP timeout: ${method}`)); }, 15000); + pending.set(id, { resolve, reject, timer }); cdp.send(JSON.stringify({ id, method, params, sessionId })); + }); + const { targetId } = await command('Target.createTarget', { url: `chrome-extension://${id}/popup.html` }); + const { sessionId } = await command('Target.attachToTarget', { targetId, flatten: true }); + const evaluate = async expression => { + const result = await command('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, sessionId); + if (result.exceptionDetails) throw Error(result.exceptionDetails.exception?.description || result.exceptionDetails.text); + return result.result.value; + }; + await until(() => evaluate("!!document.querySelector('#fast-status')")); + await evaluate("chrome.storage.local.set({uiLanguage:'en'})"); + await until(() => evaluate("document.querySelector('#fast-status')?.textContent === 'Off'")); + assert.equal(await evaluate("document.querySelector('details.adv').open"), false); + assert.equal(await evaluate("document.querySelector('#fast-form').hidden"), true); + assert.equal(await evaluate("!!document.querySelector('details.adv .fast-card')"), true); + assert.equal(await evaluate("!!(document.querySelector('.spaces').compareDocumentPosition(document.querySelector('.fast-card')) & Node.DOCUMENT_POSITION_FOLLOWING)"), true); + const capture = async name => { + await command('Emulation.setDeviceMetricsOverride', { width: 340, height: 760, deviceScaleFactor: 1, mobile: false }, sessionId); + const image = await command('Page.captureScreenshot', { format: 'png' }, sessionId); + const filename = path.join(root, 'screenshots-local', name); + fs.mkdirSync(path.dirname(filename), { recursive: true }); fs.writeFileSync(filename, Buffer.from(image.data, 'base64')); + return filename; + }; + await evaluate("chrome.storage.local.set({uiLanguage:'zh'})"); + await until(() => evaluate("document.documentElement.lang === 'zh-CN'")); + const defaultScreenshot = await capture('fast-default-zh.png'); + await evaluate("document.querySelector('details.adv > summary').click()"); + assert.equal(await evaluate("document.querySelector('#fast-form').hidden"), true, 'Opening Settings alone must not reveal API fields'); + const settingsScreenshot = await capture('fast-settings-zh.png'); + await evaluate("chrome.storage.local.set({uiLanguage:'en'})"); + await until(() => evaluate("document.documentElement.lang === 'en'")); + await evaluate("document.querySelector('#fast-configure').click()"); + assert.equal(await evaluate("document.querySelector('#fast-form').hidden"), false); + assert.equal(await evaluate("document.querySelector('#fast-configure').getAttribute('aria-expanded')"), 'true'); + await evaluate("document.querySelector('#fast-key').value='unsaved-draft'; document.querySelector('details.adv > summary').click()"); + await until(() => evaluate("document.querySelector('#fast-form').hidden")); + assert.equal(await evaluate("document.querySelector('#fast-key').value === ''"), true); + await evaluate("document.querySelector('details.adv > summary').click()"); + assert.equal(await evaluate("document.querySelector('#fast-form').hidden"), true); + await evaluate("document.querySelector('#fast-configure').click()"); + await evaluate("document.querySelector('#fast-test').click()"); + assert.equal(providerCalls, 0, 'No model call before consent'); + if (!live) { + await evaluate(`document.querySelector('#fast-key').value='wrong-synthetic-key'; document.querySelector('#fast-consent').checked=true; document.querySelector('#fast-test').click()`); + await until(() => evaluate("document.querySelector('#fast-message').textContent.includes('BeatAPI rejected')")); + assert.equal(settings.status().enabled, false); + await evaluate(`document.querySelector('#fast-key').value=${JSON.stringify(key)}; document.querySelector('#fast-test').click()`); + await until(() => evaluate("document.querySelector('#fast-message').textContent.includes('connection verified')")); + assert.equal(fs.existsSync(settings.filename), false, 'Test must not save'); + } else { + // Do not spend real credits on negative-key tests or a redundant test request. + await evaluate(`document.querySelector('#fast-key').value=${JSON.stringify(key)}; document.querySelector('#fast-consent').checked=true`); + } + await evaluate("document.querySelector('#fast-enable').click()"); + await until(async () => { + if (await evaluate("document.querySelector('#fast-message').dataset.error === 'true'")) { + throw Error(await evaluate("document.querySelector('#fast-message').textContent")); + } + return evaluate("document.querySelector('#fast-status').textContent === 'On'"); + }); + assert.equal(settings.status().enabled, true); + assert.equal(await evaluate("document.querySelector('#fast-key').value === ''"), true); + assert.equal(await evaluate(`Promise.all([chrome.storage.local.get(null),chrome.storage.session.get(null)]).then(x=>JSON.stringify(x).includes(${JSON.stringify(key)}))`), false); + // Connect an authenticated synthetic outer agent to the same real extension. + agent = new WebSocket(`ws://127.0.0.1:${port}`); await once(agent, 'open'); + const waiting = new Map(); let n = 0; + agent.on('message', raw => { + const message = JSON.parse(raw), waiter = waiting.get(message.id); + if (waiter) { waiting.delete(message.id); clearTimeout(waiter.timer); message.ok ? waiter.resolve(message.data) : waiter.reject(Error(message.error?.message)); } + }); + agent.send(JSON.stringify({ type: 'hello', role: 'agent', client: 'fast-test', sessionId: 'fast-isolated', token: bridge.token })); + await once(agent, 'message'); + const rpc = { ws: agent, extensionOnline: true, close() {}, call(cmd, params, options) { + return new Promise((resolve, reject) => { + const id = `f${++n}`, timer = setTimeout(() => { waiting.delete(id); reject(Error('Browser command timeout')); }, 10000); + waiting.set(id, { resolve, reject, timer }); + agent.send(JSON.stringify({ type: 'cmd', id, cmd, params, tabId: options?.tabId })); + }); + } }; + const result = await runTask({ enabled: true, url, goal: 'Click Verify FAST.', clickNames: ['Verify FAST'], + assertions: [{ textContains: 'FAST verified' }], tracePath: path.join(tmp, 'trace.jsonl'), + maxSteps: 3, maxModelCalls: 3, timeoutMs: 20000 }, + { bridge: rpc, env: settings.runtime().env, fetchImpl, isEnabled: () => settings.runtime().enabled }); + assert.equal(result.status, 'completed', JSON.stringify(result)); + assert.equal(result.verified, true); + assert(result.metrics.jevCalls > 0); + const rejected = await evaluate(`chrome.scripting.executeScript({target:{tabId:${result.tabId}}, + func:async()=>chrome.runtime.sendMessage({__hcPopup:'fastSettings',params:{action:'disable'}})}).then(rows=>rows[0].result)`); + assert.equal(rejected.error, 'FAST_UI_REQUIRED'); + assert.equal(settings.status().enabled, true, 'Content scripts cannot change FAST setup'); + await evaluate("chrome.storage.local.set({uiLanguage:'zh'})"); + await until(() => evaluate("document.querySelector('#fast-status').textContent === '\u5df2\u5f00\u542f'")); + await evaluate("document.querySelector('#fast-configure').click()"); + await evaluate("document.querySelector('.fast-card').scrollIntoView({block:'start'})"); + await command('Emulation.setDeviceMetricsOverride', { width: 340, height: 850, deviceScaleFactor: 1, mobile: false }, sessionId); + assert.equal(await evaluate('document.documentElement.scrollWidth > innerWidth'), false); + const shot = await command('Page.captureScreenshot', { format: 'png' }, sessionId); + const output = path.join(root, 'screenshots-local', live ? 'fast-entry-live-zh.png' : 'fast-entry-zh.png'); + fs.mkdirSync(path.dirname(output), { recursive: true }); fs.writeFileSync(output, Buffer.from(shot.data, 'base64')); + await command('Page.navigate', { url: `chrome-extension://${id}/panel.html` }, sessionId); + await until(() => evaluate("document.querySelector('#fast-status')?.textContent === '\u5df2\u5f00\u542f'")); + assert.equal(await evaluate("document.querySelector('details.adv').open"), false); + assert.equal(await evaluate("document.querySelector('#fast-form').hidden"), true); + assert.equal(await evaluate("document.querySelector('#fast-key').value === ''"), true, 'Fresh sidebar cannot retrieve the saved key'); + await evaluate("document.querySelector('details.adv > summary').click()"); + await evaluate("document.querySelector('#fast-configure').click()"); + await evaluate("document.querySelector('#fast-disable').click()"); + await until(() => evaluate("document.querySelector('#fast-status').textContent === '\u5df2\u5173\u95ed'")); + await evaluate("document.querySelector('#fast-forget').click()"); + await until(() => evaluate("document.querySelector('#fast-message').textContent.includes('\u5df2\u79fb\u9664')")); + assert.equal(settings.status().configured, false); + const report = { popup: true, consent: true, rejectedKey: live ? 'covered in offline acceptance' : true, + tasksFirst: true, settingsCollapsedByDefault: true, apiFieldsRequireConfigure: true, unsavedKeyClearedOnSettingsClose: true, + ephemeralTest: live ? 'covered in offline acceptance' : true, + enableDisableForget: true, noKeyInChromeStorage: true, contentScriptRejected: true, + sidebarPersistence: true, chinese: true, noOverflow: true, + browserTask: { status: result.status, verified: result.verified, jevCalls: result.metrics.jevCalls, actions: result.metrics.actions }, + provider: live ? 'live BeatAPI /v1/systemone' : 'synthetic responses; no real JEV request', + model: settings.status().model, providerCalls, providerChecks, screenshot: output, defaultScreenshot, settingsScreenshot }; + const reportPath = path.join(root, 'screenshots-local', live ? 'fast-live-results.json' : 'fast-offline-results.json'); + fs.writeFileSync(reportPath, JSON.stringify(report, null, 2)); + console.log(JSON.stringify(report, null, 2)); +} finally { + for (const entry of pending.values()) clearTimeout(entry.timer); + cdp?.close(); agent?.close(); browser.kill(); bridge.close(); fixture.close(); + await once(browser, 'exit').catch(() => {}); + fs.rmSync(tmp, { recursive: true, force: true }); +} diff --git a/src/bridge.js b/src/bridge.js index b409f00..48d4028 100644 --- a/src/bridge.js +++ b/src/bridge.js @@ -12,6 +12,7 @@ import { DEFAULT_PORT, writeBridgeInfo, newToken, tokenEquals, audit, ensureHome import { VERSION } from './lib/version.js'; import { scrubProse } from '../extension/redact.js'; +import { createFastSettings } from './fast-agent/settings.js'; export { VERSION }; const PROTOCOL = 1; @@ -23,7 +24,8 @@ const EXT_PROBE_MS = 15000; const ORPHAN_GRACE_MS = 15000; export function startBridge({ port = DEFAULT_PORT, token = newToken(), writeInfo = true, orphanGraceMs = ORPHAN_GRACE_MS, - silenceMs = EXT_SILENCE_MS, probeMs = EXT_PROBE_MS, tickMs = 20000, auditFn = audit } = {}) { + silenceMs = EXT_SILENCE_MS, probeMs = EXT_PROBE_MS, tickMs = 20000, auditFn = audit, + fastSettings = createFastSettings() } = {}) { if (writeInfo) ensureHome(); const audit = auditFn; @@ -286,6 +288,18 @@ export function startBridge({ port = DEFAULT_PORT, token = newToken(), writeInfo } function route(ws, msg) { + // Settings never enter command dispatch, audit logs, queues or agent responses. + if (msg.type === 'fast_settings') { + if (!extensions.has(ws) || typeof msg.id !== 'string' || msg.id.length > 80) return; + void fastSettings.handle(msg.params).then(data => { + send(ws, { type: 'fast_settings_result', id: msg.id, data }); + }).catch(error => { + const code = ['INVALID_SETTINGS', 'FAST_PROCESS_DISABLED', 'MISSING_API_KEY', 'INVALID_API_KEY', 'PROVIDER_HTTP_ERROR', 'INVALID_DECISION', 'INVALID_RESPONSE', 'NETWORK_ERROR', 'TIMEOUT'].includes(error.code) + ? error.code : 'SETTINGS_FAILED'; + send(ws, { type: 'fast_settings_result', id: msg.id, error: code }); + }); + return; + } // agent → extension if (msg.type === 'cmd') { if (!agents.has(ws)) return; diff --git a/src/cli.js b/src/cli.js index 31bd372..24ddd73 100755 --- a/src/cli.js +++ b/src/cli.js @@ -24,7 +24,13 @@ switch (cmd) { case 'run': { const { runCli } = await import('./fast-agent/cli.js'); - process.exitCode = await runCli(argv.slice(1)); + let dependencies = {}; + if (has('--enable-fast-agent') && !has('--dry-run')) { + const { createFastSettings } = await import('./fast-agent/settings.js'); + const settings = createFastSettings(); + dependencies = { env: settings.runtime(true).env, isEnabled: () => settings.runtime(true).enabled }; + } + process.exitCode = await runCli(argv.slice(1), { dependencies }); break; } @@ -33,7 +39,8 @@ switch (cmd) { await startMcpServer({ client: flag('--client', 'unknown'), - fastAgentEnabled: has('--enable-fast-agent') || process.env.BEAT_BROWSER_FAST_AGENT === '1', + fastAgentEnabled: process.env.BEAT_BROWSER_FAST_AGENT === '0' ? false + : has('--enable-fast-agent') || process.env.BEAT_BROWSER_FAST_AGENT === '1' ? true : undefined, }); break; } diff --git a/src/fast-agent/runner.js b/src/fast-agent/runner.js index 3b3435c..36f2c9a 100644 --- a/src/fast-agent/runner.js +++ b/src/fast-agent/runner.js @@ -223,6 +223,7 @@ export async function runTask(options = {}, dependencies = {}) { catch { throw fail('TRACE_WRITE_FAILED'); } }; const check = () => { + if (dependencies.isEnabled && !dependencies.isEnabled()) throw fail('FAST_AGENT_DISABLED'); if (options.signal?.aborted) throw fail('ABORTED'); if (context && Date.now() >= context.deadline) throw fail('TIMEOUT'); if (controller.signal.aborted) throw fail('ABORTED'); diff --git a/src/fast-agent/settings.js b/src/fast-agent/settings.js new file mode 100644 index 0000000..0fc72b2 --- /dev/null +++ b/src/fast-agent/settings.js @@ -0,0 +1,99 @@ +// [INPUT] Trusted extension settings and process-level environment. +// [OUTPUT] Private local FAST configuration and credential-free status. +// [POS] Node-only configuration boundary. [PROTOCOL] Never return or log keys. +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import { HOME } from '../lib/paths.js'; +import { createBeatAPIClient } from './client.js'; +import { buildQuestions } from './decision.js'; + +export const FAST_MODEL = 'jev-1.13'; +const ENDPOINT = 'https://api.beatapi.io'; +const invalid = () => Object.assign(new Error('Invalid FAST settings.'), { code: 'INVALID_SETTINGS' }); + +export function createFastSettings({ + filename = process.env.BEAT_BROWSER_FAST_CONFIG_FILE || path.join(HOME, 'fast-settings.json'), + env = process.env, createClient = createBeatAPIClient, +} = {}) { + function read() { + try { + const stat = fs.lstatSync(filename); + if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 8192 || (stat.mode & 0o077)) throw invalid(); + const data = JSON.parse(fs.readFileSync(filename, 'utf8')); + if (!data || typeof data.enabled !== 'boolean' || typeof data.model !== 'string' + || (data.apiKey !== undefined && typeof data.apiKey !== 'string')) throw invalid(); + return data; + } catch (error) { + if (error.code === 'ENOENT') return null; + // An unreadable existing configuration must fail closed, even with env opt-in. + return { enabled: false, model: FAST_MODEL, invalid: true }; + } + } + function runtime(override) { + const saved = read(); + const enabled = override !== false && env.BEAT_BROWSER_FAST_AGENT !== '0' + && (saved ? saved.enabled : override === true || env.BEAT_BROWSER_FAST_AGENT === '1'); + const provider = { ...env }; + if (saved?.apiKey) { + provider.BEATAPI_API_KEY = saved.apiKey; + provider.BEATAPI_BASE_URL = ENDPOINT; + } + provider.BEAT_BROWSER_JEV_MODEL = saved?.model || env.BEAT_BROWSER_JEV_MODEL || FAST_MODEL; + return { enabled, env: provider }; + } + function status() { + const current = runtime(env.BEAT_BROWSER_FAST_AGENT === '0' ? false : undefined); + return { enabled: current.enabled, configured: !!current.env.BEATAPI_API_KEY, + model: current.env.BEAT_BROWSER_JEV_MODEL, endpoint: ENDPOINT, + savedKey: !!read()?.apiKey, invalid: read()?.invalid === true }; + } + function write(data) { + fs.mkdirSync(path.dirname(filename), { recursive: true, mode: 0o700 }); + const temporary = `${filename}.${crypto.randomUUID()}.tmp`; + try { + fs.writeFileSync(temporary, JSON.stringify(data), { mode: 0o600, flag: 'wx' }); + fs.renameSync(temporary, filename); + } finally { try { fs.unlinkSync(temporary); } catch { /* Already renamed. */ } } + } + function draft(params) { + const saved = read(); + const model = params.model ?? saved?.model ?? env.BEAT_BROWSER_JEV_MODEL ?? FAST_MODEL; + const apiKey = params.apiKey || saved?.apiKey || env.BEATAPI_API_KEY; + if (typeof model !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(model) + || typeof apiKey !== 'string' || apiKey.length > 4096 || !/^[A-Za-z0-9._~+/-]+=*$/.test(apiKey)) throw invalid(); + return { enabled: true, model, apiKey }; + } + async function probe(data) { + // Fixed synthetic state: connection tests never read a browser page. + const client = createClient({ env: { BEATAPI_API_KEY: data.apiKey, BEATAPI_BASE_URL: ENDPOINT, + BEAT_BROWSER_JEV_MODEL: data.model }, timeoutMs: 15000 }); + await client.decide({ state: { goal: 'Connection test. Choose DONE.', page: { title: 'BeatBrowser connection test' } }, + questions: buildQuestions({ operations: ['DONE'], targets: {} }) }); + } + let queue = Promise.resolve(); + async function handleOne(params = {}) { + if (!params || typeof params !== 'object' || Array.isArray(params) + || Object.keys(params).some(key => !['action', 'apiKey', 'model', 'cloudConsent'].includes(key))) throw invalid(); + if (params.action === 'status') return status(); + if (params.action === 'disable' || params.action === 'forget') { + const saved = read(); + write({ enabled: false, model: saved?.model || FAST_MODEL, + ...(params.action === 'disable' && saved?.apiKey ? { apiKey: saved.apiKey } : {}) }); + return status(); + } + if (!['test', 'enable'].includes(params.action) || params.cloudConsent !== true) throw invalid(); + if (params.action === 'enable' && env.BEAT_BROWSER_FAST_AGENT === '0') { + throw Object.assign(new Error('FAST is disabled by the local process.'), { code: 'FAST_PROCESS_DISABLED' }); + } + const data = draft(params); + await probe(data); + if (params.action === 'enable') write(data); + return { ...status(), tested: true, testedModel: data.model }; + } + return { filename, runtime, status, handle(params) { + const result = queue.then(() => handleOne(params)); + queue = result.catch(() => {}); + return result; + } }; +} diff --git a/src/fast-agent/task.js b/src/fast-agent/task.js index 5053c8d..25e3c2f 100644 --- a/src/fast-agent/task.js +++ b/src/fast-agent/task.js @@ -81,6 +81,7 @@ export async function handleBrowserTask(args, { env = process.env, stderr = process.stderr, runTaskImpl = runTask, + isEnabled, } = {}) { if (enabled !== true) return failure('disabled', 'FAST_AGENT_DISABLED', 'The server has not enabled browser_task. Manual browser tools remain available.'); if (!args || typeof args !== 'object' || Array.isArray(args) @@ -92,7 +93,7 @@ export async function handleBrowserTask(args, { const { cloudConsent: _consent, ...task } = args; const options = validateTaskOptions({ ...task, enabled: true }); if (!options.dryRun) stderr.write(cloudConsentNotice(options.allowTextHelper, env) + '\n'); - const result = await runTaskImpl({ ...options, signal }, { bridge, env }); + const result = await runTaskImpl({ ...options, signal }, { bridge, env, ...(isEnabled ? { isEnabled } : {}) }); // Keep the MCP result small. In particular, never forward a snapshot or page body. const output = {}; for (const key of ['status', 'verified', 'summary', 'tracePath', 'blockedReason', 'verification', 'metrics', 'tabId']) { diff --git a/src/mcp-server.js b/src/mcp-server.js index f9d4cc3..7bad677 100644 --- a/src/mcp-server.js +++ b/src/mcp-server.js @@ -15,6 +15,7 @@ import fs from 'node:fs'; import path from 'node:path'; import { VERSION } from './lib/version.js'; import { BROWSER_TASK_TOOL, handleBrowserTask } from './fast-agent/task.js'; +import { createFastSettings } from './fast-agent/settings.js'; const REF = { type: 'string', description: 'Element ref from the latest snapshot, e.g. "e3"' }; const SNAP = { type: 'string', description: 'snapshotId the ref came from' }; @@ -515,8 +516,13 @@ reply — it must survive context compaction. With 2+ work-lines (a subagent, tw pass tabId on EVERY call — the implicit slot is SHARED with subagents and any of them can move it. Lost track? tabs(action:"list"). -OPTIONAL FAST LOOP: a cheap subagent can own the goal, site learnings and its own tab -(tabId on every call); it escalates payments, ask outcomes and plan changes back to you. +FAST JEV. When listed, browser_task is the user's enabled FAST executor. Prefer it +for bounded top-frame light-DOM interaction tasks with a concrete goal, exact inputs +and success assertions, after reviewing site learnings. Set cloudConsent:true only +with task-specific cloud-processing consent. It opens its own tab; preserve the +returned tabId. Check status and verified before claiming success. Existing-tab, +iframe, shadow-DOM and TaskSpace tasks should keep their supported manual tools. +The FAST switch alone does not authorize a website action or start a task. Information lives in three places; use them in this order: 1. NETWORK for DATA — \`network\` first: the API names its own fields; screen-read numbers @@ -548,14 +554,31 @@ export function getToolList({ fastAgentEnabled = false } = {}) { return fastAgentEnabled === true ? [...tools, BROWSER_TASK_TOOL] : tools; } -export async function startMcpServer({ client = 'unknown', fastAgentEnabled = process.env.BEAT_BROWSER_FAST_AGENT === '1' } = {}) { +export async function startMcpServer({ client = 'unknown', fastAgentEnabled, + fastSettings = createFastSettings() } = {}) { + const runtime = () => fastSettings.runtime(process.env.BEAT_BROWSER_FAST_AGENT === '0' ? false : fastAgentEnabled); const bridge = new BridgeClient({ client }); const server = new Server( { name: 'beat-browser', version: VERSION }, - { capabilities: { tools: {} }, instructions: STRATEGY } + { capabilities: { tools: { listChanged: true } }, instructions: STRATEGY } ); - server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: getToolList({ fastAgentEnabled }) })); + server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: getToolList({ fastAgentEnabled: runtime().enabled }) })); + const runningFastTasks = new Set(); + let advertisedFast = runtime().enabled; + fs.watchFile(fastSettings.filename, { persistent: false, interval: 500 }, () => { + const enabled = runtime().enabled; + if (!enabled) for (const controller of runningFastTasks) controller.abort(); + if (enabled !== advertisedFast) { + advertisedFast = enabled; + void server.sendToolListChanged().catch(() => {}); + } + }); + server.onclose = () => { + fs.unwatchFile(fastSettings.filename); + for (const controller of runningFastTasks) controller.abort(); + bridge.close(); + }; @@ -574,7 +597,19 @@ export async function startMcpServer({ client = 'unknown', fastAgentEnabled = pr // Dispatch before manual identification/connect. Disabled, invalid and dry-run // tasks must not touch Chrome or perform inference. if (name === 'browser_task') { - return handleBrowserTask(args, { enabled: fastAgentEnabled, bridge, signal: extra?.signal }); + const current = runtime(); + const controller = new AbortController(); + const cancel = () => controller.abort(); + extra?.signal?.addEventListener('abort', cancel, { once: true }); + if (extra?.signal?.aborted) controller.abort(); + runningFastTasks.add(controller); + try { + return await handleBrowserTask(args, { enabled: current.enabled, bridge, signal: controller.signal, + env: current.env, isEnabled: () => runtime().enabled }); + } finally { + runningFastTasks.delete(controller); + extra?.signal?.removeEventListener('abort', cancel); + } } identify(); try { diff --git a/test/fast-settings.test.js b/test/fast-settings.test.js new file mode 100644 index 0000000..c5b2379 --- /dev/null +++ b/test/fast-settings.test.js @@ -0,0 +1,154 @@ +// [INPUT] Synthetic keys, temporary files and isolated MCP/bridge peers. +// [OUTPUT] Configuration, live gating and credential-boundary assertions. +// [POS] FAST integration tests. [PROTOCOL] No real provider or user profile. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { once } from 'node:events'; +import WebSocket from 'ws'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; +import { ToolListChangedNotificationSchema } from '@modelcontextprotocol/sdk/types.js'; +import { createFastSettings } from '../src/fast-agent/settings.js'; +import { startBridge } from '../src/bridge.js'; +import { runTask } from '../src/fast-agent/runner.js'; + +function fixture(t, extra = {}) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'beat-fast-settings-')); + t.after(() => fs.rmSync(directory, { recursive: true, force: true })); + const calls = []; + const settings = createFastSettings({ filename: path.join(directory, 'settings.json'), env: {}, + createClient: config => ({ async decide(request) { calls.push({ config, request }); return {}; } }), ...extra }); + return { directory, calls, settings }; +} +const KEY = ['synthetic', 'fast', 'credential'].join('-'); +const enable = { action: 'enable', cloudConsent: true, apiKey: KEY, model: 'jev-1.13' }; + +test('test is ephemeral; enable persists privately; status never discloses key; disable/forget revoke', async t => { + const { settings, calls } = fixture(t); + assert.equal(settings.status().enabled, false); + await settings.handle({ ...enable, action: 'test' }); + assert.equal(fs.existsSync(settings.filename), false); + assert.equal(settings.status().configured, false); + const result = await settings.handle(enable); + assert.equal(result.enabled, true); + assert.equal(fs.statSync(settings.filename).mode & 0o777, 0o600); + assert.equal(JSON.stringify(result).includes(KEY), false); + assert.equal(calls.length, 2); + assert.equal(JSON.stringify(calls[0].request).includes(KEY), false); + assert.equal(settings.runtime().env.BEATAPI_API_KEY, KEY); + assert.equal(settings.runtime(false).enabled, false, 'Remote explicit opt-out always wins'); + assert.equal((await settings.handle({ action: 'disable' })).enabled, false); + assert.equal(settings.status().configured, true); + assert.equal(settings.runtime(true).enabled, false, 'UI disable revokes a CLI startup opt-in'); + await settings.handle({ action: 'forget' }); + assert.equal(settings.status().configured, false); + assert.equal(fs.readFileSync(settings.filename, 'utf8').includes(KEY), false); +}); + +test('consent and fixed endpoint are enforced; failed probes cannot enable or replace a working key', async t => { + let failed = false; + const { settings } = fixture(t, { env: { BEATAPI_BASE_URL: 'https://untrusted.test' }, + createClient: ({ env }) => ({ async decide() { + assert.equal(env.BEATAPI_BASE_URL, 'https://api.beatapi.io'); + if (failed) throw Object.assign(Error('private provider detail'), { code: 'PROVIDER_HTTP_ERROR' }); + } }) }); + await assert.rejects(settings.handle({ ...enable, cloudConsent: false }), { code: 'INVALID_SETTINGS' }); + await assert.rejects(settings.handle({ ...enable, baseUrl: 'https://untrusted.test' }), { code: 'INVALID_SETTINGS' }); + await settings.handle(enable); + const before = fs.readFileSync(settings.filename, 'utf8'); + failed = true; + await assert.rejects(settings.handle({ ...enable, apiKey: 'another-synthetic-value' }), { code: 'PROVIDER_HTTP_ERROR' }); + assert.equal(fs.readFileSync(settings.filename, 'utf8'), before); + assert.equal(settings.runtime().env.BEATAPI_BASE_URL, 'https://api.beatapi.io'); +}); + +test('unreadable, broad-permission and symlinked settings fail closed', async t => { + const { settings, directory } = fixture(t, { env: { BEAT_BROWSER_FAST_AGENT: '1' } }); + fs.writeFileSync(settings.filename, 'malformed', { mode: 0o600 }); + assert.equal(settings.runtime(true).enabled, false); + fs.writeFileSync(settings.filename, JSON.stringify(enable)); + fs.chmodSync(settings.filename, 0o644); + assert.equal(settings.runtime(true).enabled, false); + fs.unlinkSync(settings.filename); + const target = path.join(directory, 'target.json'); + fs.writeFileSync(target, JSON.stringify({ enabled: true, model: 'jev-1.13', apiKey: KEY }), { mode: 0o600 }); + fs.symlinkSync(target, settings.filename); + assert.equal(settings.runtime(true).enabled, false); +}); + +test('a disable requested during connection testing wins after the pending enable', async t => { + let release; + const wait = new Promise(resolve => { release = resolve; }); + const { settings } = fixture(t, { createClient: () => ({ decide: () => wait }) }); + const enabling = settings.handle(enable); + const disabling = settings.handle({ action: 'disable' }); + release({}); + await Promise.all([enabling, disabling]); + assert.equal(settings.status().enabled, false); +}); + +test('process-level explicit opt-out cannot be bypassed by saved settings or CLI opt-in', async t => { + const { settings } = fixture(t, { env: { BEAT_BROWSER_FAST_AGENT: '0' } }); + fs.writeFileSync(settings.filename, JSON.stringify({ enabled: true, model: 'jev-1.13', apiKey: KEY }), { mode: 0o600 }); + await assert.rejects(settings.handle(enable), { code: 'FAST_PROCESS_DISABLED' }); + assert.equal(settings.runtime(true).enabled, false); + assert.equal(settings.status().enabled, false); +}); + +test('MCP discovers UI-enabled FAST without restart and rejects it immediately after disable', { timeout: 10000 }, async t => { + const { settings } = fixture(t); + const transport = new StdioClientTransport({ command: process.execPath, + args: ['src/cli.js', 'mcp'], cwd: path.resolve(import.meta.dirname, '..'), stderr: 'pipe', + env: { ...process.env, BEAT_BROWSER_FAST_AGENT: '', BEATAPI_API_KEY: '', BEAT_BROWSER_FAST_CONFIG_FILE: settings.filename } }); + const client = new Client({ name: 'settings-test', version: '1.0.0' }); + t.after(() => client.close()); + let changes = 0; + client.setNotificationHandler(ToolListChangedNotificationSchema, () => { changes++; }); + await client.connect(transport); + assert.equal((await client.listTools()).tools.some(tool => tool.name === 'browser_task'), false); + await settings.handle(enable); + assert.equal((await client.listTools()).tools.some(tool => tool.name === 'browser_task'), true); + const args = { cloudConsent: true, dryRun: true, url: 'https://example.com', goal: 'Check example' }; + assert.equal(JSON.parse((await client.callTool({ name: 'browser_task', arguments: args })).content[0].text).status, 'dry_run'); + const until = Date.now() + 3000; + while (!changes && Date.now() < until) await new Promise(resolve => setTimeout(resolve, 50)); + assert(changes > 0, 'Advertise the updated tool list to clients'); + await settings.handle({ action: 'disable' }); + assert.equal(JSON.parse((await client.callTool({ name: 'browser_task', arguments: args })).content[0].text).status, 'disabled'); +}); + +test('runner rechecks the switch before any browser command after revocation', async t => { + const { directory } = fixture(t); + let enabled = true, observed = 0; + const result = await runTask({ enabled: true, url: 'https://example.com', goal: 'Test revocation', + tracePath: path.join(directory, 'trace.jsonl') }, { + client: {}, isEnabled: () => enabled, + adapter: { open: async () => { enabled = false; return { tabId: 1 }; }, + observe: async () => { observed++; }, abort: async () => {}, close() {} }, + }); + assert.equal(result.blockedReason, 'FAST_AGENT_DISABLED'); + assert.equal(observed, 0); +}); + +test('settings wire replies only to its extension and never enters audit or agent broadcast', { timeout: 5000 }, async t => { + const { settings } = fixture(t); + const audit = []; + const bridge = startBridge({ port: 0, writeInfo: false, fastSettings: settings, auditFn: entry => audit.push(entry) }); + await bridge.ready; + t.after(() => bridge.close()); + const socket = new WebSocket(`ws://127.0.0.1:${bridge.wss.address().port}`, { headers: { Origin: 'chrome-extension://settings-test' } }); + t.after(() => socket.close()); + await once(socket, 'open'); + socket.send(JSON.stringify({ type: 'hello', role: 'extension', instanceId: 'settings-test', version: '1.4.1' })); + await once(socket, 'message'); + socket.send(JSON.stringify({ type: 'fast_settings', id: 'test-1', params: enable })); + const [raw] = await once(socket, 'message'); + const response = JSON.parse(raw); + assert.equal(response.type, 'fast_settings_result'); + assert.equal(response.data.enabled, true); + assert.equal(raw.toString().includes(KEY), false); + assert.equal(JSON.stringify(audit).includes(KEY), false); +});