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
Plugins: a browser plugin, connected once per workspace and included per harness (#266)
github-actions[bot]98f65a7dd2e1
diff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.mdindex c31d8708..6c62b246 100644--- a/docs/self-hosting-guide.md+++ b/docs/self-hosting-guide.md@@ -7,6 +7,7 @@ Detailed installation, configuration, API, and deployment instructions. For the- [Install](#install)- [Restarts, upgrades, and backups](#restarts-upgrades-and-backups)- [Starter kits](#starter-kits)+- [Plugins](#plugins)- [What it is](#what-it-is)- [Why self-host](#why-self-host)- [The Unified Harness Protocol](#the-unified-harness-protocol)@@ -588,6 +589,64 @@ spends.---+## Plugins++A plugin is a service your workspace connects once; each harness then includes the ones it needs,+and its agent gets that service's tools on every task. The catalog is on the **Plugins** page of the+Console, and every row of it is one plugin: what it is, its state here (Connected, Needs auth,+Disabled, Not connected), what it costs, and how many harnesses include it.++| Plugin | What the agent gets | What you provide |+|---|---|---|+| Browser | A real web browser: open a page, read it, click, type, scroll, wait, take a screenshot, go back, switch tabs. Thirteen tools, no JavaScript evaluation, no downloads. | Nothing on the page. The instance needs a [Browser Use Cloud](https://browser-use.com) key in its environment (below). |+| GitHub | The connected repository: files, branches, commits, pull requests. | An access token and the repository (`owner/name`). |+| Vercel | The connected project: deployments and domains. | An access token, the project id and team id. |+| InsForge | The connected backend: its tables and records. | The API key and the backend's address. |++**Turning a plugin on.** Open **Plugins**, and on the row choose **Turn on** (the browser) or+**Connect** (a plugin that needs a credential; the credential is kept in the instance's secret store+and never shown again). **Settings** changes what the plugin may do: the browser's site lists ("only+these sites", "never these sites", matched by domain suffix; empty means any public site), a GitHub+plugin's repository. **Turn off** keeps the record and refuses the agent's calls with a sentence+until it is turned on again. Nothing is included on a harness by turning a plugin on.++**Including it on a harness.** Open the harness, find **Plugins** under its settings, and mark the+plugin **Included**. Over the API, the harness's plugins are its `plugs` attachment:++```bash+curl -s -X PUT "$HARNESSROUTER_BASE_URL/v1/plugs/browser" \+ -H "Authorization: Bearer $HARNESSROUTER_API_KEY" -H "Content-Type: application/json" \+ -d '{"enabled":true,"config":{"allow_domains":["example.com"],"deny_domains":[]}}'+curl -s -X POST "$HARNESSROUTER_BASE_URL/v1/harnesses/$HID/servers/plugs" \+ -H "Authorization: Bearer $HARNESSROUTER_API_KEY" -H "Content-Type: application/json" \+ -d '{"plugs":["browser"]}'+```++`GET /v1/plugs` lists the catalog with each plugin's state for your workspace;+`GET /v1/plugs/browser/attachments` says how many harnesses include it. A package can ask for a+plugin with `"requires": {"plugs": ["browser"]}` in its `plugin.json`; the harness it lands on+includes the plugin, and the workspace still has to have connected it.++**The browser.** The browser runs in Browser Use Cloud and is driven from this instance; the agent+never holds the browser's address or the key. Set the key in the container's environment:++```bash+docker run -e BROWSER_USE_API_KEY=... ...+```++Until it is set, the browser's tools answer that the browser service is not set up on this+deployment. Every session is one browser per task, opened on the agent's first browser tool call+and stopped when the task ends, after two idle minutes, or after twenty minutes, whichever comes+first; each call has sixty seconds; at most three browsers per workspace are open at once+(`HR_BROWSER_ORG_SESSIONS`) and nine per instance (`HR_BROWSER_MAX_SESSIONS`). Private, loopback+and link-local addresses are never reachable, on a page or in anything a page loads. Screenshots+are kept with the task's files. What the vendor charges ($0.02 per browser hour at the time of+writing, rounded up to the minute) is what a session costs you on your Browser Use account; this+instance keeps no ledger, and the price shown on the Plugins page is the vendor's list price with+no markup, read from the same table the hosted service bills from. Every call and every session is+written down on the task's trace (event type `plug`, plug `browser`, with the minutes and the+vendor's figure on the session row).+## What it isAn *agent harness* is the runtime layer around a model; Codex, Claude Code, and Hermes are harnesses. In this repo's API you also create *harness* objects: a saved configuration whose `base` is one of those runtimes, plus a model, instructions, and limits. A *task* is one run of that configuration, a real conversation against a real POSIX workspace with bash and git, streamed back as it happens.@@ -726,15 +785,17 @@ It is created in this self-hosted instance and authenticates requests to that CEneither a Cloud key, your Console password, nor the model-provider key configuredin **Integrations**. Never put it in browser-side code or commit it to Git.-### Install a plugin on a harness+### Install a package on a harness-A plugin is a folder in the [Agent Plugins](https://agent-plugins.org) format: `plugin.json` at its+A package is a folder in the [Agent Plugins](https://agent-plugins.org) format: `plugin.json` at itsroot, tools in `mcp.json`, Skills under `skills/`. Installing one gives a harness all of it at once,and the harness records it as a named, versioned package it can export again. Starter kits built from-the kit release that carries plugin packages ship their Skills this way, so a kit launched from such-an image shows the kit as an installed plugin; a kit launched earlier keeps its Skills as its own.+the kit release that carries packages ship their Skills this way, so a kit launched from such+an image shows the kit as an installed package; a kit launched earlier keeps its Skills as its own.+(A package is not a plugin in the sense of the [Plugins](#plugins) page: a plugin is a service the+workspace connects once; a package is files a harness carries.)-In the Console, open the harness, find **Plugins**, and choose **Install from folder**. Over the API,+In the Console, open the harness, find **Packages**, and choose **Install from folder**. Over the API,`plugins` is a field of the harness record. The simplest case is a new harness created with thepackage in it:diff --git a/gateway/app.py b/gateway/app.pyindex 87e8f6a1..74b4b85d 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -46,6 +46,8 @@ from pydantic import AliasChoices, BaseModel, ConfigDict, Fieldimport backing # pluggable graph/blob/secret stores (vg | local)import media_plane # the media plane (capability catalog, provider adapters, ffmpeg)+import plugs_plane # the plugs surface: the vendor tools behind the hosted plugs server+import browser_plane # the browser surface: a cloud browser over CDP behind the browser plugimport sql_plane # the read-only SQL data plane (gate, row cap, introspection)import control_store # durable transactional control state (idempotency / lease / monotonic cancel)@@ -98,9 +100,10 @@ class _OpsDrops:_billing_drops = _OpsDrops("billing", 60, ("errors", "rejects"))-def _report_usage(org: str, metric: str, amount: float) -> None:+def _report_usage(org: str, metric: str, amount: float, **_attribution) -> None:"""Fire-and-forget metering to the billing harvest service. Never blocks or- fails a turn: 3s timeout; failures are COUNTED (never raised)."""+ fails a turn: 3s timeout; failures are COUNTED (never raised). The hosted service's+ per-task attribution keywords are accepted and, with no ledger here, dropped."""if not BILLING_HARVEST_URL or not org or amount <= 0:returnasync def _post():@@ -8018,6 +8021,8 @@ async def create_response(body: CreateResponseBody, request: Request):{"type": "harness.turn.started", "user_text": user_text, "response_id": resp_id})async def persist(status: str) -> None:+ if status != "running":+ await _browser_close(sid, "turn_end") # the turn's browser, if it opened onestored = {**tr._response_obj(status), "_session_id": sid, "_org": org,"_member": member, "_input": input_items, "_backend": backend}await _resp_put(resp_id, stored, org, sid, body.previous_response_id, status, created_at, body.store)@@ -10068,6 +10073,7 @@ _NOT_CONNECTED = "No database is connected to this agent yet."_HOSTED_NOT_CONNECTED = {"database": ("database_not_connected", _NOT_CONNECTED),"media": ("media_not_connected", "No media tools are connected to this agent yet."),+ "plugs": ("plugs_not_connected", "No plugins are connected to this agent yet."),}@@ -10434,6 +10440,8 @@ async def get_harness_server(hid: str, sid: str, request: Request) -> dict:"enabled": str(entry.get("enabled", True)) not in ("False", "false", "0")}if str(rec.get("server") or "") == _MEDIA_SERVER:return {**out, **await _media_server_out()}+ if str(rec.get("server") or "") == _PLUGS_SERVER:+ return await _plugs_server_out(org, entry, rec)return {**out, "connection": _connection_out(rec)}@@ -13086,7 +13094,8 @@ async def _media_server_out() -> dict:return {"capabilities": caps, "export": {"available": media_plane.have_ffmpeg()}}-async def _media_route(hid: str, sid: str, eid: str, request: Request) -> tuple[str, dict, dict]:+async def _media_route(hid: str, sid: str, eid: str, request: Request,+ servers: tuple[str, ...] = ()) -> tuple[str, dict, dict]:"""(org, entry, session vertex) — the FOUR binds every app route to this server shares.Member of the org → the harness → the entry on that harness → AND THE SESSION ON THAT@@ -13107,7 +13116,14 @@ async def _media_route(hid: str, sid: str, eid: str, request: Request) -> tuple["""org, _ = await _pub_org_member(request)v = await _harness_for_route(hid, org)- entry, _rec = await _hosted_resolve(_MEDIA_SERVER, hid, org, _mcp_list(v), entry_id=eid)+ if servers:+ # the bytes route only: a screenshot the browser plug stored is the session's media too+ entry, rec0 = await _hosted_resolve_any(hid, org, _mcp_list(v), entry_id=eid)+ if str(rec0.get("server") or "") not in servers:+ code, msg = _HOSTED_NOT_CONNECTED[_MEDIA_SERVER]+ raise uhp_error(404, code, msg, "harness_id")+ else:+ entry, _rec = await _hosted_resolve(_MEDIA_SERVER, hid, org, _mcp_list(v), entry_id=eid)sv: dict = {}if sid:_o, sv = await _owned_session(request, sid)@@ -13294,7 +13310,7 @@ async def get_media_bytes(hid: str, eid: str, sid: str, med: str, request: RequeRange is not a nicety: without it Safari refuses to play at all and a timeline cannot scrub.The media id is immutable, so it is its own ETag and may be cached forever."""- await _media_route(hid, sid, eid, request)+ await _media_route(hid, sid, eid, request, servers=(_MEDIA_SERVER, _PLUGS_SERVER))meta = await _media_meta(sid, med)if not meta:raise uhp_error(404, "media_not_found", "No media with that id in this video.", "med")@@ -13398,6 +13414,719 @@ async def _media_session_purge(sid: str) -> None:await _vg_upsert(_MEDIA_JOB_LABEL, job["id"], {"deleted": "1", "status": "deleted"})+# ── plugs: services connected once for a workspace, reached through one hosted server ─────────+# A plug is a vendor account the workspace connected (its GitHub repository, its Vercel project,+# its InsForge backend); the registry on the engine minted and keeps the per-workspace credential.+# A harness attaches the plugs it needs, and from then on the agent calls them through this+# gateway: the credential is resolved here at the moment of the call, used in process, never+# handed to a sandbox and never returned, and every call is written down. Same entry, record,+# per-turn credential and resolution as the database and media servers above; what is new is only+# that the record names a WORKSPACE, because that is what a plug belongs to.+_PLUGS_SERVER = "plugs"+_PLUGS_ENTRY = {"name": "plugs", "id": "mcp.plugs"}+_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.+PLUGS_REGISTRY_URL = os.environ.get("HR_PLUGS_REGISTRY_URL", "").rstrip("/")+# Who may attach and call the held plug types: org ids, or "*" for everyone. A self-hosted+# instance is its operator's own box, so everyone by default; the hosted service names its orgs.+_PLUGS_ORGS = {o.strip() for o in os.environ.get("HR_PLUGS_ORGS", "*").split(",") if o.strip()}+_PLUG_STATUSES = ("connected", "needs_auth", "disabled")+++class PlugsBody(BaseModel):+ plugs: list[str] # plug type names to attach (github, vercel, insforge)+ tools: dict[str, list[str]] | None = None # per plug, the tool names this harness may call; absent = all+++def _plugs_allowed(org: str, plug: str | None = None) -> bool:+ """Whether this org may use plugs: every org for the open types (the browser, since Richard+ opened it on 2026-09-24), the held list for the rest while they are verified."""+ if plug in plugs_plane.OPEN_TYPES:+ return True+ return "*" in _PLUGS_ORGS or org in _PLUGS_ORGS+++def _plugs_gate(org: str, plugs: list[str]) -> None:+ held = [t for t in plugs if not _plugs_allowed(org, t)]+ if held:+ raise uhp_error(404, "plugs_unavailable",+ f"The {plugs_plane.TYPES.get(held[0], held[0])} plugin is not available on this account yet.", "plugs")+++async def _plug_lookup(org: str, workspace: str, plug_type: str) -> tuple[str, dict | None]:+ """(status, record) for one plug type in a workspace: connected, needs_auth, disabled, missing+ (no such plug) or unavailable (the registry did not answer). Never a secret in the record.++ Read on every call and not cached: the registry refreshes a short-lived credential on this+ read (a GitHub installation token lives an hour), so a cached record would hold an expired one.+ """+ if not workspace:+ return "missing", None+ if not PLUGS_REGISTRY_URL:+ return await _plug_lookup_local(org, workspace, plug_type)+ try:+ r = await _client().get(f"{PLUGS_REGISTRY_URL}/v1/plugs/by",+ params={"workspace": workspace, "type": plug_type},+ headers={"X-Internal-Key": INTERNAL_KEY}, timeout=15)+ except Exception as e: # noqa: BLE001+ print(f"[plugs] registry unreachable for {plug_type} in {workspace}: {type(e).__name__}", flush=True)+ return "unavailable", None+ if r.status_code == 404:+ return "missing", None+ if r.status_code >= 400:+ print(f"[plugs] registry answered {r.status_code} for {plug_type} in {workspace}", flush=True)+ return "unavailable", None+ try:+ rec = r.json()+ except ValueError:+ return "unavailable", None+ if (not isinstance(rec, dict) or str(rec.get("org_id") or "") != org+ or str(rec.get("workspace") or "") != workspace):+ # A record of another org is not this workspace's plug, whatever the registry was asked.+ print(f"[plugs] registry record for {plug_type} in {workspace} belongs elsewhere; refused", flush=True)+ return "missing", None+ status = str(rec.get("effective_status") or rec.get("status") or "")+ return (status if status in _PLUG_STATUSES else "needs_auth"), rec+++# The derived credential of a plug, by plug id and version: a rotation bumps the version, and a+# record read with a new version reads the vault again. Bounded by the number of plugs served.+_plug_fields_cache: dict[str, tuple[int, dict]] = {}+++async def _plug_fields(rec: dict) -> dict:+ """The plug's derived credential fields, from the org's own vault tenant and nowhere else. A+ ref outside the plug- namespace is not read: a record can name only what the registry wrote,+ never a connection string or a provider key."""+ pid = str(rec.get("id") or "")+ try:+ version = int(rec.get("version") or 0)+ except (TypeError, ValueError):+ version = 0+ hit = _plug_fields_cache.get(pid)+ if hit and hit[0] == version:+ return dict(hit[1])+ tenant = str(rec.get("vault_tenant") or "")+ if not _vault_tenant_ok(tenant):+ return {}+ out: dict = {}+ for ref in rec.get("key_refs") or []:+ name, field = str((ref or {}).get("ref") or ""), str((ref or {}).get("field") or "")+ if not name.startswith("plug-") or not field:+ continue+ v = await _vault_get(tenant, name)+ if v:+ out[field] = v+ if pid:+ _plug_fields_cache[pid] = (version, dict(out))+ return out+++# ── the local plug registry: a self-hosted instance has no engine, so the records live here ──+# One record per workspace and plug type in the instance's own store: the status, the settings+# the tools read, and for a plug that needs a credential (GitHub, Vercel, InsForge) the refs of+# the secrets kept in the instance's secret store under the plug- namespace, the same namespace+# the hosted registry writes, so _plug_fields reads both the same way. The browser is a platform+# plug: no credential, only its site lists.+_PLUG_LABEL = "Plug"+_PLUG_FORMS: dict[str, dict] = {+ "browser": {"secrets": [], "config": ["allow_domains", "deny_domains"], "source": "platform"},+ "github": {"secrets": ["token"], "config": ["repo", "owner", "default_branch"], "source": "local"},+ "vercel": {"secrets": ["token"], "config": ["project", "project_id", "team_id"], "source": "local"},+ "insforge": {"secrets": ["api_key"], "config": ["project", "project_id", "url", "region"], "source": "local"},+}+++def _plug_safe(s: str) -> str:+ return re.sub(r"[^a-z0-9]+", "-", (s or "").lower()).strip("-")+++def _plug_vid(workspace: str, plug_type: str) -> str:+ return f"plug.{_plug_safe(workspace)}.{_plug_safe(plug_type)}"+++def _plug_domains_ok(names, param: str) -> list[str]:+ if names is None:+ return []+ if not isinstance(names, list) or not all(isinstance(n, str) for n in names):+ raise uhp_error(400, "invalid_input", f"{param} must be a list of domain names.", param)+ out = []+ for n in names:+ n = n.strip().lower().lstrip("*").lstrip(".").rstrip(".")+ if not n:+ continue+ if not re.fullmatch(r"[a-z0-9.-]{1,253}", n) or ".." in n:+ raise uhp_error(400, "invalid_input", f"{n!r} is not a domain name.", param)+ out.append(n)+ return list(dict.fromkeys(out))[:100]+++def _plug_record_out(row: dict) -> dict:+ """The record in the registry's own shape, from this instance's row."""+ try:+ config = json.loads(row.get("config") or "{}")+ except ValueError:+ config = {}+ try:+ key_refs = json.loads(row.get("key_refs") or "[]")+ except ValueError:+ key_refs = []+ status = str(row.get("status") or "connected")+ return {"id": str(row.get("id") or ""), "org_id": str(row.get("org") or ""), "workspace": str(row.get("workspace") or ""),+ "type": str(row.get("type") or ""), "status": status, "effective_status": status,+ "source": str(row.get("source") or "local"), "vault_tenant": str(row.get("org") or ""),+ "key_refs": key_refs if isinstance(key_refs, list) else [], "config": config if isinstance(config, dict) else {},+ "version": int(float(row.get("version") or 1)), "updated_at": row.get("updated_at") or ""}+++async def _plug_lookup_local(org: str, workspace: str, plug_type: str) -> tuple[str, dict | None]:+ rows = await BACKING.graph.find(_PLUG_LABEL, {"workspace": workspace, "type": plug_type})+ row = next((r for r in rows if str(r.get("org") or "") == org), None)+ if not row:+ return "missing", None+ rec = _plug_record_out(row)+ return (rec["status"] if rec["status"] in _PLUG_STATUSES else "needs_auth"), rec+++def _plug_workspace(request: Request) -> str:+ """The workspace a plug route is about: the console names it; a bare API call means the+ instance's default workspace, the one the console's own harnesses are in."""+ return str(request.headers.get("x-harness-workspace") or "default")+++class PlugBody(BaseModel):+ enabled: bool = True+ config: dict | None = None # the type's settings (the browser's site lists, a GitHub plug's repo)+ secrets: dict | None = None # field -> value for the type's credential fields; absent keeps what is stored+++def _plug_public(org: str, workspace: str, plug_type: str, rec: dict | None, status: str) -> dict:+ form = _PLUG_FORMS[plug_type]+ cfg = dict((rec or {}).get("config") or {})+ have = sorted({str((r or {}).get("field") or "") for r in ((rec or {}).get("key_refs") or [])} - {""})+ return {"type": plug_type, "label": plugs_plane.TYPES.get(plug_type, plug_type), "source": form["source"],+ "official": True, "status": status, "config": cfg, "secrets_set": have, "secrets_needed": list(form["secrets"]),+ "config_fields": list(form["config"]), "version": int((rec or {}).get("version") or 0),+ "tools": len(plugs_plane.tools_of(plug_type)),+ **({"pricing": browser_plane.pricing()} if plug_type == plugs_plane.BROWSER else {})}++[email protected]("/v1/plugs")+async def list_plugs(request: Request) -> dict:+ """The plugin catalog for the caller's workspace: every type this instance serves, with its+ state here (connected, disabled, needs_auth, missing)."""+ org, _ = await _pub_org_member(request)+ workspace = _plug_workspace(request)+ out = []+ for t in _PLUG_FORMS:+ status, rec = await _plug_lookup(org, workspace, t)+ out.append(_plug_public(org, workspace, t, rec, status))+ return {"workspace": workspace, "plugs": out}++[email protected]("/v1/plugs/{plug_type}")+async def put_plug(plug_type: str, body: PlugBody, request: Request) -> dict:+ """Connect a plugin for the caller's workspace, change its settings, or turn it off. A+ credential goes to the instance's secret store, never onto the record; a plug that needs one+ and has none yet reads needs_auth until it is given."""+ org, _ = await _pub_org_member(request)+ if PLUGS_REGISTRY_URL:+ raise uhp_error(409, "registry_elsewhere", "Plugins on this deployment are managed on the Plugins page of the workspace.", "plug_type")+ form = _PLUG_FORMS.get(plug_type)+ if not form:+ raise uhp_error(404, "plug_not_found", f"No plugin of type {plug_type!r}.", "plug_type",+ {"supported": sorted(_PLUG_FORMS)})+ _plugs_gate(org, [plug_type])+ workspace = _plug_workspace(request)+ _status, prev = await _plug_lookup_local(org, workspace, plug_type)+ config = dict((prev or {}).get("config") or {})+ for k, v in (body.config or {}).items():+ if k not in form["config"]:+ raise uhp_error(400, "invalid_input", f"{plug_type} has no setting {k!r}.", "config")+ if plug_type == plugs_plane.BROWSER:+ config[k] = _plug_domains_ok(v, k)+ elif v in (None, ""):+ config.pop(k, None)+ elif isinstance(v, str):+ config[k] = v.strip()+ else:+ raise uhp_error(400, "invalid_input", f"{k} must be a string.", "config")+ if plug_type == plugs_plane.BROWSER:+ config.setdefault("allow_domains", [])+ config.setdefault("deny_domains", [])+ config["proxy"] = False+ refs = {str(r.get("field")): str(r.get("ref")) for r in ((prev or {}).get("key_refs") or []) if isinstance(r, dict)}+ for field, value in (body.secrets or {}).items():+ if field not in form["secrets"]:+ raise uhp_error(400, "invalid_input", f"{plug_type} takes no secret {field!r}.", "secrets")+ if not isinstance(value, str) or not value.strip():+ continue+ ref = f"plug-{_plug_safe(workspace)}-{_plug_safe(plug_type)}-{_plug_safe(field)}"+ await _vault_put(org, ref, value.strip())+ refs[field] = ref+ missing = [f for f in form["secrets"] if f not in refs]+ status = "disabled" if not body.enabled else ("needs_auth" if missing else "connected")+ version = int((prev or {}).get("version") or 0) + 1+ now = int(time.time() * 1000)+ await _vg_upsert(_PLUG_LABEL, _plug_vid(workspace, plug_type),+ {"org": org, "workspace": workspace, "type": plug_type, "status": status, "source": form["source"],+ "config": json.dumps(config, separators=(",", ":")),+ "key_refs": json.dumps([{"field": f, "ref": r} for f, r in refs.items()], separators=(",", ":")),+ "version": str(version), "updated_at": str(now)})+ _plug_fields_cache.pop(_plug_vid(workspace, plug_type), None)+ status2, rec = await _plug_lookup_local(org, workspace, plug_type)+ print(f"[plugs] {workspace}: {plug_type} {status2} (v{version})", flush=True)+ return _plug_public(org, workspace, plug_type, rec, status2)++[email protected]("/v1/plugs/{plug_type}/attachments")+async def plug_attachments_public(plug_type: str, request: Request) -> dict:+ """How many of the caller's workspace's harnesses include this plugin, from the bindings."""+ org, _ = await _pub_org_member(request)+ if plug_type not in _PLUG_FORMS:+ raise uhp_error(404, "plug_not_found", f"No plugin of type {plug_type!r}.", "plug_type")+ workspace = _plug_workspace(request)+ rows = _plugs_harness_rows(org, workspace, await BACKING.graph.find("Harness", {"org": org}))+ attached = []+ for r in rows:+ hid = str(r.get("id") or "")+ entry = next((e for e in _mcp_list(r) if str(e.get("id") or "") == _PLUGS_ENTRY["id"]), None)+ if not entry:+ continue+ rec = await _hosted_record(org, _vault_key(entry.get("auth")))+ if rec and rec.get("harness") == hid and plug_type in (rec.get("plugs") or []):+ attached.append({"id": hid, "name": str(r.get("name") or "")})+ return {"workspace": workspace, "type": plug_type, "harnesses": len(rows), "attached": len(attached), "harness_list": attached}+++def _plugs_types_ok(plugs: list) -> list[str]:+ if not isinstance(plugs, list) or not plugs or not all(isinstance(t, str) for t in plugs):+ raise uhp_error(400, "invalid_input", "plugs must be a non-empty list of plug type names.", "plugs")+ bad = [t for t in plugs if t not in plugs_plane.TYPES]+ if bad:+ raise uhp_error(400, "invalid_plug", f"No plug of type {bad[0]!r} on this server.", "plugs",+ {"supported": sorted(plugs_plane.TYPES)})+ return list(dict.fromkeys(plugs))+++def _plugs_tools_ok(tools, plugs: list[str]) -> dict | None:+ if tools is None:+ return None+ if not isinstance(tools, dict):+ raise uhp_error(400, "invalid_input", "tools must be an object of plug type to tool names.", "tools")+ out = {}+ for plug, names in tools.items():+ if plug not in plugs:+ raise uhp_error(400, "invalid_input", f"tools names {plug!r}, which is not being attached.", "tools")+ if not isinstance(names, list) or not all(isinstance(n, str) for n in names):+ raise uhp_error(400, "invalid_input", f"tools.{plug} must be a list of tool names.", "tools")+ known = {t["name"] for t in plugs_plane.tools_of(plug)}+ unknown = [n for n in names if n not in known]+ if unknown:+ raise uhp_error(400, "invalid_input", f"No tool named {plug}.{unknown[0]}.", "tools")+ out[plug] = list(dict.fromkeys(names))+ return out or None+++def _harness_workspace_for_plugs(v: dict | None) -> str:+ """The workspace a harness's plugins bind to. A harness created without a workspace header+ carries no stamp; on a self-hosted instance (no registry elsewhere) that harness is in the+ instance's default workspace, the same leniency its listing applies (workspace_default), so+ the guide's bare API calls, PUT /v1/plugs/browser then POST .../servers/plugs, meet in one+ workspace. Behind a registry the stamp is required: a tenant is never guessed there."""+ stamp = str((v or {}).get("workspace") or "")+ if stamp or PLUGS_REGISTRY_URL:+ return stamp+ return _WORKSPACE_DEFAULT_ID+++def _plugs_harness_rows(org: str | None, workspace: str, rows: list[dict]) -> list[dict]:+ """The harnesses of a workspace for the attachment count: those stamped with it, and on a+ self-hosted instance the unstamped ones when it is the default workspace (see above)."""+ lenient = not PLUGS_REGISTRY_URL and workspace == _WORKSPACE_DEFAULT_ID+ return [r for r in rows+ if (org is None or str(r.get("org") or "") == org)+ and str(r.get("deleted")) not in ("1", "true", "True")+ and (str(r.get("workspace") or "") == workspace or (lenient and not r.get("workspace")))]+++async def _plugs_attach(org: str, hid: str, v: dict | None, plugs: list[str], tools: dict | None) -> None:+ """Bind plugs to a harness: the record (with the harness's workspace) and one entry. Idempotent;+ a second attach keeps the entry's name and switch. The workspace is the harness's own and never+ taken from a request: a harness reaches its own company's plugs and no other."""+ origins = _own_origins()+ if not origins:+ raise uhp_error(501, "gateway_address_not_configured",+ "This server has no address an agent could reach it on — set "+ "HARNESS_PUBLIC_BASE_URL.", "plugs")+ workspace = _harness_workspace_for_plugs(v)+ if not workspace:+ raise uhp_error(400, "workspace_required",+ "This agent is not in a named workspace; plugins connect to a workspace.", "plugs")+ cur = _mcp_list(v)+ prev = next((e for e in cur if str(e.get("id") or "") == _PLUGS_ENTRY["id"]), None) or {}+ prev_key = _vault_key(prev.get("auth"))+ key = prev_key if prev_key.startswith(_HOSTED_SECRET_PREFIX) else _hosted_secret_key(hid, _PLUGS_ENTRY["id"])+ record = {"server": _PLUGS_SERVER, "harness": hid, "workspace": workspace, "plugs": plugs,+ **({"tools_enabled": tools} if tools else {}), "updated_at": int(time.time() * 1000)}+ await _hosted_put_record(org, key, record, secret=False, param="plugs")+ entry = {"id": _PLUGS_ENTRY["id"], "name": str(prev.get("name") or _PLUGS_ENTRY["name"]),+ "url": origins[0] + _HOSTED_MCP_PREFIX + _PLUGS_SERVER, "transport": "http",+ "auth": f"vault:{key}",+ "enabled": str(prev.get("enabled", True)) not in ("False", "false", "0")}+ await _mcp_write(hid, [e for e in cur if str(e.get("id") or "") != _PLUGS_ENTRY["id"]] + [entry])+ print(f"[plugs] {hid}: {', '.join(plugs)} attached for {workspace}", flush=True)+++async def _plugs_server_out(org: str, entry: dict, rec: dict) -> dict:+ """The plugs server on a harness, describing itself: the binding and each plug's state. One+ shape for the attach route's answer and for the server read (get_harness_server)."""+ plugs = [t for t in rec.get("plugs") or [] if isinstance(t, str)]+ status = {}+ for t in plugs:+ status[t], _ = await _plug_lookup(org, str(rec.get("workspace") or ""), t)+ return {"id": entry.get("id"), "name": entry.get("name"),+ "enabled": str(entry.get("enabled", True)) not in ("False", "false", "0"),+ "workspace": str(rec.get("workspace") or ""), "plugs": plugs,+ **({"tools": rec["tools_enabled"]} if isinstance(rec.get("tools_enabled"), dict) else {}),+ "status": status}++[email protected]("/v1/harnesses/{hid}/servers/plugs")+async def attach_plugs(hid: str, body: PlugsBody, request: Request) -> dict:+ """Attach the workspace's plugs to one of the caller's harnesses. Idempotent: attaching again+ replaces the list of plugs and tools and rewrites nothing else."""+ org, _ = await _pub_org_member(request)+ v = await _harness_for_route(hid, org)+ plugs = _plugs_types_ok(body.plugs)+ _plugs_gate(org, plugs)+ await _plugs_attach(org, hid, v, plugs, _plugs_tools_ok(body.tools, plugs))+ entry, rec = await _hosted_resolve(_PLUGS_SERVER, hid, org, _mcp_list(await _vertex_get(hid) or v),+ entry_id=_PLUGS_ENTRY["id"])+ return await _plugs_server_out(org, entry, rec)++[email protected]("/v1/harnesses/{hid}/servers/plugs")+async def detach_plugs(hid: str, request: Request) -> dict:+ """Detach them: the entry goes and its binding record is scrubbed. The plugs themselves stay+ connected to the workspace for every other harness."""+ org, _ = await _pub_org_member(request)+ v = await _harness_for_route(hid, org)+ cur = _mcp_list(v)+ after = [e for e in cur if str(e.get("id") or "") != _PLUGS_ENTRY["id"]]+ if len(after) == len(cur):+ code, msg = _HOSTED_NOT_CONNECTED[_PLUGS_SERVER]+ raise uhp_error(404, code, msg, "harness_id")+ await _mcp_write(hid, after)+ await _hosted_scrub_removed(org, hid, cur, after)+ return {"id": _PLUGS_ENTRY["id"], "detached": True}+++async def _plugs_ensure_required(org: str, hid: str) -> bool:+ """A package that declares `requires.plugs` gets those plugs attached to the harness it is+ installed on, with the harness's workspace bound: the package never names a tenant. Runs after+ every write that can install a package. True when the harness changed."""+ v = await _vertex_get(hid)+ want = sorted({t for e in _plugins_of(v) if e.get("enabled")+ for t in (((e.get("manifest") or {}).get("requires") or {}).get("plugs") or [])+ if isinstance(t, str) and t in plugs_plane.TYPES})+ held = [t for t in want if not _plugs_allowed(org, t)]+ if held:+ print(f"[plugs] {hid}: a package requires {', '.join(held)}; not open to {org} yet", flush=True)+ want = [t for t in want if t not in held]+ if not want:+ return False+ entry = next((e for e in _mcp_list(v) if str(e.get("id") or "") == _PLUGS_ENTRY["id"]), None)+ rec = await _hosted_record(org, _vault_key((entry or {}).get("auth"))) if entry else None+ have = ([t for t in (rec.get("plugs") or []) if isinstance(t, str)]+ if rec and rec.get("harness") == hid else [])+ if entry and set(want) <= set(have):+ return False+ await _plugs_attach(org, hid, v, list(dict.fromkeys(have + want)), (rec or {}).get("tools_enabled") or None)+ return True+++_PLUG_REFUSALS = {+ "missing": ("The workspace has no {label} plugin connected. Ask the person to connect one on the "+ "workspace's Plugins page, then try again; you cannot connect it yourself."),+ "needs_auth": "The workspace's {label} plugin needs attention on the Plugins page before it can be used. Tell the person.",+ "disabled": "The workspace's {label} plugin is turned off. Tell the person if you need it.",+ "unavailable": "The plugin registry did not answer. Try again in a moment.",+}+++async def _plug_call_record(hid: str, sid: str, org: str, workspace: str, plug: str, tool: str, risk: str,+ started: float, outcome: str, error: str = "", *, unit: str = "call",+ usd: float = 0.0, detail: dict | None = None) -> None:+ """Every call, written down: an audit row, an event in the session's trace, and the meter.+ Best effort in every part, because a failed record must not turn a served call into an error.++ `unit` and `usd` are the row's money: a call is a `call` (or a `screenshot`) at nothing; a+ browser session's own row carries `browser.usd` and the vendor's dollars, and that row is the+ one the meter posts under that unit. `detail` is the row's figures (a session's minutes,+ reason and source), kept as JSON text."""+ now = time.time()+ ms = int((now - started) * 1000)+ props = {"harness": hid, "session": sid, "org": org, "workspace": workspace, "plug": plug, "tool": tool,+ "risk": risk, "started": str(int(started * 1000)), "finished": str(int(now * 1000)), "ms": str(ms),+ "outcome": outcome, "error": (error or "")[:300], "unit": unit, "usd": repr(round(float(usd), 6)),+ "detail": json.dumps(detail or {}, separators=(",", ":"))[:600], "created_at": str(int(now * 1000))}+ with contextlib.suppress(Exception):+ await _vg_upsert(_PLUG_CALL_LABEL, _rid("pcall"), props)+ tr = _session_trace.get(sid)+ if tr and tr.get("prefix"):+ with contextlib.suppress(Exception):+ await _trace_flush(tr, {"events": [{"type": "plug", "plug": plug, "tool": tool, "risk": risk,+ "outcome": outcome, "ms": ms, "unit": unit, "usd": round(float(usd), 6),+ **({"error": error[:300]} if error else {}),+ **({"detail": detail} if detail else {}), "_ts": now}]})+ if unit == browser_plane.UNIT:+ if usd > 0:+ _report_usage(org, browser_plane.UNIT, float(usd), workspace=workspace, task_id=sid, harness_id=hid,+ title="Browser", harness_name="Browser")+ elif outcome in ("ok", "error"):+ # What was served is what is metered: a call the vendor refused still ran here; a call+ # refused before any credential was resolved did not.+ _report_usage(org, "plug.call", 1.0, workspace=workspace, task_id=sid, harness_id=hid)++[email protected]("/v1/mcp/plugs")+async def plugs_mcp(request: Request):+ """The MCP endpoint the agent's CLI talks to for its plugs. Streamable HTTP, stateless, the+ same shape as the database server's: the token names the harness, the session and the record;+ the record names the workspace and the plugs; each call resolves the plug's credential here."""+ claims = _verify_hosted_cred(_broker_token(request))+ if not claims:+ raise HTTPException(401, "invalid or expired turn credential")+ hid, sid, key = claims+ try:+ req = json.loads(await request.body() or b"{}")+ except Exception: # noqa: BLE001+ raise HTTPException(400, "malformed JSON-RPC request") from None+ method, rid, params = req.get("method") or "", req.get("id"), req.get("params") or {}++ if method == "initialize":+ return _jsonrpc_result(rid, {+ "protocolVersion": str(params.get("protocolVersion") or "2024-11-05"),+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "plugs", "version": "1"}})+ if rid is None:+ return Response(status_code=202)+ if method not in ("tools/list", "tools/call"):+ return JSONResponse({"jsonrpc": "2.0", "id": rid,+ "error": {"code": -32601, "message": f"method not found: {method}"}})++ v = await _harness_vertex(hid)+ if v and str(v.get("deleted")) in ("1", "true", "True"):+ v = None # a token outlives the agent it was minted for; its plugs must not+ org = str((v or {}).get("org") or "")+ try:+ _entry, rec = await _hosted_resolve(_PLUGS_SERVER, hid, org, _mcp_list(v), key=key, check_enabled=True)+ except HTTPException:+ if method == "tools/list":+ return _jsonrpc_result(rid, {"tools": []})+ return _jsonrpc_result(rid, _tool_text(+ "No plugins are connected to this agent. Ask the person to include them, then try again; "+ "you cannot include them yourself.", True))+ plugs = [t for t in rec.get("plugs") or [] if isinstance(t, str) and t in plugs_plane.TYPES]+ enabled = rec.get("tools_enabled") if isinstance(rec.get("tools_enabled"), dict) else None+ if method == "tools/list":+ return _jsonrpc_result(rid, {"tools": plugs_plane.tool_list(plugs, enabled)})++ 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+ if 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 "")+ label = plugs_plane.TYPES.get(plug, plug)+ started = time.time()+ if not _plugs_allowed(org, plug):+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "refused",+ "plugs not open to this org")+ return _jsonrpc_result(rid, _tool_text(f"The {label} plugin is not available on this account yet.", True))+ status, prec = await _plug_lookup(org, workspace, plug)+ if status != "connected" or not prec:+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "refused", status)+ return _jsonrpc_result(rid, _tool_text(_PLUG_REFUSALS[status].format(label=label), True))+ config = prec.get("config") if isinstance(prec.get("config"), dict) else {}+ if plug == plugs_plane.BROWSER:+ # A platform plug: the record carries no credential (source platform, key_refs []), only+ # the sites the workspace allows; the browser itself is this gateway's session plane.+ return await _browser_plug_call(rid, hid, sid, org, workspace, tool, spec, args if isinstance(args, dict) else {},+ config, started)+ fields = await _plug_fields(prec)+ if not fields:+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "refused", "no credential")+ return _jsonrpc_result(rid, _tool_text(_PLUG_REFUSALS["needs_auth"].format(label=label), True))+ need = plugs_plane.permission_of(plug, tool)+ if need and need in (config.get("permissions_missing") or []):+ # The record knows what the installation was not granted; saying so beats a vendor 403+ # the model would spend the turn retrying around.+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "refused", f"no {need} permission")+ return _jsonrpc_result(rid, _tool_text(+ f"The workspace's {label} plug was not granted {need} access, so {tool} cannot run. The person can "+ "grant it on the app installation and reconnect the plug.", True))+ try:+ text = await plugs_plane.call(plug, tool, args if isinstance(args, dict) else {}, fields, config)+ except plugs_plane.PlugToolError as e:+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "error", str(e))+ return _jsonrpc_result(rid, _tool_text(str(e), True))+ except Exception as e: # noqa: BLE001+ 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))+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "ok")+ return _jsonrpc_result(rid, _tool_text(text))+++# ── The browser plug: a cloud browser over CDP behind the plugs server ──────────────────────────+# A workspace connects it once (a Plug record of type browser: platform auth, its site lists), a+# harness includes it like any plug, and the agent gets navigate, snapshot, click, type and+# friends, never a JavaScript evaluator, a download, a cookie, the vendor's key or the browser's+# address. The browser itself lives in browser_plane.py: one per harness session, opened on the+# first call, stopped at the turn's end, after idle, or at the cap. Money is the vendor's list+# price passed through under one unit, browser.usd, on the session's own audit row.+async def _browser_plug_call(rid, hid: str, sid: str, org: str, workspace: str, tool: str, spec: dict, args: dict,+ config: dict, started: float):+ plug = plugs_plane.BROWSER+ allow = [d for d in config.get("allow_domains") or [] if isinstance(d, str)]+ deny = [d for d in config.get("deny_domains") or [] if isinstance(d, str)]++ async def refused(code: str, text: str):+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "refused", code)+ return _jsonrpc_result(rid, _tool_text(text, True))++ if not browser_plane.configured():+ return await refused("not configured", "The browser service is not set up on this deployment. Tell the person.")+ s = browser_plane.sessions().get(sid)+ if s is None:+ # The first call opens the browser: the estimate is written on the row for the record (a+ # self-hosted instance keeps no task cost cap; the vendor's own credit is the ceiling).+ estimate = browser_plane.session_estimate_usd()+ try:+ s = await browser_plane.open_session(sid, hid, org, workspace, allow, deny)+ except browser_plane.BrowserRefused as e:+ return await refused(e.code, str(e))+ except Exception as e: # noqa: BLE001+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "error",+ f"open: {type(e).__name__}: {e}")+ return _jsonrpc_result(rid, _tool_text(f"The browser could not be started ({type(e).__name__}). Try again.", True))+ s.reserved = estimate+ 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})+ elif (s.allow, s.deny) != (allow, deny):+ s.allow, s.deny, s.host_cache = list(allow), list(deny), {} # the workspace changed its lists+ 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.")+ try:+ out = await asyncio.wait_for(browser_plane.call(s, tool, args), browser_plane.CALL_CAP_S)+ except asyncio.TimeoutError:+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "error", "timeout")+ return _jsonrpc_result(rid, _tool_text(+ f"The call took longer than {browser_plane.CALL_CAP_S:.0f} seconds and was stopped.", True))+ except browser_plane.BrowserToolError as e:+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "error", str(e))+ return _jsonrpc_result(rid, _tool_text(str(e), True))+ except Exception as e: # noqa: BLE001+ 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))+ if isinstance(out, tuple) and out[0] == "image":+ png, caption = out[1], out[2]+ stored = None+ with contextlib.suppress(Exception):+ stored = await _media_store(sid, "image", png, {"source": "browser", "caption": caption[:160]})+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "ok", unit="screenshot",+ detail={"bytes": len(png), **({"media_id": stored["media_id"]} if stored else {})})+ note = caption + (f"\nKept with the task's files as {_media_url(hid, _PLUGS_ENTRY['id'], sid, stored['media_id'])}"+ if stored else "")+ return _jsonrpc_result(rid, {"content": [{"type": "image", "data": base64.b64encode(png).decode(), "mimeType": "image/png"},+ {"type": "text", "text": note}], "isError": False})+ await _plug_call_record(hid, sid, org, workspace, plug, tool, spec["risk"], started, "ok")+ return _jsonrpc_result(rid, _tool_text(str(out)))+++async def _browser_close(sid: str, reason: str) -> None:+ """Stop the session's browser, if it opened one, and write its one money row: the minutes it+ ran and the vendor's dollars for them, metered under browser.usd. Closing the CDP socket alone+ keeps the vendor's meter running, so the stop is explicit and it is in the audit trail."""+ s = browser_plane.sessions().get(sid)+ if not s or s.closed:+ return+ try:+ fig = await browser_plane.close_session_browser(s)+ except Exception as e: # noqa: BLE001+ fig = {"minutes": s.minutes, "usd": round(s.minutes * browser_plane.PRICES["browser.minute"], 6),+ "usd_source": "table", "calls": s.calls, "screenshots": s.screenshots, "blocked": [],+ "stop_error": f"{type(e).__name__}: {str(e)[:120]}"}+ print(f"[browser] {sid}: stopped ({reason}) after {fig['minutes']} min, ${fig['usd']:.6f} ({fig['usd_source']})", flush=True)+ released = round(max(0.0, s.reserved - float(fig["usd"])), 6)+ await _plug_call_record(s.hid, sid, s.org, s.workspace, plugs_plane.BROWSER, "session", "session", s.created, "ok", "",+ unit=browser_plane.UNIT, usd=float(fig["usd"]),+ detail={"reason": reason, "vendor": browser_plane.VENDOR, "vendor_session": s.vendor_id,+ "reserved_usd": s.reserved, "released_usd": released, **fig})++[email protected]_event("startup")+async def _browser_reaper_start() -> None:+ """Idle and over-cap browsers are stopped whether or not another call ever comes."""+ async def loop() -> None:+ while True:+ await asyncio.sleep(15)+ for s, why in browser_plane.expired_sessions():+ with contextlib.suppress(Exception):+ await _browser_close(s.sid, why)+ asyncio.get_running_loop().create_task(loop())++[email protected]("/internal/plugs/attachments", dependencies=[Depends(_internal_only)])+async def plug_attachments(workspace: str, type: str) -> dict:+ """How many of a workspace's harnesses include one plug type, for the Plugins page's+ "attached N of M harnesses": M is the workspace's harnesses, N those whose plugs binding+ names the type. Read from the bindings, never guessed."""+ rows = _plugs_harness_rows(None, workspace, await BACKING.graph.find("Harness", {"workspace": workspace})+ + (await BACKING.graph.find("Harness", {"workspace": ""}) if not PLUGS_REGISTRY_URL else []))+ attached = []+ for r in rows:+ hid = str(r.get("id") or "")+ entry = next((e for e in _mcp_list(r) if str(e.get("id") or "") == _PLUGS_ENTRY["id"]), None)+ if not entry:+ continue+ rec = await _hosted_record(str(r.get("org") or ""), _vault_key(entry.get("auth")))+ if rec and rec.get("harness") == hid and type in (rec.get("plugs") or []):+ attached.append(hid)+ return {"workspace": workspace, "type": type, "harnesses": len(rows), "attached": len(attached), "harness_ids": attached}++[email protected]("/internal/plugs/pricing", dependencies=[Depends(_internal_only)])+async def plug_pricing(type: str = "") -> dict:+ """What a plug costs, from the one place that charges it, for the Plugins page's price line.+ The browser passes the vendor's list price through; the other plugs cost nothing here."""+ rows = [browser_plane.pricing()] + [{"type": t, "unit": "call", "usd_per_unit": 0.0, "markup": 0.0,+ "source": "no charge", "billed_as": "plug.call"}+ for t in plugs_plane.TYPES if t not in (plugs_plane.BROWSER, "github_app")]+ if type:+ row = next((r for r in rows if r["type"] == type), None)+ if not row:+ raise uhp_error(404, "plug_not_found", f"No plug of type {type!r}.", "type")+ return row+ return {"pricing": rows}++[email protected]("/internal/plugs/tools", dependencies=[Depends(_internal_only)])+async def plug_tools(type: str) -> dict:+ """The tools a plug type serves, from the same list the agent gets."""+ if type not in plugs_plane.TYPES:+ raise uhp_error(404, "plug_not_found", f"No plug of type {type!r}.", "type")+ return {"type": type, "label": plugs_plane.TYPES[type],+ "tools": [{"name": t["name"], "description": t["description"], "risk": t["risk"]} for t in plugs_plane.tools_of(type)]}++# ── Starter Kits ──────────────────────────────────────────────────────────────────────────────# A kit is a whole product in a folder: the Harness it needs, and a UI that talks to that Harness# as its backend. Both are baked into the image from HarnessRouter/starter-kit (see@@ -14173,7 +14902,7 @@ _PLUGIN_NAME_RE = re.compile(r"^(?!.*(--|\.\.))[a-z0-9]([a-z0-9.-]*[a-z0-9])?$")_SKILL_NAME_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")_PLUGIN_PACKAGE_MAX = 16 * 1024 * 1024 # the JSON-encoded package; a plugin is code and prose, not data_PLUGIN_MANIFEST_FIELDS = {"$schema", "name", "version", "description", "author", "homepage",- "repository", "license", "keywords", "extensions"}+ "repository", "license", "keywords", "extensions", "requires"}_PLUGIN_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")_PLUGIN_BLOB_RE = re.compile(r"^plg_[0-9a-f]{32}$")# The derived object rides on the harness record beside the blob handle; the record has a hard@@ -14401,6 +15130,17 @@ def _plugin_read_package(files: list, sent_name: str | None = None) -> dict:and all(isinstance(x, str) for x in v.values())):raise _plugin_invalid(name, "plugin.json#/author","author may carry only name, email and url, each a string")+ elif k == "requires":+ # requires.plugs names plug TYPES, never a tenant: the workspace a harness is in supplies+ # the tenancy when the package is installed (_plugs_ensure_required).+ plugs_req = v.get("plugs", []) if isinstance(v, dict) else None+ if not (isinstance(v, dict) and set(v) <= {"plugs"} and isinstance(plugs_req, list)+ and all(isinstance(x, str) for x in plugs_req)):+ raise _plugin_invalid(name, "plugin.json#/requires", "requires may carry plugs, a list of plug type names")+ for t in plugs_req:+ if t not in plugs_plane.TYPES:+ skipped.append({"path": f"plugin.json#/requires/plugs/{t}",+ "reason": "no plug of that type on this server, ignored"})elif k == "extensions" and not isinstance(v, dict):skipped.append({"path": "plugin.json#/extensions", "reason": "extensions is not an object, ignored"})@@ -14695,6 +15435,8 @@ async def create_harness(org: str, body: HarnessBody, request: Request) -> dict:props = {"org": org, "member": member, "workspace": workspace, **_harness_props(body),"custom": "1", "created_at": now, "updated_at": now, "deleted": "0"}await _vg_upsert("Harness", hid, props)+ if await _plugs_ensure_required(org, hid):+ return _harness_out(await _vertex_get(hid) or {"id": hid, **props})return _harness_out({"id": hid, **props})@@ -14808,6 +15550,7 @@ async def update_harness(org: str, hid: str, body: HarnessBody, request: Request# AFTER the write: _harness_props can still refuse this save (an unsupported base), and a# refused save that had already scrubbed a record would disconnect a database nobody removed.await _hosted_scrub_removed(org, hid, _mcp_list(cur), body.mcp_servers)+ await _plugs_ensure_required(org, hid)v = await _vertex_get(hid)return _harness_out(v or {"id": hid})@@ -14957,6 +15700,8 @@ async def create_harness_public(body: HarnessBody, request: Request) -> dict:**_harness_props(body),"custom": "1", "created_at": now, "updated_at": now, "deleted": "0"}await _vg_upsert("Harness", hid, props)+ if await _plugs_ensure_required(org, hid):+ return _harness_out(await _vertex_get(hid) or {"id": hid, **props})return _harness_out({"id": hid, **props})@@ -15181,6 +15926,8 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Non"updated_at": str(int(time.time() * 1000))})existing = await _vertex_get(hid0) or {**existing, "system_prompt": want_prompt}print(f"[kits] {kit_id}: prompt refreshed on {hid0}", flush=True)+ if await _plugs_ensure_required(org, hid0):+ existing = await _vertex_get(hid0) or existingreturn {"kit": kit_id, "harnessId": hid0,"route": (kit.get("app") or {}).get("route") or "", "created": False,"harness": _harness_out(existing)}@@ -15241,6 +15988,8 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Nonif media_decl:await _hosted_media_attach(org, hid, v, media_decl)v = await _vertex_get(hid) or v+ if await _plugs_ensure_required(org, hid):+ v = await _vertex_get(hid) or vprint(f"[kits] launched {kit_id} -> {hid}", flush=True)return {"kit": kit_id, "harnessId": hid,"route": (kit.get("app") or {}).get("route") or "", "created": True,@@ -15693,7 +16442,7 @@ async def get_harness_public(hid: str, request: Request) -> dict:# upload, workspaces) and every route behind the internal key stay out. Served on the same host as the API, and once per process._OPENAPI_PUBLIC_PREFIXES = ("/v1/responses", "/v1/files", "/v1/sessions", "/v1/harnesses", "/v1/bases","/v1/models", "/v1/mcp-secrets", "/v1/mcp-test", "/v1/containers", "/v1/traces",- "/v1/uhp", "/v1/openapi.json")+ "/v1/plugs", "/v1/uhp", "/v1/openapi.json")_openapi_doc: dict | None = None@@ -15931,6 +16680,7 @@ async def update_harness_public(hid: str, body: HarnessBody, request: Request) -await _vg_upsert("Harness", hid, {**_harness_props(body), "updated_at": str(int(time.time() * 1000))})# AFTER the write: see update_harness.await _hosted_scrub_removed(org, hid, _mcp_list(v), body.mcp_servers)+ await _plugs_ensure_required(org, hid)return _harness_out(await _vertex_get(hid) or {"id": hid})diff --git a/gateway/browser_plane.py b/gateway/browser_plane.pynew file mode 100644index 00000000..c6051978--- /dev/null+++ b/gateway/browser_plane.py@@ -0,0 +1,597 @@+"""The browser server's plane: a real browser in a vendor's cloud, driven from this gateway over+the Chrome DevTools Protocol, handed to the agent as a dozen typed tools and nothing else.++One browser session per harness session, made on the first call and stopped at the end of the+turn, after idle, or at the session cap. The vendor is behind one adapter (Browser Use Cloud+first; Browserbase has the same shape: a session id and a CDP address), so the tools, the guards+and the metering never learn a vendor's name.++What the agent is never given: a JavaScript evaluator, downloads, cookies, the vendor's key, the+CDP address. What every request is checked against, subresources and redirects included: the+harness's allow and deny lists and the private, loopback, link-local and metadata address ranges.++Money: the vendor's list price, no markup. A session is priced BEFORE it starts as the session cap+times the per-minute rate (that is what counts against the task's cost cap), and metered AFTER+from the vendor's own figures for the minutes it ran (rounded up, one-minute minimum). The prices+below are the estimate's; the meter reads what the vendor reports.+"""+from __future__ import annotations++import asyncio+import ipaddress+import json+import math+import os+import socket+import time+import urllib.parse++import httpx++API_KEY = os.environ.get("BROWSER_USE_API_KEY", "")+# The key as a mounted secret file, read at every use: a rotated Key Vault secret reaches a+# mounted file without a new revision, where an environment variable holds the value the process+# started with.+API_KEY_FILE = os.environ.get("BROWSER_USE_API_KEY_FILE", "")+API_BASE = os.environ.get("BROWSER_USE_API_BASE", "https://api.browser-use.com/api/v4").rstrip("/")+SESSION_CAP_MIN = int(os.environ.get("HR_BROWSER_SESSION_MINUTES", "20")) # per harness session+# Fair share of the vendor's concurrency (10 sessions until $1,000 lifetime spend, then 250):+# no org holds more than its share, and this process stops one below the vendor's ceiling so the+# refusal an agent reads is ours, in a sentence, not the vendor's 429. Per process: a second+# gateway replica has its own counts.+ORG_SESSIONS = int(os.environ.get("HR_BROWSER_ORG_SESSIONS", "3"))+MAX_SESSIONS = int(os.environ.get("HR_BROWSER_MAX_SESSIONS", "9"))+CALL_CAP_S = float(os.environ.get("HR_BROWSER_CALL_SECONDS", "60")) # per tool call+IDLE_S = float(os.environ.get("HR_BROWSER_IDLE_SECONDS", "120")) # no call for this long: stopped+TEXT_CAP = 20000 # characters of extracted text+SNAPSHOT_CAP = 150 # elements in a snapshot++# The vendor's list prices, no markup (browser-use.com/pricing and the v4 API docs, read+# 2026-09-24): browser time $0.02 per hour, rounded up to whole minutes, one-minute minimum;+# residential proxy $5 per GB (this slice runs with no proxy, so the unit never appears);+# screenshots are Playwright's and cost nothing. The meter posts dollars under one unit.+PRICES = {"browser.minute": 0.02 / 60, "browser.proxy_mb": 0.005, "browser.screenshot": 0.0}+UNIT = "browser.usd"+VENDOR = "browser-use"++transport: httpx.BaseTransport | None = None # tests: the vendor's API+connector = None # tests: async (cdp_url) -> a browser-like object+++def api_key() -> str:+ if API_KEY_FILE:+ try:+ with open(API_KEY_FILE, encoding="utf-8") as f:+ key = f.read().strip()+ if key:+ return key+ except OSError:+ pass+ return API_KEY+++def configured() -> bool:+ return bool(api_key())+++def pricing() -> dict:+ """The browser's price line, for the page that shows it before a workspace turns it on."""+ return {"type": "browser", "unit": "browser hour", "usd_per_unit": round(PRICES["browser.minute"] * 60, 6),+ "markup": 0.0, "source": "vendor list price", "vendor": VENDOR, "billed_as": UNIT,+ "rounding": "up to the minute, one-minute minimum", "session_cap_minutes": SESSION_CAP_MIN,+ "session_estimate_usd": session_estimate_usd()}+++def session_estimate_usd() -> float:+ """What a session may cost at most, before it starts: the cap in minutes at the list price."""+ return round(SESSION_CAP_MIN * PRICES["browser.minute"], 6)+++class BrowserRefused(RuntimeError):+ """A call that must not run, with the sentence the agent reads."""++ def __init__(self, code: str, message: str):+ super().__init__(message)+ self.code = code+++class BrowserToolError(RuntimeError):+ """A call that ran and failed in a way the agent can act on."""+++# ── the vendor ───────────────────────────────────────────────────────────────────────────────+def _vendor_client() -> httpx.AsyncClient:+ return httpx.AsyncClient(transport=transport, timeout=60,+ headers={"X-Browser-Use-API-Key": api_key(), "content-type": "application/json"})+++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."""+ async with _vendor_client() as c:+ r = await c.post(f"{API_BASE}/browsers", json={+ "timeout": int(timeout_min), "proxyCountryCode": None, "solveCaptchas": False,+ "enableRecording": False, "metadata": {k: str(v)[:100] for k, v in metadata.items()}})+ if r.status_code == 402:+ raise BrowserRefused("vendor_credits", "The browser service has no credit left. Tell the person.")+ if r.status_code == 429:+ raise BrowserRefused("vendor_busy", "Every browser is in use right now. Try again in a minute.")+ if r.status_code >= 400:+ raise BrowserRefused("vendor_error", f"The browser service refused to start a browser ({r.status_code}).")+ d = r.json()+ if not d.get("id") or not d.get("cdpUrl"):+ raise BrowserRefused("vendor_error", "The browser service answered without a browser address.")+ return d+++async def vendor_stop(vendor_id: str) -> dict:+ """Stop the browser and read what it cost: closing the CDP socket alone keeps the meter+ running on the vendor's side."""+ async with _vendor_client() as c:+ r = await c.patch(f"{API_BASE}/browsers/{vendor_id}", json={"action": "stop"})+ if r.status_code >= 400:+ r = await c.get(f"{API_BASE}/browsers/{vendor_id}")+ try:+ return r.json() if r.status_code < 400 else {}+ except ValueError:+ return {}+++def vendor_cost(d: dict) -> float | None:+ """Dollars the vendor reports for a session: its browser time, plus proxy traffic when any.+ None when it reported no browser cost, which is the figure of record."""+ if d.get("browserCost") is None:+ return None+ total = 0.0+ for p in (d.get("browserCost"), d.get("proxyCost")):+ try:+ total += float(p or 0)+ except (TypeError, ValueError):+ pass+ return round(total, 6)+++# ── the address guard ────────────────────────────────────────────────────────────────────────+_PRIVATE_NAMES = ("localhost", ".localhost", ".local", ".internal", ".home.arpa", ".lan", ".corp")+++def _ip_private(ip: str) -> bool:+ try:+ a = ipaddress.ip_address(ip)+ except ValueError:+ return False+ return (a.is_private or a.is_loopback or a.is_link_local or a.is_multicast or a.is_reserved+ or a.is_unspecified or (a.version == 6 and a.ipv4_mapped is not None and _ip_private(str(a.ipv4_mapped))))+++def _suffix_match(host: str, patterns: list[str]) -> bool:+ for p in patterns:+ p = (p or "").strip().lower().lstrip("*").lstrip(".")+ if p and (host == p or host.endswith("." + p)):+ return True+ return False+++def host_policy(host: str, allow: list[str], deny: list[str]) -> str | None:+ """Why this host may not be reached, or None. Name rules only; the address rule follows."""+ h = (host or "").strip().lower().rstrip(".")+ if not h:+ return "no host"+ if h.startswith("[") and h.endswith("]"):+ h = h[1:-1]+ if _ip_private(h):+ return "a private or local address"+ if h == "localhost" or any(h.endswith(s) for s in _PRIVATE_NAMES[1:]):+ return "a private or local address"+ if deny and _suffix_match(h, deny):+ return "a site this agent is not allowed to visit"+ if allow and not _suffix_match(h, allow):+ return "a site outside the ones this agent is allowed to visit"+ return None+++async def resolves_private(host: str) -> bool:+ """Whether any address the name resolves to is private. A name that does not resolve counts+ as private: this is an address a page chose, and it is asked again on every request."""+ h = (host or "").strip().lower().rstrip(".").strip("[]")+ if _ip_private(h):+ return True+ try:+ ipaddress.ip_address(h)+ return False+ except ValueError:+ pass+ try:+ infos = await asyncio.wait_for(asyncio.to_thread(socket.getaddrinfo, h, None), 4)+ except Exception: # noqa: BLE001+ return True+ return any(_ip_private(str(i[4][0])) for i in infos) or not infos+++# ── the session ──────────────────────────────────────────────────────────────────────────────+class Session:+ def __init__(self, sid: str, hid: str, org: str, workspace: str, allow: list[str], deny: list[str]):+ self.sid, self.hid, self.org, self.workspace = sid, hid, org, workspace+ self.allow, self.deny = list(allow), list(deny)+ self.vendor_id = ""+ self.live_url = ""+ self.browser = None+ self.context = None+ self.page = None+ self.created = time.time()+ self.last_used = self.created+ self.calls = 0+ self.screenshots = 0+ self.reserved = 0.0 # what was counted against the task before the browser opened+ self.blocked: list[str] = [] # hosts refused during this session, for the record+ self.host_cache: dict[str, bool] = {}+ self.lock = asyncio.Lock()+ self.closed = False++ @property+ def minutes(self) -> int:+ return max(1, math.ceil((time.time() - self.created) / 60))++ def expired(self, now: float | None = None) -> str | None:+ now = now or time.time()+ if now - self.created > SESSION_CAP_MIN * 60:+ return "session_cap"+ if now - self.last_used > IDLE_S:+ return "idle"+ return None+++_SESSIONS: dict[str, Session] = {}+_pw = None+++def sessions() -> dict[str, Session]:+ return _SESSIONS+++async def _connect(cdp_url: str):+ global _pw+ if connector is not None:+ return await connector(cdp_url)+ from playwright.async_api import async_playwright+ if _pw is None:+ _pw = await async_playwright().start()+ return await _pw.chromium.connect_over_cdp(cdp_url, timeout=30000)+++async def _allowed(s: Session, url: str) -> str | None:+ """Why this URL may not be requested from this session, or None; resolved once per host."""+ try:+ u = urllib.parse.urlsplit(url)+ except ValueError:+ return "not a valid address"+ if u.scheme not in ("http", "https"):+ return f"a {u.scheme or 'non-web'} address" if u.scheme not in ("about", "data", "blob") else None+ host = u.hostname or ""+ why = host_policy(host, s.allow, s.deny)+ if why:+ return why+ if host not in s.host_cache:+ s.host_cache[host] = await resolves_private(host)+ return "a private or local address" if s.host_cache[host] else None+++async def open_session(sid: str, hid: str, org: str, workspace: str, allow: list[str], deny: list[str]) -> Session:+ """A browser for this harness session: the vendor's, then Playwright over CDP, then a fresh+ context that accepts no downloads, with every request of every page gated by _allowed."""+ if not configured():+ raise BrowserRefused("not_configured", "The browser service is not set up on this deployment. Tell the person.")+ live = [x for x in _SESSIONS.values() if not x.closed]+ if sum(1 for x in live if x.org == org) >= ORG_SESSIONS:+ raise BrowserRefused("org_busy", f"This account already has {ORG_SESSIONS} browsers open. Try again when one of them finishes.")+ if len(live) >= MAX_SESSIONS:+ raise BrowserRefused("busy", "Every browser is in use right now. Try again in a minute.")+ s = Session(sid, hid, org, workspace, allow, deny)+ d = await vendor_create(SESSION_CAP_MIN, {"harness": hid, "session": sid})+ s.vendor_id, s.live_url = str(d["id"]), str(d.get("liveUrl") or "")+ try:+ s.browser = await _connect(str(d["cdpUrl"]))+ s.context = await s.browser.new_context(accept_downloads=False, viewport={"width": 1280, "height": 800})++ async def gate(route, request):+ why = await _allowed(s, request.url)+ if why:+ host = urllib.parse.urlsplit(request.url).hostname or request.url[:60]+ if host not in s.blocked:+ s.blocked.append(host)+ await route.abort("blockedbyclient")+ else:+ await route.continue_()++ await s.context.route("**/*", gate)+ s.page = await s.context.new_page()+ s.page.set_default_timeout(30000)+ except Exception:+ await close_session_browser(s)+ raise+ _SESSIONS[sid] = s+ return s+++async def close_session_browser(s: Session) -> dict:+ """Stop everything and read the vendor's figures. Every step is best effort: a browser that+ would not close must not keep its minutes from being metered."""+ s.closed = True+ _SESSIONS.pop(s.sid, None)+ for closer in (getattr(s.context, "close", None), getattr(s.browser, "close", None)):+ if closer:+ try:+ await asyncio.wait_for(closer(), 10)+ except Exception: # noqa: BLE001+ pass+ figures: dict = {}+ if s.vendor_id:+ try:+ figures = await vendor_stop(s.vendor_id)+ except Exception: # noqa: BLE001+ figures = {}+ usd = vendor_cost(figures)+ source = "vendor"+ if usd is None:+ usd, source = round(s.minutes * PRICES["browser.minute"], 6), "table"+ return {"minutes": s.minutes, "usd": usd, "usd_source": source, "calls": s.calls,+ "screenshots": s.screenshots, "blocked": s.blocked[:20],+ "proxy_mb": figures.get("proxyUsedMb") or 0}+++def expired_sessions(now: float | None = None) -> list[tuple[Session, str]]:+ now = now or time.time()+ return [(s, why) for s in list(_SESSIONS.values()) if (why := s.expired(now))]+++# ── the tools ────────────────────────────────────────────────────────────────────────────────+_TOOLS: list[dict] = []+++def _tool(name: str, risk: str, description: str, schema: dict):+ _TOOLS.append({"name": name, "risk": risk, "description": description,+ "inputSchema": {"type": "object", "properties": schema.get("properties", {}),+ "required": schema.get("required", []), "additionalProperties": False}})+++_REF = {"ref": {"type": "string", "description": "An element ref from the last snapshot, like e12."},+ "selector": {"type": "string", "description": "A CSS selector, when there is no ref for the element."}}++_tool("navigate", "act", "Open a web address in the current tab and read what is on the page.",+ {"properties": {"url": {"type": "string", "description": "An http or https address."}}, "required": ["url"]})+_tool("get_url", "read", "The current tab's address and title.", {})+_tool("snapshot", "read", "What is on the page: headings, links, buttons and fields, each with a ref to act on.",+ {"properties": {"max_elements": {"type": "integer", "description": f"At most this many elements (default {SNAPSHOT_CAP})."}}})+_tool("extract_text", "read", "The readable text of the page, or of one element.",+ {"properties": {"selector": {"type": "string", "description": "A CSS selector; the whole page when absent."},+ "max_chars": {"type": "integer", "description": f"At most this many characters (default {TEXT_CAP})."}}})+_tool("click", "act", "Click an element, by ref or selector.", {"properties": dict(_REF)})+_tool("type", "act", "Type text into a field, by ref or selector, replacing what is there.",+ {"properties": {**_REF, "text": {"type": "string"}, "submit": {"type": "boolean", "description": "Press Enter afterwards."}},+ "required": ["text"]})+_tool("press_key", "act", "Press a key, like Enter, Tab, Escape or ArrowDown.",+ {"properties": {"key": {"type": "string"}}, "required": ["key"]})+_tool("scroll", "act", "Scroll the page.",+ {"properties": {"direction": {"type": "string", "enum": ["down", "up"]},+ "pixels": {"type": "integer", "description": "How far (default 600)."}}})+_tool("wait_for", "read", "Wait until text or an element appears, or for a number of milliseconds.",+ {"properties": {"text": {"type": "string"}, "selector": {"type": "string"},+ "ms": {"type": "integer", "description": f"Milliseconds, at most {int(CALL_CAP_S * 1000)}."}}})+_tool("screenshot", "read", "A picture of the current tab, kept with the task's files and shown to you.",+ {"properties": {"full_page": {"type": "boolean", "description": "The whole page, not only the visible part."}}})+_tool("back", "act", "Go back one page in the current tab.", {})+_tool("list_tabs", "read", "The open tabs, with their index, address and title.", {})+_tool("switch_tab", "act", "Make one of the open tabs the current tab.",+ {"properties": {"index": {"type": "integer"}}, "required": ["index"]})+++def tool_list() -> list[dict]:+ 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]+++def find(name: str) -> dict | None:+ return next((t for t in _TOOLS if t["name"] == name), None)+++_SNAPSHOT_JS = """+(max) => {+ const out = []; let n = 0;+ const seen = new Set();+ const vis = (el) => { const r = el.getBoundingClientRect(); const cs = getComputedStyle(el);+ return r.width > 0 && r.height > 0 && 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';+ for (const el of document.querySelectorAll(sel)) {+ if (n >= max) { out.push({truncated: true}); break; }+ if (!vis(el) || seen.has(el)) continue;+ seen.add(el);+ const tag = el.tagName.toLowerCase();+ const role = el.getAttribute('role') || (tag === 'a' ? 'link' : tag === 'button' || tag === 'summary' ? 'button'+ : tag === 'select' ? 'combobox' : tag === 'textarea' ? 'textbox' : tag === 'input' ? ((el.type === 'checkbox' || el.type === 'radio' || el.type === 'submit' || el.type === 'button') ? el.type : 'textbox')+ : /^h[1-3]$/.test(tag) ? 'heading' : tag);+ const row = {role, name: nameOf(el)};+ if (role !== 'heading') { const ref = 'e' + (++n); el.setAttribute('data-hr-ref', ref); row.ref = ref; }+ else row.level = Number(tag[1]);+ if (tag === 'a') row.href = (el.getAttribute('href') || '').slice(0, 120);+ if (tag === 'input' || tag === 'textarea') { if (el.value && el.type !== 'password') row.value = String(el.value).slice(0, 60); if (el.disabled) row.disabled = true; }+ if (el.type === 'checkbox' || el.type === 'radio') row.checked = !!el.checked;+ out.push(row);+ }+ return out;+}+"""+++def _fmt_snapshot(rows: list[dict]) -> str:+ lines = []+ for r in rows:+ if r.get("truncated"):+ lines.append("… more elements below; scroll or ask for a larger snapshot")+ continue+ if r.get("role") == "heading":+ lines.append(f"h{r.get('level', 2)} \"{r.get('name', '')}\"")+ continue+ extra = ""+ if r.get("href"):+ extra += f" href={r['href']}"+ if "value" in r:+ extra += f" value=\"{r['value']}\""+ if "checked" in r:+ extra += " checked" if r["checked"] else " unchecked"+ if r.get("disabled"):+ extra += " disabled"+ lines.append(f"{r.get('ref')} {r.get('role')} \"{r.get('name', '')}\"{extra}")+ return "\n".join(lines) if lines else "(nothing interactive is visible on this page)"+++async def _snapshot(s: Session, max_elements: int) -> str:+ rows = await s.page.evaluate(_SNAPSHOT_JS, max(1, min(int(max_elements or SNAPSHOT_CAP), 500)))+ return _fmt_snapshot(rows or [])+++def _target(s: Session, args: dict):+ ref, selector = str(args.get("ref") or "").strip(), str(args.get("selector") or "").strip()+ if ref:+ return s.page.locator(f'[data-hr-ref="{ref}"]').first+ if selector:+ return s.page.locator(selector).first+ raise BrowserToolError("Say which element: a ref from the snapshot or a selector.")+++async def _where(s: Session) -> str:+ try:+ title = await s.page.title()+ except Exception: # noqa: BLE001+ title = ""+ return f"{s.page.url}" + (f" ({title})" if title else "")+++async def _settled(s: Session) -> None:+ with_timeout = getattr(s.page, "wait_for_load_state", None)+ if with_timeout:+ try:+ await asyncio.wait_for(s.page.wait_for_load_state("domcontentloaded"), 8)+ except Exception: # noqa: BLE001+ pass+++async def call(s: Session, name: str, args: dict):+ """Run one tool on this session. Returns text, or ("image", png bytes, caption) for a+ screenshot the caller stores. Raises BrowserToolError with a sentence the agent can act on."""+ s.calls += 1+ s.last_used = time.time()+ page = s.page+ if name == "navigate":+ url = str(args.get("url") or "").strip()+ if not url:+ raise BrowserToolError("Give a web address to open.")+ if "://" not in url:+ url = "https://" + url+ why = await _allowed(s, url)+ if why:+ raise BrowserToolError(f"That address is {why}, so it cannot be opened.")+ try:+ await page.goto(url, wait_until="domcontentloaded")+ except Exception as e: # noqa: BLE001+ raise BrowserToolError(f"The page did not open: {str(e).splitlines()[0][:200]}") from None+ return f"Opened {await _where(s)}\n\n{await _snapshot(s, 80)}"+ if name == "get_url":+ return await _where(s)+ if name == "snapshot":+ return f"{await _where(s)}\n\n{await _snapshot(s, args.get('max_elements') or SNAPSHOT_CAP)}"+ if name == "extract_text":+ selector = str(args.get("selector") or "").strip() or "body"+ cap = max(200, min(int(args.get("max_chars") or TEXT_CAP), TEXT_CAP))+ try:+ text = await page.locator(selector).first.inner_text()+ except Exception as e: # noqa: BLE001+ raise BrowserToolError(f"No readable text at {selector!r}: {str(e).splitlines()[0][:160]}") from None+ text = "\n".join(line.strip() for line in text.splitlines() if line.strip())+ return text[:cap] + (f"\n… {len(text) - cap} more characters" if len(text) > cap else "")+ if name == "click":+ loc = _target(s, args)+ try:+ await loc.click(timeout=15000)+ except Exception as e: # noqa: BLE001+ raise BrowserToolError(f"The click did not land: {str(e).splitlines()[0][:160]}") from None+ await _settled(s)+ return f"Clicked. Now at {await _where(s)}"+ if name == "type":+ loc = _target(s, args)+ text = str(args.get("text") or "")+ try:+ await loc.fill(text, timeout=15000)+ if args.get("submit"):+ await loc.press("Enter")+ await _settled(s)+ except Exception as e: # noqa: BLE001+ raise BrowserToolError(f"Typing failed: {str(e).splitlines()[0][:160]}") from None+ return f"Typed {len(text)} characters." + (f" Now at {await _where(s)}" if args.get("submit") else "")+ if name == "press_key":+ key = str(args.get("key") or "").strip()+ if not key:+ raise BrowserToolError("Say which key.")+ await page.keyboard.press(key)+ await _settled(s)+ return f"Pressed {key}. Now at {await _where(s)}"+ if name == "scroll":+ px = max(50, min(int(args.get("pixels") or 600), 5000))+ dy = -px if str(args.get("direction") or "down") == "up" else px+ await page.mouse.wheel(0, dy)+ return f"Scrolled {'up' if dy < 0 else 'down'} {abs(dy)} pixels."+ if name == "wait_for":+ text, selector = str(args.get("text") or "").strip(), str(args.get("selector") or "").strip()+ ms = int(args.get("ms") or 0)+ budget = int(CALL_CAP_S * 1000) - 2000+ try:+ if text:+ await page.get_by_text(text).first.wait_for(timeout=budget)+ return f"\"{text}\" is on the page."+ if selector:+ await page.locator(selector).first.wait_for(timeout=budget)+ return f"{selector} is on the page."+ except Exception: # noqa: BLE001+ raise BrowserToolError("It did not appear within the wait.") from None+ if ms > 0:+ await asyncio.sleep(min(ms, budget) / 1000)+ return f"Waited {min(ms, budget)} ms."+ raise BrowserToolError("Say what to wait for: text, a selector or a number of milliseconds.")+ if name == "screenshot":+ try:+ png = await page.screenshot(type="png", full_page=bool(args.get("full_page")))+ except Exception as e: # noqa: BLE001+ raise BrowserToolError(f"The screenshot failed: {str(e).splitlines()[0][:160]}") from None+ s.screenshots += 1+ return ("image", png, f"Screenshot of {await _where(s)}")+ if name == "back":+ try:+ await page.go_back(wait_until="domcontentloaded")+ except Exception as e: # noqa: BLE001+ raise BrowserToolError(f"Could not go back: {str(e).splitlines()[0][:160]}") from None+ return f"Back at {await _where(s)}"+ if name == "list_tabs":+ rows = []+ for i, p in enumerate(s.context.pages):+ try:+ t = await p.title()+ except Exception: # noqa: BLE001+ t = ""+ rows.append(f"{i}{' *' if p is s.page else ''} {p.url}" + (f" ({t})" if t else ""))+ return "\n".join(rows) or "(no tabs)"+ if name == "switch_tab":+ pages = s.context.pages+ i = int(args.get("index") or 0)+ if i < 0 or i >= len(pages):+ raise BrowserToolError(f"There is no tab {i}; there are {len(pages)}.")+ 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}.")+++def audit_line(d: dict) -> str:+ """The record's one-line shape, for the trace and the log."""+ return json.dumps(d, separators=(",", ":"))diff --git a/gateway/plugs_plane.py b/gateway/plugs_plane.pynew file mode 100644index 00000000..535089d4--- /dev/null+++ b/gateway/plugs_plane.py@@ -0,0 +1,850 @@+"""Plugs: the vendor tools an agent reaches through the `plugs` MCP server this gateway hosts.++A plug is a service connected once for a workspace (its GitHub repository, its Vercel project, its+InsForge backend). The registry on the engine mints and keeps the per-workspace credential; this+module is the tool surface over it: what tools each plug type offers, with the risk of each, and+how one call maps onto the vendor's API. The credential arrives as `fields` resolved by the caller+(app.py, from the org vault) at the moment of the call, is used in process, and is never returned:+every tool answers data, never the token that fetched it.++Tool names are the vendor's own where a vendor MCP server exists (GitHub's, verbatim), so an agent+package written against the vendor's server works unchanged under `github.<name>`. Vercel and+InsForge have no vendor MCP server; their surfaces are the operations a company's agents need with+a project-scoped credential, on routes verified against the live services. Nothing here creates or+deletes the tenancy itself (a repository, a project): that is the provisioner's, and a plug's+credential is scoped so it could not anyway.++Risk hints ride on every tool: `read` answers without changing anything, `write` changes the+company's own resources, `destructive` is hard to undo (a delete, a merge, a push to a shared+branch). They reach the agent as MCP tool annotations and the audit row as a column.+"""+from __future__ import annotations++import asyncio+import base64+import json+import time++import httpx++GITHUB_API = "https://api.github.com"+VERCEL_API = "https://api.vercel.com"+CALL_TIMEOUT_S = 60 # one vendor request+DEPLOY_WAIT_S = 120 # how long deploy_from_repo watches a deployment before handing back+DEPLOY_POLL_S = 5+TEXT_CAP = 200_000 # the most text one tool result carries back to the agent++# Tests set an httpx transport here so every vendor call is exercised and nothing is spent.+transport: httpx.BaseTransport | None = None+++def client() -> httpx.AsyncClient:+ return httpx.AsyncClient(timeout=CALL_TIMEOUT_S, transport=transport, follow_redirects=True)+++class PlugToolError(RuntimeError):+ """The vendor refused or the arguments do not make a call; the message is for the agent."""+++# ── the registry of tools ─────────────────────────────────────────────────────────────────────+# One plug type answers under its own name; an alias shares another's tools (the OAuth-consent+# GitHub plug carries the same `token` field as the provisioned one).+TYPES: dict[str, str] = {"github": "GitHub", "github_app": "GitHub", "vercel": "Vercel", "insforge": "InsForge",+ "browser": "Browser"}+BROWSER = "browser" # a platform plug: no customer credential; served by the gateway's browser plane+OPEN_TYPES = {BROWSER} # open to every org (Richard, 2026-09-24); the rest are held to HR_PLUGS_ORGS while verified+_ALIAS = {"github_app": "github"}+RISKS = ("read", "write", "destructive")+_TOOLS: dict[str, list[dict]] = {}+++def _tool(plug: str, name: str, risk: str, description: str, schema: dict):+ assert risk in RISKS+ if plug == "github":+ # An OAuth-consent GitHub plug may cover several repositories; every tool then takes the one+ # it means. A provisioned plug covers one and the argument is not needed.+ schema["properties"].setdefault("repo", _s("Repository as owner/name, when the plug covers several; "+ "the plug's own repository when omitted"))+ def deco(fn):+ _TOOLS.setdefault(plug, []).append({"name": name, "risk": risk, "description": description,+ "inputSchema": schema, "fn": fn})+ return fn+ return deco+++# The GitHub App permission each tool needs. A plug whose installation was not granted one says so+# on its record (config.permissions_missing), and the refusal names the grant rather than a 403.+_GITHUB_PERMISSION = {+ **{t: "contents" for t in ("get_repo", "get_file_contents", "list_branches", "list_commits", "get_commit",+ "search_code", "create_or_update_file", "push_files", "create_branch", "delete_file")},+ **{t: "issues" for t in ("list_issues", "get_issue", "get_issue_comments", "search_issues", "create_issue",+ "update_issue", "add_issue_comment")},+ **{t: "pull_requests" for t in ("list_pull_requests", "get_pull_request", "get_pull_request_files",+ "get_pull_request_diff", "create_pull_request", "update_pull_request",+ "create_pull_request_review", "merge_pull_request")},+ **{t: "actions" for t in ("list_workflows", "list_workflow_runs", "get_workflow_run", "get_job_logs",+ "run_workflow", "rerun_workflow_run", "cancel_workflow_run")},+}+++def permission_of(plug: str, name: str) -> str | None:+ """The vendor permission a tool needs, where the plug type records grants; None otherwise."""+ return _GITHUB_PERMISSION.get(name) if _ALIAS.get(plug, plug) == "github" else None+++def _obj(props: dict, required: tuple = ()) -> dict:+ return {"type": "object", "properties": props, "required": list(required), "additionalProperties": False}+++def _s(desc: str, **kw) -> dict:+ return {"type": "string", "description": desc, **kw}+++def _i(desc: str) -> dict:+ return {"type": "integer", "description": desc}+++def _b(desc: str) -> dict:+ return {"type": "boolean", "description": desc}+++def tools_of(plug: str) -> list[dict]:+ return list(_TOOLS.get(_ALIAS.get(plug, plug), []))+++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."""+ 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']}",+ "description": f"[{TYPES.get(plug, plug)}, {t['risk']}] {t['description']}",+ "inputSchema": t["inputSchema"],+ "annotations": {"readOnlyHint": t["risk"] == "read",+ "destructiveHint": t["risk"] == "destructive"}})+ return out+++def find(plug: str, name: str) -> dict | None:+ return next((t for t in tools_of(plug) if t["name"] == name), None)+++async def call(plug: str, name: str, args: dict, fields: dict, config: dict) -> str:+ """Run one tool and answer its result as text for the agent. Raises PlugToolError with the+ vendor's own sentence when the vendor refuses."""+ t = find(plug, name)+ if t is None:+ raise PlugToolError(f"No tool named {plug}.{name} on this server.")+ if not isinstance(args, dict):+ raise PlugToolError("arguments must be an object")+ async with client() as c:+ out = await t["fn"](c, fields, config, args)+ text = out if isinstance(out, str) else json.dumps(out, ensure_ascii=False, default=str)+ if len(text) > TEXT_CAP:+ text = text[:TEXT_CAP] + f"\n…[{len(text) - TEXT_CAP} more characters not shown]"+ return text+++def _pick(d, keys: tuple) -> dict:+ return {k: d.get(k) for k in keys if isinstance(d, dict) and d.get(k) is not None}+++def _need(args: dict, key: str):+ v = args.get(key)+ if v is None or v == "":+ raise PlugToolError(f"{key} is required")+ return v+++# ── GitHub: the company repository, through an installation token scoped to it ───────────────+def _gh_msg(r: httpx.Response) -> str:+ try:+ d = r.json()+ return str(d.get("message") or d)[:300] if isinstance(d, dict) else r.text[:300]+ except ValueError:+ return r.text[:300]+++async def _gh(c: httpx.AsyncClient, fields: dict, method: str, path: str, *, body=None, params=None,+ accept: str = "application/vnd.github+json", text: bool = False):+ r = await c.request(method, GITHUB_API + path, json=body, params=params,+ headers={"Authorization": f"Bearer {fields.get('token', '')}", "Accept": accept,+ "X-GitHub-Api-Version": "2022-11-28"})+ if r.status_code >= 400:+ raise PlugToolError(f"GitHub answered {r.status_code}: {_gh_msg(r)}")+ if text:+ return r.text+ return r.json() if r.content else {}+++def _repo(config: dict, args: dict | None = None) -> str:+ """The repository a call addresses: the one asked for when the plug covers several (config.repos),+ else the plug's own (config.repo). Never one outside the plug."""+ repos = [r for r in (config.get("repos") or []) if isinstance(r, str)]+ own = str(config.get("repo") or "")+ want = str((args or {}).get("repo") or "")+ if want:+ if "/" not in want or want not in (repos or [own]):+ raise PlugToolError(f"the GitHub plug does not cover {want}; it covers "+ + (", ".join(repos[:20]) if repos else (own or "no repository")))+ return want+ if "/" in own:+ return own+ if repos:+ raise PlugToolError("the GitHub plug covers several repositories; pass repo, one of " + ", ".join(repos[:20]))+ raise PlugToolError("the GitHub plug names no repository; reconnect it in the workspace's Plugs page")+++def _branch(config: dict, args: dict, key: str = "branch") -> str:+ return str(args.get(key) or config.get("default_branch") or "main")+++_ISSUE = ("number", "title", "state", "html_url", "created_at", "updated_at", "body")+_PULL = ("number", "title", "state", "html_url", "draft", "merged", "mergeable", "created_at", "updated_at", "body")+_COMMIT_KEYS = ("sha", "html_url")+++def _user(d) -> str:+ return str(((d or {}).get("user") or {}).get("login") or "")+++def _issue_out(d: dict) -> dict:+ return {**_pick(d, _ISSUE), "user": _user(d), "labels": [x.get("name") for x in d.get("labels") or [] if isinstance(x, dict)]}+++def _pull_out(d: dict) -> dict:+ return {**_pick(d, _PULL), "user": _user(d), "head": (d.get("head") or {}).get("ref"),+ "base": (d.get("base") or {}).get("ref")}+++def _commit_out(d: dict) -> dict:+ c = d.get("commit") or {}+ return {**_pick(d, _COMMIT_KEYS), "message": c.get("message"),+ "author": (c.get("author") or {}).get("name"), "date": (c.get("author") or {}).get("date")}+++@_tool("github", "get_repo", "read", "The company repository: name, default branch, visibility, url.",+ _obj({}))+async def _(c, f, cfg, a):+ d = await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}")+ return _pick(d, ("full_name", "default_branch", "private", "html_url", "description", "pushed_at", "size", "open_issues_count"))+++@_tool("github", "get_file_contents", "read",+ "Read a file (decoded text) or list a directory at a path, on a branch or commit.",+ _obj({"path": _s("File or directory path; empty for the repository root"),+ "ref": _s("Branch, tag or commit sha; the default branch when omitted")}, ("path",)))+async def _(c, f, cfg, a):+ path = str(a.get("path") or "").strip("/")+ d = await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/contents/{path}", params={"ref": a["ref"]} if a.get("ref") else None)+ if isinstance(d, list):+ return {"path": path, "entries": [_pick(e, ("name", "path", "type", "size", "sha")) for e in d]}+ if d.get("encoding") == "base64" and d.get("content") is not None:+ raw = base64.b64decode(d["content"])+ try:+ content = raw.decode("utf-8")+ except UnicodeDecodeError:+ return {**_pick(d, ("path", "sha", "size")), "binary": True}+ return {**_pick(d, ("path", "sha", "size")), "content": content}+ return _pick(d, ("path", "sha", "size", "type", "download_url"))+++@_tool("github", "list_branches", "read", "Branches of the repository with their head commits.", _obj({}))+async def _(c, f, cfg, a):+ d = await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/branches", params={"per_page": 100})+ return [{"name": b.get("name"), "sha": (b.get("commit") or {}).get("sha"), "protected": b.get("protected")} for b in d]+++@_tool("github", "list_commits", "read", "Recent commits, optionally on one branch or touching one path.",+ _obj({"sha": _s("Branch name or commit sha to start from"), "path": _s("Only commits touching this path"),+ "per_page": _i("How many, at most 100")}))+async def _(c, f, cfg, a):+ params = {k: a[k] for k in ("sha", "path") if a.get(k)}+ params["per_page"] = min(int(a.get("per_page") or 30), 100)+ return [_commit_out(x) for x in await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/commits", params=params)]+++@_tool("github", "get_commit", "read", "One commit with the files it changed.", _obj({"sha": _s("Commit sha or ref")}, ("sha",)))+async def _(c, f, cfg, a):+ d = await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/commits/{_need(a, 'sha')}")+ return {**_commit_out(d), "stats": d.get("stats"),+ "files": [_pick(x, ("filename", "status", "additions", "deletions")) for x in d.get("files") or []]}+++@_tool("github", "search_code", "read", "Search code in the repository (GitHub code search syntax).",+ _obj({"query": _s("Search terms; the repository qualifier is added for you")}, ("query",)))+async def _(c, f, cfg, a):+ d = await _gh(c, f, "GET", "/search/code", params={"q": f"{_need(a, 'query')} repo:{_repo(cfg, a)}", "per_page": 30})+ return {"total": d.get("total_count"), "items": [_pick(x, ("path", "sha", "html_url")) for x in d.get("items") or []]}+++@_tool("github", "list_issues", "read", "Issues of the repository (pull requests excluded).",+ _obj({"state": _s("open, closed or all", enum=["open", "closed", "all"]), "labels": _s("Comma-separated label names"),+ "per_page": _i("How many, at most 100")}))+async def _(c, f, cfg, a):+ params = {k: a[k] for k in ("state", "labels") if a.get(k)}+ params["per_page"] = min(int(a.get("per_page") or 30), 100)+ d = await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/issues", params=params)+ return [_issue_out(x) for x in d if "pull_request" not in x]+++@_tool("github", "get_issue", "read", "One issue.", _obj({"number": _i("Issue number")}, ("number",)))+async def _(c, f, cfg, a):+ return _issue_out(await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/issues/{int(_need(a, 'number'))}"))+++@_tool("github", "get_issue_comments", "read", "Comments on an issue or pull request.",+ _obj({"number": _i("Issue or pull request number")}, ("number",)))+async def _(c, f, cfg, a):+ d = await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/issues/{int(_need(a, 'number'))}/comments", params={"per_page": 100})+ return [{**_pick(x, ("id", "body", "created_at", "html_url")), "user": _user(x)} for x in d]+++@_tool("github", "search_issues", "read", "Search issues and pull requests in the repository.",+ _obj({"query": _s("Search terms; the repository qualifier is added for you")}, ("query",)))+async def _(c, f, cfg, a):+ d = await _gh(c, f, "GET", "/search/issues", params={"q": f"{_need(a, 'query')} repo:{_repo(cfg, a)}", "per_page": 30})+ return {"total": d.get("total_count"), "items": [_issue_out(x) for x in d.get("items") or []]}+++@_tool("github", "list_pull_requests", "read", "Pull requests of the repository.",+ _obj({"state": _s("open, closed or all", enum=["open", "closed", "all"]), "per_page": _i("How many, at most 100")}))+async def _(c, f, cfg, a):+ params = {"state": a.get("state") or "open", "per_page": min(int(a.get("per_page") or 30), 100)}+ return [_pull_out(x) for x in await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/pulls", params=params)]+++@_tool("github", "get_pull_request", "read", "One pull request.", _obj({"number": _i("Pull request number")}, ("number",)))+async def _(c, f, cfg, a):+ return _pull_out(await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/pulls/{int(_need(a, 'number'))}"))+++@_tool("github", "get_pull_request_files", "read", "Files a pull request changes.",+ _obj({"number": _i("Pull request number")}, ("number",)))+async def _(c, f, cfg, a):+ d = await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/pulls/{int(_need(a, 'number'))}/files", params={"per_page": 100})+ return [_pick(x, ("filename", "status", "additions", "deletions", "patch")) for x in d]+++@_tool("github", "get_pull_request_diff", "read", "The unified diff of a pull request.",+ _obj({"number": _i("Pull request number")}, ("number",)))+async def _(c, f, cfg, a):+ return await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/pulls/{int(_need(a, 'number'))}",+ accept="application/vnd.github.diff", text=True)+++@_tool("github", "list_workflows", "read", "GitHub Actions workflows of the repository.", _obj({}))+async def _(c, f, cfg, a):+ d = await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/actions/workflows")+ return [_pick(x, ("id", "name", "path", "state")) for x in d.get("workflows") or []]+++@_tool("github", "list_workflow_runs", "read", "Recent workflow runs, for one workflow or all.",+ _obj({"workflow_id": _s("Workflow id or file name (ci.yml); all workflows when omitted"),+ "branch": _s("Only runs on this branch"), "per_page": _i("How many, at most 100")}))+async def _(c, f, cfg, a):+ params = {"per_page": min(int(a.get("per_page") or 20), 100)}+ if a.get("branch"):+ params["branch"] = a["branch"]+ path = (f"/repos/{_repo(cfg, a)}/actions/workflows/{a['workflow_id']}/runs" if a.get("workflow_id")+ else f"/repos/{_repo(cfg, a)}/actions/runs")+ d = await _gh(c, f, "GET", path, params=params)+ return [_pick(x, ("id", "name", "head_branch", "head_sha", "status", "conclusion", "html_url", "created_at", "run_number"))+ for x in d.get("workflow_runs") or []]+++@_tool("github", "get_workflow_run", "read", "One workflow run with its jobs.", _obj({"run_id": _i("Run id")}, ("run_id",)))+async def _(c, f, cfg, a):+ rid = int(_need(a, "run_id"))+ d = await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/actions/runs/{rid}")+ jobs = await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/actions/runs/{rid}/jobs")+ return {**_pick(d, ("id", "name", "head_branch", "head_sha", "status", "conclusion", "html_url", "created_at", "updated_at")),+ "jobs": [_pick(j, ("id", "name", "status", "conclusion", "started_at", "completed_at")) for j in jobs.get("jobs") or []]}+++@_tool("github", "get_job_logs", "read", "The log of one workflow job (the tail, when long).", _obj({"job_id": _i("Job id")}, ("job_id",)))+async def _(c, f, cfg, a):+ text = await _gh(c, f, "GET", f"/repos/{_repo(cfg, a)}/actions/jobs/{int(_need(a, 'job_id'))}/logs", accept="*/*", text=True)+ return text if len(text) <= 60_000 else "…" + text[-60_000:]+++async def _gh_sha_of(c, f, repo: str, path: str, branch: str) -> str | None:+ r = await c.get(f"{GITHUB_API}/repos/{repo}/contents/{path}", params={"ref": branch},+ headers={"Authorization": f"Bearer {f.get('token', '')}", "Accept": "application/vnd.github+json"})+ if r.status_code == 404:+ return None+ if r.status_code >= 400:+ raise PlugToolError(f"GitHub answered {r.status_code}: {_gh_msg(r)}")+ d = r.json()+ return d.get("sha") if isinstance(d, dict) else None+++@_tool("github", "create_or_update_file", "write", "Create or update one file with a commit.",+ _obj({"path": _s("File path"), "content": _s("The whole file content (text)"),+ "message": _s("Commit message"), "branch": _s("Branch; the default branch when omitted"),+ "sha": _s("The file's current blob sha when updating; looked up when omitted")},+ ("path", "content", "message")))+async def _(c, f, cfg, a):+ repo, path, branch = _repo(cfg, a), str(_need(a, "path")).strip("/"), _branch(cfg, a)+ body = {"message": _need(a, "message"), "branch": branch,+ "content": base64.b64encode(str(a.get("content") or "").encode()).decode()}+ sha = a.get("sha") or await _gh_sha_of(c, f, repo, path, branch)+ if sha:+ body["sha"] = sha+ d = await _gh(c, f, "PUT", f"/repos/{repo}/contents/{path}", body=body)+ return {"path": path, "branch": branch, "sha": (d.get("content") or {}).get("sha"),+ "commit": (d.get("commit") or {}).get("sha"), "html_url": (d.get("content") or {}).get("html_url")}+++@_tool("github", "push_files", "destructive", "Commit several files to a branch at once (one commit). Prefer a branch and a pull request over a shared branch.",+ _obj({"branch": _s("Branch to commit to"), "message": _s("Commit message"),+ "files": {"type": "array", "description": "Files to write", "items": _obj({"path": _s("File path"), "content": _s("Whole file content")}, ("path", "content"))}},+ ("branch", "message", "files")))+async def _(c, f, cfg, a):+ repo, branch = _repo(cfg, a), str(_need(a, "branch"))+ files = a.get("files") or []+ if not files:+ raise PlugToolError("files is empty")+ ref = await _gh(c, f, "GET", f"/repos/{repo}/git/ref/heads/{branch}")+ head = (ref.get("object") or {}).get("sha")+ base = await _gh(c, f, "GET", f"/repos/{repo}/git/commits/{head}")+ tree = await _gh(c, f, "POST", f"/repos/{repo}/git/trees", body={+ "base_tree": (base.get("tree") or {}).get("sha"),+ "tree": [{"path": str(x["path"]).strip("/"), "mode": "100644", "type": "blob", "content": str(x.get("content") or "")}+ for x in files]})+ commit = await _gh(c, f, "POST", f"/repos/{repo}/git/commits",+ body={"message": _need(a, "message"), "tree": tree.get("sha"), "parents": [head]})+ await _gh(c, f, "PATCH", f"/repos/{repo}/git/refs/heads/{branch}", body={"sha": commit.get("sha")})+ return {"branch": branch, "commit": commit.get("sha"), "files": len(files)}+++@_tool("github", "create_branch", "write", "Create a branch from another branch (the default branch when not named).",+ _obj({"branch": _s("New branch name"), "from_branch": _s("Branch to start from")}, ("branch",)))+async def _(c, f, cfg, a):+ repo, name = _repo(cfg, a), str(_need(a, "branch"))+ src = await _gh(c, f, "GET", f"/repos/{repo}/git/ref/heads/{_branch(cfg, a, 'from_branch')}")+ d = await _gh(c, f, "POST", f"/repos/{repo}/git/refs", body={"ref": f"refs/heads/{name}", "sha": (src.get("object") or {}).get("sha")})+ return {"branch": name, "sha": (d.get("object") or {}).get("sha")}+++@_tool("github", "delete_file", "destructive", "Delete one file with a commit.",+ _obj({"path": _s("File path"), "message": _s("Commit message"), "branch": _s("Branch; the default branch when omitted"),+ "sha": _s("The file's blob sha; looked up when omitted")}, ("path", "message")))+async def _(c, f, cfg, a):+ repo, path, branch = _repo(cfg, a), str(_need(a, "path")).strip("/"), _branch(cfg, a)+ sha = a.get("sha") or await _gh_sha_of(c, f, repo, path, branch)+ if not sha:+ raise PlugToolError(f"no file at {path} on {branch}")+ d = await _gh(c, f, "DELETE", f"/repos/{repo}/contents/{path}", body={"message": _need(a, "message"), "branch": branch, "sha": sha})+ return {"path": path, "branch": branch, "commit": (d.get("commit") or {}).get("sha")}+++@_tool("github", "create_issue", "write", "Open an issue.",+ _obj({"title": _s("Title"), "body": _s("Body (markdown)"),+ "labels": {"type": "array", "items": {"type": "string"}, "description": "Label names"},+ "assignees": {"type": "array", "items": {"type": "string"}, "description": "GitHub logins"}}, ("title",)))+async def _(c, f, cfg, a):+ body = {"title": _need(a, "title"), **{k: a[k] for k in ("body", "labels", "assignees") if a.get(k)}}+ return _issue_out(await _gh(c, f, "POST", f"/repos/{_repo(cfg, a)}/issues", body=body))+++@_tool("github", "update_issue", "write", "Edit an issue's title, body, state or labels.",+ _obj({"number": _i("Issue number"), "title": _s("New title"), "body": _s("New body"),+ "state": _s("open or closed", enum=["open", "closed"]),+ "labels": {"type": "array", "items": {"type": "string"}, "description": "Label names (replaces the set)"}}, ("number",)))+async def _(c, f, cfg, a):+ body = {k: a[k] for k in ("title", "body", "state", "labels") if a.get(k) is not None}+ return _issue_out(await _gh(c, f, "PATCH", f"/repos/{_repo(cfg, a)}/issues/{int(_need(a, 'number'))}", body=body))+++@_tool("github", "add_issue_comment", "write", "Comment on an issue or pull request.",+ _obj({"number": _i("Issue or pull request number"), "body": _s("Comment (markdown)")}, ("number", "body")))+async def _(c, f, cfg, a):+ d = await _gh(c, f, "POST", f"/repos/{_repo(cfg, a)}/issues/{int(_need(a, 'number'))}/comments", body={"body": _need(a, "body")})+ return {**_pick(d, ("id", "html_url", "created_at")), "user": _user(d)}+++@_tool("github", "create_pull_request", "write", "Open a pull request from a branch.",+ _obj({"title": _s("Title"), "head": _s("Branch with the changes"), "base": _s("Branch to merge into; the default branch when omitted"),+ "body": _s("Description (markdown)"), "draft": _b("Open as a draft")}, ("title", "head")))+async def _(c, f, cfg, a):+ body = {"title": _need(a, "title"), "head": _need(a, "head"), "base": _branch(cfg, a, "base"),+ **{k: a[k] for k in ("body", "draft") if a.get(k) is not None}}+ return _pull_out(await _gh(c, f, "POST", f"/repos/{_repo(cfg, a)}/pulls", body=body))+++@_tool("github", "update_pull_request", "write", "Edit a pull request's title, body, state or base.",+ _obj({"number": _i("Pull request number"), "title": _s("New title"), "body": _s("New body"),+ "state": _s("open or closed", enum=["open", "closed"]), "base": _s("New base branch")}, ("number",)))+async def _(c, f, cfg, a):+ body = {k: a[k] for k in ("title", "body", "state", "base") if a.get(k) is not None}+ return _pull_out(await _gh(c, f, "PATCH", f"/repos/{_repo(cfg, a)}/pulls/{int(_need(a, 'number'))}", body=body))+++@_tool("github", "create_pull_request_review", "write", "Review a pull request: approve, request changes or comment.",+ _obj({"number": _i("Pull request number"), "event": _s("APPROVE, REQUEST_CHANGES or COMMENT", enum=["APPROVE", "REQUEST_CHANGES", "COMMENT"]),+ "body": _s("Review text")}, ("number", "event")))+async def _(c, f, cfg, a):+ body = {"event": _need(a, "event"), **({"body": a["body"]} if a.get("body") else {})}+ d = await _gh(c, f, "POST", f"/repos/{_repo(cfg, a)}/pulls/{int(_need(a, 'number'))}/reviews", body=body)+ return {**_pick(d, ("id", "state", "html_url", "submitted_at")), "user": _user(d)}+++@_tool("github", "merge_pull_request", "destructive", "Merge a pull request into its base branch.",+ _obj({"number": _i("Pull request number"), "merge_method": _s("merge, squash or rebase", enum=["merge", "squash", "rebase"]),+ "commit_title": _s("Title of the merge commit")}, ("number",)))+async def _(c, f, cfg, a):+ body = {k: a[k] for k in ("merge_method", "commit_title") if a.get(k)}+ d = await _gh(c, f, "PUT", f"/repos/{_repo(cfg, a)}/pulls/{int(_need(a, 'number'))}/merge", body=body)+ return _pick(d, ("sha", "merged", "message"))+++@_tool("github", "run_workflow", "write", "Dispatch a workflow run on a branch.",+ _obj({"workflow_id": _s("Workflow id or file name (ci.yml)"), "ref": _s("Branch or tag"),+ "inputs": {"type": "object", "description": "Workflow inputs", "additionalProperties": {"type": "string"}}}, ("workflow_id", "ref")))+async def _(c, f, cfg, a):+ body = {"ref": _need(a, "ref"), **({"inputs": a["inputs"]} if isinstance(a.get("inputs"), dict) else {})}+ await _gh(c, f, "POST", f"/repos/{_repo(cfg, a)}/actions/workflows/{_need(a, 'workflow_id')}/dispatches", body=body)+ return {"dispatched": True, "workflow_id": a["workflow_id"], "ref": a["ref"]}+++@_tool("github", "rerun_workflow_run", "write", "Re-run a workflow run.", _obj({"run_id": _i("Run id")}, ("run_id",)))+async def _(c, f, cfg, a):+ await _gh(c, f, "POST", f"/repos/{_repo(cfg, a)}/actions/runs/{int(_need(a, 'run_id'))}/rerun")+ return {"rerun": True, "run_id": a["run_id"]}+++@_tool("github", "cancel_workflow_run", "write", "Cancel a workflow run.", _obj({"run_id": _i("Run id")}, ("run_id",)))+async def _(c, f, cfg, a):+ await _gh(c, f, "POST", f"/repos/{_repo(cfg, a)}/actions/runs/{int(_need(a, 'run_id'))}/cancel")+ return {"cancelled": True, "run_id": a["run_id"]}+++# ── Vercel: the company project, through a project-scoped token ───────────────────────────────+def _vc_msg(r: httpx.Response) -> str:+ try:+ d = r.json()+ return str(((d.get("error") or {}).get("message")) or d)[:300] if isinstance(d, dict) else r.text[:300]+ except ValueError:+ return r.text[:300]+++async def _vc(c: httpx.AsyncClient, fields: dict, config: dict, method: str, path: str, *, body=None, params=None):+ params = {**(params or {})}+ if config.get("team_id"):+ params["teamId"] = config["team_id"]+ r = await c.request(method, VERCEL_API + path, json=body, params=params,+ headers={"Authorization": f"Bearer {fields.get('token', '')}"})+ if r.status_code >= 400:+ raise PlugToolError(f"Vercel answered {r.status_code}: {_vc_msg(r)}")+ return r.json() if r.content else {}+++def _project(config: dict) -> str:+ pid = str(config.get("project_id") or config.get("project") or "")+ if not pid:+ raise PlugToolError("the Vercel plug names no project; reconnect it in the workspace's Plugs page")+ return pid+++_DEPLOY = ("uid", "id", "url", "name", "state", "readyState", "target", "createdAt", "ready", "errorMessage", "inspectorUrl")+++def _deploy_out(d: dict) -> dict:+ out = _pick(d, _DEPLOY)+ if out.get("uid") and not out.get("id"):+ out["id"] = out.pop("uid")+ meta = d.get("meta") or {}+ for k in ("githubCommitRef", "githubCommitSha", "githubCommitMessage"):+ if meta.get(k):+ out[k] = meta[k]+ if d.get("alias"):+ out["alias"] = d["alias"]+ return out+++@_tool("vercel", "get_project", "read", "The company project: framework, linked repository, domains, latest deployment.", _obj({}))+async def _(c, f, cfg, a):+ d = await _vc(c, f, cfg, "GET", f"/v9/projects/{_project(cfg)}")+ doms = await _vc(c, f, cfg, "GET", f"/v9/projects/{_project(cfg)}/domains")+ latest = [(_deploy_out(x)) for x in d.get("latestDeployments") or []][:3]+ return {**_pick(d, ("id", "name", "framework", "nodeVersion", "rootDirectory", "updatedAt")),+ "link": _pick(d.get("link") or {}, ("type", "org", "repo", "repoId", "productionBranch")),+ "domains": [x.get("name") for x in doms.get("domains") or []], "latestDeployments": latest}+++@_tool("vercel", "list_deployments", "read", "Recent deployments with state and url.",+ _obj({"limit": _i("How many, at most 100"), "state": _s("Only this state (READY, ERROR, BUILDING, QUEUED, CANCELED)"),+ "target": _s("production or preview", enum=["production", "preview"])}))+async def _(c, f, cfg, a):+ params = {"projectId": _project(cfg), "limit": min(int(a.get("limit") or 20), 100)}+ for k in ("state", "target"):+ if a.get(k):+ params[k] = a[k]+ d = await _vc(c, f, cfg, "GET", "/v6/deployments", params=params)+ return [_deploy_out(x) for x in d.get("deployments") or []]+++@_tool("vercel", "get_deployment", "read", "One deployment: state, url, error.", _obj({"id": _s("Deployment id or url")}, ("id",)))+async def _(c, f, cfg, a):+ return _deploy_out(await _vc(c, f, cfg, "GET", f"/v13/deployments/{_need(a, 'id')}"))+++@_tool("vercel", "get_deployment_logs", "read", "Build and runtime log lines of a deployment.",+ _obj({"id": _s("Deployment id"), "limit": _i("How many lines, at most 500")}, ("id",)))+async def _(c, f, cfg, a):+ d = await _vc(c, f, cfg, "GET", f"/v3/deployments/{_need(a, 'id')}/events",+ params={"limit": min(int(a.get("limit") or 200), 500), "builds": 1, "direction": "backward"})+ rows = d if isinstance(d, list) else d.get("events") or []+ lines = []+ for e in rows:+ payload = e.get("payload") or {}+ lines.append(f"{e.get('type') or ''} {payload.get('text') or e.get('text') or ''}".strip())+ return "\n".join(lines)+++@_tool("vercel", "list_env", "read", "Environment variables of the project (names and targets, never values).", _obj({}))+async def _(c, f, cfg, a):+ d = await _vc(c, f, cfg, "GET", f"/v9/projects/{_project(cfg)}/env")+ return [_pick(x, ("id", "key", "target", "type", "updatedAt")) for x in d.get("envs") or []]+++async def _vc_link(c, f, cfg) -> dict:+ d = await _vc(c, f, cfg, "GET", f"/v9/projects/{_project(cfg)}")+ return d.get("link") or {}+++@_tool("vercel", "deploy_from_repo", "write",+ "Create a deployment from the linked GitHub repository at a ref, then watch it for up to two minutes. "+ "Returns the deployment's id, state and url; call get_deployment to keep watching a slow build.",+ _obj({"ref": _s("Branch, tag or commit; the production branch when omitted"),+ "production": _b("Deploy to production rather than as a preview"),+ "repo": _s("owner/name, when the project is not linked yet")}))+async def _(c, f, cfg, a):+ link = await _vc_link(c, f, cfg)+ src: dict = {"type": "github"}+ if link.get("repoId"):+ src["repoId"] = link["repoId"]+ elif a.get("repo") and "/" in str(a["repo"]):+ src["org"], src["repo"] = str(a["repo"]).split("/", 1)+ elif link.get("org") and link.get("repo"):+ src["org"], src["repo"] = link["org"], link["repo"]+ else:+ raise PlugToolError("the project is not linked to a repository; call link_repo first or pass repo")+ src["ref"] = str(a.get("ref") or link.get("productionBranch") or "main")+ body = {"name": str(cfg.get("project") or _project(cfg)), "project": _project(cfg), "gitSource": src}+ if a.get("production"):+ body["target"] = "production"+ d = await _vc(c, f, cfg, "POST", "/v13/deployments", body=body)+ did = d.get("id") or d.get("uid")+ started = time.monotonic()+ while did and time.monotonic() - started < DEPLOY_WAIT_S:+ if d.get("readyState") in ("READY", "ERROR", "CANCELED"):+ break+ await asyncio.sleep(DEPLOY_POLL_S)+ d = await _vc(c, f, cfg, "GET", f"/v13/deployments/{did}")+ return _deploy_out(d)+++@_tool("vercel", "link_repo", "write", "Link the project to a GitHub repository (owner/name).",+ _obj({"repo": _s("owner/name")}, ("repo",)))+async def _(c, f, cfg, a):+ d = await _vc(c, f, cfg, "POST", f"/v9/projects/{_project(cfg)}/link", body={"type": "github", "repo": _need(a, "repo")})+ return {"link": _pick(d.get("link") or d, ("type", "org", "repo", "repoId", "productionBranch"))}+++@_tool("vercel", "set_env", "write", "Set an environment variable on the project (created or replaced).",+ _obj({"key": _s("Name"), "value": _s("Value"),+ "target": {"type": "array", "items": {"type": "string", "enum": ["production", "preview", "development"]},+ "description": "Where it applies; all three when omitted"},+ "sensitive": _b("Store as a sensitive variable (never readable back)")}, ("key", "value")))+async def _(c, f, cfg, a):+ row = {"key": _need(a, "key"), "value": str(a.get("value") or ""),+ "type": "sensitive" if a.get("sensitive") else "encrypted",+ "target": a.get("target") or ["production", "preview", "development"]}+ d = await _vc(c, f, cfg, "POST", f"/v10/projects/{_project(cfg)}/env", body=[row], params={"upsert": "true"})+ created = d.get("created") or []+ return {"key": row["key"], "target": row["target"], "ids": [x.get("id") for x in created if isinstance(x, dict)]}+++@_tool("vercel", "delete_env", "destructive", "Remove an environment variable from the project.",+ _obj({"key": _s("Name")}, ("key",)))+async def _(c, f, cfg, a):+ key = _need(a, "key")+ d = await _vc(c, f, cfg, "GET", f"/v9/projects/{_project(cfg)}/env")+ ids = [x.get("id") for x in d.get("envs") or [] if x.get("key") == key]+ if not ids:+ raise PlugToolError(f"no environment variable named {key}")+ for eid in ids:+ await _vc(c, f, cfg, "DELETE", f"/v9/projects/{_project(cfg)}/env/{eid}")+ return {"key": key, "removed": len(ids)}+++@_tool("vercel", "create_deploy_hook", "write", "Create a deploy hook url for a branch.",+ _obj({"name": _s("Hook name"), "ref": _s("Branch the hook deploys")}, ("name", "ref")))+async def _(c, f, cfg, a):+ d = await _vc(c, f, cfg, "POST", f"/v1/projects/{_project(cfg)}/deploy-hooks", body={"name": _need(a, "name"), "ref": _need(a, "ref")})+ hooks = (d.get("link") or {}).get("deployHooks") or d.get("deployHooks") or []+ mine = next((h for h in hooks if h.get("name") == a["name"] and h.get("ref") == a["ref"]), hooks[-1] if hooks else d)+ return _pick(mine, ("id", "name", "ref", "url", "createdAt"))+++@_tool("vercel", "cancel_deployment", "write", "Cancel a deployment that is building.", _obj({"id": _s("Deployment id")}, ("id",)))+async def _(c, f, cfg, a):+ return _deploy_out(await _vc(c, f, cfg, "PATCH", f"/v12/deployments/{_need(a, 'id')}/cancel"))+++# ── InsForge: the company backend, through its project key ───────────────────────────────────+# Routes are the ones verified against a live project (health, auth users, database tables and+# records); anything else the backend serves under /api/ goes through `request`, so a verified+# route the agent knows is reachable without this file guessing its shape.+def _inf_base(config: dict) -> str:+ url = str(config.get("url") or "").rstrip("/")+ if not url.startswith("http"):+ raise PlugToolError("the InsForge plug names no backend url; reconnect it in the workspace's Plugs page")+ return url+++async def _inf(c: httpx.AsyncClient, fields: dict, config: dict, method: str, path: str, *, body=None, params=None,+ prefer: str | None = None):+ if not path.startswith("/api/"):+ raise PlugToolError("path must start with /api/")+ headers = {"Authorization": f"Bearer {fields.get('api_key', '')}"}+ if prefer:+ headers["Prefer"] = prefer+ r = await c.request(method, _inf_base(config) + path, json=body, params=params, headers=headers)+ if r.status_code >= 400:+ raise PlugToolError(f"InsForge answered {r.status_code}: {r.text[:300]}")+ if not r.content:+ return {}+ try:+ return r.json()+ except ValueError:+ return r.text+++def _filters(a: dict) -> dict:+ """PostgREST filters as query parameters: {"status": "eq.open", "age": "gte.18"}."""+ flt = a.get("filters") or {}+ if not isinstance(flt, dict) or not all(isinstance(v, str) and "." in v for v in flt.values()):+ raise PlugToolError('filters must be an object of column: "operator.value" (eq.open, gte.18, like.*x*)')+ return dict(flt)+++@_tool("insforge", "get_project", "read", "The company backend: url, project, health, public anon key.", _obj({}))+async def _(c, f, cfg, a):+ try:+ health = await _inf(c, f, cfg, "GET", "/api/health")+ except PlugToolError as e:+ health = {"error": str(e)}+ return {**_pick(cfg, ("project", "project_id", "url", "region")), "anon_key": f.get("anon_key") or None, "health": health}+++@_tool("insforge", "list_tables", "read", "Tables in the company database.", _obj({}))+async def _(c, f, cfg, a):+ return await _inf(c, f, cfg, "GET", "/api/database/tables")+++@_tool("insforge", "describe_table", "read", "Columns of one table.", _obj({"table": _s("Table name")}, ("table",)))+async def _(c, f, cfg, a):+ return await _inf(c, f, cfg, "GET", f"/api/database/tables/{_need(a, 'table')}")+++@_tool("insforge", "query_rows", "read", "Read rows of a table with optional column selection, filters, order and limit.",+ _obj({"table": _s("Table name"), "select": _s("Columns, comma-separated; all when omitted"),+ "filters": {"type": "object", "description": 'Column filters, "operator.value" each (eq.open, gte.18, like.*x*)',+ "additionalProperties": {"type": "string"}},+ "order": _s("Column with direction, e.g. created_at.desc"), "limit": _i("At most this many rows (default 100)"),+ "offset": _i("Skip this many rows")}, ("table",)))+async def _(c, f, cfg, a):+ params = {**_filters(a), "limit": min(int(a.get("limit") or 100), 1000)}+ for k in ("select", "order", "offset"):+ if a.get(k) not in (None, ""):+ params[k] = a[k]+ return await _inf(c, f, cfg, "GET", f"/api/database/records/{_need(a, 'table')}", params=params)+++@_tool("insforge", "create_table", "write", "Create a table. id, created_at and updated_at are added for you.",+ _obj({"table": _s("Table name"),+ "columns": {"type": "array", "description": "Columns",+ "items": _obj({"name": _s("Column name"),+ "type": _s("string, integer, boolean, uuid, datetime, float or json",+ enum=["string", "integer", "boolean", "uuid", "datetime", "float", "json"]),+ "nullable": _b("May be null (default true)"), "unique": _b("Unique (default false)")},+ ("name", "type"))}}, ("table", "columns")))+async def _(c, f, cfg, a):+ cols = [{"columnName": x["name"], "type": x["type"], "isNullable": x.get("nullable", True) is not False,+ "isUnique": bool(x.get("unique"))} for x in a.get("columns") or []]+ if not cols:+ raise PlugToolError("columns is empty")+ return await _inf(c, f, cfg, "POST", "/api/database/tables", body={"tableName": _need(a, "table"), "columns": cols})+++@_tool("insforge", "delete_table", "destructive", "Drop a table and every row in it.", _obj({"table": _s("Table name")}, ("table",)))+async def _(c, f, cfg, a):+ return await _inf(c, f, cfg, "DELETE", f"/api/database/tables/{_need(a, 'table')}") or {"deleted": a["table"]}+++@_tool("insforge", "insert_rows", "write", "Insert rows into a table.",+ _obj({"table": _s("Table name"), "rows": {"type": "array", "items": {"type": "object"}, "description": "Row objects"}},+ ("table", "rows")))+async def _(c, f, cfg, a):+ rows = a.get("rows") or []+ if not isinstance(rows, list) or not rows:+ raise PlugToolError("rows must be a non-empty array of objects")+ return await _inf(c, f, cfg, "POST", f"/api/database/records/{_need(a, 'table')}", body=rows, prefer="return=representation")+++@_tool("insforge", "update_rows", "write", "Update the rows a filter selects.",+ _obj({"table": _s("Table name"), "filters": {"type": "object", "description": 'Which rows, "operator.value" each',+ "additionalProperties": {"type": "string"}},+ "values": {"type": "object", "description": "Columns to set"}}, ("table", "filters", "values")))+async def _(c, f, cfg, a):+ flt = _filters(a)+ if not flt:+ raise PlugToolError("filters must select the rows to update")+ if not isinstance(a.get("values"), dict) or not a["values"]:+ raise PlugToolError("values must be a non-empty object")+ return await _inf(c, f, cfg, "PATCH", f"/api/database/records/{_need(a, 'table')}", body=a["values"], params=flt,+ prefer="return=representation")+++@_tool("insforge", "delete_rows", "destructive", "Delete the rows a filter selects.",+ _obj({"table": _s("Table name"), "filters": {"type": "object", "description": 'Which rows, "operator.value" each',+ "additionalProperties": {"type": "string"}}}, ("table", "filters")))+async def _(c, f, cfg, a):+ flt = _filters(a)+ if not flt:+ raise PlugToolError("filters must select the rows to delete")+ return await _inf(c, f, cfg, "DELETE", f"/api/database/records/{_need(a, 'table')}", params=flt, prefer="return=representation")+++@_tool("insforge", "create_user", "write", "Create a sign-in user on the company backend.",+ _obj({"email": _s("Email"), "password": _s("Password")}, ("email", "password")))+async def _(c, f, cfg, a):+ d = await _inf(c, f, cfg, "POST", "/api/auth/users", body={"email": _need(a, "email"), "password": _need(a, "password")})+ return _pick(d if isinstance(d, dict) else {}, ("id", "email", "created_at", "createdAt", "user")) or d+++@_tool("insforge", "request", "write",+ "Call any route of the company backend under /api/ (storage, functions, auth, secrets) with the project key. "+ "GET reads; other methods change things.",+ _obj({"method": _s("GET, POST, PUT, PATCH or DELETE", enum=["GET", "POST", "PUT", "PATCH", "DELETE"]),+ "path": _s("Route, starting with /api/"), "body": {"description": "JSON body"},+ "params": {"type": "object", "description": "Query parameters", "additionalProperties": {"type": "string"}}},+ ("method", "path")))+async def _(c, f, cfg, a):+ return await _inf(c, f, cfg, str(_need(a, "method")).upper(), str(_need(a, "path")), body=a.get("body"),+ params=a.get("params") or None)+++# The browser plug's tools come from its own plane; a page action is a write, a look is a read.+import browser_plane as _browser_plane # noqa: E402++for _t in _browser_plane._TOOLS:+ _TOOLS.setdefault(BROWSER, []).append({"name": _t["name"], "risk": "write" if _t["risk"] == "act" else "read",+ "description": _t["description"], "inputSchema": _t["inputSchema"], "fn": None})diff --git a/gateway/tests/test_browser.py b/gateway/tests/test_browser.pynew file mode 100644index 00000000..1c6f6d38--- /dev/null+++ b/gateway/tests/test_browser.py@@ -0,0 +1,698 @@+"""The browser plug on the hosted gateway: a workspace connects it once (a Plug record of type+browser, platform auth, its site lists), a harness includes it like any plug, and the agent gets a+cloud browser over CDP as typed tools on the plugs server.++Every request goes through the real app with local backing; the plug registry and the vendor are+httpx MockTransports and the browser is a fake that answers the shapes the tools read and routes+every request through the same gate a real context would. What is asserted is what a caller+receives, what the vendor was sent, what was written down, and what was metered. The vendor key+and the CDP address are sentinels: the last test asserts they appear in no response the agent+could read.+"""+from __future__ import annotations++import asyncio+import base64+import json+import os+import sys+import urllib.parse+import zlib+from pathlib import Path++import httpx+import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import app as gw # noqa: E402+import browser_plane # noqa: E402+import plugs_plane # noqa: E402+from fastapi.testclient import TestClient # noqa: E402++ORG = "browserorg"+WS = "browserorg__hrws1"+HEADERS = {"x-harness-internal": "test-internal-key", "x-harness-org": ORG,+ "x-harness-member": "m@browser", "x-harness-workspace": WS}+VENDOR_KEY = "bu_SENTINEL_never_returned_5e5e"+CDP = "wss://cdp.example/SENTINEL_never_returned_9d9d"+PLUGIN_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"+TENANT = "browserorg-1a2b3c4d"+_seen: list[str] = []+++def _png(w: int = 2, h: int = 2) -> bytes:+ """A real PNG, the smallest that verifies: the screenshot the fake page takes."""+ raw = b"".join(b"\x00" + b"\x10\x20\x30" * w for _ in range(h))++ def chunk(t: bytes, d: bytes) -> bytes:+ return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big")+ ihdr = w.to_bytes(4, "big") + h.to_bytes(4, "big") + b"\x08\x02\x00\x00\x00"+ return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")+++def _record(status: str = "connected", allow=None, deny=None, version: int = 1) -> dict:+ """The engine's record for a workspace's browser plug: platform auth, nothing in the vault."""+ return {"id": "plug.browser1", "org_id": ORG, "workspace": WS, "type": "browser", "status": status,+ "effective_status": status, "source": "platform", "vault_tenant": TENANT, "key_refs": [],+ "config": {"allow_domains": allow or [], "deny_domains": deny or [], "proxy": False},+ "version": version, "expires_at": ""}+++class Registry:+ """The engine's read door: the workspace's browser record, or 404."""++ def __init__(self):+ self.record: dict | None = None+ self.reads = 0+ self.any_workspace = False++ def handle(self, r: httpx.Request) -> httpx.Response:+ assert r.url.path == "/v1/plugs/by" and r.method == "GET", r.url+ assert r.headers.get("X-Internal-Key") == "test-internal-key"+ self.reads += 1+ if self.record and (self.any_workspace or r.url.params.get("workspace") == WS) and r.url.params.get("type") == "browser":+ ws = r.url.params.get("workspace")+ return httpx.Response(200, json={**self.record, "workspace": ws, "org_id": ws.split("__")[0]})+ return httpx.Response(404, json={"detail": "no such plug"})+++class Vendor:+ """Browser Use Cloud's v4 browsers API: create, stop, read."""++ def __init__(self):+ self.calls: list[httpx.Request] = []+ self.created: list[dict] = []+ self.stopped: list[str] = []+ self.refuse: int | None = None # 402 or 429 on the next create+ self.cost = 0.000667 # what a stopped session reports++ def handle(self, r: httpx.Request) -> httpx.Response:+ self.calls.append(r)+ assert r.headers.get("X-Browser-Use-API-Key") == VENDOR_KEY, "the vendor key, never anything else"+ if r.url.path == "/api/v4/browsers" and r.method == "POST":+ if self.refuse:+ code, self.refuse = self.refuse, None+ return httpx.Response(code, json={"detail": "no"})+ body = json.loads(r.content)+ self.created.append(body)+ bid = f"bu_{len(self.created)}"+ return httpx.Response(201, json={"id": bid, "cdpUrl": CDP, "liveUrl": "https://live.example/x",+ "status": "active", "timeoutAt": "2026-09-24T22:00:00Z"})+ if r.url.path.startswith("/api/v4/browsers/") and r.method == "PATCH":+ bid = r.url.path.rsplit("/", 1)[1]+ assert json.loads(r.content) == {"action": "stop"}+ self.stopped.append(bid)+ return httpx.Response(200, json={"id": bid, "status": "stopped", "browserCost": self.cost,+ "proxyCost": 0, "proxyUsedMb": 0})+ return httpx.Response(404, json={"detail": f"no mock for {r.method} {r.url.path}"})+++class Route:+ def __init__(self):+ self.aborted = None++ async def abort(self, why):+ self.aborted = why++ async def continue_(self):+ self.aborted = None+++class Req:+ def __init__(self, url):+ self.url = url+++class Locator:+ def __init__(self, page, sel):+ self.page, self.sel, self.first = page, sel, self++ async def click(self, timeout=None):+ if self.sel not in self.page.dom:+ raise RuntimeError(f"Timeout 15000ms exceeded waiting for {self.sel}")+ target = self.page.dom[self.sel].get("href")+ self.page.clicks.append(self.sel)+ if target:+ await self.page.goto(target)++ async def fill(self, text, timeout=None):+ if self.sel not in self.page.dom:+ raise RuntimeError(f"Timeout 15000ms exceeded waiting for {self.sel}")+ self.page.dom[self.sel]["value"] = text++ async def press(self, key):+ self.page.pressed.append(key)++ async def inner_text(self):+ if self.sel == "body":+ return self.page.text+ if self.sel not in self.page.dom:+ raise RuntimeError(f"Timeout 30000ms exceeded waiting for {self.sel}")+ return self.page.dom[self.sel].get("name", "")++ async def wait_for(self, timeout=None):+ if self.sel != "body" and self.sel not in self.page.dom:+ raise RuntimeError("Timeout")+++class Keyboard:+ def __init__(self, page):+ self.page = page++ async def press(self, key):+ self.page.pressed.append(key)+++class Mouse:+ def __init__(self):+ self.wheels = []++ async def wheel(self, dx, dy):+ self.wheels.append((dx, dy))+++class Page:+ """A page whose DOM is a dict of selector -> element; navigation goes through the context's+ route handler exactly as Chromium would put every request through it."""++ def __init__(self, ctx):+ self.ctx, self.url, self.dom, self.text = ctx, "about:blank", {}, ""+ self.clicks, self.pressed, self.history = [], [], []+ self.keyboard, self.mouse = Keyboard(self), Mouse()+ self.slow = 0.0++ def set_default_timeout(self, ms):+ pass++ async def goto(self, url, wait_until=None):+ if self.slow:+ await asyncio.sleep(self.slow)+ u = urllib.parse.urlsplit(url)+ url = urllib.parse.urlunsplit(u._replace(path=u.path or "/")) # Chromium's own normalisation+ route = Route()+ await self.ctx.handler(route, Req(url))+ if route.aborted:+ raise RuntimeError(f"net::ERR_BLOCKED_BY_CLIENT at {url}")+ self.history.append(self.url)+ self.url = url+ self.dom = dict(SITES.get(url, {}).get("dom", {}))+ self.text = SITES.get(url, {}).get("text", "")++ async def go_back(self, wait_until=None):+ if not self.history:+ raise RuntimeError("no history")+ await self.goto(self.history.pop())++ async def title(self):+ return SITES.get(self.url, {}).get("title", "")++ async def evaluate(self, js, arg=None):+ rows = []+ for n, (sel, el) in enumerate(self.dom.items(), start=1):+ if n > arg:+ rows.append({"truncated": True})+ break+ rows.append({"ref": f"e{n}", "role": el.get("role", "link"), "name": el.get("name", ""),+ **({"href": el["href"]} if el.get("href") else {}),+ **({"value": el["value"]} if "value" in el else {})})+ el["ref"] = f"e{n}"+ return rows++ def locator(self, sel):+ ref = sel[len('[data-hr-ref="'):-2] if sel.startswith('[data-hr-ref="') else ""+ if ref:+ sel = next((s for s, el in self.dom.items() if el.get("ref") == ref), sel)+ return Locator(self, sel)++ def get_by_text(self, text):+ return Locator(self, "body" if text in self.text else "__absent__")++ async def wait_for_load_state(self, state):+ pass++ async def screenshot(self, type="png", full_page=False):+ return _png()+++class Context:+ def __init__(self, browser, **kw):+ self.browser, self.kw, self.pages, self.handler, self.closed = browser, kw, [], None, False++ async def route(self, pattern, handler):+ self.handler = handler++ async def new_page(self):+ p = Page(self)+ self.pages.append(p)+ return p++ async def close(self):+ self.closed = True+++class Browser:+ def __init__(self, cdp):+ self.cdp, self.contexts, self.closed = cdp, [], False++ async def new_context(self, **kw):+ c = Context(self, **kw)+ self.contexts.append(c)+ return c++ async def close(self):+ self.closed = True+++SITES = {+ "https://example.com/": {"title": "Example Domain", "text": "Example Domain\nThis domain is for examples.\nMore information...",+ "dom": {"a.more": {"role": "link", "name": "More information...", "href": "https://www.iana.org/domains/example"},+ "input#q": {"role": "textbox", "name": "Search", "value": ""}}},+ "https://www.iana.org/domains/example": {"title": "Example Domains", "text": "Example Domains\nAs described in RFC 2606.",+ "dom": {"a.home": {"role": "link", "name": "Home", "href": "https://www.iana.org/"}}},+ "https://public.example/leak": {"title": "Leak", "text": "", "dom": {"img": {"role": "img", "name": "", "href": "http://10.0.0.5/secret.png"}}},+}+browsers: list[Browser] = []+++async def _connect(cdp):+ b = Browser(cdp)+ browsers.append(b)+ return b++[email protected](scope="module")+def client():+ with TestClient(gw.app) as c:+ yield c+++def world(monkeypatch):+ reg, ven, posted = Registry(), Vendor(), []+ rc = httpx.AsyncClient(transport=httpx.MockTransport(reg.handle))+ monkeypatch.setattr(gw, "PLUGS_REGISTRY_URL", "https://registry.example")+ monkeypatch.setattr(gw, "_PLUGS_ORGS", {ORG})+ monkeypatch.setattr(gw, "_client", lambda: rc)+ monkeypatch.setattr(browser_plane, "API_KEY", VENDOR_KEY)+ monkeypatch.setattr(browser_plane, "transport", httpx.MockTransport(ven.handle))+ monkeypatch.setattr(browser_plane, "connector", _connect)+ # names resolve without the network: one internal name, the rest public+ monkeypatch.setattr(browser_plane, "resolves_private", _resolves)+ monkeypatch.setattr(gw, "_report_usage", lambda org, metric, amount, **kw: posted.append((org, metric, amount, kw)))+ browsers.clear()+ for s in list(browser_plane.sessions().values()):+ s.closed = True+ browser_plane.sessions().clear()+ yield reg, ven, posted+ asyncio.run(rc.aclose())+++async def _resolves(host: str) -> bool:+ return host in ("intranet.example",) or browser_plane._ip_private(host)+++def _post(client, path, body=None, headers=None):+ r = client.post(path, json=body, headers={**HEADERS, **(headers or {})})+ _seen.append(r.text)+ return r+++def _get(client, path, headers=None):+ r = client.get(path, headers={**HEADERS, **(headers or {})})+ _seen.append(r.text)+ return r+++def _harness(client, headers=None, **extra) -> str:+ return _post(client, "/v1/harnesses", {"name": "Browsing", "base": "claude-code", **extra}, headers).json()["id"]+++def _key(hid: str) -> str:+ return gw._hosted_secret_key(hid, "mcp.plugs")+++def _include(client, hid: str, plugs=("browser",)) -> dict:+ r = _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": list(plugs)})+ assert r.status_code == 200, r.text+ return r.json()+++def _rpc(client, tok: str, method: str, params: dict | None = None, rid=1):+ r = client.post("/v1/mcp/plugs", headers={"authorization": f"Bearer {tok}"},+ json={"jsonrpc": "2.0", "id": rid, "method": method, "params": params or {}})+ _seen.append(r.text)+ return r.json().get("result") if r.status_code == 200 else r+++def _call(client, tok, name, **args):+ return _rpc(client, tok, "tools/call", {"name": f"browser.{name}", "arguments": args})+++def _rows(hid: str) -> list[dict]:+ rows = [r for r in asyncio.run(gw.BACKING.graph.find("PlugCall", {"harness": hid})) if r.get("plug") == "browser"]+ # by end time; on a same-millisecond tie the row that STARTED first (the session's) sorts last+ return sorted(rows, key=lambda r: (int(r["finished"]), -int(r["started"])))+++def _session_of(hid: str, org: str = ORG) -> str:+ sid = "sess_" + os.urandom(6).hex()+ asyncio.run(gw._vg_upsert("HarnessSession", sid, {"tenant": org, "status": "idle", "turn_status": "idle", "harness_id": hid}))+ return sid+++# ── the include and the workspace's record ───────────────────────────────────────────────────+def test_a_harness_includes_the_browser_like_any_plug_and_the_workspace_must_have_connected_it(client, world):+ reg, ven, _ = world+ hid = _harness(client)+ # no include: the plugs server lists nothing of the browser's+ other = _harness(client)+ _include(client, other, ("github",))+ tok_other = gw._mint_hosted_cred(other, "sess0", _key(other))+ assert not [t for t in _rpc(client, tok_other, "tools/list")["tools"] if t["name"].startswith("browser.")]+ # the include, with the workspace not yet connected: attached, status missing, a call refused+ d = _include(client, hid)+ assert d["plugs"] == ["browser"] and d["status"] == {"browser": "missing"}+ assert d["workspace"] == WS and d["id"] == "mcp.plugs"+ assert _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]")+ 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"+ # connected, then turned off by the workspace+ reg.record = _record()+ assert _get(client, f"/v1/harnesses/{hid}/servers/mcp.plugs").json()["status"] == {"browser": "connected"}+ reg.record = _record("disabled")+ out = _call(client, tok, "navigate", url="https://example.com/")+ assert out["isError"] and "turned off" in out["content"][0]["text"] and ven.created == []+ # a narrowed include lists only the named tools+ r = _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"]+ r = _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["browser"], "tools": {"browser": ["evaluate"]}})+ assert r.status_code == 400 and "evaluate" in r.text+++# ── the agent's session, priced, metered, stopped ────────────────────────────────────────────+def test_a_turn_browses_and_the_session_is_priced_metered_and_stopped(client, world):+ 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))+ assert _rpc(client, tok, "initialize")["serverInfo"]["name"] == "plugs"++ # the first call opens the browser: the vendor is asked for a bare session, the estimate is reserved+ out = _call(client, tok, "navigate", url="example.com")+ assert out["isError"] is False, out+ text = out["content"][0]["text"]+ assert text.startswith("Opened https://example.com/ (Example Domain)") and 'e1 link "More information..." href=https://www.iana.org/domains/example' in text+ assert ven.created == [{"timeout": 20, "proxyCountryCode": None, "solveCaptchas": False, "enableRecording": False,+ "metadata": {"harness": hid, "session": sid}}]+ assert browsers[-1].cdp == CDP and browsers[-1].contexts[0].kw == {"accept_downloads": False, "viewport": {"width": 1280, "height": 800}}++ assert _call(client, tok, "get_url")["content"][0]["text"] == "https://example.com/ (Example Domain)"+ snap = _call(client, tok, "snapshot")["content"][0]["text"]+ assert 'e2 textbox "Search" value=""' in snap+ out = _call(client, tok, "type", ref="e2", text="hello")+ assert out["content"][0]["text"] == "Typed 5 characters."+ assert 'value="hello"' in _call(client, tok, "snapshot")["content"][0]["text"]+ out = _call(client, tok, "click", ref="e1")+ assert out["content"][0]["text"] == "Clicked. Now at https://www.iana.org/domains/example (Example Domains)"+ assert _call(client, tok, "extract_text")["content"][0]["text"] == "Example Domains\nAs described in RFC 2606."+ assert _call(client, tok, "extract_text", max_chars=200, selector="a.home")["content"][0]["text"] == "Home"+ assert _call(client, tok, "back")["content"][0]["text"] == "Back at https://example.com/ (Example Domain)"+ assert _call(client, tok, "scroll", pixels=300)["content"][0]["text"] == "Scrolled down 300 pixels."+ assert _call(client, tok, "press_key", key="Escape")["content"][0]["text"].startswith("Pressed Escape.")+ assert _call(client, tok, "wait_for", text="examples")["content"][0]["text"] == '"examples" is on the page.'+ assert _call(client, tok, "wait_for", ms=10)["content"][0]["text"] == "Waited 10 ms."+ assert _call(client, tok, "list_tabs")["content"][0]["text"] == "0 * https://example.com/ (Example Domain)"+ out = _call(client, tok, "switch_tab", index=3)+ assert out["isError"] and "no tab 3" in out["content"][0]["text"]+ out = _call(client, tok, "click", selector="button.absent")+ assert out["isError"] and out["content"][0]["text"].startswith("The click did not land")++ # a screenshot: shown to the agent and kept as the session's media, served by the bytes route+ out = _call(client, tok, "screenshot")+ assert out["isError"] is False and out["content"][0]["type"] == "image" and out["content"][0]["mimeType"] == "image/png"+ assert base64.b64decode(out["content"][0]["data"]) == _png()+ note = out["content"][1]["text"]+ assert note.startswith("Screenshot of https://example.com/") and "/servers/mcp.plugs/sessions/" in note+ path = note.split("as ", 1)[1].strip()+ r = client.get(path, headers=HEADERS)+ assert r.status_code == 200 and r.headers["content-type"].startswith("image/png") and r.content == _png()+ # the same bytes are not served through a media entry that is not on this harness+ assert client.get(path.replace("mcp.plugs", "mcp.media"), headers=HEADERS).status_code == 404++ # every call is written down as a plug call; the money has not been metered yet (the session runs)+ rows = _rows(hid)+ assert rows[0]["tool"] == "open" and rows[0]["unit"] == "call" and json.loads(rows[0]["detail"])["estimate_usd"] == 0.006667+ assert [r["tool"] for r in rows[1:6]] == ["navigate", "get_url", "snapshot", "type", "snapshot"]+ assert all(r["session"] == sid and r["org"] == ORG and r["workspace"] == WS and r["plug"] == "browser" for r in rows)+ shot = next(r for r in rows if r["tool"] == "screenshot")+ assert shot["unit"] == "screenshot" and shot["usd"] == "0.0" and shot["outcome"] == "ok"+ bad = next(r for r in rows if r["tool"] == "click" and r["outcome"] == "error")+ assert bad["error"].startswith("The click did not land")+ assert [p[1] for p in posted] == ["plug.call"] * 18 and ven.stopped == []++ # the turn ends: the vendor is told to stop, the session row carries its minutes and the+ # vendor's dollars, and that is what the meter posts+ asyncio.run(gw._browser_close(sid, "turn_end"))+ assert ven.stopped == ["bu_1"] and browsers[-1].closed and browsers[-1].contexts[0].closed+ end = _rows(hid)[-1]+ assert end["tool"] == "session" and end["unit"] == "browser.usd" and end["usd"] == "0.000667" and end["outcome"] == "ok"+ detail = json.loads(end["detail"])+ assert detail["reason"] == "turn_end" and detail["minutes"] == 1 and detail["usd_source"] == "vendor" and detail["calls"] == 17+ assert detail["vendor_session"] == "bu_1"+ # the estimate and what the vendor did not charge are on the row, for the record+ assert detail["reserved_usd"] == 0.006667 and detail["released_usd"] == 0.006+ assert posted[-1] == (ORG, "browser.usd", 0.000667, {"workspace": WS, "task_id": sid, "harness_id": hid, "title": "Browser", "harness_name": "Browser"})+ assert sid not in browser_plane.sessions()+ # closing again is nothing; a later call opens a new browser+ asyncio.run(gw._browser_close(sid, "turn_end"))+ assert len(ven.stopped) == 1+ assert _call(client, tok, "get_url")["isError"] is False and len(ven.created) == 2+ asyncio.run(gw._browser_close(sid, "turn_end"))+++def test_the_vendor_figure_missing_bills_the_table(client, world):+ reg, ven, posted = world+ reg.record = _record()+ ven.cost = None+ hid = _harness(client)+ _include(client, hid)+ sid = _session_of(hid)+ tok = gw._mint_hosted_cred(hid, sid, _key(hid))+ assert _call(client, tok, "navigate", url="https://example.com/")["isError"] is False+ asyncio.run(gw._browser_close(sid, "turn_end"))+ end = _rows(hid)[-1]+ assert end["unit"] == "browser.usd" and end["usd"] == "0.000333" and json.loads(end["detail"])["usd_source"] == "table"+ assert posted[-1][1:3] == ("browser.usd", 0.000333)+++# ── the guards ───────────────────────────────────────────────────────────────────────────────+def test_private_and_disallowed_addresses_are_refused_for_pages_and_their_requests(client, world):+ reg, ven, _ = world+ reg.record = _record(deny=["iana.org"])+ hid = _harness(client)+ _include(client, hid)+ sid = _session_of(hid)+ tok = gw._mint_hosted_cred(hid, sid, _key(hid))+ for url, why in [("http://127.0.0.1:8080/admin", "private or local"), ("http://169.254.169.254/latest/meta-data", "private or local"),+ ("http://10.0.0.5/", "private or local"), ("http://localhost/", "private or local"),+ ("http://vault.internal/", "private or local"), ("http://intranet.example/", "private or local"),+ ("http://[::1]/", "private or local"), ("ftp://example.com/", "ftp address"),+ ("https://www.iana.org/", "not allowed to visit")]:+ out = _call(client, tok, "navigate", url=url)+ assert out["isError"] and why in out["content"][0]["text"], (url, out)+ assert len(ven.created) == 1 # one browser opened, then every refusal happened here, before any request+ # a page's own request to a private address is aborted by the context gate+ assert _call(client, tok, "navigate", url="https://public.example/leak")["isError"] is False+ out = _call(client, tok, "click", ref="e1") # the "image" link into 10.0.0.5+ assert out["isError"] and "ERR_BLOCKED_BY_CLIENT" in out["content"][0]["text"]+ ctx = browsers[-1].contexts[0]+ route = Route()+ asyncio.run(ctx.handler(route, Req("http://10.0.0.5/secret.png")))+ assert route.aborted == "blockedbyclient"+ route = Route()+ asyncio.run(ctx.handler(route, Req("https://cdn.public.example/a.css")))+ assert route.aborted is None+ # the workspace changes its lists: the next call sees them, on the same browser+ reg.record = _record(allow=["example.com"], version=2)+ out = _call(client, tok, "navigate", url="https://public.example/leak")+ assert out["isError"] and "outside the ones" in out["content"][0]["text"]+ assert _call(client, tok, "navigate", url="https://example.com/")["isError"] is False and len(ven.created) == 1+ asyncio.run(gw._browser_close(sid, "turn_end"))+ assert json.loads(_rows(hid)[-1]["detail"])["blocked"] == ["10.0.0.5"]+++def test_caps_and_the_vendor_saying_no(client, world, monkeypatch):+ reg, ven, _ = world+ reg.record = _record()+ hid = _harness(client)+ _include(client, hid)+ sid = _session_of(hid)+ tok = gw._mint_hosted_cred(hid, sid, _key(hid))+ # the vendor's wallet and its concurrency, in the agent's words+ ven.refuse = 402+ out = _call(client, tok, "navigate", url="https://example.com/")+ assert out["isError"] and "no credit left" in out["content"][0]["text"]+ ven.refuse = 429+ out = _call(client, tok, "navigate", url="https://example.com/")+ assert out["isError"] and "Every browser is in use" in out["content"][0]["text"]+ assert [r["error"] for r in _rows(hid)[-2:]] == ["vendor_credits", "vendor_busy"]+ # the per-call cap+ monkeypatch.setattr(browser_plane, "CALL_CAP_S", 0.2)+ assert _call(client, tok, "navigate", url="https://example.com/")["isError"] is False+ browsers[-1].contexts[0].pages[0].slow = 1.0+ out = _call(client, tok, "navigate", url="https://example.com/")+ assert out["isError"] and "longer than" in out["content"][0]["text"]+ assert _rows(hid)[-1]["error"] == "timeout"+ monkeypatch.setattr(browser_plane, "CALL_CAP_S", 60.0)+ # idle and the session cap are found by the reaper, and each stop is in the trail+ s = browser_plane.sessions()[sid]+ s.last_used -= browser_plane.IDLE_S + 1+ assert [(x.sid, why) for x, why in browser_plane.expired_sessions()] == [(sid, "idle")]+ asyncio.run(gw._browser_close(sid, "idle"))+ assert ven.stopped == ["bu_1"] and json.loads(_rows(hid)[-1]["detail"])["reason"] == "idle"+ assert _call(client, tok, "navigate", url="https://example.com/")["isError"] is False+ s = browser_plane.sessions()[sid]+ s.created -= browser_plane.SESSION_CAP_MIN * 60 + 1+ assert [why for _, why in browser_plane.expired_sessions()] == ["session_cap"]+ asyncio.run(gw._browser_close(sid, "session_cap"))+ assert ven.stopped == ["bu_1", "bu_2"] and json.loads(_rows(hid)[-1]["detail"])["minutes"] == 21+++def test_not_configured_a_stolen_credential_and_the_org_gate(client, world, monkeypatch):+ reg, ven, _ = world+ reg.record = _record()+ hid = _harness(client)+ _include(client, hid)+ sid = _session_of(hid)+ tok = gw._mint_hosted_cred(hid, sid, _key(hid))+ monkeypatch.setattr(browser_plane, "API_KEY", "")+ out = _call(client, tok, "navigate", url="https://example.com/")+ assert out["isError"] and "not set up on this deployment" in out["content"][0]["text"]+ monkeypatch.setattr(browser_plane, "API_KEY", VENDOR_KEY)+ # another harness's credential over this harness's record key+ thief = _harness(client)+ _include(client, thief)+ stolen = gw._mint_hosted_cred(thief, "sessX", _key(hid))+ out = _call(client, stolen, "navigate", url="https://example.com/")+ assert out["isError"] and "No plugins are connected" in out["content"][0]["text"] and ven.created == []+ # the org gate: the browser is open to every org; the held plugs are not, by name+ monkeypatch.setattr(gw, "_PLUGS_ORGS", set())+ sid2 = _session_of(thief)+ tok2 = gw._mint_hosted_cred(thief, sid2, _key(thief))+ out = _call(client, tok2, "navigate", url="https://example.com/")+ assert out["isError"] is False and len(ven.created) == 1+ asyncio.run(gw._browser_close(sid2, "turn_end"))+ r = _post(client, f"/v1/harnesses/{thief}/servers/plugs", {"plugs": ["browser", "github"]})+ assert r.status_code == 404 and r.json()["error"]["code"] == "plugs_unavailable" and "GitHub plug" in r.json()["error"]["message"]+ assert _post(client, f"/v1/harnesses/{thief}/servers/plugs", {"plugs": ["browser"]}).status_code == 200+ # a package that requires both gets the open one now and the held one when the org is let in+ manifest = {"$schema": PLUGIN_SCHEMA, "name": "needs-both", "version": "1.0.0", "requires": {"plugs": ["browser", "github"]}}+ r = _post(client, "/v1/harnesses", {"name": "Held", "base": "claude-code",+ "plugins": [{"files": [{"path": "plugin.json", "content": json.dumps(manifest)}]}]})+ assert r.status_code == 200 and _get(client, f"/v1/harnesses/{r.json()['id']}/servers/mcp.plugs").json()["plugs"] == ["browser"]+++def test_a_package_that_requires_the_browser_includes_it_and_the_count_reads_the_bindings(client, world):+ reg, _, _ = world+ reg.record = _record()+ manifest = {"$schema": PLUGIN_SCHEMA, "name": "needs-browser", "version": "1.0.0", "requires": {"plugs": ["browser"]}}+ r = _post(client, "/v1/harnesses", {"name": "Packaged", "base": "claude-code",+ "plugins": [{"files": [{"path": "plugin.json", "content": json.dumps(manifest)}]}]})+ assert r.status_code == 200, r.text+ hid = r.json()["id"]+ assert [e["id"] for e in r.json()["mcpServers"]] == ["mcp.plugs"]+ assert _get(client, f"/v1/harnesses/{hid}/servers/mcp.plugs").json() == {+ "id": "mcp.plugs", "name": "plugs", "enabled": True, "workspace": WS, "plugs": ["browser"], "status": {"browser": "connected"}}+ # "attached N of M harnesses" for the Plugins page, from the bindings+ other = _harness(client)+ _include(client, other, ("github",))+ _harness(client)+ r = client.get("/internal/plugs/attachments", params={"workspace": WS, "type": "browser"}, headers={"x-harness-internal": "test-internal-key"})+ assert r.status_code == 200, r.text+ d = r.json()+ assert d["type"] == "browser" and d["workspace"] == WS and hid in d["harness_ids"] and other not in d["harness_ids"]+ assert d["attached"] == len(d["harness_ids"]) and d["harnesses"] > d["attached"]+ assert client.get("/internal/plugs/attachments", params={"workspace": WS, "type": "browser"}).status_code == 401+++def test_fair_share_of_the_vendors_concurrency(client, world, monkeypatch):+ reg, ven, _ = world+ reg.record = _record(); reg.any_workspace = True+ monkeypatch.setattr(browser_plane, "ORG_SESSIONS", 2)+ monkeypatch.setattr(browser_plane, "MAX_SESSIONS", 3)+ hid = _harness(client)+ _include(client, hid)+ toks = [(sid := _session_of(hid), gw._mint_hosted_cred(hid, sid, _key(hid))) for _ in range(3)]+ assert _call(client, toks[0][1], "get_url")["isError"] is False+ assert _call(client, toks[1][1], "get_url")["isError"] is False+ out = _call(client, toks[2][1], "get_url")+ assert out["isError"] and "already has 2 browsers open" in out["content"][0]["text"] and len(ven.created) == 2+ assert _rows(hid)[-1]["error"] == "org_busy"+ # another org takes the third and last seat; its second is the ceiling+ other = {**HEADERS, "x-harness-org": "otherorg", "x-harness-workspace": "otherorg__hrws"}+ oh = _post(client, "/v1/harnesses", {"name": "Other", "base": "claude-code"}, other).json()["id"]+ assert client.post(f"/v1/harnesses/{oh}/servers/plugs", json={"plugs": ["browser"]}, headers=other).status_code == 200+ s1, s2 = _session_of(oh, "otherorg"), _session_of(oh, "otherorg")+ out = _call(client, gw._mint_hosted_cred(oh, s1, _key(oh)), "get_url")+ assert out["isError"] is False, out+ out = _call(client, gw._mint_hosted_cred(oh, s2, _key(oh)), "get_url")+ assert out["isError"] and "Every browser is in use" in out["content"][0]["text"] and len(ven.created) == 3+ # a stop frees the seat+ asyncio.run(gw._browser_close(toks[0][0], "turn_end"))+ assert _call(client, toks[2][1], "get_url")["isError"] is False+ for sid_, _t in toks:+ asyncio.run(gw._browser_close(sid_, "turn_end"))+ asyncio.run(gw._browser_close(s1, "turn_end"))+++def test_the_key_is_read_from_the_mounted_file_at_every_use(client, world, monkeypatch, tmp_path):+ reg, ven, _ = world+ reg.record = _record()+ f = tmp_path / "browser-use-api-key"+ monkeypatch.setattr(browser_plane, "API_KEY", "")+ monkeypatch.setattr(browser_plane, "API_KEY_FILE", str(f))+ assert browser_plane.configured() is False+ f.write_text(VENDOR_KEY + "\n")+ assert browser_plane.configured() is True+ hid = _harness(client)+ _include(client, hid)+ sid = _session_of(hid)+ tok = gw._mint_hosted_cred(hid, sid, _key(hid))+ assert _call(client, tok, "get_url")["isError"] is False and ven.calls[-1].headers["X-Browser-Use-API-Key"] == VENDOR_KEY+ asyncio.run(gw._browser_close(sid, "turn_end"))+++def test_the_page_reads_the_price_and_the_tools_from_here(client, world):+ hdr = {"x-harness-internal": "test-internal-key"}+ r = client.get("/internal/plugs/pricing", params={"type": "browser"}, headers=hdr)+ assert r.status_code == 200 and r.json() == {"type": "browser", "unit": "browser hour", "usd_per_unit": 0.02, "markup": 0.0,+ "source": "vendor list price", "vendor": "browser-use", "billed_as": "browser.usd",+ "rounding": "up to the minute, one-minute minimum", "session_cap_minutes": 20,+ "session_estimate_usd": 0.006667}+ rows = client.get("/internal/plugs/pricing", headers=hdr).json()["pricing"]+ assert [x["type"] for x in rows] == ["browser", "github", "vercel", "insforge"] and rows[1]["usd_per_unit"] == 0.0+ r = client.get("/internal/plugs/tools", params={"type": "browser"}, headers=hdr)+ assert r.status_code == 200 and r.json()["label"] == "Browser" and len(r.json()["tools"]) == 13+ assert r.json()["tools"][0] == {"name": "navigate", "description": "Open a web address in the current tab and read what is on the page.", "risk": "write"}+ assert client.get("/internal/plugs/tools", params={"type": "printer"}, headers=hdr).status_code == 404+ assert client.get("/internal/plugs/pricing").status_code == 401+++def test_no_secret_ever_reached_a_caller():+ """Every response body every test above received: the vendor key and the browser address are+ in none of them."""+ assert _seen+ for body in _seen:+ assert VENDOR_KEY not in body and CDP not in body and "SENTINEL" not in bodydiff --git a/gateway/tests/test_harness_env.py b/gateway/tests/test_harness_env.pyindex 444fcde3..d8b808a8 100644--- a/gateway/tests/test_harness_env.py+++ b/gateway/tests/test_harness_env.py@@ -106,7 +106,11 @@ def test_openapi_describes_the_customer_surface_only():assert not [p for p in paths if p.startswith(("/v1/admin", "/v1/orgs", "/v1/mcp/", "/v1/kits", "/v1/cloud-upload", "/v1/hr", "/internal", "/share"))]# console-owned routes under a public prefix stay out (#245, reported by trifonnt): the cloud# upload handlers and the kits' server state, vendor and media handlers- assert not [p for p in paths if p.startswith(("/v1/harnesses/upload", "/v1/harnesses/{hid}/upload", "/v1/harnesses/{hid}/servers"))], sorted(paths)+ assert not [p for p in paths if p.startswith(("/v1/harnesses/upload", "/v1/harnesses/{hid}/upload", "/v1/harnesses/{hid}/servers"))+ and p != "/v1/harnesses/{hid}/servers/plugs"], sorted(paths)+ # a customer app connects a plugin for its workspace and includes it on a harness by API+ for p in ("/v1/plugs", "/v1/plugs/{plug_type}", "/v1/plugs/{plug_type}/attachments", "/v1/harnesses/{hid}/servers/plugs"):+ assert p in paths, pfor p in ("/v1/harnesses/{harness_id}/events", "/v1/harnesses/{hid}/plugin", "/v1/harnesses/{hid}/plugins/{name}/files"):assert p in paths, passert "env" in doc["components"]["schemas"]["HarnessBody"]["properties"]diff --git a/gateway/tests/test_plugs.py b/gateway/tests/test_plugs.pynew file mode 100644index 00000000..3b3aacaf--- /dev/null+++ b/gateway/tests/test_plugs.py@@ -0,0 +1,494 @@+"""Plugs on the hosted gateway: a workspace's services (GitHub, Vercel, InsForge) attached to a+harness and reached through the hosted `plugs` MCP server.++Every request goes through the real app with local backing; the plug registry (the engine's door)+and every vendor are httpx MockTransports, so what is asserted is what a caller receives and what+the vendor was actually sent. The credential is a sentinel string: the last tests assert it appears+in no response the agent could read, whatever the route.+"""+from __future__ import annotations++import asyncio+import base64+import json+import sys+from pathlib import Path++import httpx+import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import app as gw # noqa: E402+import plugs_plane # noqa: E402+from fastapi.testclient import TestClient # noqa: E402++ORG = "plugorg"+WS = "plugorg__hrws1"+HEADERS = {"x-harness-internal": "test-internal-key", "x-harness-org": ORG,+ "x-harness-member": "m@plug", "x-harness-workspace": WS}+TOKEN = "ghs_SENTINEL_never_returned_7f3a9c"+VC_TOKEN = "vc_SENTINEL_never_returned_11aa"+INF_KEY = "ik_SENTINEL_never_returned_22bb"+TENANT = "plugorg-1a2b3c4d"+PLUGIN_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json"+_seen: list[str] = []+++def _record(plug: str, *, status: str = "connected", version: int = 1, org: str = ORG, refs=None, tenant=TENANT) -> dict:+ cfg = {"github": {"repo": "acme/site", "owner": "acme", "default_branch": "main"},+ "vercel": {"project": "site", "project_id": "prj_1", "team_id": "team_1"},+ "insforge": {"project": "site", "project_id": "p1", "url": "https://acme.insforge.app", "region": "eu-central"}}[plug]+ field = {"github": "token", "vercel": "token", "insforge": "api_key"}[plug]+ return {"id": f"plug.{plug}1", "org_id": org, "workspace": WS, "type": plug, "status": status,+ "effective_status": status, "source": "provisioned", "config": cfg, "vault_tenant": tenant,+ "key_refs": refs if refs is not None else [{"field": field, "ref": f"plug-plugorg-hrws1-{plug}-{field}"}],+ "version": version, "expires_at": ""}+++class Registry:+ """The engine's read door: one record per (workspace, type), or 404."""++ def __init__(self):+ self.records: dict[tuple[str, str], dict] = {}+ self.fail = False+ self.reads = 0++ def handle(self, r: httpx.Request) -> httpx.Response:+ assert r.url.path == "/v1/plugs/by" and r.method == "GET", r.url+ if r.headers.get("X-Internal-Key") != "test-internal-key":+ return httpx.Response(401, json={"detail": "who?"})+ self.reads += 1+ if self.fail:+ return httpx.Response(500, text="boom")+ rec = self.records.get((r.url.params.get("workspace"), r.url.params.get("type")))+ return httpx.Response(200, json=rec) if rec else httpx.Response(404, json={"detail": "no such plug"})+++class Vendor:+ """GitHub, Vercel and InsForge, answering the shapes the tools read."""++ def __init__(self):+ self.calls: list[httpx.Request] = []++ def handle(self, r: httpx.Request) -> httpx.Response:+ self.calls.append(r)+ host, path = r.url.host, r.url.path+ if host == "api.github.com":+ assert r.headers.get("Authorization") == f"Bearer {TOKEN}", "the plug's own token, always"+ if path == "/repos/acme/site/contents/README.md":+ return httpx.Response(200, json={"type": "file", "encoding": "base64", "path": "README.md", "sha": "abc",+ "size": 5, "content": base64.b64encode(b"hello").decode()})+ if path == "/repos/acme/site/contents/bad.md":+ return httpx.Response(422, json={"message": "Validation Failed"})+ if path == "/repos/acme/site/git/ref/heads/main":+ return httpx.Response(200, json={"object": {"sha": "head1"}})+ if path == "/repos/acme/site/git/commits/head1":+ return httpx.Response(200, json={"tree": {"sha": "tree0"}})+ if path == "/repos/acme/site/git/trees" and r.method == "POST":+ return httpx.Response(201, json={"sha": "tree1"})+ if path == "/repos/acme/site/git/commits" and r.method == "POST":+ return httpx.Response(201, json={"sha": "commit1"})+ if path == "/repos/acme/site/git/refs/heads/main" and r.method == "PATCH":+ return httpx.Response(200, json={"object": {"sha": "commit1"}})+ if path == "/repos/acme/site/pulls" and r.method == "POST":+ body = json.loads(r.content)+ return httpx.Response(201, json={"number": 7, "title": body["title"], "state": "open", "html_url": "https://github.com/acme/site/pull/7",+ "head": {"ref": body["head"]}, "base": {"ref": body["base"]}, "user": {"login": "bot"}})+ return httpx.Response(404, json={"message": f"no mock for {r.method} {path}"})+ if host == "api.vercel.com":+ assert r.headers.get("Authorization") == f"Bearer {VC_TOKEN}"+ assert r.url.params.get("teamId") == "team_1"+ if path == "/v9/projects/prj_1":+ return httpx.Response(200, json={"id": "prj_1", "name": "site", "framework": "nextjs",+ "link": {"type": "github", "org": "acme", "repo": "site", "repoId": 42, "productionBranch": "main"},+ "latestDeployments": []})+ if path == "/v9/projects/prj_1/domains":+ return httpx.Response(200, json={"domains": [{"name": "site.vercel.app"}]})+ if path == "/v13/deployments" and r.method == "POST":+ body = json.loads(r.content)+ assert body["gitSource"] == {"type": "github", "repoId": 42, "ref": "main"}+ return httpx.Response(200, json={"id": "dpl_1", "url": "site-abc.vercel.app", "readyState": "QUEUED"})+ if path == "/v13/deployments/dpl_1":+ return httpx.Response(200, json={"id": "dpl_1", "url": "site-abc.vercel.app", "readyState": "READY", "target": "production"})+ return httpx.Response(404, json={"error": {"message": f"no mock for {path}"}})+ if host == "acme.insforge.app":+ assert r.headers.get("Authorization") == f"Bearer {INF_KEY}"+ if path == "/api/database/records/orders" and r.method == "GET":+ return httpx.Response(200, json=[{"id": 1, "status": "open"}])+ if path == "/api/database/records/orders" and r.method == "POST":+ assert r.headers.get("Prefer") == "return=representation"+ return httpx.Response(201, json=json.loads(r.content))+ if path == "/api/health":+ return httpx.Response(200, json={"status": "ok"})+ return httpx.Response(404, text=f"no mock for {path}")+ return httpx.Response(500, text=f"unexpected host {host}")++[email protected](scope="module")+def client():+ with TestClient(gw.app) as c:+ yield c+++def world(monkeypatch):+ reg, ven, posted = Registry(), Vendor(), []+ rc = httpx.AsyncClient(transport=httpx.MockTransport(reg.handle))+ monkeypatch.setattr(gw, "PLUGS_REGISTRY_URL", "https://registry.example")+ monkeypatch.setattr(gw, "_PLUGS_ORGS", {ORG})+ monkeypatch.setattr(gw, "_client", lambda: rc)+ monkeypatch.setattr(plugs_plane, "transport", httpx.MockTransport(ven.handle))+ monkeypatch.setattr(plugs_plane, "DEPLOY_POLL_S", 0)+ monkeypatch.setattr(gw, "_report_usage", lambda org, metric, amount, **kw: posted.append((org, metric, amount, kw)))+ gw._plug_fields_cache.clear()+ asyncio.run(gw._vault_put(TENANT, "plug-plugorg-hrws1-github-token", TOKEN))+ asyncio.run(gw._vault_put(TENANT, "plug-plugorg-hrws1-vercel-token", VC_TOKEN))+ asyncio.run(gw._vault_put(TENANT, "plug-plugorg-hrws1-insforge-api_key", INF_KEY))+ yield reg, ven, posted+ asyncio.run(rc.aclose())+++def _post(client, path, body=None, headers=None):+ r = client.post(path, json=body, headers={**HEADERS, **(headers or {})})+ _seen.append(r.text)+ return r+++def _get(client, path):+ r = client.get(path, headers=HEADERS)+ _seen.append(r.text)+ return r+++def _delete(client, path):+ r = client.delete(path, headers=HEADERS)+ _seen.append(r.text)+ return r+++def _harness(client, headers=None) -> str:+ return _post(client, "/v1/harnesses", {"name": "Plugged", "base": "claude-code"}, headers).json()["id"]+++def _key(hid: str) -> str:+ return gw._hosted_secret_key(hid, "mcp.plugs")+++def _rpc(client, tok: str, method: str, params: dict | None = None, rid=1):+ r = client.post("/v1/mcp/plugs", headers={"authorization": f"Bearer {tok}"},+ json={"jsonrpc": "2.0", "id": rid, "method": method, "params": params or {}})+ _seen.append(r.text)+ return r.json().get("result") if r.status_code == 200 else r+++def _calls(hid: str) -> list[dict]:+ return asyncio.run(gw.BACKING.graph.find("PlugCall", {"harness": hid}))+++# ── attach, read, detach ─────────────────────────────────────────────────────────────────────+def test_attach_binds_the_harness_workspace_and_detach_scrubs(client, world):+ reg, _, _ = world+ hid = _harness(client)+ r = _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github"]})+ assert r.status_code == 200, r.text+ assert r.json() == {"id": "mcp.plugs", "name": "plugs", "enabled": True, "workspace": WS,+ "plugs": ["github"], "status": {"github": "missing"}}+ v = asyncio.run(gw._vertex_get(hid))+ entries = gw._mcp_list(v)+ assert [e["url"] for e in entries] == ["https://gateway.example/v1/mcp/plugs"]+ assert entries[0]["auth"] == f"vault:{_key(hid)}"+ rec = asyncio.run(gw._hosted_record(ORG, _key(hid)))+ assert rec["server"] == "plugs" and rec["harness"] == hid and rec["workspace"] == WS and rec["plugs"] == ["github"]++ # again, with more plugs and a narrowed tool list: still one entry, the record replaced+ reg.records[(WS, "github")] = _record("github")+ reg.records[(WS, "vercel")] = _record("vercel", status="needs_auth")+ r = _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github", "vercel"], "tools": {"vercel": ["get_project"]}})+ assert r.status_code == 200, r.text+ assert r.json()["plugs"] == ["github", "vercel"] and r.json()["tools"] == {"vercel": ["get_project"]}+ assert r.json()["status"] == {"github": "connected", "vercel": "needs_auth"}+ assert len(gw._mcp_list(asyncio.run(gw._vertex_get(hid)))) == 1+ assert _get(client, f"/v1/harnesses/{hid}/servers/mcp.plugs").json()["plugs"] == ["github", "vercel"]++ assert _delete(client, f"/v1/harnesses/{hid}/servers/plugs").json() == {"id": "mcp.plugs", "detached": True}+ assert gw._mcp_list(asyncio.run(gw._vertex_get(hid))) == []+ assert not asyncio.run(gw._hosted_record(ORG, _key(hid)))+ assert _get(client, f"/v1/harnesses/{hid}/servers/mcp.plugs").status_code == 404+ assert _delete(client, f"/v1/harnesses/{hid}/servers/plugs").status_code == 404+++def test_attach_refusals(client, world, monkeypatch):+ hid = _harness(client)+ r = _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["stripe"]})+ assert r.status_code == 400 and r.json()["error"]["code"] == "invalid_plug"+ r = _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github"], "tools": {"github": ["rm_rf"]}})+ assert r.status_code == 400 and "rm_rf" in r.json()["error"]["message"]+ r = _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": []})+ assert r.status_code == 400+ # a harness outside a named workspace has no company to bind+ bare = _harness(client, {"x-harness-workspace": ""})+ r = _post(client, f"/v1/harnesses/{bare}/servers/plugs", {"plugs": ["github"]})+ assert r.status_code == 400 and r.json()["error"]["code"] == "workspace_required"+ # while the feature is held, an org not on the list gets nothing+ monkeypatch.setattr(gw, "_PLUGS_ORGS", set())+ r = _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github"]})+ assert r.status_code == 404 and r.json()["error"]["code"] == "plugs_unavailable"+ monkeypatch.setattr(gw, "_PLUGS_ORGS", {"*"})+ assert _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github"]}).status_code == 200+++# ── the server the agent talks to ────────────────────────────────────────────────────────────+def test_the_agent_lists_and_calls_the_bound_plugs(client, world):+ reg, ven, posted = world+ hid = _harness(client)+ _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github", "insforge"], "tools": {"insforge": ["query_rows"]}})+ reg.records[(WS, "github")] = _record("github")+ reg.records[(WS, "insforge")] = _record("insforge")+ tok = gw._mint_hosted_cred(hid, "sess1", _key(hid))++ 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 listed["annotations"] == {"readOnlyHint": False, "destructiveHint": True}++ out = _rpc(client, tok, "tools/call", {"name": "github.get_file_contents", "arguments": {"path": "README.md"}})+ assert out["isError"] is False, out+ assert 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"+ rows = _calls(hid)+ assert len(rows) == 1 and rows[0]["outcome"] == "ok" and rows[0]["tool"] == "get_file_contents"+ 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",+ "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"):+ out = _rpc(client, tok, "tools/call", {"name": name, "arguments": {}})+ assert out["isError"] and "No tool named" in out["content"][0]["text"], name+++def test_the_vendors_refusal_is_the_agents_tool_error_and_still_a_call(client, world):+ reg, ven, posted = world+ hid = _harness(client)+ _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"}})+ 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": {}})+ 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]+++def test_refusals_by_plug_state_are_not_metered(client, world, monkeypatch):+ reg, ven, posted = world+ 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"}}++ def refused(contains: str):+ out = _rpc(client, tok, "tools/call", call)+ assert out["isError"] and contains in out["content"][0]["text"], out+ refused("no GitHub plugin connected") # nothing in the registry+ reg.records[(WS, "github")] = _record("github", status="needs_auth")+ refused("needs attention")+ reg.records[(WS, "github")] = _record("github", status="disabled")+ refused("turned off")+ reg.records[(WS, "github")] = _record("github", org="someone.else") # the registry's answer is not this org's+ refused("no GitHub plugin connected")+ reg.fail = True+ refused("did not answer")+ reg.fail = False+ reg.records[(WS, "github")] = _record("github", refs=[{"field": "token", "ref": "harness-conn-openai"}]) # outside plug-+ refused("needs attention")+ reg.records[(WS, "github")] = _record("github", tenant="global") # never the platform pool+ refused("needs attention")+ monkeypatch.setattr(gw, "_PLUGS_ORGS", set())+ reg.records[(WS, "github")] = _record("github")+ refused("not available on this account")+ assert ven.calls == [] and posted == []+ assert {r["outcome"] for r in _calls(hid)} == {"refused"}++ # a switched-off entry and a token for another harness's record answer the same way+ monkeypatch.setattr(gw, "_PLUGS_ORGS", {ORG})+ thief = _harness(client)+ _post(client, f"/v1/harnesses/{thief}/servers/plugs", {"plugs": ["github"]})+ stolen = gw._mint_hosted_cred(thief, "sessX", _key(hid))+ out = _rpc(client, stolen, "tools/call", call)+ assert out["isError"] and "No plugins are connected to this agent" in out["content"][0]["text"]+ assert _rpc(client, stolen, "tools/list") == {"tools": []}+ v = asyncio.run(gw._vertex_get(hid))+ asyncio.run(gw._mcp_write(hid, [{**e, "enabled": False} for e in gw._mcp_list(v)]))+ out = _rpc(client, tok, "tools/call", call)+ assert out["isError"] and "No plugins are connected to this agent" in out["content"][0]["text"]+ assert ven.calls == []+++def test_the_credential_is_read_again_only_when_the_version_changes(client, world):+ reg, ven, _ = world+ hid = _harness(client)+ _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"}}+ reg.reads = 0 # the attach read the status once+ assert _rpc(client, tok, "tools/call", call)["isError"] is False+ assert reg.reads == 1+ asyncio.run(gw._vault_put(TENANT, "plug-plugorg-hrws1-github-token", "ghs_ROTATED"))+ assert _rpc(client, tok, "tools/call", call)["isError"] is False # same version: the cached token+ assert ven.calls[-1].headers["Authorization"] == f"Bearer {TOKEN}" and reg.reads == 2+ reg.records[(WS, "github")] = _record("github", version=4)+ out = _rpc(client, tok, "tools/call", call) # new version: the vault again+ assert ven.calls[-1].headers["Authorization"] == "Bearer ghs_ROTATED"+ assert out["isError"], "the mock vendor only knows the first token, so the rotated one is refused there"+ asyncio.run(gw._vault_put(TENANT, "plug-plugorg-hrws1-github-token", TOKEN))+++def test_every_call_lands_in_the_sessions_trace(client, world, monkeypatch):+ reg, _, _ = world+ hid = _harness(client)+ _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github"]})+ reg.records[(WS, "github")] = _record("github")+ chunks = []++ async def _put(file_id, data):+ chunks.append((file_id, data))+ return True+ 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"}})+ 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"+ assert ev["risk"] == "read" and ev["outcome"] == "ok" and "error" not in ev and isinstance(ev["ms"], int)+ assert gw._session_trace["sess5"]["count"] == 1+++# ── packages that need plugs ─────────────────────────────────────────────────────────────────+def _package(requires):+ manifest = {"$schema": PLUGIN_SCHEMA, "name": "needs-plugs", "version": "1.0.0", "requires": requires}+ return {"files": [{"path": "plugin.json", "content": json.dumps(manifest)}]}+++def test_a_package_that_requires_plugs_gets_them_on_install(client, world, monkeypatch):+ r = _post(client, "/v1/harnesses", {"name": "Packaged", "base": "claude-code",+ "plugins": [_package({"plugs": ["github", "nope"]})]})+ assert r.status_code == 200, r.text+ hid = r.json()["id"]+ assert r.json()["plugins"][0]["skipped"] == [{"path": "plugin.json#/requires/plugs/nope",+ "reason": "no plug of that type on this server, ignored"}]+ assert [e["id"] for e in r.json()["mcpServers"]] == ["mcp.plugs"]+ assert _get(client, f"/v1/harnesses/{hid}/servers/mcp.plugs").json()["plugs"] == ["github"]+ # an update that keeps the package keeps the binding; one that adds a requirement widens it+ r = client.put(f"/v1/harnesses/{hid}", headers=HEADERS,+ json={"name": "Packaged", "base": "claude-code", "mcpServers": r.json()["mcpServers"],+ "plugins": [_package({"plugs": ["github", "vercel"]})]})+ assert r.status_code == 200, r.text+ assert _get(client, f"/v1/harnesses/{hid}/servers/mcp.plugs").json()["plugs"] == ["github", "vercel"]+ # a malformed requires is refused, not guessed at+ r = _post(client, "/v1/harnesses", {"name": "Bad", "base": "claude-code", "plugins": [_package({"plugs": "github"})]})+ assert r.status_code == 422 and "requires" in r.text+ # held: the package installs, the plugs wait for the org to be let in+ monkeypatch.setattr(gw, "_PLUGS_ORGS", set())+ r = _post(client, "/v1/harnesses", {"name": "Held", "base": "claude-code", "plugins": [_package({"plugs": ["github"]})]})+ assert r.status_code == 200 and r.json()["mcpServers"] == []+++# ── the tool surface itself ──────────────────────────────────────────────────────────────────+def test_the_tool_table_is_well_formed():+ for plug in plugs_plane.TYPES:+ tools = plugs_plane.tools_of(plug)+ assert tools, plug+ names = [t["name"] for t in tools]+ assert len(names) == len(set(names)), plug+ for t in tools:+ assert t["risk"] in plugs_plane.RISKS and t["inputSchema"]["type"] == "object" and t["description"]+ assert plugs_plane.tools_of("github_app") == plugs_plane.tools_of("github")+ assert plugs_plane.find("github", "push_files")["risk"] == "destructive"+ 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]")+++def test_push_files_deploy_and_insert_drive_the_vendors_as_documented(world):+ _, ven, _ = world+ out = json.loads(asyncio.run(plugs_plane.call("github", "push_files",+ {"branch": "main", "message": "m", "files": [{"path": "a.txt", "content": "A"}]},+ {"token": TOKEN}, _record("github")["config"])))+ assert out == {"branch": "main", "commit": "commit1", "files": 1}+ assert [(c.method, c.url.path) for c in ven.calls] == [+ ("GET", "/repos/acme/site/git/ref/heads/main"), ("GET", "/repos/acme/site/git/commits/head1"),+ ("POST", "/repos/acme/site/git/trees"), ("POST", "/repos/acme/site/git/commits"),+ ("PATCH", "/repos/acme/site/git/refs/heads/main")]+ assert json.loads(ven.calls[2].content)["tree"] == [{"path": "a.txt", "mode": "100644", "type": "blob", "content": "A"}]+ out = json.loads(asyncio.run(plugs_plane.call("github", "create_pull_request", {"title": "T", "head": "feat"},+ {"token": TOKEN}, _record("github")["config"])))+ assert out["number"] == 7 and out["base"] == "main"++ ven.calls.clear()+ out = json.loads(asyncio.run(plugs_plane.call("vercel", "deploy_from_repo", {"production": True},+ {"token": VC_TOKEN}, _record("vercel")["config"])))+ assert out["id"] == "dpl_1" and out["readyState"] == "READY"+ assert json.loads(ven.calls[1].content)["target"] == "production"+ out = json.loads(asyncio.run(plugs_plane.call("vercel", "get_project", {}, {"token": VC_TOKEN}, _record("vercel")["config"])))+ assert out["domains"] == ["site.vercel.app"] and out["link"]["repo"] == "site"++ out = json.loads(asyncio.run(plugs_plane.call("insforge", "insert_rows", {"table": "orders", "rows": [{"status": "new"}]},+ {"api_key": INF_KEY}, _record("insforge")["config"])))+ assert out == [{"status": "new"}]+ with pytest.raises(plugs_plane.PlugToolError):+ asyncio.run(plugs_plane.call("insforge", "delete_rows", {"table": "orders", "filters": {}}, {"api_key": INF_KEY},+ _record("insforge")["config"]))+ with pytest.raises(plugs_plane.PlugToolError):+ asyncio.run(plugs_plane.call("insforge", "request", {"method": "GET", "path": "/etc/passwd"}, {"api_key": INF_KEY},+ _record("insforge")["config"]))+++def test_a_plug_over_several_repositories_takes_the_one_meant(world):+ _, ven, _ = world+ many = {"repos": ["acme/site", "acme/docs"], "default_branch": "main"}+ out = json.loads(asyncio.run(plugs_plane.call("github_app", "get_file_contents", {"path": "README.md", "repo": "acme/site"},+ {"token": TOKEN}, many)))+ assert out["content"] == "hello" and ven.calls[-1].url.path == "/repos/acme/site/contents/README.md"+ with pytest.raises(plugs_plane.PlugToolError, match="covers several"):+ asyncio.run(plugs_plane.call("github_app", "get_file_contents", {"path": "README.md"}, {"token": TOKEN}, many))+ with pytest.raises(plugs_plane.PlugToolError, match="does not cover"):+ asyncio.run(plugs_plane.call("github_app", "get_file_contents", {"path": "README.md", "repo": "evil/repo"}, {"token": TOKEN}, many))+ with pytest.raises(plugs_plane.PlugToolError, match="does not cover"):+ asyncio.run(plugs_plane.call("github", "get_file_contents", {"path": "README.md", "repo": "evil/repo"}, {"token": TOKEN},+ _record("github")["config"]))+ assert "repo" in plugs_plane.find("github", "merge_pull_request")["inputSchema"]["properties"]+ assert plugs_plane.permission_of("github", "create_issue") == "issues" and plugs_plane.permission_of("vercel", "deploy_from_repo") is None+++def test_a_missing_grant_is_named_before_the_vendor_is_asked(client, world):+ reg, ven, posted = world+ hid = _harness(client)+ _post(client, f"/v1/harnesses/{hid}/servers/plugs", {"plugs": ["github"]})+ rec = _record("github")+ rec["config"]["permissions_missing"] = ["issues", "actions"]+ reg.records[(WS, "github")] = rec+ tok = gw._mint_hosted_cred(hid, "sess6", _key(hid))+ 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"}})+ assert out["isError"] is False # contents was granted+++def test_no_credential_ever_came_back_out():+ for s in (TOKEN, VC_TOKEN, INF_KEY):+ assert not [b for b in _seen if s in b], "a credential left the gateway"diff --git a/gateway/tests/test_plugs_local.py b/gateway/tests/test_plugs_local.pynew file mode 100644index 00000000..2f6e995d--- /dev/null+++ b/gateway/tests/test_plugs_local.py@@ -0,0 +1,199 @@+"""The local plugin registry: a self-hosted instance has no engine, so a workspace connects a+plugin through this gateway's own routes and the records live in its own store. The plugs server+reads them exactly as it reads the hosted registry's, so the same tools, the same include, the+same audit rows follow. The browser is a platform plug (no credential); GitHub carries one.+"""+from __future__ import annotations++import asyncio+import json+import sys+from pathlib import Path++import httpx+import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+sys.path.insert(0, str(Path(__file__).resolve().parent))+import app as gw # noqa: E402+import browser_plane # noqa: E402+import plugs_plane # noqa: E402+import test_browser as tb # noqa: E402+from fastapi.testclient import TestClient # noqa: E402++ORG = "localorg"+WS = "default"+HEADERS = {"x-harness-internal": "test-internal-key", "x-harness-org": ORG,+ "x-harness-member": "m@local", "x-harness-workspace": WS}+GH_TOKEN = "ghp_SENTINEL_never_returned_3c3c"+_seen: list[str] = []++[email protected](scope="module")+def client():+ with TestClient(gw.app) as c:+ yield c+++def world(monkeypatch):+ ven, posted = tb.Vendor(), []+ monkeypatch.setattr(gw, "PLUGS_REGISTRY_URL", "") # no engine: the local registry answers+ monkeypatch.setattr(gw, "_PLUGS_ORGS", {"*"})+ monkeypatch.setattr(browser_plane, "API_KEY", tb.VENDOR_KEY)+ monkeypatch.setattr(browser_plane, "transport", httpx.MockTransport(ven.handle))+ monkeypatch.setattr(browser_plane, "connector", tb._connect)+ monkeypatch.setattr(browser_plane, "resolves_private", tb._resolves)+ monkeypatch.setattr(gw, "_report_usage", lambda org, metric, amount, **kw: posted.append((org, metric, amount)))+ tb.browsers.clear()+ for s in list(browser_plane.sessions().values()):+ s.closed = True+ browser_plane.sessions().clear()+ gw._plug_fields_cache.clear()+ yield ven, posted+++def _req(client, method, path, body=None, headers=None):+ r = client.request(method, path, json=body, headers={**HEADERS, **(headers or {})})+ _seen.append(r.text)+ return r+++def _harness(client, **extra) -> str:+ return _req(client, "POST", "/v1/harnesses", {"name": "Local", "base": "claude-code", **extra}).json()["id"]+++def _rpc(client, tok: str, name: str, args: dict | None = None):+ r = client.post("/v1/mcp/plugs", headers={"authorization": f"Bearer {tok}"},+ json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": name, "arguments": args or {}}})+ _seen.append(r.text)+ return r.json()["result"]+++def _rows(hid: str, plug: str) -> list[dict]:+ rows = [r for r in asyncio.run(gw.BACKING.graph.find("PlugCall", {"harness": hid})) if r.get("plug") == plug]+ return sorted(rows, key=lambda r: (int(r["finished"]), -int(r["started"])))+++def test_the_catalog_and_the_browser_connected_here(client, world):+ ven, posted = world+ cat = _req(client, "GET", "/v1/plugs").json()+ assert cat["workspace"] == WS+ assert [p["type"] for p in cat["plugs"]] == ["browser", "github", "vercel", "insforge"]+ b = cat["plugs"][0]+ assert b["status"] == "missing" and b["source"] == "platform" and b["official"] is True and b["tools"] == 13+ assert b["pricing"]["usd_per_unit"] == 0.02 and b["pricing"]["markup"] == 0.0 and b["secrets_needed"] == []+ assert cat["plugs"][1]["secrets_needed"] == ["token"] and cat["plugs"][1]["status"] == "missing"++ # a harness may include it before the workspace connects it: the tool list is there, a call says so+ hid = _harness(client)+ 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")+ 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+ r = _req(client, "PUT", "/v1/plugs/browser", {"enabled": True, "config": {"allow_domains": ["Example.com", "*.iana.org"], "deny_domains": ["ads.example.com"]}})+ assert r.status_code == 200, r.text+ d = r.json()+ assert d["status"] == "connected" and d["config"] == {"allow_domains": ["example.com", "iana.org"], "deny_domains": ["ads.example.com"], "proxy": False}+ 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/"})+ assert out["isError"] is False, out+ assert out["content"][0]["text"].startswith("Opened https://example.com/ (Example Domain)")+ 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 call+ r = _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+ # the count the Plugins page shows+ other = _harness(client)+ a = _req(client, "GET", "/v1/plugs/browser/attachments").json()+ assert a["attached"] == 1 and a["harnesses"] >= 2 and a["harness_list"][0]["id"] == hid and other not in [h["id"] for h in a["harness_list"]]+ # the stop writes the session row with the vendor's dollars, and the meter is asked+ asyncio.run(gw._browser_close("sess1", "turn_end"))+ end = _rows(hid, "browser")[-1]+ assert end["unit"] == "browser.usd" and end["usd"] == "0.000667" and json.loads(end["detail"])["reason"] == "turn_end"+ assert posted[-1] == (ORG, "browser.usd", 0.000667) and ven.stopped == ["bu_1"]+ # turned off: the tools refuse in a sentence, the record stays+ r = _req(client, "PUT", "/v1/plugs/browser", {"enabled": False})+ assert r.json()["status"] == "disabled"+ 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"+++def test_a_credentialed_plugin_keeps_its_secret_in_the_store(client, world, monkeypatch):+ calls = []++ def vendor(r: httpx.Request) -> httpx.Response:+ calls.append(r)+ assert r.headers.get("Authorization") == f"Bearer {GH_TOKEN}"+ if r.url.path == "/repos/acme/site/contents/README.md":+ return httpx.Response(200, json={"type": "file", "encoding": "base64", "path": "README.md", "sha": "abc", "size": 5, "content": "aGVsbG8="})+ return httpx.Response(404, json={"message": "no"})+ monkeypatch.setattr(plugs_plane, "transport", httpx.MockTransport(vendor))+ # without its token the plug needs auth; with it, connected; the token is in the store, not the record+ r = _req(client, "PUT", "/v1/plugs/github", {"enabled": True, "config": {"repo": "acme/site", "owner": "acme", "default_branch": "main"}})+ assert r.status_code == 200 and r.json()["status"] == "needs_auth" and r.json()["secrets_set"] == []+ r = _req(client, "PUT", "/v1/plugs/github", {"enabled": True, "secrets": {"token": GH_TOKEN}})+ assert r.json()["status"] == "connected" and r.json()["secrets_set"] == ["token"] and r.json()["config"]["repo"] == "acme/site"+ assert asyncio.run(gw._vault_get(ORG, "plug-default-github-token")) == GH_TOKEN+ row = asyncio.run(gw.BACKING.graph.find("Plug", {"workspace": WS, "type": "github"}))[0]+ assert GH_TOKEN not in json.dumps(row)+ hid = _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"})+ assert out["isError"] is False, out+ assert json.loads(out["content"][0]["text"])["content"] == "hello" and calls[-1].url.host == "api.github.com"+ assert _rows(hid, "github")[-1]["outcome"] == "ok"+ # a bad setting and an unknown plugin are refused+ assert _req(client, "PUT", "/v1/plugs/github", {"config": {"colour": "red"}}).status_code == 400+ assert _req(client, "PUT", "/v1/plugs/github", {"secrets": {"password": "x"}}).status_code == 400+ assert _req(client, "PUT", "/v1/plugs/printer", {"enabled": True}).status_code == 404+ # another workspace of the same instance has its own records+ other = _req(client, "GET", "/v1/plugs", headers={"x-harness-workspace": "ws2"}).json()+ assert other["workspace"] == "ws2" and all(p["status"] == "missing" for p in other["plugs"])+++def test_a_package_that_requires_the_browser_includes_it_here_too(client, world):+ _req(client, "PUT", "/v1/plugs/browser", {"enabled": True})+ manifest = {"$schema": tb.PLUGIN_SCHEMA, "name": "needs-browser", "version": "1.0.0", "requires": {"plugs": ["browser"]}}+ r = _req(client, "POST", "/v1/harnesses", {"name": "Packaged", "base": "claude-code",+ "plugins": [{"files": [{"path": "plugin.json", "content": json.dumps(manifest)}]}]})+ assert r.status_code == 200, r.text+ assert [e["id"] for e in r.json()["mcpServers"]] == ["mcp.plugs"]+ assert _req(client, "GET", f"/v1/harnesses/{r.json()['id']}/servers/mcp.plugs").json()["status"] == {"browser": "connected"}+++def test_no_secret_ever_reached_a_caller():+ assert _seen+ for body in _seen:+ assert GH_TOKEN not in body and tb.VENDOR_KEY not in body and "SENTINEL" not in body+++def test_a_harness_created_without_a_workspace_header_is_in_the_default_workspace(client, world):+ """The guide's bare API calls carry no workspace header: PUT /v1/plugs/browser lands in the+ default workspace, and a harness created the same way carries no stamp. On a self-hosted+ instance that harness is in the default workspace, the leniency its listing already applies,+ so the include succeeds, binds to "default", and the attachment count sees it."""+ bare = {k: v for k, v in HEADERS.items() if k != "x-harness-workspace"}+ _req(client, "PUT", "/v1/plugs/browser", {"enabled": True})+ r = client.request("POST", "/v1/harnesses", json={"name": "Bare", "base": "claude-code"}, headers=bare)+ hid = r.json()["id"]+ assert not r.json().get("workspace")+ r = client.request("POST", f"/v1/harnesses/{hid}/servers/plugs", json={"plugs": ["browser"]}, headers=bare)+ assert r.status_code == 200, r.text+ assert r.json()["workspace"] == "default" and r.json()["status"]["browser"] == "connected"+ a = _req(client, "GET", "/v1/plugs/browser/attachments").json()+ assert hid in {h["id"] for h in a["harness_list"]} and a["attached"] <= a["harnesses"]+ # behind a registry the stamp is required: a tenant is never guessed there+ import unittest.mock as um+ with um.patch.object(gw, "PLUGS_REGISTRY_URL", "http://registry"):+ assert gw._harness_workspace_for_plugs({"workspace": ""}) == ""+ assert gw._harness_workspace_for_plugs({"workspace": "ws1"}) == "ws1"diff --git a/scripts/support-matrix/plugs/browser.py b/scripts/support-matrix/plugs/browser.pynew file mode 100644index 00000000..d81fb480--- /dev/null+++ b/scripts/support-matrix/plugs/browser.py@@ -0,0 +1,120 @@+#!/usr/bin/env python3+"""Prove the browser plugin on a HarnessRouter instance, end to end, directly. No workflow.++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.++ 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]+"""+from __future__ import annotations++import argparse+import json+import secrets+import sys+import time+import urllib.error+import urllib.request++PROMPT = ("Use your browser tools for 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"]+++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 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,+ headers={**H, **({"Idempotency-Key": secrets.token_hex(8)} if path.endswith("/responses") else {})}, method=method)+ try:+ with urllib.request.urlopen(req, timeout=timeout) as r:+ raw = r.read()+ return r.status, (json.loads(raw) if raw.strip().startswith(b"{") or raw.strip().startswith(b"[") else raw.decode())+ except urllib.error.HTTPError as e:+ raw = e.read()+ try:+ return e.code, json.loads(raw)+ except ValueError:+ return e.code, raw.decode()[:300]++ 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+ code, h = call("POST", "/v1/harnesses", body)+ if code != 200:+ print("FAIL harness:", code, h); return 2+ hid = 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:+ print("FAIL turn:", code, resp); return 2+ rid, sid = resp.get("id"), (resp.get("metadata") or {}).get("session_id") or ""+ print("turn:", resp.get("status"), "sid", sid)+ t0 = time.time(); 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 ""+ 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)+ code, trace = call("GET", f"/v1/traces/{sid}/all?compact=0", timeout=120)+ rows = []+ for line in (trace if isinstance(trace, str) else "").splitlines():+ try:+ ev = json.loads(line)+ except ValueError:+ continue+ if 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"}+ 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}")+ finally:+ if not a.keep:+ call("DELETE", f"/v1/harnesses/{hid}")+ if a.out:+ with open(a.out, "w") as f:+ json.dump(result, f, indent=1)+ return 0 if result.get("ok") else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/ui/src/app/(app)/plugins/page.tsx b/ui/src/app/(app)/plugins/page.tsxnew file mode 100644index 00000000..0c36d8be--- /dev/null+++ b/ui/src/app/(app)/plugins/page.tsx@@ -0,0 +1,146 @@+'use client';+// Plugins: services a workspace connects once (a browser, a GitHub repository, a Vercel project,+// an InsForge backend); each Harness then includes the ones it needs under Harness Settings.+// One catalog, every plugin a row of it: its state here, what it costs, how many Harnesses+// include it. Nothing on this page is a copy: the catalog, the tool counts and the price come+// from the server that serves and charges them.+import { useCallback, useEffect, useState } from 'react';+import { useRouter } from 'next/navigation';+import { SkelRows } from '@/components/Skel';+import { listPlugs, setPlug, plugAttachments, type Plug } from '@/lib/harness';++const ICON: Record<string, string> = { browser: 'tabler:world', github: 'tabler:brand-github', vercel: 'tabler:triangle', insforge: 'tabler:database' };+const BLURB: Record<string, string> = {+ browser: 'A real web browser the agent can open, read, click through and screenshot.',+ github: 'The repository this workspace connects: files, branches and pull requests.',+ vercel: 'The project this workspace connects: deployments and domains.',+ insforge: 'The backend this workspace connects: its tables and records.',+};+const FIELD_LABEL: Record<string, string> = {+ allow_domains: 'Only these sites', deny_domains: 'Never these sites', token: 'Access token', api_key: 'API key',+ repo: 'Repository (owner/name)', owner: 'Owner', default_branch: 'Default branch', project: 'Project', project_id: 'Project id',+ team_id: 'Team id', url: 'Address', region: 'Region',+};+const STATUS_LABEL: Record<Plug['status'], string> = { connected: 'Connected', disabled: 'Disabled', needs_auth: 'Needs auth', missing: 'Not connected' };+const listOf = (v: unknown) => (Array.isArray(v) ? v.map(String).join(', ') : '');+const domainsOf = (text: string) => text.split(/[\s,]+/).map((d) => d.trim()).filter(Boolean);++export default function PluginsPage() {+ const router = useRouter();+ const [plugs, setPlugs] = useState<Plug[] | null>(null);+ const [counts, setCounts] = useState<Record<string, { attached: number; harnesses: number }>>({});+ const [err, setErr] = useState('');+ const [busy, setBusy] = useState('');+ const [editing, setEditing] = useState<Plug | null>(null);+ const [form, setForm] = useState<Record<string, string>>({});++ const reload = useCallback(async () => {+ try {+ const d = await listPlugs();+ setPlugs(d.plugs);+ const c: Record<string, { attached: number; harnesses: number }> = {};+ for (const p of d.plugs) {+ if (p.status === 'missing') continue;+ try { const a = await plugAttachments(p.type); c[p.type] = { attached: a.attached, harnesses: a.harnesses }; } catch { /* the line stays off */ }+ }+ setCounts(c);+ } catch (e) { setErr(e instanceof Error ? e.message : 'The plugins could not be read.'); }+ }, []);+ useEffect(() => { void reload(); }, [reload]);++ const open = (p: Plug) => {+ const f: Record<string, string> = {};+ for (const k of p.config_fields) f[k] = p.type === 'browser' ? listOf(p.config[k]) : String(p.config[k] ?? '');+ for (const k of p.secrets_needed) f[k] = '';+ setForm(f); setEditing(p);+ };+ const save = async (p: Plug, enabled: boolean, withForm: boolean) => {+ setBusy(p.type); setErr('');+ try {+ const body: { enabled: boolean; config?: Record<string, unknown>; secrets?: Record<string, string> } = { enabled };+ if (withForm) {+ body.config = Object.fromEntries(p.config_fields.map((k) => [k, p.type === 'browser' ? domainsOf(form[k] || '') : (form[k] || '')]));+ const secrets = Object.fromEntries(p.secrets_needed.filter((k) => (form[k] || '').trim()).map((k) => [k, form[k].trim()]));+ if (Object.keys(secrets).length) body.secrets = secrets;+ }+ await setPlug(p.type, body);+ setEditing(null);+ await reload();+ } catch (e) { setErr(e instanceof Error ? e.message : 'The plugin was not saved. Try again.'); }+ finally { setBusy(''); }+ };++ return (+ <section className="view is-active" id="view-plugins">+ <div className="page">+ <div className="page-header">+ <div>+ <h1>Plugins</h1>+ <p>Connect a service once for this workspace. Each Harness then chooses which plugins it includes, under its settings.</p>+ </div>+ </div>+ {err && <div className="notice"><iconify-icon icon="tabler:alert-triangle"></iconify-icon><div><strong>Something went wrong</strong>{err}</div></div>}+ {!plugs ? <SkelRows rows={4} /> : (+ <div className="capability-list">+ {plugs.map((p) => {+ const on = p.status === 'connected';+ const c = counts[p.type];+ const price = p.pricing ? `$${p.pricing.usd_per_unit.toFixed(2)} per ${p.pricing.unit}, billed at the service's own price` : 'No charge';+ return (+ <div key={p.type} className="capability-row">+ <span className="capability-icon"><iconify-icon icon={ICON[p.type] || 'tabler:plug'}></iconify-icon></span>+ <div className="capability-copy">+ <strong>{p.label} {p.official && <span className="status neutral">Official</span>} <span className={'status ' + (on ? 'healthy' : p.status === 'needs_auth' ? 'warning' : 'neutral')}>{STATUS_LABEL[p.status]}</span></strong>+ <span>{BLURB[p.type] || ''} {p.tools} tools · {price}{c ? ` · ${c.attached} of ${c.harnesses} Harnesses include it` : ''}</span>+ </div>+ <div className="capability-actions">+ {p.status === 'missing' && (p.secrets_needed.length === 0+ ? <button className="button small" type="button" disabled={busy === p.type} onClick={() => void save(p, true, false)}>Turn on</button>+ : <button className="button small" type="button" disabled={busy === p.type} onClick={() => open(p)}>Connect</button>)}+ {p.status === 'needs_auth' && <button className="button small" type="button" disabled={busy === p.type} onClick={() => open(p)}>Add credentials</button>}+ {p.status === 'disabled' && <button className="button small" type="button" disabled={busy === p.type} onClick={() => void save(p, true, false)}>Turn on</button>}+ {p.status !== 'missing' && <button className="button quiet small" type="button" disabled={busy === p.type} onClick={() => open(p)}>Settings</button>}+ {on && <button className="button quiet small" type="button" disabled={busy === p.type} onClick={() => void save(p, false, false)}>Turn off</button>}+ </div>+ </div>+ );+ })}+ </div>+ )}+ <p className="field-help" style={{ marginTop: 14 }}>+ A Harness includes a plugin under its settings. <button className="hr-link-sm" type="button" onClick={() => router.push('/harnesses')}>Open Agent Harnesses</button>+ </p>+ </div>++ {editing && (+ <div className="modal-backdrop" onClick={() => busy || setEditing(null)}>+ <section className="modal" role="dialog" aria-modal="true" aria-labelledby="plug-title" onClick={(e) => e.stopPropagation()}>+ <div className="modal-header"><div><h2 id="plug-title">{editing.label}</h2><p>{BLURB[editing.type] || ''}</p></div>+ <button className="icon-button modal-close" type="button" aria-label="Close dialog" onClick={() => setEditing(null)}><iconify-icon icon="tabler:x"></iconify-icon></button></div>+ <div className="modal-body">+ <div className="field-stack">+ {editing.secrets_needed.map((k) => (+ <div className="field" key={k}><label htmlFor={`plug-${k}`}>{FIELD_LABEL[k] || k}</label>+ <input id={`plug-${k}`} type="password" autoComplete="off" value={form[k] || ''}+ placeholder={editing.secrets_set.includes(k) ? '•••••••• (saved, leave blank to keep)' : ''}+ onChange={(e) => setForm({ ...form, [k]: e.target.value })} /></div>+ ))}+ {editing.config_fields.map((k) => (+ <div className="field" key={k}><label htmlFor={`plug-${k}`}>{FIELD_LABEL[k] || k}</label>+ <input id={`plug-${k}`} type="text" value={form[k] || ''}+ placeholder={editing.type === 'browser' ? (k === 'allow_domains' ? 'example.com, docs.example.org (empty means any public site)' : 'ads.example.com') : ''}+ onChange={(e) => setForm({ ...form, [k]: e.target.value })} /></div>+ ))}+ {editing.pricing && <span className="field-help">{`Up to ${editing.pricing.session_cap_minutes} minutes of browsing per task, at most $${editing.pricing.session_estimate_usd.toFixed(4)} a task. Private and local addresses are never reachable.`}</span>}+ </div>+ </div>+ <div className="modal-footer">+ <button className="button" type="button" onClick={() => setEditing(null)} disabled={Boolean(busy)}>Cancel</button>+ <button className="button primary" type="button" disabled={Boolean(busy)} onClick={() => void save(editing, true, true)}>{busy ? 'Saving…' : editing.status === 'missing' ? 'Connect' : 'Save'}</button>+ </div>+ </section>+ </div>+ )}+ </section>+ );+}diff --git a/ui/src/components/HarnessSettings.tsx b/ui/src/components/HarnessSettings.tsxindex bab2f7c2..a9063bb7 100644--- a/ui/src/components/HarnessSettings.tsx+++ b/ui/src/components/HarnessSettings.tsx@@ -11,6 +11,7 @@ import {OOB, oobById, oobDefaultModel, oobModels, useModelCatalog, modelAvailable, modelAvailability, availabilityNote, useBases, getCustom, saveCustom, deleteCustom, createCustom, getSkillFiles, storeMcpSecret, pluginSchemas,type CustomHarness, type OobHarness, type HarnessPlugin, getPluginFiles,useRuntimeDefaults,+ listPlugs, getHarnessPlugs, setHarnessPlugs, type Plug, type HarnessPlugs,} from '@/lib/harness';import { HarnessLogo } from '@/components/HarnessLogo';import { CopyId } from '@/components/CopyId';@@ -73,6 +74,27 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {// Plugins: which row is expanded (by name, so removing another row cannot move it), the folder// picker, the export in flight, and a notice that belongs to this section rather than to Save.const [pluginOpen, setPluginOpen] = useState<string | null>(null);+ // The workspace's plugins and which of them this Harness includes; both read from the server.+ const [wsPlugs, setWsPlugs] = useState<Plug[] | null>(null);+ const [included, setIncluded] = useState<HarnessPlugs | null | undefined>(undefined);+ const [plugBusy, setPlugBusy] = useState('');+ const [plugErr, setPlugErr] = useState('');+ useEffect(() => {+ if (!id || oob) { setIncluded(null); return; }+ let alive = true;+ listPlugs().then((d) => { if (alive) setWsPlugs(d.plugs); }).catch(() => { if (alive) setWsPlugs([]); });+ getHarnessPlugs(id).then((p) => { if (alive) setIncluded(p); }).catch(() => { if (alive) setIncluded(null); });+ return () => { alive = false; };+ }, [id, oob]);+ const togglePlug = async (type: string) => {+ if (!id) return;+ const have = included?.plugs || [];+ const next = have.includes(type) ? have.filter((t) => t !== type) : [...have, type];+ setPlugBusy(type); setPlugErr('');+ try { setIncluded(await setHarnessPlugs(id, next)); setDraft(await getCustom(id)); }+ catch (e) { setPlugErr(e instanceof Error ? e.message : 'The plugin was not changed. Try again.'); }+ finally { setPlugBusy(''); }+ };const [pluginBusy, setPluginBusy] = useState(false);const [pluginNote, setPluginNote] = useState<{ kind: 'error' | 'info'; text: string } | null>(null);const pluginDirRef = useRef<HTMLInputElement>(null);@@ -88,7 +110,7 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {try {let total = 0;for (let i = 0; i < list.length; i++) total += list[i].size;- if (total > PLUGIN_PACKAGE_MAX) throw new Error(`That folder is ${fmtMb(total)}; a plugin package can be at most ${fmtMb(PLUGIN_PACKAGE_MAX)}.`);+ if (total > PLUGIN_PACKAGE_MAX) throw new Error(`That folder is ${fmtMb(total)}; a package can be at most ${fmtMb(PLUGIN_PACKAGE_MAX)}.`);const files: NonNullable<HarnessPlugin['files']> = [];for (let i = 0; i < list.length; i++) {const f = list[i];@@ -98,7 +120,7 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {files.push(await readSkillUpload(f, path));}const manifestFile = files.find((f) => f.path === 'plugin.json');- if (!manifestFile || manifestFile.content === undefined) throw new Error('That folder has no plugin.json at its root, so it is not a plugin package.');+ if (!manifestFile || manifestFile.content === undefined) throw new Error('That folder has no plugin.json at its root, so it is not a package.');let manifest: (HarnessPlugin['manifest'] & { $schema?: string }) = {};try { manifest = JSON.parse(manifestFile.content) as typeof manifest; } catch { throw new Error('plugin.json is not valid JSON.'); }const name = String(manifest?.name || '');@@ -336,6 +358,38 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {</div></section>+ {!oob && (+ <section className="form-section">+ <div><h3>Plugins</h3><p>Services this workspace connected. Include the ones this Harness needs; the agent gets their tools on every Task.</p></div>+ <div className="field-stack">+ {wsPlugs === null && <div className="capability-row"><span className="capability-icon"><iconify-icon icon="tabler:plug-connected"></iconify-icon></span><div className="capability-copy"><strong>Reading the workspace's plugins</strong></div></div>}+ {wsPlugs && wsPlugs.filter((p) => p.status !== 'missing').length === 0 && (+ <div className="capability-row"><span className="capability-icon"><iconify-icon icon="tabler:plug-connected"></iconify-icon></span>+ <div className="capability-copy"><strong>No plugins connected for this workspace yet</strong><span>Connect one on the Plugins page, then include it here.</span></div>+ <div className="capability-actions"><button className="button small" type="button" onClick={() => router.push('/plugins')}>Open Plugins</button></div>+ </div>)}+ {wsPlugs && wsPlugs.filter((p) => p.status !== 'missing').length > 0 && (+ <div className="capability-list">+ {wsPlugs.filter((p) => p.status !== 'missing').map((p) => {+ const on = (included?.plugs || []).includes(p.type);+ return (+ <div key={p.type} className="capability-row">+ <span className="capability-icon"><iconify-icon icon={on ? 'tabler:circle-check' : 'tabler:circle-dashed'}></iconify-icon></span>+ <div className="capability-copy"><strong>{p.label}</strong>+ <span>{p.status === 'connected' ? `${p.tools} tools` : p.status === 'disabled' ? 'Turned off for the workspace' : 'Needs credentials on the Plugins page'}{p.pricing ? ` · $${p.pricing.usd_per_unit.toFixed(2)} per ${p.pricing.unit}` : ''}</span></div>+ <div className="capability-actions">+ <button className="toggle-button" type="button" disabled={readOnly || plugBusy === p.type} aria-pressed={on} onClick={() => void togglePlug(p.type)}>+ {on ? 'Included' : 'Not included'}</button>+ </div>+ </div>+ );+ })}+ </div>)}+ {plugErr && <span className="field-help" role="alert">{plugErr}</span>}+ </div>+ </section>+ )}+{!takesSkills ? (<section className="form-section"><div><h3>Skills</h3><p>What this base can take.</p></div>@@ -419,9 +473,9 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {)}<section className="form-section">- <div><h3>Plugins</h3><p>A plugin is a package of tools and Skills in the Agent Plugins format. What it brings joins this Harness's own tools and Skills on every Task.</p></div>+ <div><h3>Packages</h3><p>A package is a bundle of tools and Skills in the Agent Plugins format. What it brings joins this Harness's own tools and Skills on every Task.</p></div><div className="field-stack">- <div className="section-actions plugin-head"><strong>{(draft?.plugins || []).length} installed {(draft?.plugins || []).length === 1 ? 'plugin' : 'plugins'}</strong>+ <div className="section-actions plugin-head"><strong>{(draft?.plugins || []).length} installed {(draft?.plugins || []).length === 1 ? 'package' : 'packages'}</strong>{!readOnly && <button className="button small" type="button" disabled={pluginBusy} onClick={() => pluginDirRef.current?.click()}><iconify-icon icon="tabler:plus"></iconify-icon>Install from folder</button>}<input ref={pluginDirRef} type="file" hidden onChange={(e) => void installPluginFolder(e.target.files)}@@ -481,8 +535,8 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {<span className="capability-icon"><iconify-icon icon="tabler:puzzle"></iconify-icon></span><div className="capability-copy"><strong>No plugins installed</strong><span>{readOnly- ? 'A built-in Harness carries no plugins. Create a Harness of your own to install packages of tools and Skills.'- : 'A plugin is a folder with a plugin.json at its root, tools in mcp.json and Skills under skills. Install one to add all of it at once.'}</span></div>+ ? 'A built-in Harness carries no packages. Create a Harness of your own to install packages of tools and Skills.'+ : 'A package is a folder with a plugin.json at its root, tools in mcp.json and Skills under skills. Install one to add all of it at once.'}</span></div></div>)}</div>diff --git a/ui/src/components/revamp/Shell.tsx b/ui/src/components/revamp/Shell.tsxindex 36cc583b..9c43fbf0 100644--- a/ui/src/components/revamp/Shell.tsx+++ b/ui/src/components/revamp/Shell.tsx@@ -65,6 +65,9 @@ const NAV_GROUPS: { label: string | null; items: NavItem[] }[] = [// The mark itself, in greyscale (public/harnessrouter-logo-gray.svg, generated by luminance// from the colour mark), stands for the product's core object.{ href: '/harnesses', img: '/harnessrouter-logo-gray.svg', label: 'Agent Harnesses' },+ // Services the workspace connects once (a browser, a repository, a project); each Harness+ // includes the ones it needs under its settings.+ { href: '/plugins', icon: 'tabler:plug-connected', label: 'Plugins' },] },{ label: 'Access', items: [{ href: '/keys', icon: 'tabler:key', label: 'API Keys' },diff --git a/ui/src/lib/edition.ts b/ui/src/lib/edition.tsindex d42e67de..7861285c 100644--- a/ui/src/lib/edition.ts+++ b/ui/src/lib/edition.ts@@ -32,7 +32,7 @@ export const LOCAL_MEMBER = 'local@localhost';* API Keys is here because the box mints and serves them itself: /keys worked in every CE* release and only the entry was missing, so the README sent people to the URL by hand. The* key is how a product calls its own instance, which is the point of self-hosting. */-export const SELF_HOSTED_NAV = ['/kits', '/harnesses', '/tasks', '/keys', '/integrations'];+export const SELF_HOSTED_NAV = ['/kits', '/harnesses', '/tasks', '/plugins', '/keys', '/integrations'];/** Orgs allowed to see platform-admin surfaces (global model routing).*diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.tsindex d3d8b72e..891c49a7 100644--- a/ui/src/lib/harness.ts+++ b/ui/src/lib/harness.ts@@ -537,3 +537,42 @@ export async function storeMcpSecret(serverId: string, token: string): Promise<sif (!r.ok) throw new Error(`mcp-secret store failed: ${r.status}`);return (await r.json()).ref as string;}++// ── plugins: services a workspace connects once, each Harness including the ones it needs ────+export interface PlugPricing { unit: string; usd_per_unit: number; markup: number; source: string; vendor: string; billed_as: string; rounding: string; session_cap_minutes: number; session_estimate_usd: number }+export interface Plug {+ type: string; label: string; source: 'platform' | 'local'; official: boolean;+ status: 'connected' | 'disabled' | 'needs_auth' | 'missing';+ config: Record<string, unknown>; secrets_set: string[]; secrets_needed: string[]; config_fields: string[];+ version: number; tools: number; pricing?: PlugPricing;+}+export const PLUGS_ENTRY_ID = 'mcp.plugs';++/** The plugin catalog for the current workspace, with each plugin's state here. */+export function listPlugs(): Promise<{ workspace: string; plugs: Plug[] }> {+ return gw<{ workspace: string; plugs: Plug[] }>('GET', '/v1/plugs');+}+/** Connect a plugin for the workspace, change its settings, or turn it off. */+export function setPlug(type: string, body: { enabled: boolean; config?: Record<string, unknown>; secrets?: Record<string, string> }): Promise<Plug> {+ return gw<Plug>('PUT', `/v1/plugs/${encodeURIComponent(type)}`, body);+}+export function plugAttachments(type: string): Promise<{ harnesses: number; attached: number; harness_list: { id: string; name: string }[] }> {+ return gw<{ harnesses: number; attached: number; harness_list: { id: string; name: string }[] }>('GET', `/v1/plugs/${encodeURIComponent(type)}/attachments`);+}+export interface HarnessPlugs { id: string; name: string; enabled: boolean; workspace: string; plugs: string[]; tools?: Record<string, string[]>; status: Record<string, string> }+/** The plugins one Harness includes, or null when it includes none. */+export async function getHarnessPlugs(harnessId: string): Promise<HarnessPlugs | null> {+ const r = await harnessFetch(`/api/harness/v1/harnesses/${encodeURIComponent(harnessId)}/servers/${PLUGS_ENTRY_ID}`, { headers: gwHeaders(), cache: 'no-store' });+ if (r.status === 404) return null;+ if (!r.ok) throw new Error(`plugins read failed (${r.status})`);+ return (await r.json()) as HarnessPlugs;+}+/** Set the plugins a Harness includes; an empty list detaches the server. */+export async function setHarnessPlugs(harnessId: string, plugs: string[]): Promise<HarnessPlugs | null> {+ if (plugs.length === 0) {+ const r = await harnessFetch(`/api/harness/v1/harnesses/${encodeURIComponent(harnessId)}/servers/plugs`, { method: 'DELETE', headers: gwHeaders() });+ if (!r.ok && r.status !== 404) throw new Error(`plugins update failed (${r.status})`);+ return null;+ }+ return gw<HarnessPlugs>('POST', `/v1/harnesses/${encodeURIComponent(harnessId)}/servers/plugs`, { plugs });+}