# ESP — Echo-Skeleton Perception ESP is a stateful, event-driven screen-perception runtime for text-only computer-use agents. Classical pixel processing, OCR, and active coordinate probes build a persistent text skeleton. After initialization, agents receive typed changes instead of a fresh screenshot at every step. The model never receives image bytes. Playwright and Tesseract form the mechanical perception layer; any model that can emit JSON tool calls can act as the reasoner. ## Status This repository now contains a reusable implementation of the paper architecture under `src/esp/`, deterministic browser tasks, unit/integration tests, model adapters, and runnable examples. Implemented: - variance quadtree with retained region hierarchy; - content-region coalescing and duplicate suppression; - bounded PNG cropping and confidence-bearing Tesseract OCR; - multi-point hit testing for clickable, editable, disabled, and scrollable affordances; - title/ARIA label hints and keyboard focus primitives; - persistent node identity with `appeared`, `changed`, and `vanished` events; - resize-safe frame differencing; - quiet detection, action windows, explicit `no_change`, and animation muting; - schema-validated `click`, `type`, `scroll`, `wait_for`, `probe`, `read`, and `focus_next` actions; - one initial hierarchical skeleton payload followed by event-only perception payloads; - external goal verification rather than trusting a model's `done` claim; - Ollama and OpenAI-compatible model adapters; - exact ESP contract-payload bytes, model request-body bytes, provider token usage when available, and perception-operation counters. The implementation is an experimental runtime, not evidence that H1–H4 are supported. Current integration tests cover deterministic T1 upload and form/modal workflows. T2 frozen-site tasks, T3 canvas/animation/flaky-control suites, baseline agents, repeated trials, and statistical reporting remain experimental work. ## Requirements - Node.js 20 or newer - Tesseract available as `tesseract` on `PATH` - Playwright Chromium - Ollama only when running the model-driven example ```bash npm install npx playwright install chromium npm test ``` ## Run the deterministic perception example ```bash npm run demo ``` This drives `experiments/tasks/t1/upload.html` through ESP, verifies the real page state, prints the complete trace, and writes a timestamped JSON artifact under `experiments/results/esp/`. ## Run a blind local model ```bash ollama serve ollama pull qwen3:4b ESP_MODEL=qwen3:4b npm run agent ``` The Ollama adapter receives only JSON skeleton/event messages. Page screenshots remain inside the perception runtime. ## Library API ```js import { chromium } from "playwright"; import { createEspSession, OllamaModel, runAgent, } from "./src/esp/index.mjs"; const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto("https://example.test/task"); const session = createEspSession({ page }); const model = new OllamaModel({ model: "qwen3:4b" }); const result = await runAgent({ session, model, goal: "Complete the task.", verify: async () => page.locator("[data-success]").isVisible(), }); await browser.close(); ``` For an existing agent framework, call `session.start()` once and then `session.act(action)` on each turn. The first return value has `type: "skeleton"`; subsequent values have `type: "events"` and intentionally omit the full node list. The bundled stateless HTTP model adapters still resend conversation history on each request, as chat-completion APIs require; their wire accounting includes those repeated request bodies. ## Action schema ```json {"type":"click","nodeId":12} {"type":"type","nodeId":8,"text":"Ada Lovelace"} {"type":"scroll","nodeId":4,"dy":600} {"type":"wait_for","event":"appeared","timeoutMs":5000} {"type":"probe","nodeId":7} {"type":"read","nodeId":9} {"type":"focus_next"} {"type":"done","detail":"Observed completion confirmation"} ``` `EspSession` validates node existence and affordance before executing an action. A click against an inert or disabled node is rejected rather than sent to the page. ## Source layout ```text src/esp/ agent.mjs model-independent agent loop and action parser events.mjs action windows, no-change, quiet, salience filtering geometry.mjs safe screen-box operations hierarchy.mjs compact model-facing containment tree index.mjs public exports and createEspSession() models.mjs Ollama and OpenAI-compatible adapters ocr.mjs bounded PNG crops and Tesseract TSV parsing perception.mjs screenshot → regions → OCR/probes → persistent events pixels.mjs grayscale decode, quadtree, coalescing, frame diffs probe.mjs multi-point affordance probes and focus walk session.mjs safe action execution and event-only agent contract skeleton.mjs stable node matching and lifecycle events src/examples/ runnable production-API examples src/poc/ original rough proof of concept, retained for comparison experiments/tasks/ deterministic local task pages experiments/results generated traces and recordings paper/ thesis and pre-registered hypotheses launch/ launch-video source and rendered assets tests/ unit and Playwright integration tests ``` ## Tests ```bash npm run test:unit npm test ``` The full suite launches Chromium and runs real Tesseract OCR. Unit tests use injected mechanical adapters where deterministic edge-case coverage is more useful. ## Measurement discipline `session.metrics()` reports exact UTF-8 bytes in ESP's skeleton/event payloads as `contractPayloadBytes`, plus exact counts for screenshots, full scans, OCR calls, and probes. This is not model-wire traffic. Bundled model adapters separately report cumulative serialized `requestBodyBytes`—including retransmitted conversation history—and provider-reported prompt/completion token counts when the endpoint supplies them. Experimental token accounting must use the exact tested endpoint and tokenizer rather than treating payload bytes as tokens. Task success must always be scored by a page/environment predicate, never by the model's self-report. See `paper/sections/06-plan.tex` for the pre-registered comparisons and decision rules. ## Known limits - Pixel segmentation can still under- or over-segment visually unusual controls. - OCR remains the principal semantic bottleneck, especially for stylized fonts and non-Latin text. - Browser probes infer affordances from rendered hit targets and conventions; custom controls can lie. - Hover-dwell tooltip/repaint discovery and spatial controls inside a single canvas remain incomplete. - This implementation polls screenshots when no dirty-rectangle transport is available. A VNC/RDP dirty-rectangle adapter is still needed for the paper's lowest-latency deployment path. - CAPTCHA, chart interpretation, color judgment, and other irreducibly visual tasks require a separate vision fallback. No empirical claim in the paper should be marked supported until the registered baseline matrix has been run and archived. ## Build the paper ```bash cd paper tectonic main.tex ```