Skip to content

Latest commit

 

History

History
290 lines (235 loc) · 19.1 KB

architecture.md

File metadata and controls

290 lines (235 loc) · 19.1 KB

browser-skill architecture

Developer-oriented overview of how the CLI, daemon, and extension fit together. Consolidates design §2, §3, §5, and §6.

System diagram

The diagram shows the default local setup. In remote mode, the CLI and daemon run on a server; the extension connects from the user's browser over authenticated WSS. CLI-to-daemon communication remains local IPC on the server.

flowchart TB
  subgraph harness [Agent harness]
    Agent[Claude Code / Cursor / Codex]
  end

  subgraph host [Developer machine]
  Agent -->|shell: bsk ...| CLI[bsk CLI]
  Agent <-->|stdio MCP| MCP[bsk mcp — 11 domain tools]
  CLI <-->|IpcEnvelope JSONL / UDS or Named Pipe| Daemon[bsk daemon]
  MCP <-->|IpcEnvelope JSONL / UDS or Named Pipe| Daemon
  Daemon <-->|WebSocket JSON — Protocol 2.0| Ext[bsk extension MV3]
  end

  subgraph browser [Chromium]
  Ext -->|CDP + WebExt| Tabs[User tabs + Agent Windows]
  end

  Skill[SKILL.md] -.->|documents workflow| Agent
Loading

Components

bsk CLI & MCP server (crates/bsk-cli)

  • Parses verb-noun subcommands (bsk open, bsk sync, bsk click, bsk step, bsk plan, …) and hosts the stdio MCP server (bsk mcp) exposing 11 default domain tools (bsk_session, bsk_page, bsk_inspect, bsk_interact, bsk_plan, bsk_tabs, bsk_assist, bsk_ledger, bsk_debug, bsk_video, bsk_record, plus opt-in bsk_recipe when BSK_RECIPES=1).
  • Uses IPC to discover a running daemon. Automatically starts one only when discovery or its listener is absent, unless BSK_AUTO_START=0 disables implicit startup. See sandboxed agent setup for host-managed daemons.
  • Speaks IpcEnvelope JSON Lines over $BSK_HOME/run/daemon.sock (Unix domain socket) or a deterministic Named Pipe \\.\pipe\bsk-daemon-<hash> derived from the user and endpoint/BSK_HOME (Windows); the default home is ~/.bsk.
  • Renders human-readable output by default; --json emits structured responses.

Key modules:

Module Role
cli/ Clap command tree, zero-ceremony lifecycle (open/sync/close), step/plan/view, and cli/mcp/ (11 MCP domain tools)
ipc_client.rs UDS / Windows Named Pipe client, IpcEnvelope line framing, rolling-upgrade envelope negotiation
daemon/ WS server, SessionRegistry (queue + activity leases), ImplicitScopeRegistry (scopes.rs), IntentWal (intent_wal.rs), DialogOperations, RunLogs, idle shutdown

bsk daemon (same binary: bsk daemon)

  • In local mode, listens on loopback WebSocket (default 52800, configurable with bsk daemon start --port) for extensions. The extension popup saves the matching connection port; saving ends existing sessions and reconnects when enabled.
  • Server mode supports authenticated remote extension connections with device pairing, renewal and revocation. Native TLS or a TLS reverse proxy provides WSS; the deployment supervisor owns server restarts.
  • Validates Origin: chrome-extension://… on upgrade and authenticates paired local peers with nonce-bound HMAC proofs before the business handshake. Local pairing is optional; unpaired peers retain the legacy handshake. Paired identities cannot be claimed by unverified peers unless TrustLocal is explicitly enabled. Origin is transcript context, not authorization. See local pairing.
  • Maintains browsers (connected extensions), sessions (Agent Window bindings + RAII activity leases), scopes (caller-isolated implicit session/tab bindings, short cN/oN receipt aliases, and authoritative VOM cache), intent_wal (per-session/tab side-effect ledger gating retries after effect_state: "unknown"), dialog_operations (per-session native dialog state and decision lock), and run_logs (per-tab redacted step trace).
  • Per-session queue serializes session-queued tool calls while allowing Unlocked control/wait operations (tool.cooperate, tool.dialog_accept, tool.dialog_dismiss, operation.*) to run with active session liveness leases.
  • Forwards tool.* RPCs to the correct extension connection.

State files under ~/.bsk/:

File Purpose
daemon.lock Advisory lock — single daemon instance
local-pairings.json Local daemon identity, active/unactivated devices and pending key transactions; private atomic storage
settings.json Persistent local authentication policy
daemon.json { sock_path, pid, ws_port, version, protocol_version, ipc_envelope }
intent_ledger.jsonl Durable append-only IntentWal journal for uncertain browser side effects
daemon.log Rolling trace log
daemon.pid PID for status/doctor

bsk extension (apps/extension)

WXT / MV3 Chromium extension. Built with React popup and a service worker background.

Directory Responsibility
transport/ WSTransport + generated Protocol 2.0 contracts (transport/generated/)
cooperation/ CooperationController (target & strict guard policies, human intervention detection, VOM delta patching)
tools/ ToolDispatcher → tool handlers, dialog control, file transfers, DOM extraction
session-manager/ Sessions, Agent Window, stable ref-store (@e1)
browser-driver/ CDP-backed browser operations
entrypoints/popup/ Connection status & pairing UI
content/ Control overlay & human activity probes in controlled tabs

bsk-protocol (crates/bsk-protocol)

Single source of truth (MethodSpec in method.rs + catalog.rs) for Protocol 2.0 wire frames, dispatch/deadline/outcome policies, ActionMetadata injection, JSON Schemas (crates/bsk-protocol/schema/), and generated TypeScript contracts (apps/extension/src/transport/generated/, verified by pnpm protocol:check).

Control policy and action evidence

Protocol 2.0 enforces a unified handshake floor across CLI, daemon, and extension (see version compatibility) and negotiates control_policy on tool.cooperate sync/enable. Zero-ceremony bsk open / bsk sync, cooperate sync, and step post-syncs request auto by default, selecting target policy for an unconfigured session and preserving an established policy thereafter. Explicit --policy strict or --policy target fixes the session's policy on first sync. Daemon ImplicitScopeRegistry mints short cN / oN aliases for context_id / observation_id in CLI and MCP envelopes and caches the latest authoritative VOM per (session_id, tab_id) across unchanged and text-patched delta syncs.

ActionMetadata defines the shared wire fields below. Schema generation merges them into guarded action parameter schemas, including script/file operations and the active variants of observe/debug. Passive variants do not evaluate conditions. Operation structs retain their existing fields; generated clients can combine them with the shared metadata without inventing a separate protocol. Expectation target and attribute limits count Unicode code points.

Field Contract
context_id Caller-supplied control receipt bound to session, tab, document and human intervention epoch. Reusable for target-policy DOM actions; single-use under strict policy.
observation_id Sync's strict baseline for target-policy actions without a DOM recipient, including scripts and visual clicks. Supplementary reads do not replace this baseline. Under strict policy, drag retains its existing optional ref-map freshness token; target-policy DOM drag uses stable refs.
expect Up to 16 literal target conditions: text, value, checked, attribute or exists, each with equals; only attribute conditions carry an attribute name. Text is exact textContent, including whitespace. Selectors search the main document; frame/shadow targets require observed refs. Target/attribute limits are 1024/256 Unicode code points.
depends_on Legacy strict-policy decision regions. Target policy rejects it with guidance to use explicit conditions.

Target policy checks the resolved element and declared facts before input, preserving native hit testing and the human-control dispatch fence without recapturing the whole VOM on ordinary DOM actions. Stable refs identify nodes across supplementary observations; document replacement invalidates them, and visual captures keep their own single-use freshness rules. A recycled table row is still the same node, so business identity must be an explicit condition. Refs also do not freeze a node's role, name or action meaning: a Save button changed in place to Delete requires an explicit text/attribute condition when that distinction matters. Inferred VOM labels are not automatically treated as DOM text or a frozen semantic fingerprint. Conditions are browser-side preconditions, not an atomic transaction with the application server.

Action failures preserve reason, phase, effect_state and recovery guidance; failed conditions include target, field, expected and actual values. Unknown outcomes require application reconciliation. The daemon and bsk mcp never replace explicit caller receipts or automatically replay a business action. Completed tool results survive ordinary page/frame changes and unavailable post-action collection. Document or coverage changes still revoke the old context; subsequent actions require a fresh sync. In-flight input guards, human intervention, stop and cancellation remain enforced. A completed tool result does not by itself prove that the application committed a business transaction. See shared browser control for lifecycle details and regressions.

Typical tool call

  1. Agent uses its sync receipt: bsk click @e1 --tab-id 42 --session ab12 --context CONTEXT_ID.
  2. CLI ensures daemon is running, opens UDS, sends one JSON request line.
  3. Daemon resolves session ab12 → browser client → forwards tool.click over WS.
  4. Extension dispatcher validates sandbox rules, invokes CDP via BrowserDriver.
  5. Response travels CLI ← daemon ← extension; CLI prints result and exits.

The scroll-to primitive reference documents tool.scroll_to, including its CLI/MCP mappings, visible-bounds contract and cancellation behavior. It follows the same routing path and is classified as a browser mutation for session queueing and user-interruption gating.

Structured extraction follows the same routing path as a passive read. The extension gathers bounded DOM facts and normalizes tables/lists; the CLI owns CSV encoding and file output. Discovery handles are scoped to session, tab, attachment and frame document. See structured extraction.

Session and sandbox model

  • Session = opaque ID (4 lowercase letters in v0.1) + dedicated Agent Window
    • session-scoped ref-store + borrow table.
  • Sandbox-only: write tools require tabs inside the Agent Window unless the tab was borrowed from the user profile.
  • Session stop is mandatory in agent workflows (bsk session stop); idle timeout (default 5 min) is a safety net only.
  • Multiple sessions on one browser → multiple Agent Windows, fully isolated.
  • Remote content reads and actions require task-created or explicitly borrowed tabs. A page-opened popup or a user tab moved into the Agent Window does not become controlled automatically; see remote tab ownership.

tab_list scopes

scope Visible tabs
user User profile windows (default)
agent Current session's Agent Window only
all Agent Window + user windows for this session

Concurrency

Scope Policy
Same session Daemon serializes RPCs (ref-store safety)
Different sessions Parallel
Multiple browsers bsk session start --browser <id> when >1 extension connected

Module dependency graph

flowchart LR
  subgraph rust [Rust workspace]
    CLI[bsk CLI crate]
    Proto[bsk-protocol]
    CLI --> Proto
  end

  subgraph ts [Extension]
    BG[background]
    T[Transport]
    D[ToolDispatcher]
    SM[SessionManager]
    BD[BrowserDriver]
    BG --> T
    BG --> D
    D --> SM
    D --> BD
    SM --> BD
  end

  CLI <-->|JSON protocol| T
Loading

Connection security

  • Local mode binds WebSocket to loopback. Server mode permits remote access through authenticated WSS; plaintext listeners remain on loopback behind TLS termination or for development.
  • Extension origin allow-list at WS upgrade.
  • Website cookies stay in the user's browser profile. Remote device credentials are stored in extension-origin IndexedDB; the built-in server stores credential hashes in its private BSK_HOME. Pairing and device grants govern remote access.
  • evaluate restricted to Agent Window tabs in sandbox mode.
  • Operation audit, when enabled, is stored on the daemon host, including the server in remote mode. See operation audit.

File-transfer boundary

Upload and download are supported only for local connections. Remote sessions return unsupported; screenshots and other RPC content results remain available.

  • The invoking agent/harness decides whether a transfer is authorized and supplies the task-local source or destination path.
  • The CLI is the only component that reads an upload source or writes the final download destination. Before browser dispatch it owns rollback of partially staged uploads; after dispatch, ownership moves to the session because a transport timeout cannot prove that Chrome did not attach the file. Download output becomes visible through one atomic commit, and replacement is opt-in without a pre-delete window. The extension never receives either agent-facing path.
  • The daemon is the authority for storage capabilities and limits. It issues opaque session-scoped transfer IDs, stages bounded chunks in a private runtime directory, and injects only private staged upload paths. For download it mints one relative Chrome directory capability. Only after validating the reported path, file type, symlink boundary, and authoritative byte limit does it take ownership of browser-file cleanup and import the bytes.
  • The extension owns only the browser transaction. Every transfer resolves one ResolvedActionTarget. The default upload mechanism arms Chrome's chooser interception before clicking, then accepts either an exact Page.fileChooserOpened input node or an independent probe anchored in the trigger node's document; one verified input is committed with DOM.setFileInputFiles, while a non-input picker is rejected immediately. Explicit drop mode performs no click and never falls back to the chooser mechanism: after geometry resolution it temporarily excludes BrowserSkill's own overlay, verifies that the resolved drop zone still owns its local action point, and sends one native dragEnter / dragOver / drop transaction to that node's CDP target before restoring the overlay. OOPIF drops use target-local coordinates rather than top-level click coordinates. Download correlates exact-target CDP intent and chrome.downloads filename candidates in either arrival order, claims only one unique match, and never cancels an unclaimed candidate. When the click opens a new tab instead (for example a target="_blank" attachment link), the clicked target receives no CDP intent; the URL of a webNavigation navigation target whose source is the clicked tab and that appears after the mouse press is then the intent, and only candidates observed after the press can match it.
  • Browser-side operations report effect_state (none, committed, or unknown), phase, and cleanup_state. Confirmed success wins over a late cancel; an unknown effect is preserved across timeout or transport loss and must not be retried blindly. A transfer deadline sends cancellation to the extension and keeps the session queue occupied for bounded compensation rather than abandoning an in-flight browser effect.
  • Download staging is released after CLI commit. Upload staging remains until session teardown because the page may read an attached file only on a later form submission. Remaining staging is released on session stop/browser disconnect and on daemon startup after a crash. BrowserSkill does not inspect content or decide whether a transfer is appropriate.

Repository layout

browser-skill/
├── apps/extension/       # WXT Chromium extension
├── crates/
│   ├── bsk-cli/           # `bsk` binary (CLI + daemon)
│   │   └── skill/        # Canonical CLI SKILL.md + references/
│   └── bsk-protocol/      # Wire types + schemas
├── install.sh            # CLI installer (GitHub Releases)
└── docs/                 # architecture, guides

crates/bsk-cli/skill/ is the single canonical authored skill source. The CLI build embeds every file from its crate-local directory without copying or modifying sources. Installation writes the complete package. A versioned .bsk-source manifest tracks SHA-256 checksums per file; automatic updates verify all managed files and new-path collisions before replacing anything. Resources precede the entry point, and a pending manifest records expected old/new hashes so interrupted writes can be resumed safely. Known historical single-file checksums in src/skill_install/legacy-digests.txt are migration data, not a separate instruction source. They recognize exact LF originals and CRLF copies; recorded per-file checksums remain byte-exact. Frozen pre-bundle snapshots under tests/fixtures/legacy-skills/ cover adoption and edit protection without requiring Git history during CI. Explicit custom installations opt out. CI validates local links, entry point budgets, and Cargo package contents.

Local authorization lifecycle

The extension first sends system.ping with params.local_auth. The daemon selects an offered active or staged credential and proves possession of its key; only then does the extension send its client proof. No business frames, registry updates or session purges happen before authorization succeeds.

Activation and requested rotation persist a candidate, send ready.rotation, wait for the extension's strict IndexedDB commit and confirmation, then durably commit before sending committed. Recovery uses ready.commit, the saved key, and the current connection transcript. The extension promotes the candidate strictly before its business handshake. Exactly one final message is accepted.

Device gates serialize the prelude, rotation, final authorization plus registry insertion, and revocation. Replacement activates the new record and revokes the old one atomically; socket and session cleanup finishes before success is reported. The daemon owns its loaded store only after acquiring daemon.lock. Online maintenance uses IPC; offline maintenance holds that same lock. Persistent revocation is also checked every second without blocking the async executor.

The extension shares IndexedDB version 2 between independent connection, local and migration stores. Keys never enter chrome.storage, URLs sent over the network, or logs. A staged verifier has its own socket and no business dispatcher. The business transport reports connected only after its authenticator finishes.