HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
Browser live view: the card, every base on the browser, plug tool names (#305)
github-actions[bot]a79a8f30b564
diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex 35939183..478f17b8 100644--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -665,12 +665,24 @@ install_backends() {fiif wanted pi && [ ! -x "$(backend_bin pi)" ]; then- echo "[harnessrouter] installing Pi (MIT) and its MCP adapter (MIT)…"- # --ignore-scripts is pi's own documented install form. The MCP adapter is a pi extension- # (github.com/nicobailon/pi-mcp-adapter): pi deliberately ships without MCP, and the runner- # mounts this adapter via -e only on turns that actually configure MCP servers.+ echo "[harnessrouter] installing Pi (MIT)…"+ # --ignore-scripts is pi's own documented install form.try_install "Pi" npm install -g --prefix "$TOOLS" --no-audit --no-fund --ignore-scripts \- @earendil-works/pi-coding-agent pi-mcp-adapter || true+ @earendil-works/pi-coding-agent || true+ fi+ # The MCP adapter is a pi extension (github.com/nicobailon/pi-mcp-adapter): pi deliberately+ # ships without MCP, and the runner mounts this adapter via -e only on turns that configure MCP+ # servers. PINNED, and re-pinned on every start, because the adapter's major decides which file+ # it reads: 2.x read <agent dir>/mcp.json, 3.x reads <agent dir>/mcp-adapter.json and not the+ # old name at all (its README). The runner writes the 3.x name; a volume that first booted on+ # 2.x is moved here, and a fresh volume no longer takes whatever npm serves that day.+ PI_MCP_PIN="${HR_PI_MCP_ADAPTER_VERSION:-3.1.0}"+ if wanted pi && [ -x "$(backend_bin pi)" ]; then+ have_adapter="$(node -e "console.log(require('$TOOLS/lib/node_modules/pi-mcp-adapter/package.json').version)" 2>/dev/null || true)"+ if [ "$have_adapter" != "$PI_MCP_PIN" ]; then+ echo "[harnessrouter] installing pi-mcp-adapter $PI_MCP_PIN (MIT, version-pinned)${have_adapter:+, replacing $have_adapter}…"+ try_install "pi-mcp-adapter" npm install -g --prefix "$TOOLS" --no-audit --no-fund --ignore-scripts "pi-mcp-adapter@$PI_MCP_PIN" || true+ fifiif wanted omp && [ ! -x "$(backend_bin omp)" ]; thendiff --git a/docs/browser-column.json b/docs/browser-column.jsonnew file mode 100644index 00000000..29e99a8d--- /dev/null+++ b/docs/browser-column.json@@ -0,0 +1,215 @@+{+ "instance": "hr-test (self-hosted, 0.25.7-rc.17)",+ "measured": "2026-09-27",+ "prompt": "Open https://example.com/ in the browser, click the only link on that page, and reply with the URL and the title of the page you land on.",+ "rows": [+ {+ "base": "codex",+ "model": "gpt-5.4",+ "ok": true,+ "tools": [+ "click",+ "navigate",+ "open"+ ],+ "s": 33,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "claude-code",+ "model": "claude-sonnet-4.6",+ "ok": true,+ "tools": [+ "click",+ "navigate",+ "open"+ ],+ "s": 46,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "hermes",+ "model": "gpt-5.4",+ "ok": true,+ "tools": [+ "click",+ "get_url",+ "navigate",+ "open"+ ],+ "s": 52,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "pi",+ "model": "gpt-5.4",+ "ok": true,+ "tools": [+ "click",+ "get_url",+ "navigate",+ "open"+ ],+ "s": 34,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "omp",+ "model": "gpt-5.4",+ "ok": true,+ "tools": [+ "click",+ "navigate",+ "open"+ ],+ "s": 40,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "dsh",+ "model": "deepseek-v4-pro",+ "ok": true,+ "tools": [+ "click",+ "navigate",+ "open"+ ],+ "s": 27,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "goose",+ "model": "gpt-5.4",+ "ok": true,+ "tools": [+ "click",+ "get_url",+ "navigate",+ "open"+ ],+ "s": 33,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "opencode",+ "model": "gpt-5.4",+ "ok": true,+ "tools": [+ "click",+ "get_url",+ "navigate",+ "open"+ ],+ "s": 27,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "aider",+ "model": "gpt-5.4",+ "ok": true,+ "tools": [+ "click",+ "get_url",+ "navigate",+ "open",+ "snapshot"+ ],+ "s": 33,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "kimi",+ "model": "kimi-k3",+ "ok": true,+ "tools": [+ "click",+ "navigate",+ "open"+ ],+ "s": 40,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "openhands",+ "model": "gpt-5.4",+ "ok": true,+ "tools": [+ "click",+ "get_url",+ "navigate",+ "open",+ "snapshot"+ ],+ "s": 46,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "cheetahclaws",+ "model": "gpt-5.4",+ "ok": true,+ "tools": [+ "click",+ "navigate",+ "open"+ ],+ "s": 27,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "qwen",+ "model": "qwen3.7-max",+ "ok": true,+ "tools": [+ "click",+ "get_url",+ "navigate",+ "open"+ ],+ "s": 40,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "gemini",+ "model": "gemini-3.8-flash",+ "ok": true,+ "tools": [+ "click",+ "get_url",+ "navigate",+ "open"+ ],+ "s": 33,+ "usd": 0.000333,+ "why": ""+ },+ {+ "base": "cline",+ "model": "gpt-5.4",+ "ok": true,+ "tools": [+ "click",+ "get_url",+ "navigate",+ "open",+ "snapshot",+ "wait_for"+ ],+ "s": 33,+ "usd": 0.000333,+ "why": ""+ }+ ]+}diff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.mdindex aaafcf3a..fff6c4ab 100644--- a/docs/self-hosting-guide.md+++ b/docs/self-hosting-guide.md@@ -627,6 +627,30 @@ curl -s -X POST "$HARNESSROUTER_BASE_URL/v1/harnesses/$HID/servers/plugs" \plugin with `"requires": {"plugs": ["browser"]}` in its `plugin.json`; the harness it lands onincludes the plugin, and the workspace still has to have connected it.+**Watching and taking over.** When a task opens a browser, the console brings up a Browser card+beside the conversation and streams the vendor's live view of it; the edges of the screen tint+blue while the agent has the browser and breathe while it acts, and a ghost cursor glides along a+small arc to wherever the agent last clicked or typed. The browser's screen is landscape whatever+the card's shape: the card shows the whole screen at the largest size that fits, with its own+surface around it; beside the conversation it floats, centred, at the height the screen needs,+with the conversation squeezed to its left (on a phone it sits under the conversation instead;+drag the divider or go full screen for a larger view). The card's top row carries every action: **Take over**+(or a click on the screen) makes the view yours to click and type in and pauses the agent, whose+next browser call waits for you without spending tokens and runs the moment you choose **Hand back+to the agent** (after 45 seconds of waiting the call answers that you still have the browser and+the agent may keep waiting or go on without it); **Full screen** fills the window and **Close**+puts the card away. The card+closes itself when the browser closes; the **Browser** button in the task header, there whenever+the harness includes the browser plugin, opens it at any time, with or without a browser in it.+A harness that includes the plugin also tells its agent so, in a Browser section of the agent's+instructions file: use the browser tools for the web and never curl or a web search instead+(Codex keeps its MCP tools behind a tool search and reached for curl without it).+Behind it: `GET /v1/sessions/{sid}/browser` (open or not, who has it, the live view address, which+is a credential and is served only to the session's owner) and+`POST /v1/sessions/{sid}/browser/control` with `{"control": "user"}` or `{"control": "agent"}`;+the harness event feed carries `browser.opened`, `browser.call` (with the point the agent acted on+and the page's viewport), `browser.held`, `browser.control` and `browser.closed` (never the address).+**The browser.** The browser runs in Browser Use Cloud and is driven from this instance; the agentnever holds the browser's address or the key. Set the key in the container's environment:diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.mdindex eb18a128..f73e0e30 100644--- a/docs/support-matrix-notes.md+++ b/docs/support-matrix-notes.md@@ -1568,3 +1568,43 @@ on every connection, so 0.25.6 lists gpt-6-sol and gpt-6-luna on goose and its othe same way: 50 of 50 after one retest (first run 48 of 50: gpt-6-luna's recycle recall onVercel and gpt-6-sol's on OpenAI, both answering "GOOSE DONE", both passing the retest). Thesame recall flake as above, on the base that resumes through the relay like cline does.++## The browser column (2026-09-27)++Every base but System One drives the browser plugin on one task in plain words: "Open+https://example.com/ in the browser, click the only link on that page, and reply with the URL and+the title of the page you land on." A base passes when the task completed, the trace shows the+browser navigating and clicking, the answer names iana.org (where the link goes), and the browser+session was stopped and billed. Runner: `scripts/support-matrix/plugs/browser.py`; the table is+the Browser section of support-matrix.md, rendered from docs/browser-column.json.++**Result: 15 of 15 on 0.25.7-rc.17, first try, 27 to 52 seconds a base, one browser minute each.**++The baseline on rc.14, before any change, was 5 of 15 (codex, claude-code, pi, omp, dsh), and+three defects stood between it and the result, each measured on its own build:++1. **A Browser section in the agent's doc (rc.15).** Codex 0.154 keeps MCP tools behind its tool+ search and opened a page with web search and curl while the console's Browser card stayed+ empty; hermes fetched the page its own way, and cheetahclaws and opencode obeyed the prompt's+ "do not visit any other site" instead of following the link (which leads to iana.org). A+ harness that includes the browser plugin now gets a Browser section in AGENTS.md / CLAUDE.md,+ the file its own instructions go to: the tools by name, that the person is watching, never+ curl or a web search instead, look the tools up if they are deferred. The prompt lost the ban+ and names "the only link" rather than its wording, which example.com changes ("More+ information..." one week, "Learn more" the next). On rc.15 the seven bases that already had+ the tools passed 7 of 7.+2. **One header helper for every MCP writer (rc.16).** goose, opencode, aider, kimi, qwen,+ gemini, openhands and cline had no browser at all: their MCP writers passed a server's+ declared headers and dropped its `auth`, so the plugs server, whose credential the gateway+ mints per turn, answered 401 (openhands said so; kimi said the server could not be reached;+ the rest said they had no browser). claude, codex, pi, omp and hermes each carried their own+ copy of the auth handling and worked. `_mcp_headers` in runner/server.py is now the one place+ a server's headers come from, for every writer and the bridge. 14 of 15 on rc.16.+3. **Tool names are `plug_tool` (rc.17).** openhands reached the browser and the turn died on the+ Responses API's "Invalid 'input[3].name': string does not match pattern '^[a-zA-Z0-9_-]+$'":+ the plugs server named its tools browser.navigate, github.get_file_contents and so on. Claude+ Code, Codex and pi rewrite an MCP tool's name before offering it; OpenHands passes it through,+ and neither OpenAI's nor Anthropic's function-name rule allows a dot. 15 of 15 on rc.17.++Tools seen per base differ by style, not by ability: some snapshot before clicking, some read the+URL after, cline waits for the load; every one navigated and clicked through the plugin.diff --git a/docs/support-matrix.md b/docs/support-matrix.mdindex 2a214560..b7c4f65b 100644--- a/docs/support-matrix.md+++ b/docs/support-matrix.md@@ -3639,3 +3639,26 @@ Not run in this column, 198 pairs the provider serves that the harness did not r- openhands x gpt-6-astra: not run, the model answers on the Responses API only and this harness speaks chat/completions only- goose x gpt-6-astra: not run, the model answers on the Responses API only and this harness speaks chat/completions only+## Browser plugin, every base++Measured 2026-09-27 on hr-test (self-hosted, 0.25.7-rc.17). One task in plain words, "Open https://example.com/ in the browser, click the only link on that page, and reply with the URL and the title of the page you land on." A base passes when the task completed, the trace shows the browser navigating and clicking, the answer names the page the link leads to, and the browser session was stopped and billed; a failure is retested once. System One is not in the column: its models choose among offered actions and call no tools. The run's findings are in [support-matrix-notes.md](support-matrix-notes.md).++| base | model | browser | tools seen | seconds | notes |+|---|---|---|---|---:|---|+| codex | gpt-5.4 | pass | click, navigate, open | 33 | |+| claude-code | claude-sonnet-4.6 | pass | click, navigate, open | 46 | |+| hermes | gpt-5.4 | pass | click, get_url, navigate, open | 52 | |+| pi | gpt-5.4 | pass | click, get_url, navigate, open | 34 | |+| omp | gpt-5.4 | pass | click, navigate, open | 40 | |+| dsh | deepseek-v4-pro | pass | click, navigate, open | 27 | |+| goose | gpt-5.4 | pass | click, get_url, navigate, open | 33 | |+| opencode | gpt-5.4 | pass | click, get_url, navigate, open | 27 | |+| aider | gpt-5.4 | pass | click, get_url, navigate, open, snapshot | 33 | |+| kimi | kimi-k3 | pass | click, navigate, open | 40 | |+| openhands | gpt-5.4 | pass | click, get_url, navigate, open, snapshot | 46 | |+| cheetahclaws | gpt-5.4 | pass | click, navigate, open | 27 | |+| qwen | qwen3.7-max | pass | click, get_url, navigate, open | 40 | |+| gemini | gemini-3.8-flash | pass | click, get_url, navigate, open | 33 | |+| cline | gpt-5.4 | pass | click, get_url, navigate, open, snapshot, wait_for | 33 | |++15 of 15 bases drive the browser.diff --git a/gateway/app.py b/gateway/app.pyindex 41710746..95ab22fc 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -1092,6 +1092,8 @@ _INTEGRATION_SECRET_FIELDS = ("api_key", "aws_bearer_token", "aws_secret_access_# base), the model list it serves, and the connect flow that hands a key to this instance.HR_HOSTED_BASE = os.environ.get("HR_HOSTED_BASE", "https://api.harnessrouter.ai").rstrip("/")HR_HOSTED_PROVIDER_BASE = f"{HR_HOSTED_BASE}/v1/provider"+# The hosted console, where a HarnessRouter API key's credit is bought and topped up.+HR_HOSTED_CONSOLE = os.environ.get("HR_HOSTED_CONSOLE", "https://app.harnessrouter.ai").rstrip("/")HR_HOSTED_MODELS_URL = f"{HR_HOSTED_BASE}/v1/models"HR_HOSTED_BALANCE_URL = f"{HR_HOSTED_BASE}/v1/balance"HR_HOSTED_CONNECT_URL = f"{HR_HOSTED_BASE}/v1/connect"@@ -4563,6 +4565,12 @@ async def delete_trace(sid: str, request: Request) -> dict:await _vg_upsert("HarnessSession", sid, {"status": "deleted", "shared": "0"})except Exception: # noqa: BLE001pass+ # The share resolver caches token -> session and session -> shared for _SHARE_TTL seconds; a+ # link opened inside that window after the delete still answered (R-07 of the conformance+ # suite, intermittent by timing). The tombstone is not enough: the caches go with it, as they+ # do on every revoke.+ _SHARE_STATE_CACHE.pop(sid, None)+ _SHARE_TOKEN_CACHE.clear()# §6: a session is deleted with nothing still writing into it. A live turn is stopped first,# the same way cancel stops it, so the sandbox cannot repopulate storage that has no owner.if {"running", "starting"} & {str(v.get("turn_status") or ""), str(v.get("status") or "")}:@@ -4857,15 +4865,6 @@ _CUSTOM_FORMAT_BACKENDS = {}-def _custom_can_drive(backend: str) -> bool:- """Whether ANY custom-endpoint format can run this backend. A custom integration's models are- shown greyed on a backend its format cannot drive, so the reader learns why a model they- configured is not pickable there; on a backend no custom format drives at all (systemone runs- System One models only, and a custom endpoint speaks OpenAI or Anthropic text shapes) the row- is not an explanation but a chat model offered on a harness that cannot use one."""- return any(backend in bs for bs in _CUSTOM_FORMAT_BACKENDS.values())--def _integration_serves_backend(integ: dict, backend: str) -> bool:"""Can this integration actually run a turn on `backend`? For a custom provider this isgated by its api_format (see _CUSTOM_FORMAT_BACKENDS); every other provider just needs a@@ -5018,6 +5017,7 @@ async def admin_integrations_get(request: Request) -> dict:if row.get("name") == hosted.get("name"):row["balance"] = balreturn {"integrations": public,+ "hosted_console": HR_HOSTED_CONSOLE,"model_map": await _effective_model_map(),"image_model_map": await _effective_image_model_map(),"providers": sorted({p for p, _ in _INTEGRATION_WIRING}),@@ -6864,17 +6864,8 @@ async def _harness_models_view(hv: dict | None, backend: str, servable: set[str]models.append({"id": canonical, "label": canonical, "backend": backend,"available": True, "default": canonical == default})seen.add(canonical)- # A custom model whose api_format this backend can't speak is still LISTED so the operator- # can see it exists, but greyed out (available=False) rather than silently omitted — the- # picker must not offer a choice that fails at the first call.- for canonical, iname in eff_map.items():- if canonical in seen:- continue- integ = integrations.get(iname)- if integ and str(integ.get("provider") or "").lower() == "custom" and _custom_can_drive(backend):- models.append({"id": canonical, "label": canonical, "backend": backend,- "available": False, "default": canonical == default})- seen.add(canonical)+ # A custom model whose api_format this backend cannot speak is not listed here at all (it+ # was greyed once, as an explanation; read as the backend offering it: Richard, 2026-09-27).if default and default not in seen:models.insert(0, {"id": default, "label": default, "backend": backend,"available": ok(default), "default": True})@@ -7191,7 +7182,8 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s# The harness's configured instructions are the agent's CLAUDE.md (claude) / AGENTS.md (codex) —# written into the workspace by the runner, NOT injected as a system prompt. The model keeps the# CLI's default system prompt; persistent project instructions live in the doc the agent reads.- agent_doc = str((hv or {}).get("system_prompt") or "")+ agent_doc = _agent_doc_with_plugs(str((hv or {}).get("system_prompt") or ""),+ await _harness_plug_types(harness_id, org, hv))status = "failed"# A follow-up on a no-resume backend gets the conversation handed back in its prompt. Read# from the durable turn records; a read failure degrades to a fresh turn rather than failing@@ -13515,6 +13507,45 @@ async def _media_session_purge(sid: str) -> None:# that the record names a WORKSPACE, because that is what a plug belongs to._PLUGS_SERVER = "plugs"_PLUGS_ENTRY = {"name": "plugs", "id": "mcp.plugs"}++# What the agent's doc (AGENTS.md / CLAUDE.md) says about the browser when the harness includes+# it. Codex 0.154 keeps MCP tools behind its tool search, so without a word about them it opened+# a page with web search and curl while the person watched an empty Browser card (hr-test,+# 2026-09-27); pi found the tools on its own. Every base reads its doc, so every base gets it.+_BROWSER_GUIDE = (+ "## Browser\n"+ "This task has a live browser that the person can watch and take over. Its tools are on the "+ "`plugs` server: browser_navigate, browser_snapshot, browser_click, browser_type, browser_press_key, "+ "browser_scroll, browser_extract_text, browser_screenshot, browser_wait_for, browser_back, "+ "browser_get_url, browser_list_tabs, browser_switch_tab. Use them for anything on the web: "+ "opening a page, reading it, filling a form, clicking through. Do not fetch a page with curl, "+ "wget or a web search instead: the person is watching the browser, and a page fetched another "+ "way never appears there. If these tools are not in your tool list, look them up (they may be "+ "deferred) before touching the web any other way.")+++def _agent_doc_with_plugs(agent_doc: str, plug_types: list[str]) -> str:+ """The harness's instructions plus a section for each included plugin that needs one."""+ parts = [agent_doc.strip()] if agent_doc and agent_doc.strip() else []+ if "browser" in plug_types:+ parts.append(_BROWSER_GUIDE)+ return "\n\n".join(parts)+++async def _harness_plug_types(hid: str, org: str, hv: dict | None) -> list[str]:+ """The plugins a harness includes, by type, from its plugs server's record: [] when it has+ no enabled plugs entry, or the record cannot be read (the turn runs without the section)."""+ if not hid or not hv:+ return []+ try:+ servers = _mcp_list(hv)+ entry = next((e for e in servers if str(e.get("id") or "") == _PLUGS_ENTRY["id"]), None)+ if not entry or str(entry.get("enabled", True)) in ("False", "false", "0"):+ return []+ _, rec = await _hosted_resolve(_PLUGS_SERVER, hid, org, servers, entry_id=_PLUGS_ENTRY["id"])+ except Exception: # noqa: BLE001+ return []+ return [str(x) for x in (rec.get("plugs") or []) if x]_PLUG_CALL_LABEL = "PlugCall"# The registry that holds plug records: the engine's door on the platform edge (the engine's own# ingress admits no in-environment caller). Empty = no registry, so every plug reads as missing.@@ -14053,8 +14084,8 @@ async def plugs_mcp(request: Request):name = str(params.get("name") or "")args = params.get("arguments") or {}- plug, _, tool = name.partition(".")- spec = plugs_plane.find(plug, tool) if plug in plugs else None+ plug, tool = plugs_plane.split_name(name, plugs)+ spec = plugs_plane.find(plug, tool) if plug else Noneif spec is None or (enabled and enabled.get(plug) is not None and tool not in enabled[plug]):return _jsonrpc_result(rid, _tool_text(f"No tool named {name!r} on this server.", True))workspace = str(rec.get("workspace") or "")@@ -14113,7 +14144,63 @@ async def plugs_mcp(request: Request):# The record of the browser itself is the plane's registry (browser_plane.registry): one process on# a self-hosted instance keeps it in memory; the hosted service keeps it in its control store so# every replica the sandbox's calls reach attaches to the one browser instead of opening its own.++# ── the browser's live view ──────────────────────────────────────────────────────────────────+# What the console shows while a task browses: the vendor's live view of the session's browser,+# who has control, and when the agent last acted. The live URL is a credential (whoever opens it+# controls the browser), so it is read through the owned-session route and never put on the feed.++[email protected]("/v1/sessions/{sid}/browser")+async def session_browser(sid: str, request: Request) -> dict:+ await _owned_session(request, sid)+ rec = await browser_plane.registry.get(sid) if browser_plane.configured() else None+ if not rec:+ return {"session_id": sid, "open": False}+ return {"session_id": sid, "open": True, "live_url": str(rec.get("live_url") or ""),+ "control": str(rec.get("control") or "agent"), "opened_at": rec.get("created"),+ "last_call_at": rec.get("last_call"), "last_tool": str(rec.get("last_tool") or ""),+ "viewport": rec.get("viewport"), "calls": int(rec.get("calls") or 0), "session_minutes": browser_plane.SESSION_CAP_MIN}+++class BrowserControlBody(BaseModel):+ control: str++[email protected]("/v1/sessions/{sid}/browser/control")+async def session_browser_control(sid: str, body: BrowserControlBody, request: Request) -> dict:+ """Hand the browser to the person (`user`) or back to the agent (`agent`). While the person+ has it, the agent's browser calls are held and told so; nothing is stopped or lost."""+ await _owned_session(request, sid)+ who = (body.control or "").strip().lower()+ if who not in ("user", "agent"):+ raise HTTPException(400, "control is 'user' or 'agent'")+ rec = await browser_plane.registry.get(sid) if browser_plane.configured() else None+ if not rec:+ raise HTTPException(404, "this task has no open browser")+ await browser_plane.registry.bump(sid, control=who, control_at=time.time())+ _browser_notice(sid, "control", hid=str(rec.get("hid") or ""), org=str(rec.get("org") or ""), control=who)+ return {"session_id": sid, "open": True, "control": who}++_browser_open_locks: dict[str, asyncio.Lock] = {}+# How long one held browser call waits for the person to hand the browser back before answering+# that it is still theirs (under the MCP clients' 60 s request timeout), and how often it looks.+BROWSER_HOLD_SLICE_S = float(os.environ.get("HR_BROWSER_HOLD_SLICE_S", "45"))+BROWSER_HOLD_POLL_S = 0.5+++def _browser_notice(sid: str, kind: str, hid: str = "", org: str = "", **extra) -> None:+ """One event on the harness feed for the console's live view: the browser opened, a call ran,+ a call was held because the person has the browser, control changed hands, or it closed. The+ in-flight turn's org, harness, member and response id tag it (so it replays to a viewer that+ connects mid-turn and stays with the member whose session it is); a notice after the turn+ (the reaper closing an idle browser) carries the record's harness. NEVER the live URL: whoever+ holds that URL controls the browser, so it travels only through the owned-session route."""+ buf = _turn_buffers.get(sid) or {}+ ev = {"type": f"browser.{kind}", "session_id": sid, "at": time.time(), **extra}+ _bus_publish(org or str(buf.get("org") or ""), hid or str(buf.get("harness") or ""),+ str(buf.get("member") or ""), sid, str(buf.get("rid") or ""), ev)async def _browser_plug_call(rid, hid: str, sid: str, org: str, workspace: str, tool: str, spec: dict, args: dict,@@ -14153,6 +14240,7 @@ async def _browser_plug_call(rid, hid: str, sid: str, org: str, workspace: str,await _plug_call_record(hid, sid, org, workspace, plug, "open", "session", started, "ok",detail={"estimate_usd": estimate, "session_minutes": browser_plane.SESSION_CAP_MIN,"vendor": browser_plane.VENDOR, "vendor_session": s.vendor_id})+ _browser_notice(sid, "opened", hid=hid, org=org, vendor=browser_plane.VENDOR)if s is None:try:s = await browser_plane.attach(rec) # this process's attachment to the recorded browser@@ -14163,6 +14251,31 @@ async def _browser_plug_call(rid, hid: str, sid: str, org: str, workspace: str,if (s.allow, s.deny) != (allow, deny):s.allow, s.deny, s.host_cache = list(allow), list(deny), {} # the workspace changed its listsawait browser_plane.registry.bump(sid, allow=list(allow), deny=list(deny))+ # THE PERSON MAY HAVE THE BROWSER. The console's live view lets them take over with a click,+ # and a takeover pauses the agent rather than ending its work: the call WAITS here, without a+ # token spent, and runs the moment they hand the browser back. Read from the record, since the+ # takeover is a write from another request (another replica when there are several). A wait+ # is bounded below the MCP clients' own request timeouts (60 s in the reference SDKs): past+ # the bound the tool answers, not as an error, that the person still has the browser and the+ # agent may call again to keep waiting. Measured on hr-test 0.25.7-rc.4 before this: a refusal+ # made pi end its turn early with "the browser is under user control, so I can't continue".+ current = await browser_plane.registry.get(sid) if not (rec is None and s.opened) else None+ if (current or {}).get("control") == "user":+ _browser_notice(sid, "held", hid=hid, org=org, tool=tool)+ waited = 0.0+ while (current or {}).get("control") == "user" and waited < BROWSER_HOLD_SLICE_S:+ await asyncio.sleep(BROWSER_HOLD_POLL_S)+ waited += BROWSER_HOLD_POLL_S+ current = await browser_plane.registry.get(sid)+ if current is None:+ return await refused("session closed", "The browser for this task was stopped while the person had it. "+ "Call again to open a new one.")+ if current.get("control") == "user":+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "held", "still held",+ detail={"waited_s": round(waited, 1)})+ return _jsonrpc_result(rid, _tool_text(+ "The person using this task still has the browser. Call this tool again to keep waiting for it, "+ "or continue without the browser."))async with s.lock:if s.closed:return await refused("session closed", "The browser for this task was stopped. Call again to open a new one.")@@ -14179,6 +14292,9 @@ async def _browser_plug_call(rid, hid: str, sid: str, org: str, workspace: str,await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "error",f"{type(e).__name__}: {e}")return _jsonrpc_result(rid, _tool_text(f"The call failed ({type(e).__name__}). Try again.", True))+ viewport = await browser_plane.viewport_of(s) # the screen's shape, for the card's frame and cursor+ await browser_plane.registry.bump(sid, last_call=time.time(), last_tool=tool, viewport=viewport)+ _browser_notice(sid, "call", hid=hid, org=org, tool=tool, point=s.pointer, viewport=viewport)if isinstance(out, tuple) and out[0] == "image":png, caption = out[1], out[2]stored = None@@ -14211,6 +14327,7 @@ async def _browser_close(sid: str, reason: str) -> None:await browser_plane.detach(s)return_browser_open_locks.pop(sid, None)+ _browser_notice(sid, "closed", hid=str(rec.get("hid") or ""), org=str(rec.get("org") or ""), reason=reason)try:fig = await browser_plane.close_session_browser(rec, s)except Exception as e: # noqa: BLE001@@ -16743,10 +16860,10 @@ async def list_models(request: Request) -> dict:models = [{"id": m, "label": m, "backend": b, "available": ok(m),"default": m == c["default"]} for m in c["models"]]seen = set(c["models"])- # Add models from the effective map that are not already in the catalog.- # A model serves this backend only if its integration's api_format is compatible;- # on an incompatible backend it is still LISTED (so the operator sees it exists) but- # greyed out (available=False) rather than silently omitted.+ # Add models from the effective map that are not already in the catalog: a custom+ # endpoint's model, on the backends its api_format drives. Not on the others, not even+ # greyed: a Claude model under Codex read as "Codex can use Anthropic models" (Richard,+ # hr-test 2026-09-27), and a backend that can never run a model has no row for it.for canonical, iname in eff_map.items():if canonical in seen:continue@@ -16757,10 +16874,7 @@ async def list_models(request: Request) -> dict:if _integration_serves_backend(integ, b):models.append({"id": canonical, "label": canonical, "backend": b,"available": True, "default": False})- elif _custom_can_drive(b):- models.append({"id": canonical, "label": canonical, "backend": b,- "available": False, "default": False})- seen.add(canonical)+ seen.add(canonical)out[b] = {"default": c["default"], "models": models}return {"backends": out}diff --git a/gateway/browser_plane.py b/gateway/browser_plane.pyindex 1e323b86..6ab66f46 100644--- a/gateway/browser_plane.py+++ b/gateway/browser_plane.py@@ -107,7 +107,10 @@ def _vendor_client() -> httpx.AsyncClient:async def vendor_create(timeout_min: int, metadata: dict) -> dict:"""A browser in the vendor's cloud: no proxy, no CAPTCHA solving, no recording, so the only- unit that can bill is time. 402 is the vendor's wallet, 429 its concurrency."""+ unit that can bill is time. 402 is the vendor's wallet, 429 its concurrency. The screen is the+ vendor's default, landscape: what the live view streams is that screen, whatever the shape of+ the card showing it (measured on hr-test, 2026-09-28: neither an emulated viewport over CDP+ nor allowResizing changed the streamed frame), so the console fits the frame inside the card."""async with _vendor_client() as c:r = await c.post(f"{API_BASE}/browsers", json={"timeout": int(timeout_min), "proxyCountryCode": None, "solveCaptchas": False,@@ -235,6 +238,7 @@ class Session:self.lock = asyncio.Lock()self.closed = Falseself.opened = False # this call made the browser at the vendor: the caller writes the open row once+ self.pointer: dict | None = None # where the agent last acted (the element's centre), for the console's ghost cursor; kept across navigations so the next action glides from theredef minutes(rec: dict) -> int:@@ -433,6 +437,9 @@ async def attach(rec: dict) -> Session:pages = list(getattr(s.context, "pages", None) or [])s.page = pages[0] if pages else await s.context.new_page()s.page.set_default_timeout(30000)+ on = getattr(s.context, "on", None)+ if callable(on):+ on("page", lambda pg: asyncio.ensure_future(_follow_new_tab(s, sid, pg)))except Exception:await detach(s)raise@@ -440,6 +447,29 @@ async def attach(rec: dict) -> Session:return s+async def _follow_new_tab(s: Session, sid: str, pg) -> None:+ """A link the person opened in a new tab while they have the browser is followed in the tab the+ live view shows: the new page's address goes to the shown page and the new page closes, so the+ view stays with them (the console's live view shows one tab, and a link marked to open in a new+ one looked like a click that did nothing: the LinkedIn and X icons on a directory page,+ 2026-09-27). Only while the person has the browser: the agent's own tabs are its to manage+ (list_tabs, switch_tab)."""+ try:+ rec = await registry.get(sid)+ if (rec or {}).get("control") != "user" or pg is s.page:+ return+ try:+ await pg.wait_for_load_state("domcontentloaded", timeout=8000)+ except Exception: # noqa: BLE001+ pass+ url = str(getattr(pg, "url", "") or "")+ if url and url != "about:blank":+ await s.page.goto(url, wait_until="domcontentloaded", timeout=30000)+ await pg.close()+ except Exception: # noqa: BLE001+ pass++async def detach(s: Session) -> None:"""Drop this process's attachment; the browser itself stays as it is (a connected browser'sclose disconnects it and closes only the contexts this attachment made)."""@@ -538,7 +568,7 @@ _tool("switch_tab", "act", "Make one of the open tabs the current tab.",def tool_list() -> list[dict]:- return [{"name": f"browser.{t['name']}", "description": f"[browser, {t['risk']}] {t['description']}",+ return [{"name": f"browser_{t['name']}", "description": f"[browser, {t['risk']}] {t['description']}","inputSchema": t["inputSchema"],"annotations": {"readOnlyHint": t["risk"] == "read", "destructiveHint": False}} for t in _TOOLS]@@ -551,8 +581,11 @@ _SNAPSHOT_JS = """(max) => {const out = []; let n = 0;const seen = new Set();+ // Visible to a person: laid out, not hidden, and at least 8 px each way. Sites keep tiny proxy+ // controls (DuckDuckGo's 4 x 4 search input beside the field people see); an agent that types+ // into one of those types into nothing anyone can see (hr-test, 2026-09-28).const vis = (el) => { const r = el.getBoundingClientRect(); const cs = getComputedStyle(el);- return r.width > 0 && r.height > 0 && cs.visibility !== 'hidden' && cs.display !== 'none'; };+ return r.width >= 8 && r.height >= 8 && cs.visibility !== 'hidden' && cs.display !== 'none'; };const nameOf = (el) => (el.getAttribute('aria-label') || el.getAttribute('title') || el.getAttribute('placeholder')|| (el.labels && el.labels[0] && el.labels[0].innerText) || el.getAttribute('alt') || el.innerText || el.value || '').trim().replace(/\\s+/g, ' ').slice(0, 80);const sel = 'h1,h2,h3,a[href],button,input,select,textarea,[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[role=radio],[role=textbox],[contenteditable=true],summary';@@ -630,6 +663,37 @@ async def _settled(s: Session) -> None:pass+async def _mark(s: Session, loc) -> None:+ """Remember the centre of the element about to be acted on, in page coordinates, so the console+ can show a ghost cursor going there. Best effort: a locator that cannot be measured leaves the+ last point standing."""+ try:+ box = await loc.bounding_box()+ except Exception: # noqa: BLE001+ return+ if isinstance(box, dict) and box.get("width") is not None:+ s.pointer = {"x": round(float(box["x"]) + float(box["width"]) / 2, 1), "y": round(float(box["y"]) + float(box["height"]) / 2, 1)}+++async def viewport_of(s: Session) -> dict:+ """The page's own layout viewport (window.innerWidth/innerHeight), the coordinate space of+ `pointer`. Asked of the page, not of the context: the vendor's default context carries its+ window's size, not the 1280 x 800 this plane asks for when it makes a context of its own, and+ a cursor placed on the assumed size landed low and right of the element the agent clicked+ (hr-test, 2026-09-27)."""+ try:+ v = await s.page.evaluate("() => [window.innerWidth, window.innerHeight]")+ if isinstance(v, (list, tuple)) and len(v) == 2 and int(v[0]) > 0:+ return {"w": int(v[0]), "h": int(v[1])}+ except Exception: # noqa: BLE001+ pass+ try:+ vs = s.page.viewport_size if s.page is not None else None+ except Exception: # noqa: BLE001+ vs = None+ return {"w": int((vs or {}).get("width") or 1280), "h": int((vs or {}).get("height") or 800)}++async def call(s: Session, name: str, args: dict):"""Run one tool on this session. Returns text, or ("image", png bytes, caption) for ascreenshot the caller stores. Raises BrowserToolError with a sentence the agent can act on."""@@ -664,6 +728,7 @@ async def call(s: Session, name: str, args: dict):return text[:cap] + (f"\n… {len(text) - cap} more characters" if len(text) > cap else "")if name == "click":loc = _target(s, args)+ await _mark(s, loc)try:await loc.click(timeout=15000)except Exception as e: # noqa: BLE001@@ -672,6 +737,7 @@ async def call(s: Session, name: str, args: dict):return f"Clicked. Now at {await _where(s)}"if name == "type":loc = _target(s, args)+ await _mark(s, loc)text = str(args.get("text") or "")try:await loc.fill(text, timeout=15000)@@ -740,7 +806,7 @@ async def call(s: Session, name: str, args: dict):s.page = pages[i]s.page.set_default_timeout(30000)return f"Current tab is now {i}: {await _where(s)}"- raise BrowserToolError(f"No tool named browser.{name}.")+ raise BrowserToolError(f"No tool named browser_{name}.")def audit_line(d: dict) -> str:diff --git a/gateway/plugs_plane.py b/gateway/plugs_plane.pyindex 535089d4..8468d5ea 100644--- a/gateway/plugs_plane.py+++ b/gateway/plugs_plane.py@@ -112,16 +112,30 @@ def tools_of(plug: str) -> list[dict]:return list(_TOOLS.get(_ALIAS.get(plug, plug), []))+def split_name(name: str, plugs: list[str]) -> tuple[str, str]:+ """(plug, tool) for an MCP tool name `<plug>_<tool>`, the plug being the longest of `plugs`+ the name starts with (a plug's own name may carry an underscore: github_app). ("", "") when+ none does."""+ for plug in sorted(plugs, key=len, reverse=True):+ if name.startswith(plug + "_"):+ return plug, name[len(plug) + 1:]+ return "", ""++def tool_list(plugs: list[str], enabled: dict | None = None) -> list[dict]:- """MCP tool descriptors for the plugs a harness is bound to, `<plug>.<tool>` each, narrowed to- the names `enabled` lists for a plug when it lists any."""+ """MCP tool descriptors for the plugs a harness is bound to, `<plug>_<tool>` each, narrowed to+ the names `enabled` lists for a plug when it lists any. An underscore, not a dot: the model+ APIs allow no dot in a function name (OpenAI's pattern is ^[a-zA-Z0-9_-]+$), and while+ Claude Code, Codex and pi rewrite an MCP tool's name before offering it, OpenHands passes it+ through and the Responses API refused the replay of a `browser.navigate` call (hr-test,+ 2026-09-27)."""out = []for plug in plugs:allow = (enabled or {}).get(plug)for t in tools_of(plug):if allow is not None and t["name"] not in allow:continue- out.append({"name": f"{plug}.{t['name']}",+ out.append({"name": f"{plug}_{t['name']}","description": f"[{TYPES.get(plug, plug)}, {t['risk']}] {t['description']}","inputSchema": t["inputSchema"],"annotations": {"readOnlyHint": t["risk"] == "read",diff --git a/gateway/tests/test_browser.py b/gateway/tests/test_browser.pyindex 3318f578..32800287 100644--- a/gateway/tests/test_browser.py+++ b/gateway/tests/test_browser.py@@ -125,6 +125,9 @@ class Req:class Locator:+ async def bounding_box(self):+ return {"x": 100.0, "y": 200.0, "width": 50.0, "height": 20.0}+def __init__(self, page, sel):self.page, self.sel, self.first = page, sel, self@@ -355,7 +358,7 @@ def _rpc(client, tok: str, method: str, params: dict | None = None, rid=1):def _call(client, tok, name, **args):- return _rpc(client, tok, "tools/call", {"name": f"browser.{name}", "arguments": args})+ return _rpc(client, tok, "tools/call", {"name": f"browser_{name}", "arguments": args})def _rows(hid: str) -> list[dict]:@@ -386,12 +389,12 @@ def test_a_harness_includes_the_browser_like_any_plug_and_the_workspace_must_havassert _get(client, f"/v1/harnesses/{hid}/servers/mcp.plugs").json()["status"] == {"browser": "missing"}tok = gw._mint_hosted_cred(hid, _session_of(hid), _key(hid))tools = _rpc(client, tok, "tools/list")["tools"]- assert [t["name"] for t in tools] == ["browser.navigate", "browser.get_url", "browser.snapshot", "browser.extract_text",- "browser.click", "browser.type", "browser.press_key", "browser.scroll", "browser.wait_for",- "browser.screenshot", "browser.back", "browser.list_tabs", "browser.switch_tab"]- assert next(t for t in tools if t["name"] == "browser.snapshot")["annotations"] == {"readOnlyHint": True, "destructiveHint": False}- assert next(t for t in tools if t["name"] == "browser.click")["annotations"] == {"readOnlyHint": False, "destructiveHint": False}- assert next(t for t in tools if t["name"] == "browser.navigate")["description"].startswith("[Browser, write]")+ assert [t["name"] for t in tools] == ["browser_navigate", "browser_get_url", "browser_snapshot", "browser_extract_text",+ "browser_click", "browser_type", "browser_press_key", "browser_scroll", "browser_wait_for",+ "browser_screenshot", "browser_back", "browser_list_tabs", "browser_switch_tab"]+ assert next(t for t in tools if t["name"] == "browser_snapshot")["annotations"] == {"readOnlyHint": True, "destructiveHint": False}+ assert next(t for t in tools if t["name"] == "browser_click")["annotations"] == {"readOnlyHint": False, "destructiveHint": False}+ assert next(t for t in tools if t["name"] == "browser_navigate")["description"].startswith("[Browser, write]")out = _call(client, tok, "navigate", url="https://example.com/")assert out["isError"] and out["content"][0]["text"].startswith("The workspace has no Browser plugin connected")assert ven.created == [] and _rows(hid)[-1]["outcome"] == "refused" and _rows(hid)[-1]["error"] == "missing"@@ -404,7 +407,7 @@ def test_a_harness_includes_the_browser_like_any_plug_and_the_workspace_must_hav# a narrowed include lists only the named toolsr = _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["browser"], "tools": {"browser": ["navigate", "extract_text"]}})assert r.status_code == 200 and r.json()["tools"] == {"browser": ["navigate", "extract_text"]}- assert [t["name"] for t in _rpc(client, tok, "tools/list")["tools"]] == ["browser.navigate", "browser.extract_text"]+ assert [t["name"] for t in _rpc(client, tok, "tools/list")["tools"]] == ["browser_navigate", "browser_extract_text"]r = _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["browser"], "tools": {"browser": ["evaluate"]}})assert r.status_code == 400 and "evaluate" in r.text@@ -829,3 +832,66 @@ def test_a_row_served_off_the_owning_replica_still_lands_in_the_trace(client, woevents += [json.loads(line) for line in body.decode().splitlines() if line.strip()]assert [(e["type"], e["tool"], e["outcome"]) for e in events] == [("plug", "open", "ok"), ("plug", "navigate", "ok")]assert all(gw._TRACE_NONCE in it["file_id"] for it in chunks) # this process's chunks, unique beside the owner's+++def test_the_person_takes_the_browser_over_and_the_agent_waits(client, world):+ """The console's live view: a click hands the browser to the person, the agent's calls are held+ and told so, the session's route says who has it (and carries the live URL, nowhere else), and+ a hand-back lets the agent go on. The feed carries the notices without the URL."""+ reg, ven, posted = world+ reg.record = _record()+ hid = _harness(client)+ _include(client, hid)+ sid = _session_of(hid)+ tok = gw._mint_hosted_cred(hid, sid, _key(hid))+ published: list[dict] = []+ orig = gw._bus_publish+ gw._bus_publish = lambda org, h, member, s_, rid, ev: published.append({"harness": h, "sid": s_, "ev": ev})+ try:+ # no browser yet: the route says so, and nothing can be handed over+ assert client.get(f"/v1/sessions/{sid}/browser", headers=HEADERS).json() == {"session_id": sid, "open": False}+ assert client.post(f"/v1/sessions/{sid}/browser/control", json={"control": "user"}, headers=HEADERS).status_code == 404+ # the first call opens the browser: the feed learns it, the route carries the live URL+ assert _call(client, tok, "navigate", url="example.com")["isError"] is False+ kinds = [p["ev"]["type"] for p in published]+ assert kinds == ["browser.opened", "browser.call"], kinds+ assert all(p["harness"] == hid and p["sid"] == sid and "live_url" not in p["ev"] for p in published)+ info = client.get(f"/v1/sessions/{sid}/browser", headers=HEADERS).json()+ assert info["open"] is True and info["control"] == "agent" and info["last_tool"] == "navigate"+ assert info["viewport"] == {"w": 1280, "h": 800} # the screen's shape, for the card's frame+ assert info["live_url"].startswith("http") and info["session_minutes"] == gw.browser_plane.SESSION_CAP_MIN+ # the person takes over: the agent's next call waits for the hand-back, and past the wait's+ # bound answers (not as an error) that the person still has the browser; the record says who has it+ gw.BROWSER_HOLD_SLICE_S = 0.6+ assert client.post(f"/v1/sessions/{sid}/browser/control", json={"control": "user"}, headers=HEADERS).json()["control"] == "user"+ t0 = time.time()+ out = _call(client, tok, "get_url")+ assert out["isError"] is False and "still has the browser" in out["content"][0]["text"], out+ assert 0.5 <= time.time() - t0 < 5, "the call waited for the slice before answering"+ assert client.get(f"/v1/sessions/{sid}/browser", headers=HEADERS).json()["control"] == "user"+ assert [p["ev"]["type"] for p in published][-2:] == ["browser.control", "browser.held"]+ held_rows = [r for r in _rows(hid) if r["outcome"] == "held"]+ assert held_rows and held_rows[-1]["tool"] == "get_url" and json.loads(held_rows[-1]["detail"])["waited_s"] >= 0.5+ # an invalid hand is refused; a hand-back lets the agent go on+ assert client.post(f"/v1/sessions/{sid}/browser/control", json={"control": "nobody"}, headers=HEADERS).status_code == 400+ assert client.post(f"/v1/sessions/{sid}/browser/control", json={"control": "agent"}, headers=HEADERS).json()["control"] == "agent"+ assert _call(client, tok, "get_url")["content"][0]["text"] == "https://example.com/ (Example Domain)"+ assert [p["ev"]["type"] for p in published][-2:] == ["browser.control", "browser.call"]+ # another org cannot read the live URL or take the browser+ other = {**HEADERS, "x-harness-org": "someoneelse"}+ assert client.get(f"/v1/sessions/{sid}/browser", headers=other).status_code in (403, 404)+ assert client.post(f"/v1/sessions/{sid}/browser/control", json={"control": "user"}, headers=other).status_code in (403, 404)+ finally:+ gw._bus_publish = orig++++def test_a_harness_with_the_browser_tells_its_agent_to_use_it():+ """The agent's doc gets a Browser section when the harness includes the plugin, after its own+ instructions, and nothing when it does not (Codex opened a page with curl while the card+ stayed empty, hr-test 2026-09-27)."""+ assert gw._agent_doc_with_plugs("", []) == ""+ assert gw._agent_doc_with_plugs("Be brief.", ["github"]) == "Be brief."+ doc = gw._agent_doc_with_plugs("Be brief.\n", ["browser"])+ assert doc.startswith("Be brief.\n\n## Browser\n") and "browser_navigate" in doc and "curl" in doc+ assert gw._agent_doc_with_plugs("", ["browser"]) == gw._BROWSER_GUIDEdiff --git a/gateway/tests/test_plugs.py b/gateway/tests/test_plugs.pyindex 3b3aacaf..6f53252b 100644--- a/gateway/tests/test_plugs.py+++ b/gateway/tests/test_plugs.py@@ -248,13 +248,13 @@ def test_the_agent_lists_and_calls_the_bound_plugs(client, world):assert _rpc(client, tok, "initialize")["serverInfo"]["name"] == "plugs"names = [t["name"] for t in _rpc(client, tok, "tools/list")["tools"]]- assert "github.get_file_contents" in names and "github.merge_pull_request" in names- assert [n for n in names if n.startswith("insforge.")] == ["insforge.query_rows"] # narrowed- assert not [n for n in names if n.startswith("vercel.")] # not bound- listed = next(t for t in _rpc(client, tok, "tools/list")["tools"] if t["name"] == "github.merge_pull_request")+ assert "github_get_file_contents" in names and "github_merge_pull_request" in names+ assert [n for n in names if n.startswith("insforge_")] == ["insforge_query_rows"] # narrowed+ assert not [n for n in names if n.startswith("vercel_")] # not bound+ listed = next(t for t in _rpc(client, tok, "tools/list")["tools"] if t["name"] == "github_merge_pull_request")assert listed["annotations"] == {"readOnlyHint": False, "destructiveHint": True}- out = _rpc(client, tok, "tools/call", {"name": "github.get_file_contents", "arguments": {"path": "README.md"}})+ out = _rpc(client, tok, "tools/call", {"name": "github_get_file_contents", "arguments": {"path": "README.md"}})assert out["isError"] is False, outassert json.loads(out["content"][0]["text"]) == {"path": "README.md", "sha": "abc", "size": 5, "content": "hello"}assert ven.calls[-1].url.path == "/repos/acme/site/contents/README.md"@@ -263,12 +263,12 @@ def test_the_agent_lists_and_calls_the_bound_plugs(client, world):assert rows[0]["plug"] == "github" and rows[0]["risk"] == "read" and rows[0]["workspace"] == WS and rows[0]["session"] == "sess1"assert posted == [(ORG, "plug.call", 1.0, {"workspace": WS, "task_id": "sess1", "harness_id": hid})]- out = _rpc(client, tok, "tools/call", {"name": "insforge.query_rows",+ out = _rpc(client, tok, "tools/call", {"name": "insforge_query_rows","arguments": {"table": "orders", "filters": {"status": "eq.open"}, "limit": 5}})assert out["isError"] is False and json.loads(out["content"][0]["text"]) == [{"id": 1, "status": "open"}]assert dict(ven.calls[-1].url.params) == {"status": "eq.open", "limit": "5"}# a tool the binding narrowed away, and one from a plug that is not bound- for name in ("insforge.insert_rows", "vercel.get_project", "github.nothing", "nonsense"):+ for name in ("insforge_insert_rows", "vercel_get_project", "github_nothing", "nonsense"):out = _rpc(client, tok, "tools/call", {"name": name, "arguments": {}})assert out["isError"] and "No tool named" in out["content"][0]["text"], name@@ -279,13 +279,13 @@ def test_the_vendors_refusal_is_the_agents_tool_error_and_still_a_call(client, w_post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github"]})reg.records[(WS, "github")] = _record("github")tok = gw._mint_hosted_cred(hid, "sess2", _key(hid))- out = _rpc(client, tok, "tools/call", {"name": "github.get_file_contents", "arguments": {"path": "bad.md"}})+ out = _rpc(client, tok, "tools/call", {"name": "github_get_file_contents", "arguments": {"path": "bad.md"}})assert out["isError"] and out["content"][0]["text"] == "GitHub answered 422: Validation Failed"rows = _calls(hid)assert rows[0]["outcome"] == "error" and rows[0]["error"] == "GitHub answered 422: Validation Failed"assert len(posted) == 1# missing arguments never reach the vendor- out = _rpc(client, tok, "tools/call", {"name": "github.get_issue", "arguments": {}})+ out = _rpc(client, tok, "tools/call", {"name": "github_get_issue", "arguments": {}})assert out["isError"] and out["content"][0]["text"] == "number is required"assert not [c for c in ven.calls if "/issues" in c.url.path]@@ -295,7 +295,7 @@ def test_refusals_by_plug_state_are_not_metered(client, world, monkeypatch):hid = _harness(client)_post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github"]})tok = gw._mint_hosted_cred(hid, "sess3", _key(hid))- call = {"name": "github.get_file_contents", "arguments": {"path": "README.md"}}+ call = {"name": "github_get_file_contents", "arguments": {"path": "README.md"}}def refused(contains: str):out = _rpc(client, tok, "tools/call", call)@@ -341,7 +341,7 @@ def test_the_credential_is_read_again_only_when_the_version_changes(client, worl_post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github"]})reg.records[(WS, "github")] = _record("github", version=3)tok = gw._mint_hosted_cred(hid, "sess4", _key(hid))- call = {"name": "github.get_file_contents", "arguments": {"path": "README.md"}}+ call = {"name": "github_get_file_contents", "arguments": {"path": "README.md"}}reg.reads = 0 # the attach read the status onceassert _rpc(client, tok, "tools/call", call)["isError"] is Falseassert reg.reads == 1@@ -368,7 +368,7 @@ def test_every_call_lands_in_the_sessions_trace(client, world, monkeypatch):monkeypatch.setattr(gw, "_trace_put", _put)monkeypatch.setitem(gw._session_trace, "sess5", {"prefix": "traces/sess5", "count": 0})tok = gw._mint_hosted_cred(hid, "sess5", _key(hid))- _rpc(client, tok, "tools/call", {"name": "github.get_file_contents", "arguments": {"path": "README.md"}})+ _rpc(client, tok, "tools/call", {"name": "github_get_file_contents", "arguments": {"path": "README.md"}})assert len(chunks) == 1 and chunks[0][0].startswith("traces/sess5/events/")ev = json.loads(chunks[0][1])assert ev["type"] == "plug" and ev["plug"] == "github" and ev["tool"] == "get_file_contents"@@ -420,7 +420,7 @@ def test_the_tool_table_is_well_formed():assert plugs_plane.find("insforge", "delete_rows")["risk"] == "destructive"assert plugs_plane.find("vercel", "deploy_from_repo")["risk"] == "write"listed = plugs_plane.tool_list(["github"], {"github": ["get_repo"]})- assert [t["name"] for t in listed] == ["github.get_repo"] and listed[0]["description"].startswith("[GitHub, read]")+ assert [t["name"] for t in listed] == ["github_get_repo"] and listed[0]["description"].startswith("[GitHub, read]")def test_push_files_deploy_and_insert_drive_the_vendors_as_documented(world):@@ -482,10 +482,10 @@ def test_a_missing_grant_is_named_before_the_vendor_is_asked(client, world):rec["config"]["permissions_missing"] = ["issues", "actions"]reg.records[(WS, "github")] = rectok = gw._mint_hosted_cred(hid, "sess6", _key(hid))- out = _rpc(client, tok, "tools/call", {"name": "github.create_issue", "arguments": {"title": "x"}})+ out = _rpc(client, tok, "tools/call", {"name": "github_create_issue", "arguments": {"title": "x"}})assert out["isError"] and "not granted issues access" in out["content"][0]["text"]assert ven.calls == [] and posted == [] and _calls(hid)[0]["error"] == "no issues permission"- out = _rpc(client, tok, "tools/call", {"name": "github.get_file_contents", "arguments": {"path": "README.md"}})+ out = _rpc(client, tok, "tools/call", {"name": "github_get_file_contents", "arguments": {"path": "README.md"}})assert out["isError"] is False # contents was granteddiff --git a/gateway/tests/test_plugs_local.py b/gateway/tests/test_plugs_local.pyindex 4b19136f..91c12084 100644--- a/gateway/tests/test_plugs_local.py+++ b/gateway/tests/test_plugs_local.py@@ -93,7 +93,7 @@ def test_the_catalog_and_the_browser_connected_here(client, world):r = _req(client, "POST", f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["browser"]})assert r.status_code == 200 and r.json()["status"] == {"browser": "missing"}tok = gw._mint_hosted_cred(hid, "sess1", gw._hosted_secret_key(hid, "mcp.plugs"))- out = _rpc(client, tok, "browser.get_url")+ out = _rpc(client, tok, "browser_get_url")assert out["isError"] and out["content"][0]["text"].startswith("The workspace has no Browser plugin connected")# the workspace turns it on, with its site lists@@ -104,15 +104,15 @@ def test_the_catalog_and_the_browser_connected_here(client, world):assert d["version"] == 1 and d["secrets_set"] == []assert _req(client, "GET", f"/v1/harnesses/{hid}/servers/mcp.plugs").json()["status"] == {"browser": "connected"}# the agent browses; the site lists come from the record- out = _rpc(client, tok, "browser.navigate", {"url": "https://example.com/"})+ out = _rpc(client, tok, "browser_navigate", {"url": "https://example.com/"})assert out["isError"] is False, outassert out["content"][0]["text"].startswith("Opened https://example.com/ (Example Domain)")- out = _rpc(client, tok, "browser.navigate", {"url": "https://public.example/leak"})+ out = _rpc(client, tok, "browser_navigate", {"url": "https://public.example/leak"})assert out["isError"] and "outside the ones" in out["content"][0]["text"]# a settings change is a new version, read on the next callr = _req(client, "PUT", "/v1/plugs/browser", {"enabled": True, "config": {"allow_domains": []}})assert r.json()["version"] == 2 and r.json()["config"]["allow_domains"] == [] and r.json()["config"]["deny_domains"] == ["ads.example.com"]- assert _rpc(client, tok, "browser.navigate", {"url": "https://public.example/leak"})["isError"] is False+ assert _rpc(client, tok, "browser_navigate", {"url": "https://public.example/leak"})["isError"] is False# the count the Plugins page showsother = _harness(client)a = _req(client, "GET", "/v1/plugs/browser/attachments").json()@@ -125,7 +125,7 @@ def test_the_catalog_and_the_browser_connected_here(client, world):# turned off: the tools refuse in a sentence, the record staysr = _req(client, "PUT", "/v1/plugs/browser", {"enabled": False})assert r.json()["status"] == "disabled"- out = _rpc(client, tok, "browser.get_url")+ out = _rpc(client, tok, "browser_get_url")assert out["isError"] and "turned off" in out["content"][0]["text"]assert _req(client, "GET", "/v1/plugs").json()["plugs"][0]["status"] == "disabled"@@ -151,7 +151,7 @@ def test_a_credentialed_plugin_keeps_its_secret_in_the_store(client, world, monkhid = _harness(client)assert _req(client, "POST", f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github"]}).json()["status"] == {"github": "connected"}tok = gw._mint_hosted_cred(hid, "sess2", gw._hosted_secret_key(hid, "mcp.plugs"))- out = _rpc(client, tok, "github.get_file_contents", {"path": "README.md"})+ out = _rpc(client, tok, "github_get_file_contents", {"path": "README.md"})assert out["isError"] is False, outassert json.loads(out["content"][0]["text"])["content"] == "hello" and calls[-1].url.host == "api.github.com"assert _rows(hid, "github")[-1]["outcome"] == "ok"diff --git a/gateway/tests/test_systemone_catalog.py b/gateway/tests/test_systemone_catalog.pyindex d6af7a73..7fe54b0a 100644--- a/gateway/tests/test_systemone_catalog.py+++ b/gateway/tests/test_systemone_catalog.py@@ -74,7 +74,8 @@ def test_a_custom_endpoints_models_never_appear_on_the_systemone_list(monkeypatc"""Measured on hr-test 2026-09-19: a System One harness's picker showed claude-sonnet-4.6,gpt-5.5 and four more as "(no provider)". They were the rows of custom-endpoint integrations,appended to every backend as unavailable. No custom format can drive systemone, so nothing of- theirs belongs on its list; a chat backend keeps the greyed row as its explanation."""+ theirs belongs on its list (since 2026-09-27 no backend lists a custom model its format cannot+ drive, greyed or otherwise)."""import asynciointeg = [{"name": "my-openai", "provider": "custom", "config": {"api_format": "openai", "base_url": "https://x/v1"}}]@@ -86,7 +87,6 @@ def test_a_custom_endpoints_models_never_appear_on_the_systemone_list(monkeypatcmonkeypatch.setattr(gw, "_integrations_doc", _integrations)monkeypatch.setattr(gw, "_effective_model_map", _map)- assert not gw._custom_can_drive("systemone") and gw._custom_can_drive("claude") and gw._custom_can_drive("hermes")view = asyncio.run(gw._harness_models_view(None, "systemone", {"jev-1.13", "jev-latest", "jev-preview"}))assert [m["id"] for m in view["models"]] == ["jev-latest", "jev-preview", "jev-1.13","laya", "openthai-systemone", "system-one-phase2"]@@ -94,10 +94,9 @@ def test_a_custom_endpoints_models_never_appear_on_the_systemone_list(monkeypatc# HarnessRouter key serves them (the same explanation every backend gives a curated model)assert {m["id"]: m["available"] for m in view["models"]} == {"jev-latest": True, "jev-preview": True, "jev-1.13": True,"laya": False, "openthai-systemone": False, "system-one-phase2": False}- # a chat backend the custom format cannot drive still shows the row, greyed, as the explanation+ # a chat backend the custom format cannot drive lists nothing of the custom endpoint's eitherview = asyncio.run(gw._harness_models_view(None, "claude", set()))- row = next(m for m in view["models"] if m["id"] == "gpt-5.5")- assert row["available"] is False+ assert "gpt-5.5" not in [m["id"] for m in view["models"]]def test_the_base_takes_no_skills_and_none_are_mounted_for_a_turn(monkeypatch):diff --git a/runner/server.py b/runner/server.pyindex 0a110877..72df7317 100644--- a/runner/server.py+++ b/runner/server.py@@ -795,6 +795,23 @@ def _skill_dir_name(s: str) -> str:return n or "skill"+def _mcp_headers(s: dict | None) -> dict[str, str]:+ """A remote server's HTTP headers: `auth` (the bearer the gateway resolved for the harness)+ as Authorization, then the declared headers, which win on a clash. EVERY writer and the+ bridge take a server's headers from here and nowhere else: eight writers took only the+ declared headers and dropped `auth`, so the plugs server (hosted, auth minted per turn)+ answered 401 to kimi, aider, opencode, qwen, gemini, goose, openhands and cline, and those+ bases had no browser at all (the browser column on hr-test, 2026-09-27)."""+ out: dict[str, str] = {}+ auth = (s or {}).get("auth")+ if auth:+ out["Authorization"] = auth if str(auth).lower().startswith("bearer ") else f"Bearer {auth}"+ hdrs = (s or {}).get("headers")+ if isinstance(hdrs, dict):+ out.update({str(k): str(v) for k, v in hdrs.items() if k and v is not None})+ return out++def _mcp_name(s: str) -> str:"""Sanitize an MCP server name into a CLI-safe identifier (alnum + underscore)."""n = _MCP_NAME_RE.sub("_", (s or "").strip()).strip("_")@@ -821,12 +838,8 @@ def _write_mcp_config_claude(cwd: str, servers: list[dict],if url:transport = (s.get("transport") or "http").lower()entry = {"type": "sse" if transport == "sse" else "http", "url": url}- auth = s.get("auth")- if auth: # bearer token (resolved by the gateway) -> Authorization header- hdr = auth if str(auth).lower().startswith("bearer ") else f"Bearer {auth}"- entry["headers"] = {"Authorization": hdr}- if isinstance(s.get("headers"), dict):- entry.setdefault("headers", {}).update(s["headers"])+ if _mcp_headers(s):+ entry["headers"] = _mcp_headers(s)elif command:entry = {"type": "stdio", "command": command, "args": s.get("args") or []}if isinstance(s.get("env"), dict):@@ -861,18 +874,10 @@ def _codex_mcp_toml(servers: list[dict]) -> str:continueif not url:continue- auth = (s or {}).get("auth")lines = [f"[mcp_servers.{name}]", f'url = "{url}"']# One http_headers inline table: Authorization from `auth` + any extra headers the# gateway resolved (e.g. Additional Headers / $headers.{name} app-auth values).- hdrs: dict[str, str] = {}- if auth:- hdrs["Authorization"] = auth if str(auth).lower().startswith("bearer ") else f"Bearer {auth}"- extra = (s or {}).get("headers")- if isinstance(extra, dict):- for k, v in extra.items():- if k and v is not None:- hdrs[str(k)] = str(v)+ hdrs = _mcp_headers(s)if hdrs:def _tesc(x: str) -> str:return x.replace("\\", "\\\\").replace('"', '\\"')@@ -1190,12 +1195,7 @@ def _sse_bridges(cwd: str, servers: list[dict] | None, backend: str) -> list[dicout.append(s)continuename = _mcp_name(str(s.get("name") or s.get("id") or "mcp"))- headers: dict = {}- auth = s.get("auth")- if auth:- headers["Authorization"] = auth if str(auth).lower().startswith("bearer ") else f"Bearer {auth}"- if isinstance(s.get("headers"), dict):- headers.update({str(k): str(v) for k, v in s["headers"].items() if k and v is not None})+ headers = _mcp_headers(s)bdir = pathlib.Path(_safe_join(cwd, ".harness/mcp-bridge"))bdir.mkdir(parents=True, exist_ok=True)launcher = bdir / f"{name}.sh"@@ -2380,11 +2380,17 @@ def _pi_models_json(api: str, base_url: str, api_key: str, model: str,def _pi_write_mcp(home: pathlib.Path, servers: list[dict] | None) -> bool:- """Write $HOME/.pi/agent/mcp.json for pi-mcp-adapter (same input contract as the claude/codex- writers: url + optional auth/headers, or command + args for a plugin's stdio server). Returns- whether any server was written. The agent-dir- location is deliberate: project-local .pi/mcp.json sits behind pi's trust gate; the agent dir- does not."""+ """Write $HOME/.pi/agent/mcp-adapter.json for pi-mcp-adapter (same input contract as the+ claude/codex writers: url + optional auth/headers, or command + args for a plugin's stdio+ server). Returns whether any server was written. The agent-dir location is deliberate:+ project-local .pi/mcp.json sits behind pi's trust gate; the agent dir does not.++ THE FILE IS NAMED FOR ADAPTER 3.x. pi-mcp-adapter 3 reads .mcp.json, ~/.config/mcp/mcp.json+ and <agent dir>/mcp-adapter.json and, its README says, "does not read Pi's <agent dir>/mcp.json+ or .pi/mcp.json at all"; 2.x read mcp.json. A volume that installed 2.x at its first boot kept+ working on the old name while a fresh one resolved 3.x and saw no server at all (hosted,+ 2026-09-27: pi listed no MCP tool and grepped the workspace for the tool's name). The+ entrypoint pins the adapter's version, so the name here is the one that version reads."""entries: dict = {}for s in servers or []:name = _mcp_name((s or {}).get("name") or (s or {}).get("id") or "mcp")@@ -2396,17 +2402,12 @@ def _pi_write_mcp(home: pathlib.Path, servers: list[dict] | None) -> bool:entries[name] = {"command": s["command"], "args": list(s.get("args") or [])}continueentry: dict = {"url": url}- auth = (s or {}).get("auth")- if auth:- hdr = auth if str(auth).lower().startswith("bearer ") else f"Bearer {auth}"- entry["headers"] = {"Authorization": hdr}- if isinstance((s or {}).get("headers"), dict):- entry.setdefault("headers", {}).update({str(k): str(v) for k, v in s["headers"].items()- if k and v is not None})+ if _mcp_headers(s):+ entry["headers"] = _mcp_headers(s)entries[name] = entryif not entries:return False- path = home / ".pi" / "agent" / "mcp.json"+ path = home / ".pi" / "agent" / "mcp-adapter.json"path.parent.mkdir(parents=True, exist_ok=True)# directTools: the tools are registered on the agent one by one, as every other CLI lists# MCP tools. The adapter's default hides them behind one `mcp` proxy tool (search, then call),@@ -2682,13 +2683,8 @@ def _omp_write_mcp(agent_dir: pathlib.Path, servers: list[dict] | None) -> bool:if not url:continueentry: dict = {"type": "sse" if str((s or {}).get("transport") or "").lower() == "sse" else "http", "url": url}- auth = (s or {}).get("auth")- if auth:- hdr = auth if str(auth).lower().startswith("bearer ") else f"Bearer {auth}"- entry["headers"] = {"Authorization": hdr}- if isinstance((s or {}).get("headers"), dict):- entry.setdefault("headers", {}).update({str(k): str(v) for k, v in s["headers"].items()- if k and v is not None})+ if _mcp_headers(s):+ entry["headers"] = _mcp_headers(s)entries[name] = entryif not entries:return False@@ -2831,12 +2827,7 @@ def _hermes_mcp_section(servers: list[dict] | None) -> dict:entry: dict = {"url": url}if ((s or {}).get("transport") or "").lower() == "sse":entry["transport"] = "sse"- hdrs: dict[str, str] = {}- auth = (s or {}).get("auth")- if auth: # bearer token (resolved by the gateway) -> Authorization header- hdrs["Authorization"] = auth if str(auth).lower().startswith("bearer ") else f"Bearer {auth}"- if isinstance((s or {}).get("headers"), dict):- hdrs.update({str(k): str(v) for k, v in s["headers"].items() if k and v is not None})+ hdrs = _mcp_headers(s)if hdrs:entry["headers"] = hdrsout[name] = entry@@ -4033,9 +4024,9 @@ def _qwen_settings(home: pathlib.Path, mcp_servers: list[dict] | None) -> None:# Their schema names the transport by the key: `url` is an SSE endpoint, `httpUrl` a# streamable HTTP one; a server declared sse under httpUrl is silently never loaded.entry: dict = {"url": url} if str(sv.get("transport") or "").lower() == "sse" else {"httpUrl": url}- hdrs = sv.get("headers")- if isinstance(hdrs, dict) and hdrs:- entry["headers"] = {str(k): str(v) for k, v in hdrs.items()}+ hdrs = _mcp_headers(sv)+ if hdrs:+ entry["headers"] = hdrselif sv.get("command"):cmd = sv["command"]argv = cmd if isinstance(cmd, list) else [str(cmd)]@@ -4191,9 +4182,9 @@ def _kimi_mcp_config(home: pathlib.Path, mcp_servers: list[dict] | None) -> pathentry: dict = {"url": url}if str(sv.get("transport") or "").lower() == "sse":entry["transport"] = "sse"- hdrs = sv.get("headers")- if isinstance(hdrs, dict) and hdrs:- entry["headers"] = {str(k): str(v) for k, v in hdrs.items()}+ hdrs = _mcp_headers(sv)+ if hdrs:+ entry["headers"] = hdrselif sv.get("command"):cmd = sv["command"]argv = cmd if isinstance(cmd, list) else [str(cmd)]@@ -4301,9 +4292,9 @@ def _aider_mcp_servers(mcp_servers: list[dict] | None) -> dict:entry: dict = {"url": url}if str(sv.get("transport") or "").lower() == "sse":entry["transport"] = "sse"- hdrs = sv.get("headers")- if isinstance(hdrs, dict) and hdrs:- entry["headers"] = {str(k): str(v) for k, v in hdrs.items()}+ hdrs = _mcp_headers(sv)+ if hdrs:+ entry["headers"] = hdrselif sv.get("command"):cmd = sv["command"]argv = cmd if isinstance(cmd, list) else [str(cmd)]@@ -4582,9 +4573,9 @@ def _gemini_settings(home: pathlib.Path, mcp_servers: list[dict] | None, model:# Their schema names the transport by the key: `url` is an SSE endpoint, `httpUrl` a# streamable HTTP one; a server declared sse under httpUrl is silently never loaded.entry: dict = {"url": url} if str(sv.get("transport") or "").lower() == "sse" else {"httpUrl": url}- hdrs = sv.get("headers")- if isinstance(hdrs, dict) and hdrs:- entry["headers"] = {str(k): str(v) for k, v in hdrs.items()}+ hdrs = _mcp_headers(sv)+ if hdrs:+ entry["headers"] = hdrselif sv.get("command"):cmd = sv["command"]argv = cmd if isinstance(cmd, list) else [str(cmd)]@@ -4730,9 +4721,9 @@ def _cline_settings(home: pathlib.Path, base_url: str, api_key: str, model: str,if not url:continueentry: dict = {"transport": {"type": "sse" if str(sv.get("transport") or "").lower() == "sse" else "streamableHttp", "url": url}}- hdrs = sv.get("headers")- if isinstance(hdrs, dict) and hdrs:- entry["transport"]["headers"] = {str(k): str(v) for k, v in hdrs.items()}+ hdrs = _mcp_headers(sv)+ if hdrs:+ entry["transport"]["headers"] = hdrsservers[name] = entry(sdir / "cline_mcp_settings.json").write_text(json.dumps({"mcpServers": servers}, indent=2))@@ -4951,9 +4942,9 @@ def _opencode_mcp(servers: list[dict] | None) -> dict:cmd = sv.get("command")if url:entry: dict = {"type": "remote", "url": url, "oauth": False}- hdrs = sv.get("headers")- if isinstance(hdrs, dict) and hdrs:- entry["headers"] = {str(k): str(v) for k, v in hdrs.items()}+ hdrs = _mcp_headers(sv)+ if hdrs:+ entry["headers"] = hdrselif cmd:argv = cmd if isinstance(cmd, list) else [str(cmd)]argv = [str(a) for a in argv] + [str(a) for a in (sv.get("args") or [])]@@ -5451,9 +5442,9 @@ def _goose_extensions(mcp_servers: list[dict] | None, tools_disabled: list[str]if url:entry: dict = {"enabled": True, "type": "streamable_http", "name": name,"uri": url, "timeout": 300}- hdrs = sv.get("headers")- if isinstance(hdrs, dict) and hdrs:- entry["headers"] = {str(k): str(v) for k, v in hdrs.items()}+ hdrs = _mcp_headers(sv)+ if hdrs:+ entry["headers"] = hdrselif cmd:argv = cmd if isinstance(cmd, list) else [str(cmd)]argv = [str(a) for a in argv] + [str(a) for a in (sv.get("args") or [])]@@ -6072,9 +6063,9 @@ def _openhands_mcp_config(mcp_servers: list[dict] | None) -> dict:transport = str(sv.get("transport") or "").lower()if transport in ("stdio", "http", "streamable-http", "sse"):entry["transport"] = transport- hdrs = sv.get("headers")- if isinstance(hdrs, dict) and hdrs:- entry["headers"] = {str(k): str(v) for k, v in hdrs.items()}+ hdrs = _mcp_headers(sv)+ if hdrs:+ entry["headers"] = hdrselif sv.get("command"):cmd = sv["command"]argv = cmd if isinstance(cmd, list) else [str(cmd)]diff --git a/runner/tests/test_pi_normalize.py b/runner/tests/test_pi_normalize.pyindex 21b61e2e..7cd308a3 100644--- a/runner/tests/test_pi_normalize.py+++ b/runner/tests/test_pi_normalize.py@@ -198,7 +198,7 @@ def test_build_mcp_writes_config_and_flags_extension(tmp_path, monkeypatch):cmd, _ = _cmdline(tmp_path, mcp_servers=[{"name": "wiki", "url": "https://mcp.example/mcp", "auth": "tok123","headers": {"X-Org": "o1"}}])- mcp = json.loads((tmp_path / "home" / ".pi" / "agent" / "mcp.json").read_text())+ mcp = json.loads((tmp_path / "home" / ".pi" / "agent" / "mcp-adapter.json").read_text())assert mcp["mcpServers"]["wiki"]["url"] == "https://mcp.example/mcp"assert mcp["mcpServers"]["wiki"]["headers"]["Authorization"] == "Bearer tok123"assert mcp["mcpServers"]["wiki"]["headers"]["X-Org"] == "o1"diff --git a/runner/tests/test_uhp_plugins.py b/runner/tests/test_uhp_plugins.pyindex 1db01557..d4fb50e2 100644--- a/runner/tests/test_uhp_plugins.py+++ b/runner/tests/test_uhp_plugins.py@@ -143,7 +143,7 @@ def test_pi_adapter_gets_a_stdio_command_entry(tmp_path):"args": ["--data", "/ws/.harness/plugin-data/hr_probe"], "plugin": "hr-probe"},{"name": "remote", "url": "https://mcp.example.invalid/mcp", "headers": {"X-Team": "t"}}]assert rn._pi_write_mcp(home, servers) is True- doc = json.loads((home / ".pi" / "agent" / "mcp.json").read_text())+ doc = json.loads((home / ".pi" / "agent" / "mcp-adapter.json").read_text())# the tools are registered one by one, as on every other CLI; not behind the adapter's proxyassert doc["settings"] == {"directTools": True, "disableProxyTool": True}cfg = doc["mcpServers"]@@ -232,3 +232,28 @@ def test_dsh_job_keeps_a_stdio_server(tmp_path):cmd = rn._build_dsh("deepseek", rn.Auth(api_key="k", base_url="https://api.deepseek.com"), "deepseek-v4-pro", "x", str(tmp_path), env, mcp_servers=servers)job = json.loads(cmd[2])assert [s["name"] for s in job["mcp_servers"]] == ["probe", "remote"]+++def test_a_servers_auth_reaches_every_base_as_its_authorization_header(tmp_path):+ """One helper gives every writer a server's headers, `auth` first as Authorization and the+ declared headers over it. Eight writers took only the declared headers, so the hosted plugs+ server (auth minted per turn) answered 401 to kimi, aider, opencode, qwen, gemini, goose,+ openhands and cline, and those bases had no browser (hr-test browser column, 2026-09-27)."""+ import json+ assert rn._mcp_headers({"auth": "tok"}) == {"Authorization": "Bearer tok"}+ assert rn._mcp_headers({"auth": "bearer tok"}) == {"Authorization": "bearer tok"}+ assert rn._mcp_headers({"auth": "tok", "headers": {"X-Team": "t", "Authorization": "Bearer mine"}}) == {"Authorization": "Bearer mine", "X-Team": "t"}+ assert rn._mcp_headers({"headers": {"X": None}}) == {} and rn._mcp_headers(None) == {}+ sv = [{"name": "plugs", "url": "http://127.0.0.1:8080/v1/mcp/plugs", "transport": "http", "auth": "tok"}]+ want = {"Authorization": "Bearer tok"}+ assert rn._opencode_mcp(sv)["plugs"]["headers"] == want+ assert rn._goose_extensions(sv, None)["plugs"]["headers"] == want+ assert rn._openhands_mcp_config(sv)["plugs"]["headers"] == want+ assert rn._aider_mcp_servers(sv)["plugs"]["headers"] == want+ assert rn._hermes_mcp_section(sv)["plugs"]["headers"] == want+ assert json.loads(rn._kimi_mcp_config(tmp_path / "kimi", sv).read_text())["mcpServers"]["plugs"]["headers"] == want+ rn._qwen_settings(tmp_path / "qwen", sv)+ assert json.loads((tmp_path / "qwen" / ".qwen" / "settings.json").read_text())["mcpServers"]["plugs"]["headers"] == want+ rn._gemini_settings(tmp_path / "gemini", sv)+ assert json.loads((tmp_path / "gemini" / ".gemini" / "settings.json").read_text())["mcpServers"]["plugs"]["headers"] == want+ assert 'http_headers = { "Authorization" = "Bearer tok" }' in rn._codex_mcp_toml(sv)diff --git a/scripts/support-matrix/README.md b/scripts/support-matrix/README.mdindex a1b7cfdf..d07927ef 100644--- a/scripts/support-matrix/README.md+++ b/scripts/support-matrix/README.md@@ -10,7 +10,7 @@ recycle (the session's sandbox is let go on purpose through the internal recyclefollow-up must recall the first message: the history survived the checkpoint round trip).Results are one JSON record per harness x model with the outcome, seconds and reason of eachscenario; `fill-connection.py` stamps each record with the connection its session actually ran on;-`render.py` turns the records into `docs/support-matrix.md`.+`render.py` turns the records into `docs/support-matrix.md` (the Browser section at its end comes from docs/browser-column.json).```export BASE=https://your-instance HR_USER=harnessrouter HR_PASS=... PROVIDER=tokenrouter@@ -59,3 +59,19 @@ remote two against a public probe), and the answer is judged on the probe token--bases aider --out plugin-results.jsonKept in the repository since 2026-09-18 after the copy in a scratch folder was emptied mid-review.++## The browser column++`plugs/browser.py` runs the browser plugin on every base but System One, through the API, on one+task in plain words (open example.com, follow its link, report where you landed), and judges each+base on the trace: the browser navigated and clicked, the answer names the page it reached, the+browser session was stopped and billed. A failed base is retested once. The prompt names no tool;+the harness's Browser section in the agent's instructions file is what the agent goes on.++ python3 plugs/browser.py --base-url https://<instance>/api/harness --api-key "$KEY" \+ --out browser.json --md browser.md # every ready base except systemone+ python3 plugs/browser.py ... --bases codex,pi # a few bases+ python3 plugs/browser.py ... --model gpt-5.4 # one model on every base++The table (`--md`) is the Browser section of docs/support-matrix.md; the run's findings go to+docs/support-matrix-notes.md like every other column's.diff --git a/scripts/support-matrix/plugs/browser.py b/scripts/support-matrix/plugs/browser.pyindex 7c5810ff..0c54e595 100644--- a/scripts/support-matrix/plugs/browser.py+++ b/scripts/support-matrix/plugs/browser.py@@ -1,14 +1,24 @@#!/usr/bin/env python3-"""Prove the browser plugin on a HarnessRouter instance, end to end, directly. No workflow.+"""The browser column of the support matrix: every base (but System One) drives the browser+plugin on a real task, through the API, the way a customer's product would.-Turns the browser plugin on for the key's workspace, creates a harness that includes it, runs one-real task that must navigate, snapshot, click, extract text and take a screenshot, reads the-task's trace for the plug rows (each with unit and usd) and the session's stop row, then deletes-the harness. The instance needs BROWSER_USE_API_KEY in its environment; without it the probe-reports the refusal it got and fails.+For each base: the browser plugin is on for the key's workspace, a harness that includes it is+created, one task in plain words asks for a page to be opened and a link followed, the task's+trace is read for the plugin's rows (navigate, click, ... each with unit and usd) and the+session's stop row, and the harness is deleted. A base passes when the task completed, the trace+shows the browser navigating and clicking, the answer names the page it reached, and the browser+session was stopped and billed. A failed base is retested once, as every matrix column is.++The prompt names no tool: the agent's own instructions file carries a Browser section when the+harness includes the plugin (the gateway writes it), and that is what a person's prompt relies on.python3 plugs/browser.py --base-url https://20-98-237-6.sslip.io/api/harness --api-key "$KEY" \\- [--base pi] [--model claude-sonnet-5] [--workspace default] [--keep] [--out result.json]+ [--bases all|pi,codex,...] [--model ID] [--workers 2] [--keep] [--out result.json] [--md table.md]++`--bases` defaults to every ready base the instance lists except systemone (a System One model+chooses among offered actions and has no tools to call). `--model` runs every base on one model+instead of each base's default. The instance needs BROWSER_USE_API_KEY in its environment;+without it every base reports the refusal it got."""from __future__ import annotations@@ -16,34 +26,24 @@ import argparseimport jsonimport secretsimport sys+import threadingimport timeimport urllib.errorimport urllib.request+from concurrent.futures import ThreadPoolExecutor-# The tools are on the MCP server named plugs. Some CLIs list MCP tools directly; pi reaches them-# through its `mcp` tool (search, then call), and a prompt that only names browser.navigate lets the-# model answer that it has no such tool. So the prompt says where the tools are and how to reach them.-PROMPT = ("Your browser tools come from the MCP server named plugs: browser.navigate, browser.snapshot, browser.click, "- "browser.extract_text, browser.screenshot. If they are not listed directly, use your mcp tool: search it for "- "browser, then call them. Do this, in order: 1) browser.navigate to https://example.com/ ; 2) browser.snapshot ; "- "3) browser.click the 'More information...' link by its ref ; 4) browser.extract_text ; 5) browser.screenshot . "- "Then answer with: the final URL, the page title, and the first 200 characters of the extracted text. "- "Do nothing else and do not visit any other site.")-NEEDED = ["navigate", "snapshot", "click", "extract_text", "screenshot"]+# In plain words, as a person would put it. Not "do not visit any other site": the link leads to+# another site, and two bases obeyed the ban instead of the click (rc.14 baseline).+PROMPT = ("Open https://example.com/ in the browser, click the only link on that page, and reply with "+ "the URL and the title of the page you land on.")+NEEDED = ["navigate", "click"] # the rows the trace must show, each with outcome ok+REACHED = "iana.org" # where the link goes: the answer must name it+EXCLUDED = {"systemone"}-def main() -> int:- ap = argparse.ArgumentParser()- ap.add_argument("--base-url", required=True)- ap.add_argument("--api-key", required=True)- ap.add_argument("--base", default="pi")- ap.add_argument("--model", default="")- ap.add_argument("--workspace", default="default")- ap.add_argument("--keep", action="store_true")- ap.add_argument("--out", default="")- a = ap.parse_args()- base = a.base_url.rstrip("/")- H = {"Authorization": f"Bearer {a.api_key}", "Content-Type": "application/json", "x-harness-workspace": a.workspace}+def _client(base_url: str, api_key: str, workspace: str):+ base = base_url.rstrip("/")+ H = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json", "x-harness-workspace": workspace}def call(method: str, path: str, body=None, timeout=120):req = urllib.request.Request(base + path, data=json.dumps(body).encode() if body is not None else None,@@ -61,41 +61,46 @@ def main() -> int:return e.code, json.loads(raw)except ValueError:return e.code, raw.decode()[:300]+ return call- result: dict = {"ok": False}- code, d = call("PUT", "/v1/plugs/browser", {"enabled": True, "config": {"allow_domains": [], "deny_domains": []}})- print("plugin on:", code, json.dumps(d)[:200])- if code != 200 or d.get("status") != "connected":- print("FAIL the browser plugin did not connect"); return 2- body = {"name": f"Browser probe {int(time.time())}", "base": a.base}- if a.model:- body["default_model"] = a.model++def run_base(call, base: str, model: str, keep: bool, log) -> dict:+ """One base, one task: the record the table is rendered from."""+ t0 = time.time()+ out: dict = {"base": base, "model": model or "", "ok": False, "tools": [], "missing": list(NEEDED), "status": "", "answer": "", "why": ""}+ body = {"name": f"Browser matrix {base} {int(time.time())}", "base": base}+ if model:+ body["default_model"] = modelcode, h = call("POST", "/v1/harnesses", body)if code != 200:- print("FAIL harness:", code, h); return 2+ out["why"] = f"harness: HTTP {code} {json.dumps(h)[:160]}"+ return outhid = h["id"]try:code, inc = call("POST", f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["browser"]})- print("include:", code, json.dumps(inc)[:200])- if code != 200 or inc.get("status", {}).get("browser") != "connected":- print("FAIL the harness did not include a connected browser plugin"); return 2- code, resp = call("POST", "/v1/responses", {"input": PROMPT, "stream": False, "background": True, "model": a.model or None,- "metadata": {"harness_id": hid}}, timeout=180)+ if code != 200 or (inc.get("status") or {}).get("browser") != "connected":+ out["why"] = f"include: HTTP {code} {json.dumps(inc)[:160]}"+ return out+ code, resp = call("POST", "/v1/responses", {"input": PROMPT, "stream": False, "background": True,+ "model": model or None, "metadata": {"harness_id": hid}}, timeout=180)if code != 200:- print("FAIL turn:", code, resp); return 2+ out["why"] = f"turn: HTTP {code} {json.dumps(resp)[:160]}"+ return outrid, sid = resp.get("id"), (resp.get("metadata") or {}).get("session_id") or ""- print("turn:", resp.get("status"), "sid", sid)- t0 = time.time(); status = ""; d = {}+ out["session"] = sid+ status, d = "", {}while time.time() - t0 < 900:code, d = call("GET", f"/v1/responses/{rid}", timeout=60)- status = d.get("status") or "" if isinstance(d, dict) else ""+ status = (d.get("status") or "") if isinstance(d, dict) else ""if status in ("completed", "failed", "incomplete", "cancelled"):break- time.sleep(8)- text = "".join(p.get("text") or "" for it in (d.get("output") or []) for p in (it.get("content") or []) if p.get("type") in ("output_text", "text"))- print("settled:", status, "after", int(time.time() - t0), "s")- print("--- agent report ---"); print(text[:800]); print("--- end ---")- time.sleep(8)+ time.sleep(6)+ out["status"] = status+ out["model"] = model or (str(d.get("model") or "") if isinstance(d, dict) else "") # the turn's own model: the base's default+ text = "".join(p.get("text") or "" for it in (d.get("output") or []) for p in (it.get("content") or [])+ if p.get("type") in ("output_text", "text")) if isinstance(d, dict) else ""+ out["answer"] = text[-400:]+ time.sleep(6) # the stop row lands after the turn settlescode, trace = call("GET", f"/v1/traces/{sid}/all?compact=0", timeout=120)rows = []for line in (trace if isinstance(trace, str) else "").splitlines():@@ -104,24 +109,101 @@ def main() -> int:except ValueError:continueif ev.get("type") == "plug" and ev.get("plug") == "browser":- rows.append({k: ev.get(k) for k in ("tool", "risk", "outcome", "ms", "unit", "usd", "error", "detail")})- print(f"plug rows: {len(rows)}")- for r in rows:- print(f" {str(r['tool']):14} {str(r['outcome']):8} {str(r['ms']):>6} ms {str(r['unit']):12} {str(r['usd']):>9} {json.dumps(r['detail']) if r.get('detail') else (r.get('error') or '')}"[:200])- ok_tools = {r["tool"] for r in rows if r["outcome"] == "ok"}+ rows.append({k: ev.get(k) for k in ("tool", "outcome", "ms", "unit", "usd", "error")})+ ok_tools = [r["tool"] for r in rows if r.get("outcome") == "ok"]stop = next((r for r in rows if r["tool"] == "session"), None)- missing = [t for t in NEEDED if t not in ok_tools]- result = {"harness": hid, "session": sid, "status": status, "rows": rows, "stop": stop, "report": text,- "ok": status == "completed" and not missing and stop is not None and stop["unit"] == "browser.usd"}- print("stop row:", json.dumps(stop) if stop else "NONE")- print("RESULT", "PASS" if result["ok"] else f"FAIL missing={missing} stop={'yes' if stop else 'no'} status={status}")+ out["tools"] = sorted(set(t for t in ok_tools if t != "session"))+ out["missing"] = [t for t in NEEDED if t not in ok_tools]+ out["stopped"] = bool(stop and stop.get("unit") == "browser.usd")+ out["usd"] = float(stop.get("usd") or 0) if stop else 0.0+ reached = REACHED in text.lower()+ out["ok"] = status == "completed" and not out["missing"] and reached and out["stopped"]+ if not out["ok"]:+ why = []+ if status != "completed":+ why.append(f"status {status or 'unknown'}" + (f": {str((d.get('error') or {}).get('message') or '')[:120]}" if isinstance(d, dict) and d.get("error") else ""))+ if out["missing"]:+ why.append("no browser " + "/".join(out["missing"]) + " in the trace" + (" (used " + ", ".join(out["tools"]) + ")" if out["tools"] else " (no browser tool at all)"))+ if not reached:+ why.append(f"answered without {REACHED}: {text[-160:].strip()!r}")+ if not out["stopped"]:+ why.append("no stop row")+ out["why"] = "; ".join(why)finally:- if not a.keep:+ if not keep:call("DELETE", f"/v1/harnesses/{hid}")+ out["s"] = int(time.time() - t0)+ log(f"{'PASS' if out['ok'] else 'FAIL'} {base} {out['model']} {out['s']}s tools={','.join(out['tools']) or '-'} {out['why']}")+ return out+++def render(rows: list[dict]) -> str:+ """The column as a markdown table, one row per base."""+ lines = ["| base | model | browser | tools seen | seconds | notes |", "|---|---|---|---|---:|---|"]+ for r in rows:+ mark = "pass" if r.get("ok") else "FAIL"+ note = r.get("why", "")+ if r.get("retested"):+ note = ("retested once; first try: " + r["retested"].get("why", "")[:120] + (" ; " + note if note else ""))+ lines.append(f"| {r['base']} | {r.get('model', '')} | {mark} | {', '.join(r.get('tools') or []) or '-'} | {r.get('s', '')} | {note.replace('|', '/')} |")+ ok = sum(1 for r in rows if r.get("ok"))+ lines.append(f"\n{ok} of {len(rows)} bases drive the browser.")+ return "\n".join(lines)+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--base-url", required=True)+ ap.add_argument("--api-key", required=True)+ ap.add_argument("--bases", default="all")+ ap.add_argument("--model", default="")+ ap.add_argument("--workspace", default="default")+ ap.add_argument("--workers", type=int, default=2) # the plane allows a few browsers per account at once+ ap.add_argument("--keep", action="store_true")+ ap.add_argument("--out", default="")+ ap.add_argument("--md", default="")+ a = ap.parse_args()+ call = _client(a.base_url, a.api_key, a.workspace)+ lock = threading.Lock()++ def log(s: str):+ with lock:+ print(time.strftime("%H:%M:%S"), s, flush=True)++ code, d = call("PUT", "/v1/plugs/browser", {"enabled": True, "config": {"allow_domains": [], "deny_domains": []}})+ if code != 200 or d.get("status") != "connected":+ print("FAIL the browser plugin did not connect:", code, json.dumps(d)[:200]); return 2+ if a.bases == "all":+ code, bases = call("GET", "/v1/bases")+ if code != 200:+ print("FAIL bases:", code, bases); return 2+ items = bases.get("bases") if isinstance(bases, dict) else bases+ items = items if isinstance(items, list) else list(items.values())+ names = [str(b.get("id") or b.get("base")) for b in items if str(b.get("status") or "ready") == "ready"]+ names = [n for n in names if n not in EXCLUDED]+ else:+ names = [x.strip() for x in a.bases.split(",") if x.strip()]+ log(f"bases: {', '.join(names)}")++ def one(base: str) -> dict:+ r = run_base(call, base, a.model, a.keep, log)+ if not r["ok"]:+ first = r+ r = run_base(call, base, a.model, a.keep, log)+ r["retested"] = {"why": first.get("why", ""), "tools": first.get("tools", [])}+ return r++ with ThreadPoolExecutor(max_workers=max(1, a.workers)) as ex:+ rows = list(ex.map(one, names))+ table = render(rows)+ print(table)if a.out:with open(a.out, "w") as f:- json.dump(result, f, indent=1)- return 0 if result.get("ok") else 1+ json.dump(rows, f, indent=1)+ if a.md:+ with open(a.md, "w") as f:+ f.write(table + "\n")+ return 0 if all(r["ok"] for r in rows) else 1if __name__ == "__main__":diff --git a/scripts/support-matrix/render.py b/scripts/support-matrix/render.pyindex 890e3575..84f166b9 100644--- a/scripts/support-matrix/render.py+++ b/scripts/support-matrix/render.py@@ -1,5 +1,6 @@"""Render the support matrix JSON as markdown: one table per provider, a row per harness x model."""-import json, sys, collections, os+import json+import pathlib, sys, collections, ossys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from samemodel import alias_of # noqa: E402# The gateway's own tables say what each provider serves and what each harness offers, so a pair a@@ -79,4 +80,24 @@ for prov, rows in sorted(by.items()):nr = not_run(prov, rows)if nr:out += [f"Not run in this column, {len(nr)} pairs the provider serves that the harness did not run, with the reason:", ""] + nr + [""]+# The browser column: every base but System One driving the browser plugin, rendered from the+# checked-in docs/browser-column.json that plugs/browser.py writes (see its docstring).+bc = pathlib.Path(__file__).resolve().parent.parent.parent / "docs" / "browser-column.json"+if bc.is_file():+ doc = json.load(open(bc))+ out += ["## Browser plugin, every base", "",+ f"Measured {doc.get('measured', '')} on {doc.get('instance', '')}. One task in plain words, "+ f"\"{doc.get('prompt', '')}\" A base passes when the task completed, the trace shows the browser "+ "navigating and clicking, the answer names the page the link leads to, and the browser session was "+ "stopped and billed; a failure is retested once. System One is not in the column: its models choose "+ "among offered actions and call no tools. The run's findings are in "+ "[support-matrix-notes.md](support-matrix-notes.md).", "",+ "| base | model | browser | tools seen | seconds | notes |", "|---|---|---|---|---:|---|"]+ for r in doc.get("rows", []):+ note = r.get("why", "") or ""+ if r.get("retested"):+ note = "retested once; first try: " + (r["retested"].get("why", "") or "")[:120] + (" ; " + note if note else "")+ out.append(f"| {r['base']} | {r.get('model', '')} | {'pass' if r.get('ok') else 'FAIL'} | {', '.join(r.get('tools') or []) or '-'} | {r.get('s', '')} | {note.replace('|', '/')} |")+ okn = sum(1 for r in doc.get("rows", []) if r.get("ok"))+ out += ["", f"{okn} of {len(doc.get('rows', []))} bases drive the browser.", ""]print("\n".join(out))diff --git a/ui/src/app/(app)/harnesses/page.tsx b/ui/src/app/(app)/harnesses/page.tsxindex 6fab1050..d4068aec 100644--- a/ui/src/app/(app)/harnesses/page.tsx+++ b/ui/src/app/(app)/harnesses/page.tsx@@ -16,8 +16,9 @@ import { HarnessLogo } from '@/components/HarnessLogo';import { CopyId } from '@/components/CopyId';import { ConfigChat, ShareModal, type ConvTotals } from '@/components/TaskChat';import { HarnessSettings } from '@/components/HarnessSettings';-import { OOB, oobById, oobDefaultModel, oobModels, useModelCatalog, createCustom, listCustom, deleteSession,+import { OOB, oobById, oobDefaultModel, oobModels, useModelCatalog, createCustom, listCustom, deleteSession, getHarnessPlugs,type CustomHarness } from '@/lib/harness';+import { useConvState, usePaneState, setPaneState, getPaneState } from '@/lib/conversation';import { fetchHarnessRows, groupByHarness, timeAgo, p95Of, avgCreditsOf, RUNNING, TERMINAL_OK, TERMINAL_BAD,type HarnessRow, type TraceCard, fetchHarnessTasks, sortByActivity } from '@/lib/revamp-data';import { track } from '@/lib/analytics';@@ -108,6 +109,22 @@ export default function HarnessesPage() {}, []);const [adding, setAdding] = useState(false);const [sharing, setSharing] = useState(false);+ // The Browser control: there whenever this harness includes the browser plugin, its dot alive+ // with the shown task's browser, opening the pane with or without a browser in it.+ const [hasBrowser, setHasBrowser] = useState(false);+ useEffect(() => {+ let alive = true; setHasBrowser(false);+ if (!h) return;+ getHarnessPlugs(h).then((r) => { if (alive) setHasBrowser(!!r && r.enabled !== false && (r.plugs || []).includes('browser')); }).catch(() => {});+ return () => { alive = false; };+ }, [h]);+ const taskBrowser = useConvState(sid || '').browser;+ const pane = usePaneState(h);+ const toggleBrowserPane = () => {+ const open = !pane.open;+ const dismissed = !open && sid && taskBrowser?.open ? { ...getPaneState(h).dismissed, [sid]: taskBrowser.epoch } : getPaneState(h).dismissed;+ setPaneState(h, { open, dismissed, ...(open ? {} : { mode: 'docked' as const }) });+ };const [totals, setTotals] = useState<ConvTotals | null>(null);// A task about to be deleted: its id, title, and harness, for the confirm and the refresh after.const [confirmDel, setConfirmDel] = useState<{ sid: string; title: string; hid: string } | null>(null);@@ -329,6 +346,13 @@ export default function HarnessesPage() {</div></div><div className="hx-head-actions">+ {view === 'chat' && h && hasBrowser && (+ <button className={'hx-icbtn wbx-browser-hbtn' + (pane.open ? ' is-on' : '')} type="button" aria-pressed={pane.open}+ title={pane.open ? 'Hide the browser' : taskBrowser?.open ? 'Show the browser the agent is using' : 'Browser'} aria-label="Browser" onClick={toggleBrowserPane}>+ <iconify-icon icon="tabler:browser"></iconify-icon>+ <span className={'wbx-live-dot' + (taskBrowser?.open ? (taskBrowser.control === 'user' ? ' is-user' : ' is-on') : '')} aria-hidden="true" />+ </button>+ )}{view === 'chat' && sid && (<button className="hx-icbtn" type="button" title="Share this task" aria-label="Share this task" onClick={() => setSharing(true)}><iconify-icon icon="tabler:share-2"></iconify-icon>diff --git a/ui/src/app/(app)/integrations/page.tsx b/ui/src/app/(app)/integrations/page.tsxindex 071bf7d2..80f493bf 100644--- a/ui/src/app/(app)/integrations/page.tsx+++ b/ui/src/app/(app)/integrations/page.tsx@@ -48,6 +48,8 @@ interface ProviderMeta {interface Doc {integrations: Integration[];model_map: Record<string, string>;+ /** the hosted console, where a HarnessRouter API key's credit is bought and topped up */+ hosted_console?: string;/** Images route separately from chat: the integration serving your chat models is usually not* the one serving images, and an image model in a chat picker is a broken choice. */image_model_map?: Record<string, string>;@@ -255,6 +257,8 @@ export default function IntegrationsPage() {<span className={'itg-balance' + (i.balance.usd <= 0 ? ' out' : '')}>{i.balance.usd <= 0 ? '$0.00 left, top up' : `$${i.balance.usd.toFixed(2)} left`}</span>+ <a className="itg-balance-topup" href={`${doc?.hosted_console || 'https://app.harnessrouter.ai'}/billing`} target="_blank" rel="noopener noreferrer"+ onClick={(e) => e.stopPropagation()}>Add credit ↗</a></div>)}</td>@@ -339,6 +343,10 @@ export default function IntegrationsPage() {<a className="itg-hosted-link" href="#get-key"onClick={(e) => { e.preventDefault(); e.stopPropagation(); setEditing({ ...editing, provider: 'harnessrouter', config: editing.provider === 'harnessrouter' ? editing.config : {} }); void getKey(); }}>Get a key ↗</a>+ {editing.provider === 'harnessrouter' && editingOriginal && (+ <a className="itg-hosted-link" href={`${doc?.hosted_console || 'https://app.harnessrouter.ai'}/billing`} target="_blank" rel="noopener noreferrer"+ onClick={(e) => e.stopPropagation()}>Add credit ↗</a>+ )}</span><span className="itg-hosted-accent">Every model at its listed price, no markup</span><span className="itg-hosted-muted">One universal key, every model on the list.</span>diff --git a/ui/src/app/hr.css b/ui/src/app/hr.cssindex 1c3be774..e40e3a2e 100644--- a/ui/src/app/hr.css+++ b/ui/src/app/hr.css@@ -241,7 +241,7 @@ a { color: inherit; text-decoration: none; }.wbx-typing span:nth-child(2) { animation-delay: .2s; } .wbx-typing span:nth-child(3) { animation-delay: .4s; }.wbx-think { font-size: 12.5px; color: var(--sidebar-mute); }.wbx-think summary { cursor: pointer; }-.wbx-think > div { white-space: pre-wrap; padding: 6px 0 0 10px; border-left: 2px solid var(--line); margin-top: 5px; }+.wbx-think > div { white-space: pre-wrap; overflow-wrap: anywhere; min-width: 0; padding: 6px 0 0 10px; border-left: 2px solid var(--line); margin-top: 5px; } /* a long unbroken token (a base64 key) wraps instead of running off the card */.wbx-tool { font-size: 12px; font-family: ui-monospace, monospace; background: var(--brand-50); border: 1px solid var(--line);border-radius: 8px; padding: 6px 10px; align-self: flex-start; }.wbx-tool-name { color: var(--brand); font-weight: 600; }@@ -441,6 +441,9 @@ a { color: inherit; text-decoration: none; }z-index: 30; box-shadow: -10px 0 30px rgba(17, 19, 23, 0.14);}.wbx-conv.split .wbx-vresize { display: none; }+ /* the browser card is not an overlay: it keeps a narrower column of its own and the conversation+ is squeezed to the left of it (Richard, 2026-09-27) */+ .wbx-conv.split .wbx-browser-pane { position: static; width: 46% !important; min-width: 240px; max-width: 62%; box-shadow: none; padding: 12px 12px 12px 0; }}.fp-head { height: 50px; flex-shrink: 0; display: flex; align-items: center; gap: 10px; padding: 0 10px 0 14px; border-bottom: 1px solid var(--line); }.fp-ic { flex-shrink: 0; width: 30px; height: 30px; display: inline-flex; align-items: center; justify-content: center; border-radius: 8px; background: var(--brand-50, #f2f0ff); }@@ -948,3 +951,112 @@ body.hr-resizing iframe { pointer-events: none; }/* Why an incomplete turn is incomplete — one quiet line under the neutral badge, only when therecord actually knows the cause. */.wbx-incomplete-why { font-size: 12.5px; color: var(--mut, #6b7280); margin: 4px 0 0 2px; }++/* ── the task's browser: one floating card ──────────────────────────────────────────────────+ The right slot holds a rounded card lifted off the page; its top row carries every action and+ the vendor's live view fills the rest. The card's edge glows the brand blue while the agent has+ the browser and the tint breathes faster while the agent acts; the person's card has a calm green+ edge. Reduced motion keeps the colours and drops the animation. The card also fills the window+ (full). */+/* the column the docked card sits in is invisible (no surface, no edge, no shadow) and lets the+ page beneath be used around the card, which floats in it, centred (Richard, 2026-09-27). The+ conversation keeps at least half the width: at 686 px the 62% a file preview may take left a+ 254 px conversation with a crushed composer (hr-test rc.13). */+.wbx-browser-pane { background: transparent; padding: 12px 12px 12px 0; align-items: center; pointer-events: none; max-width: 50%; }+.wbx-browser-pane > * { pointer-events: auto; }+.wbx-browser-card { position: relative; display: flex; flex-direction: column; min-width: 0; min-height: 0; flex: 1 1 auto;+ border-radius: 16px; background: var(--surface); box-shadow: 0 1px 2px rgba(17, 19, 23, .06), 0 12px 32px rgba(17, 19, 23, .12), 0 0 0 1px var(--line);+ overflow: visible; transition: box-shadow .4s ease; }+.wbx-browser-card.is-full { position: fixed; inset: 12px; z-index: 80; }+/* the card's edge says who has the browser, quietly: a thin blue or green line, no motion outside */+.wbx-browser-card.is-agent { box-shadow: 0 12px 32px rgba(17, 19, 23, .12), 0 0 0 1.5px var(--brand); }+.wbx-browser-card.is-user { box-shadow: 0 12px 32px rgba(17, 19, 23, .12), 0 0 0 1.5px #1f9d63; }+/* inside the screen: the edges tint blue and breathe, the middle stays clear; while the agent acts+ the breathing quickens (Richard, 2026-09-27: the tint, no rings) */+.wbx-browser-veil { position: absolute; inset: 0; pointer-events: none; overflow: hidden; border-radius: inherit;+ background: radial-gradient(ellipse 70% 62% at 50% 50%, transparent 0%, transparent 60%, color-mix(in srgb, var(--brand) 9%, transparent) 84%, color-mix(in srgb, var(--brand) 26%, transparent) 100%);+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--brand) 45%, transparent), inset 0 0 36px color-mix(in srgb, var(--brand) 22%, transparent);+ animation: wbx-veil 3.2s ease-in-out infinite; }+.wbx-browser-veil.is-acting { animation-duration: 1.9s; }+@keyframes wbx-veil { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }+/* the ghost cursor: where the agent last acted, gliding there along an arc; a ring on a click */+.wbx-ghost { position: absolute; left: 0; top: 0; pointer-events: none; will-change: transform; z-index: 2;+ filter: drop-shadow(0 2px 4px rgba(17, 19, 23, .35)); }+.wbx-ghost svg { display: block; margin: -3px 0 0 -4px; }+.wbx-ghost-ring { position: absolute; left: -10px; top: -10px; width: 26px; height: 26px; border-radius: 50%; border: 2px solid var(--brand);+ opacity: 0; animation: wbx-ghost-ring .7s ease-out 1; }+@keyframes wbx-ghost-ring { 0% { transform: scale(.3); opacity: .8; } 100% { transform: scale(1.6); opacity: 0; } }+/* the action row */+.wbx-browser-bar { display: flex; align-items: center; gap: 8px; padding: 8px 8px 8px 14px; min-height: 46px; border-bottom: 1px solid var(--line);+ border-radius: 16px 16px 0 0; background: var(--surface); }+.wbx-browser-title { display: flex; flex-direction: column; min-width: 0; line-height: 1.2; }+.wbx-browser-title b { font-size: 13px; font-weight: 600; color: var(--ink); }+.wbx-browser-status { font-size: 12px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.wbx-browser-bar-gap { flex: 1 1 auto; }+.wbx-browser-btn { flex: 0 0 auto; height: 30px; padding: 0 12px; margin-left: 4px; border-radius: 8px; border: 1px solid var(--line); background: var(--surface);+ color: var(--ink); font: inherit; font-size: 12.5px; font-weight: 600; cursor: pointer; white-space: nowrap; }+.wbx-browser-btn:hover { background: var(--brand-50); }+.wbx-browser-btn.is-primary { background: var(--brand); border-color: var(--brand); color: #fff; }+.wbx-browser-btn.is-primary:hover { background: var(--brand-hover); }+.wbx-browser-btn:disabled { opacity: .6; cursor: default; }+.wbx-browser-ic { flex: 0 0 auto; width: 30px; height: 30px; display: inline-flex; align-items: center; justify-content: center;+ border-radius: 8px; border: 0; background: transparent; color: var(--muted); cursor: pointer; }+.wbx-browser-ic:hover { background: var(--brand-50); color: var(--ink); }+/* the screen: the browser's own shape (landscape, whatever the card's), fitted inside the card and+ centred; the card's surface, never black, is what shows around it. Beside the conversation the+ card takes only the height the screen needs; full screen fits the screen to the card. */+.wbx-browser-stream { position: relative; flex: 1 1 auto; min-height: 0; border-radius: 0 0 16px 16px; overflow: hidden; background: var(--surface);+ display: flex; align-items: center; justify-content: center; }+.wbx-browser-screen { position: relative; width: 100%; aspect-ratio: var(--sw, 16) / var(--sh, 10); overflow: hidden; background: var(--line); }+.wbx-browser-stream.is-fit { container-type: size; }+.wbx-browser-stream.is-fit .wbx-browser-screen { width: min(100cqw, calc(100cqh * var(--sw, 16) / var(--sh, 10))); }+.wbx-browser-card.is-docked { align-self: center; }+/* the grip: the card's own left edge resizes its column (Richard, 2026-09-27: the drag range is the+ card's border, not a strip the height of the column); a short bar shows on hover and while dragging */+.wbx-browser-grip { position: absolute; left: -7px; top: 10px; bottom: 10px; width: 14px; cursor: col-resize; z-index: 3; }+.wbx-browser-grip::after { content: ''; position: absolute; left: 5px; top: 50%; width: 4px; height: 44px; margin-top: -22px; border-radius: 2px;+ background: var(--brand); opacity: 0; transition: opacity .15s ease; }+.wbx-browser-grip:hover::after, body.hr-resizing .wbx-browser-grip::after { opacity: .7; }+.wbx-browser-view, .wbx-browser-view iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; display: block; }+.wbx-browser-view[inert] iframe { pointer-events: none; }+.wbx-browser-loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: #aab1bd; font-size: 13px; }+.wbx-browser-takeover { position: absolute; inset: 0; border: 0; background: transparent; cursor: pointer; padding: 0; }+.wbx-browser-takeover:focus-visible { outline: 3px solid var(--brand); outline-offset: -3px; }+/* the empty state: a small window on a soft glow */+.wbx-browser-empty { flex: 1 1 auto; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center;+ padding: 24px 28px; color: var(--muted); font-size: 13px; line-height: 1.5; gap: 6px; }+.wbx-browser-empty p { margin: 0; max-width: 380px; }+.wbx-browser-empty-title { color: var(--ink); font-weight: 600; font-size: 14px; margin-top: 8px !important; }+.wbx-browser-empty-art { position: relative; margin-bottom: 4px; }+.wbx-browser-empty-art::before { content: ''; position: absolute; inset: -30px -40px; border-radius: 50%;+ background: radial-gradient(closest-side, color-mix(in srgb, var(--brand) 14%, transparent), transparent 70%); }+.wbx-browser-empty-art svg { position: relative; }+.wbx-browser-empty-art .art-window { fill: var(--surface); stroke: color-mix(in srgb, var(--brand) 55%, var(--line)); stroke-width: 1.5; }+.wbx-browser-empty-art .art-line { stroke: var(--line); stroke-width: 1.5; }+.wbx-browser-empty-art .art-dot { fill: color-mix(in srgb, var(--brand) 45%, var(--line)); }+.wbx-browser-empty-art .art-bar { fill: var(--brand-50); }+.wbx-browser-empty-art .art-text { fill: color-mix(in srgb, var(--ink) 18%, var(--surface)); }+.wbx-browser-empty-art .art-text.is-light { fill: color-mix(in srgb, var(--ink) 9%, var(--surface)); }+.wbx-browser-empty-art .art-cursor { fill: var(--brand); stroke: var(--surface); stroke-width: 1.5; stroke-linejoin: round; }+/* the live dot: blue and pulsing while the agent acts, green when the person has the browser */+.wbx-live-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--muted); flex: 0 0 auto; }+.wbx-live-dot.is-idle { background: var(--brand); opacity: .55; }+.wbx-live-dot.is-on { background: var(--brand); box-shadow: 0 0 0 0 color-mix(in srgb, var(--brand) 50%, transparent); animation: wbx-dot 1.4s ease-out infinite; }+.wbx-live-dot.is-user { background: #1f9d63; }+@keyframes wbx-dot { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--brand) 55%, transparent); } 100% { box-shadow: 0 0 0 7px transparent; } }+/* the header's Browser control */+.wbx-browser-hbtn { position: relative; }+.wbx-browser-hbtn .wbx-live-dot { position: absolute; right: 4px; top: 4px; width: 7px; height: 7px; background: transparent; }+.wbx-browser-hbtn.is-on { color: var(--brand); border-color: color-mix(in srgb, var(--brand) 45%, var(--line)); }+@media (prefers-reduced-motion: reduce) {+ .wbx-browser-veil, .wbx-ghost-ring, .wbx-live-dot.is-on { animation: none; }+}+/* phones: the card is a sheet under the conversation, full width at the height the screen needs,+ and the conversation keeps the rest of the screen above it */+@media (max-width: 720px) {+ .wbx-conv.split:has(.wbx-browser-pane) { flex-direction: column; }+ .wbx-conv.split .wbx-browser-pane { position: static; width: 100% !important; min-width: 0; max-width: none; height: auto; flex: 0 0 auto !important; padding: 0 8px 8px; }+ .wbx-browser-card.is-docked { width: 100%; }+ .wbx-browser-grip { display: none; }+ .wbx-browser-btn { padding: 0 10px; }+}diff --git a/ui/src/app/revamp.css b/ui/src/app/revamp.cssindex 5133d127..5d9cf9f8 100644--- a/ui/src/app/revamp.css+++ b/ui/src/app/revamp.css@@ -1670,6 +1670,8 @@ main .hr-wrap { max-width: 1320px; margin: 0 auto; padding: 28px 32px 64px; }.itg-or::before, .itg-or::after { content: ''; flex: 1; border-top: 1px solid var(--line); }/* what is left to spend on the hosted account: an amber pill on its own row under the name */.itg-balance-row { margin-top: 5px; }+.itg-balance-topup { margin-left: 8px; font-size: 12px; color: var(--brand); text-decoration: none; white-space: nowrap; }+.itg-balance-topup:hover { text-decoration: underline; }.itg-balance { display: inline-block; padding: 2px 9px; border-radius: 999px;font-size: 11.5px; font-weight: 600; line-height: 16px; color: #8a5a00;background: #fff3cf; border: 1px solid rgba(214, 150, 0, .38); white-space: nowrap; }diff --git a/ui/src/app/v2.css b/ui/src/app/v2.cssindex 0563f00e..8296c940 100644--- a/ui/src/app/v2.css+++ b/ui/src/app/v2.css@@ -514,6 +514,7 @@ body {/* ── the conversation, per the design: captions above turns, a tinted user bubble, the agent'sreply as plain text (no card), file cards with an extension badge and a plain Preview link ── */.run-layout.is-embedded .wbx-conv-main { background: var(--v2-bg); }+.run-layout.is-embedded .wbx-browser-pane { background: var(--v2-bg); } /* the browser card's column: no seam beside the conversation */.run-layout.is-embedded .wbx-conv-msgs { --uic-cap: var(--v2-cap); --uic-mono: var(--v2-mono); --uic-bubble-max-w: 640px; gap: 20px; }.run-layout.is-embedded .wbx-turn.user .wbx-bubble-user { background: #f0f3fe; color: var(--v2-ink); border-radius: 12px; padding: 13px 17px; font-size: 15px; line-height: 1.65; text-wrap: pretty; }.run-layout.is-embedded .wbx-turn.asst > * { max-width: 640px; }diff --git a/ui/src/components/BrowserPane.tsx b/ui/src/components/BrowserPane.tsxnew file mode 100644index 00000000..f64540e7--- /dev/null+++ b/ui/src/components/BrowserPane.tsx@@ -0,0 +1,223 @@+// The task's browser, live, as one floating card: an action row on top (who has it, take over or+// hand back, full screen, close) and the vendor's live view filling the rest. The card glows+// the brand blue while the agent has the browser, breathing while it acts; a click on the screen+// or the button takes it over, after which the view is the person's and the agent's next browser+// call waits for the hand-back. The card floats beside the conversation, centred in an invisible+// column that squeezes the conversation to the left (under it on a phone), or fills the window.+//+// The live URL is a credential (whoever holds it controls the browser): it is read through the+// session's own route, kept in component state, and never written anywhere else.+'use client';+import React, { useEffect, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { harnessFetch } from '@/lib/hfetch';+import { authHeaders } from '@/lib/chat';+import { getPaneState, setPaneState, type BrowserState, type PaneMode } from '@/lib/conversation';++export interface BrowserInfo { open: boolean; live_url?: string; control?: string; opened_at?: number | null;+ last_call_at?: number | null; last_tool?: string; viewport?: { w: number; h: number } | null; calls?: number; session_minutes?: number }++export async function fetchBrowser(sid: string): Promise<BrowserInfo | null> {+ if (!sid) return null;+ try {+ const r = await harnessFetch(`/api/harness/v1/sessions/${encodeURIComponent(sid)}/browser`, { headers: authHeaders() });+ return r.ok ? (await r.json()) as BrowserInfo : null;+ } catch { return null; }+}+async function setControl(sid: string, control: 'user' | 'agent'): Promise<boolean> {+ try {+ const r = await harnessFetch(`/api/harness/v1/sessions/${encodeURIComponent(sid)}/browser/control`,+ { method: 'POST', headers: { ...authHeaders(), 'content-type': 'application/json' }, body: JSON.stringify({ control }) });+ return r.ok;+ } catch { return false; }+}++/** The vendor's viewer without its own tabs and toolbar: the card's row is the chrome. */+function viewerUrl(liveUrl: string): string {+ if (!liveUrl) return '';+ try { const u = new URL(liveUrl); u.searchParams.set('ui', 'false'); return u.toString(); } catch { return liveUrl; }+}++const ACTING_MS = 6000; // how long after a call the card counts as "the agent is acting"++const Icon = ({ d }: { d: string }) => (+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d={d} /></svg>+);+const ICONS = {+ close: 'M6 6l12 12M18 6L6 18',+ full: 'M8 3H5a2 2 0 0 0-2 2v3M16 3h3a2 2 0 0 1 2 2v3M8 21H5a2 2 0 0 1-2-2v-3M16 21h3a2 2 0 0 0 2-2v-3',+ restore: 'M9 3H4v5M15 3h5v5M9 21H4v-5M15 21h5v-5',+};++/** A cursor that stands where the agent last acted and glides there along a small arc when the+ * point moves, with a ring on a click. Page coordinates map onto the stream assuming the vendor's+ * viewer fits the page to the stream's width from the top, which is how it letterboxes. */+function GhostCursor({ point, viewport, tool, at, host }: {+ point: { x: number; y: number }; viewport: { w: number; h: number }; tool: string; at: number; host: React.RefObject<HTMLDivElement | null>;+}) {+ const [pos, setPos] = useState<{ x: number; y: number } | null>(null);+ const [ring, setRing] = useState(0);+ const from = useRef<{ x: number; y: number } | null>(null);+ const raf = useRef(0);+ useEffect(() => {+ const el = host.current; if (!el) return;+ const scale = el.clientWidth / Math.max(1, viewport.w);+ const target = { x: point.x * scale, y: point.y * scale };+ // the first point is reached from the middle of the screen, so the cursor is seen arriving+ const start = from.current || { x: el.clientWidth / 2, y: el.clientHeight / 2 };+ cancelAnimationFrame(raf.current);+ // a quadratic arc: the control point sits off the straight line, to the side, a quarter of the way+ const dx = target.x - start.x, dy = target.y - start.y, len = Math.hypot(dx, dy) || 1;+ const ctrl = { x: (start.x + target.x) / 2 - dy / len * Math.min(90, len * 0.25), y: (start.y + target.y) / 2 + dx / len * Math.min(90, len * 0.25) };+ const dur = Math.min(900, 350 + len * 0.8); const t0 = performance.now();+ const step = (now: number) => {+ const u = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - u, 3); // ease-out+ const x = (1 - e) * (1 - e) * start.x + 2 * (1 - e) * e * ctrl.x + e * e * target.x;+ const y = (1 - e) * (1 - e) * start.y + 2 * (1 - e) * e * ctrl.y + e * e * target.y;+ setPos({ x, y });+ if (u < 1) raf.current = requestAnimationFrame(step); else { from.current = target; if (tool === 'click') setRing((n) => n + 1); }+ };+ raf.current = requestAnimationFrame(step);+ return () => cancelAnimationFrame(raf.current);+ }, [point.x, point.y, viewport.w, at, tool, host]);+ if (!pos) return null;+ return (+ <div className="wbx-ghost" style={{ transform: `translate(${pos.x}px, ${pos.y}px)` }} aria-hidden="true">+ {ring > 0 && <span key={ring} className="wbx-ghost-ring" />}+ <svg width="24" height="24" viewBox="0 0 24 24"><path d="M5 3l14 8.5-6.2 1.3L16 20l-2.6 1.1-3.2-7.3L5 18.5z" fill="#fff" stroke="var(--brand)" strokeWidth="1.6" strokeLinejoin="round" /></svg>+ </div>+ );+}++export function BrowserPane({ harnessId, sessionId, live, busy, mode, onClose, onResizeStart }: {+ harnessId: string; sessionId: string; live: BrowserState | undefined; busy: boolean; mode: PaneMode; onClose: () => void;+ /** docked: dragging the card's left edge resizes its column (the conversation takes the rest) */+ onResizeStart?: (e: React.MouseEvent) => void;+}) {+ const [info, setInfo] = useState<BrowserInfo | null>(null);+ const [pending, setPending] = useState(false);+ const frameRef = useRef<HTMLIFrameElement>(null);+ const screenRef = useRef<HTMLDivElement>(null);+ const epoch = live?.epoch ?? 0;+ // The live URL is read once per browser (a new epoch is a new browser with a new URL).+ useEffect(() => {+ let alive = true;+ setInfo(null);+ fetchBrowser(sessionId).then((i) => { if (alive) setInfo(i); });+ return () => { alive = false; };+ }, [sessionId, epoch]);+ const open = live ? live.open : !!info?.open;+ // "acting" fades a few seconds after the agent's last call, so the glow follows the work.+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ if (!live?.open) return;+ const id = window.setInterval(() => setNow(Date.now()), 1000);+ return () => window.clearInterval(id);+ }, [live?.open]);++ const control: 'agent' | 'user' = live?.control ?? (info?.control === 'user' ? 'user' : 'agent');+ const lastCallAt = live?.lastCallAt ?? ((Number(info?.last_call_at) || 0) * 1000);+ const acting = control === 'agent' && open && (busy || now - lastCallAt < ACTING_MS);+ const held = !!live?.held && control === 'user';+ const src = viewerUrl(info?.live_url || '');+ // The browser's screen is landscape whatever the card's shape (the vendor streams the screen, not+ // a viewport of the card's making): the frame keeps the screen's aspect and fits inside the card.+ const screen = live?.viewport ?? info?.viewport ?? null;+ const screenStyle = { ['--sw' as string]: screen && screen.w > 0 ? screen.w : 16, ['--sh' as string]: screen && screen.h > 0 ? screen.h : 10 } as React.CSSProperties;++ const takeOver = async () => {+ if (pending || control === 'user' || !open) return;+ setPending(true);+ const ok = await setControl(sessionId, 'user');+ setPending(false);+ if (ok) window.setTimeout(() => frameRef.current?.focus(), 50);+ };+ const handBack = async () => {+ if (pending) return;+ setPending(true);+ await setControl(sessionId, 'agent');+ setPending(false);+ };+ const setMode = (m: PaneMode) => setPaneState(harnessId, { mode: m });++ const status = !open ? 'Not open'+ : control === 'user' ? (held ? 'You have the browser. The agent is waiting.' : 'You have the browser.')+ : acting ? (live?.lastTool ? `The agent is browsing (${live.lastTool})` : 'The agent is browsing')+ : 'The agent has the browser';++ const card = (+ <div className={'wbx-browser-card is-' + mode + (open ? (control === 'user' ? ' is-user' : ' is-agent') : ' is-empty') + (acting ? ' is-acting' : '')}+ role="region" aria-label="Browser">+ {mode === 'docked' && onResizeStart && (+ <div className="wbx-browser-grip" onMouseDown={onResizeStart} title="Drag to resize" aria-hidden="true" />+ )}+ <div className="wbx-browser-bar">+ <span className={'wbx-live-dot' + (acting ? ' is-on' : control === 'user' && open ? ' is-user' : open ? ' is-idle' : '')} aria-hidden="true" />+ <div className="wbx-browser-title">+ <b>Browser</b>+ <span className="wbx-browser-status">{status}</span>+ </div>+ {open && control === 'user' && (+ <button type="button" className="wbx-browser-btn is-primary" onClick={handBack} disabled={pending}>Hand back to the agent</button>+ )}+ {open && control === 'agent' && (+ <button type="button" className="wbx-browser-btn" onClick={takeOver} disabled={pending}>Take over</button>+ )}+ <span className="wbx-browser-bar-gap" aria-hidden="true" />+ <button type="button" className="wbx-browser-ic" onClick={() => setMode(mode === 'full' ? 'docked' : 'full')}+ title={mode === 'full' ? 'Exit full screen' : 'Full screen'} aria-label={mode === 'full' ? 'Exit full screen' : 'Full screen'}>+ <Icon d={mode === 'full' ? ICONS.restore : ICONS.full} />+ </button>+ <button type="button" className="wbx-browser-ic" onClick={onClose} aria-label="Close the browser view" title="Close">+ <Icon d={ICONS.close} />+ </button>+ </div>+ {!open ? (+ <div className="wbx-browser-empty">+ <div className="wbx-browser-empty-art" aria-hidden="true">+ <svg viewBox="0 0 220 150" width="220" height="150" fill="none">+ <rect x="10" y="12" width="200" height="126" rx="14" className="art-window" />+ <path d="M10 42h200" className="art-line" />+ <circle cx="27" cy="27" r="3.5" className="art-dot" /><circle cx="40" cy="27" r="3.5" className="art-dot" /><circle cx="53" cy="27" r="3.5" className="art-dot" />+ <rect x="70" y="20" width="110" height="14" rx="7" className="art-bar" />+ <rect x="30" y="60" width="96" height="10" rx="5" className="art-text" />+ <rect x="30" y="80" width="150" height="8" rx="4" className="art-text is-light" />+ <rect x="30" y="96" width="120" height="8" rx="4" className="art-text is-light" />+ <path d="M148 98l14 30 5-11 11-5z" className="art-cursor" />+ </svg>+ </div>+ <p className="wbx-browser-empty-title">Nothing to watch yet</p>+ <p>When the agent opens a page for this task it streams here, live. Watch it work, take it over from the row above or with a click on the screen, and hand it back when you are done.</p>+ </div>+ ) : (+ <div className={'wbx-browser-stream' + (mode === 'docked' ? '' : ' is-fit')}>+ <div className="wbx-browser-screen" ref={screenRef} style={screenStyle}>+ {/* View-only while the agent drives: inert blocks focus and keys, the transparent button+ over the screen blocks the pointer and is "take over". Both go the moment the person has it. */}+ <div className="wbx-browser-view" inert={control === 'agent' ? true : undefined}>+ {src ? (+ <iframe ref={frameRef} src={src} title="Live browser" allow="autoplay" tabIndex={control === 'agent' ? -1 : 0} />+ ) : (+ <div className="wbx-browser-loading">{info === null ? 'Connecting to the live view' : 'The live view is not available for this browser.'}</div>+ )}+ </div>+ {control === 'agent' && (+ <>+ {/* the agent's presence: the edges of the screen tint blue and breathe, faster while it+ acts; the middle stays clear */}+ <div className={'wbx-browser-veil' + (acting ? ' is-acting' : '')} aria-hidden="true" />+ {live?.point && live.viewport && (+ <GhostCursor point={live.point} viewport={live.viewport} tool={live.lastTool} at={live.lastCallAt} host={screenRef} />+ )}+ <button type="button" className="wbx-browser-takeover" onClick={takeOver} disabled={pending} title="Click to take over the browser"+ aria-label="Take over the browser" />+ </>+ )}+ </div>+ </div>+ )}+ </div>+ );+ if (mode === 'docked') return card;+ return typeof document === 'undefined' ? null : createPortal(card, document.body);+}diff --git a/ui/src/components/TaskChat.tsx b/ui/src/components/TaskChat.tsxindex 5ed3f43f..9d072a8b 100644--- a/ui/src/components/TaskChat.tsx+++ b/ui/src/components/TaskChat.tsx@@ -28,7 +28,7 @@ import { withText, withReasoning, withStep, withResult, asstText } from 'reifyuiimport {// The conversation controller and its module-level singletons now live in one place so Tasks and// Arena share a single store, one realtime bus wiring and one turn lifecycle (see lib/conversation).- useConversationTurn, useHarnessBus, useConvState, getConvState, setConvState, convStore,+ useConversationTurn, useHarnessBus, useConvState, getConvState, setConvState, convStore, seedBrowserState, usePaneState, setPaneState, getPaneState,msgsFromTurns, turnIndexOf, trackTaskFinished, isInternalOutput,addPendingCard, setPendingSid, dropPending, livePending,_busSuppress, _runningSids,@@ -37,6 +37,7 @@ import {import TracesMain from '@/studio/traces/TracesMain.jsx';import { traceStore } from '@/studio/traces/store';import { FilePreview } from '@/components/FilePreview';+import { BrowserPane, fetchBrowser } from '@/components/BrowserPane';import { FileTypeIcon } from '@/components/FileTypeIcon';import { AttachCard, OutputFiles } from '@/components/ChatAttachments';@@ -483,6 +484,35 @@ function Conversation({ harnessId, sessionId, target, models, onModel, onRan, onuseEffect(() => { if (hero) taRef.current?.focus(); }, [hero, harnessId]); // a fresh draft in another harness is a fresh box tooconst [files, setFiles] = useState<{ name: string; dataUri: string }[]>([]);const [preview, setPreview] = useState<{ url: string; name: string } | null>(null);+ // The task's browser: the store carries what the feed says; the pane shows when a browser is+ // open unless the person closed it for THAT browser (epoch), and the chip brings it back.+ const liveSid = sessionId ?? liveSessionId ?? null;+ const browser = useConvState(liveSid ?? '').browser;+ const pane = usePaneState(harnessId);+ useEffect(() => {+ if (!liveSid) return;+ let alive = true;+ fetchBrowser(liveSid).then((i) => { if (alive) seedBrowserState(liveSid, i); });+ return () => { alive = false; };+ }, [liveSid]);+ // A browser opening brings the pane up on its own unless the person closed it for that very+ // browser; a browser closing takes the pane down. The header's Browser control opens it at any+ // time, with or without a browser in it.+ const epoch = browser?.open ? browser.epoch : 0;+ useEffect(() => {+ if (!liveSid || !epoch) return;+ if (getPaneState(harnessId).dismissed[liveSid] !== epoch) setPaneState(harnessId, { open: true });+ }, [liveSid, epoch, harnessId]);+ const wasOpen = useRef(false);+ useEffect(() => {+ const open = !!browser?.open;+ if (wasOpen.current && !open) setPaneState(harnessId, { open: false });+ wasOpen.current = open;+ }, [browser?.open, harnessId]);+ const closeBrowserPane = () => setPaneState(harnessId, { open: false, mode: 'docked',+ dismissed: liveSid && browser?.open ? { ...getPaneState(harnessId).dismissed, [liveSid]: browser.epoch } : getPaneState(harnessId).dismissed });+ const browserShown = pane.open && !preview;+ const browserDocked = browserShown && pane.mode === 'docked';const [modelOpen, setModelOpen] = useState(false);const modelBtnRef = useRef<HTMLElement>(null);const [previewW, onPreviewResize] = useHResize(520, 340, 1100, true);@@ -514,7 +544,7 @@ function Conversation({ harnessId, sessionId, target, models, onModel, onRan, onconst convRef = useRef<HTMLDivElement>(null);const canAttach = !!target.backend && !busy;return (- <div ref={convRef} className={'wbx-conv' + (preview ? ' split' : '')}>+ <div ref={convRef} className={'wbx-conv' + (preview || browserDocked ? ' split' : '')}>{/* A fresh draft centers on what it is for: the harness, named under its base's mark, withthe composer right under it. The first message turns it into the running thread. */}<div className={'wbx-conv-main' + (!loading && msgs.length === 0 && !busy ? ' is-hero' : '')}>@@ -709,6 +739,14 @@ function Conversation({ harnessId, sessionId, target, models, onModel, onRan, on<FilePreview file={preview} onClose={() => setPreview(null)} /></div></>}+ {browserDocked && (+ <div className="wbx-preview-pane wbx-browser-pane" style={{ width: previewW, flex: '0 0 auto' }}>+ <BrowserPane harnessId={harnessId} sessionId={liveSid ?? ''} live={browser} busy={busy} mode="docked" onClose={closeBrowserPane} onResizeStart={onPreviewResize} />+ </div>+ )}+ {browserShown && pane.mode !== 'docked' && (+ <BrowserPane harnessId={harnessId} sessionId={liveSid ?? ''} live={browser} busy={busy} mode={pane.mode} onClose={closeBrowserPane} />+ )}{outOfCredits && (<InsufficientCreditsModal balance={outOfCredits.balance}onClose={clearOutOfCredits} />diff --git a/ui/src/lib/conversation.ts b/ui/src/lib/conversation.tsindex 9becdab5..63f2c765 100644--- a/ui/src/lib/conversation.ts+++ b/ui/src/lib/conversation.ts@@ -10,7 +10,7 @@// The split that makes sharing work: this module owns the turn lifecycle (send, stream, reconcile,// stop, settle) and owns NO composer state. `send(text, files)` takes what to send as arguments, so// one composer can drive one column or six.-import { useEffect, useId, useRef, useState } from 'react';+import { useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';import { streamResponse, subscribeHarnessEvents, loadSessionTurns, cancelSession,type RespFile, type SessionTurn } from '@/lib/chat';import { getCurrentWorkspaceRef } from '@/lib/workspace';@@ -142,7 +142,14 @@ export function livePending(harness: string, cards: TraceCard[] | null): Pending// so switching is just a re-view and N concurrent turns all keep streaming.// The store mechanics live in UI Core (createConversationStore); these thin typed wrappers keep// every call site unchanged.-export type ConvState = { msgs: Msg[]; busy: boolean; prevId: string | null; firstTurn: boolean; loaded: boolean };+/** The browser a task is using, as the harness feed reports it: open or not, who has it, when the+ * agent last acted. `epoch` counts openings, so a pane the person closed stays closed for THAT+ * browser and comes back on its own for the next one. The live URL is not here: the pane reads it+ * through the session's own route, because whoever holds it controls the browser. */+export type BrowserState = { open: boolean; control: 'agent' | 'user'; lastCallAt: number; lastTool: string; held: boolean; epoch: number;+ /** where the agent last acted on the page (the element's centre) and the page's viewport, for the ghost cursor */+ point?: { x: number; y: number } | null; viewport?: { w: number; h: number } };+export type ConvState = { msgs: Msg[]; busy: boolean; prevId: string | null; firstTurn: boolean; loaded: boolean; browser?: BrowserState };export const convStore = createConversationStore();export function getConvState(key: string): ConvState { return convStore.get(key) as ConvState; }export function setConvState(key: string, patch: Partial<ConvState> | ((s: ConvState) => Partial<ConvState>)): void {@@ -216,13 +223,16 @@ function busUpdateLast(sid: string, fn: (a: AsstMsg) => void) {});}function applyBusEvent(sid: string, responseId: string, ev: Record<string, unknown>, replay = false) {- if (!sid || _busSuppress.has(sid)) return; // initiating tab's POST stream owns this one+ if (!sid) return;+ const t = ev.type as string;+ // The tab that runs the turn ignores the feed's copy of its own deltas (its POST stream owns+ // them), but the browser notices travel on the feed alone: they pass, they are state, not deltas.+ if (_busSuppress.has(sid) && !t.startsWith('browser.')) return; // initiating tab's POST stream owns this one// History catch-up frames are dropped: an in-flight turn's progress-so-far is loaded from the// authoritative durable trace via GET /v1/sessions/{sid}/turns (msgsFromTurns). Re-applying the// same events off the bus would double-render (append the same text/tools twice). The bus is the// live-FORWARD channel only; the trace snapshot + the reconcile poll own history + repair.if (replay) return;- const t = ev.type as string;switch (t) {case 'harness.turn.started': {// Ignore a REPLAYED start of a turn we've already finished (its response_id is our last prevId):@@ -272,8 +282,49 @@ function applyBusEvent(sid: string, responseId: string, ev: Record<string, unkno}case 'error':busUpdateLast(sid, (a) => { a.blocks = withError(a.blocks, (ev.message as string) || 'stream error'); }); break;+ // ── the task's browser (the browser plug's live view) ──+ case 'browser.opened':+ setConvState(sid, (st) => ({ browser: { open: true, control: 'agent', lastCallAt: Number(ev.at) * 1000 || Date.now(), lastTool: '', held: false,+ epoch: (st.browser?.epoch ?? 0) + 1 } })); break;+ case 'browser.call':+ case 'browser.held':+ setConvState(sid, (st) => ({ browser: { ...(st.browser ?? { control: 'agent', epoch: 1 }), open: true,+ lastCallAt: Number(ev.at) * 1000 || Date.now(), lastTool: String(ev.tool || ''), held: t === 'browser.held',+ ...(ev.point && typeof ev.point === 'object' ? { point: ev.point as { x: number; y: number } } : {}),+ ...(ev.viewport && typeof ev.viewport === 'object' ? { viewport: ev.viewport as { w: number; h: number } } : {}) } as BrowserState })); break;+ case 'browser.control':+ setConvState(sid, (st) => (st.browser ? { browser: { ...st.browser, control: ev.control === 'user' ? 'user' : 'agent', held: false } } : {})); break;+ case 'browser.closed':+ setConvState(sid, (st) => (st.browser ? { browser: { ...st.browser, open: false, held: false } } : {})); break;}}+/** The browser pane on a harness page: whether it is showing, how (docked beside the conversation+ * or full screen), and which browsers the person closed (by session and epoch) so a closed pane stays closed for that browser and comes+ * back for the next. The page header's Browser control and the conversation share this state. */+export type PaneMode = 'docked' | 'full';+export type PaneState = { open: boolean; mode: PaneMode; dismissed: Record<string, number> };+const _pane = new Map<string, PaneState>();+const _paneSubs = new Set<() => void>();+const _paneDefault: PaneState = { open: false, mode: 'docked', dismissed: {} };+export function getPaneState(h: string): PaneState { return _pane.get(h) ?? _paneDefault; }+export function setPaneState(h: string, patch: Partial<PaneState>): void {+ _pane.set(h, { ...getPaneState(h), ...patch }); _paneSubs.forEach((f) => f());+}+export function usePaneState(h: string): PaneState {+ return useSyncExternalStore((f) => { _paneSubs.add(f); return () => { _paneSubs.delete(f); }; }, () => getPaneState(h), () => _paneDefault);+}+/** What the session's route says about its browser, folded into the store (the feed keeps it fresh+ * from there). Called when a task is opened, so a browser that was already running shows. */+export function seedBrowserState(sid: string, info: { open: boolean; control?: string; last_call_at?: number | null; last_tool?: string;+ viewport?: { w: number; h: number } | null } | null): void {+ if (!sid || !info) return;+ setConvState(sid, (st) => {+ if (!info.open) return st.browser ? { browser: { ...st.browser, open: false } } : {};+ return { browser: { open: true, control: info.control === 'user' ? 'user' : 'agent', lastCallAt: (Number(info.last_call_at) || 0) * 1000,+ lastTool: String(info.last_tool || ''), held: false, epoch: st.browser?.epoch || 1,+ ...(info.viewport && info.viewport.w > 0 ? { viewport: info.viewport } : {}) } };+ });+}export function useHarnessBus(harnessId: string, onActivity?: () => void) {useEffect(() => {if (!harnessId) return;