Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

initial: pinchtab — browser control service for AI agents

bot8347f3222391
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..dffc758e
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+node_modules/
+browser-bridge
+pinchtab
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..6f6286da
--- /dev/null
+++ b/README.md
@@ -0,0 +1,75 @@
+# Browser Bridge
+
+Local browser control service for AI agents. Runs on your machine, connects to your Chrome, survives restarts.
+
+## Why
+
+Agents need a browser that:
+- **Persists sessions** — cookies, auth, tabs survive Chrome/agent restarts
+- **Is directly controllable** — any agent talks to it via HTTP, no SDK needed
+- **Uses accessibility trees** — not screenshots. 4x cheaper, works with any LLM
+- **Stays out of the way** — zero config, single process, no cloud
+
+## Architecture
+
+```
+┌─────────────┐ HTTP :18800 ┌──────────────┐ CDP ┌─────────┐
+│ Any Agent │ ──────────────► │ Browser │ ─────────────► │ Chrome │
+│ (OpenClaw, │ snapshot, act, │ Bridge │ DevTools │ │
+│ PicoClaw, │ navigate, eval │ │ Protocol │ │
+│ curl) │ │ sessions + │ │ │
+└─────────────┘ │ tab state │ └─────────┘
+ └──────────────┘
+```
+
+## API
+
+```bash
+# What's open
+curl localhost:18800/tabs
+
+# See the page (accessibility tree — cheap, structured, actionable)
+curl localhost:18800/snapshot?tabId=X
+
+# Interact
+curl -X POST localhost:18800/action -d '{"tabId":"X","kind":"click","ref":"e5"}'
+curl -X POST localhost:18800/action -d '{"tabId":"X","kind":"type","ref":"e12","text":"hello"}'
+
+# Navigate
+curl -X POST localhost:18800/navigate -d '{"tabId":"X","url":"https://example.com"}'
+
+# Run JS
+curl -X POST localhost:18800/evaluate -d '{"tabId":"X","expression":"document.title"}'
+
+# Visual check (opt-in, expensive)
+curl localhost:18800/screenshot?tabId=X
+
+# Readable text (like reader mode)
+curl localhost:18800/text?tabId=X
+```
+
+## Sessions
+
+Browser Bridge saves tab state (URLs, positions) to `~/.browser-bridge/sessions.json`. When Chrome restarts, it restores your tabs. When the bridge restarts, it reconnects.
+
+Auth cookies, localStorage, sessionStorage — all live in Chrome's profile. Bridge doesn't touch them, they just persist naturally.
+
+## Quick Start
+
+```bash
+# 1. Start Chrome with remote debugging
+/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
+
+# 2. Start the bridge
+node server.js
+
+# 3. Use it
+curl localhost:18800/health
+```
+
+## Not Goals
+
+- Not a product, not a cloud service
+- Not a scraping tool
+- Not trying to replace Playwright MCP
+- No plugin system, no SDK, no React UI
diff --git a/TODO.md b/TODO.md
new file mode 100644
index 00000000..e96da553
--- /dev/null
+++ b/TODO.md
@@ -0,0 +1,36 @@
+# Browser Bridge — TODO
+
+## Goal
+Better browser for our agents: session persistence across restarts + direct controllability via HTTP.
+
+## P0: Working Foundation
+- [ ] **Test with Chrome CDP** — restart Chrome with `--remote-debugging-port=9222`
+- [ ] **Session persistence** — save tab state (URLs, scroll position) to `~/.browser-bridge/sessions.json` on shutdown, restore on startup
+- [ ] **Auto-reconnect** — when Chrome restarts, bridge reconnects without dying
+- [ ] **Improve ref resolution** — current `resolveRef()` is fragile. Use CDP `DOM.resolveNode` from a11y node backendDOMNodeId
+- [ ] **`/text` endpoint** — readable text extraction (Readability/Defuddle style) for content reading tasks
+
+## P1: Daily Driver Quality
+- [ ] **Snapshot pruning** — `?filter=interactive` (buttons/links/inputs only), `?depth=N`, `?maxNodes=N`
+- [ ] **Smart diff** — `?diff=true` returns only changes since last snapshot for that tab. Massive token savings on multi-step tasks
+- [ ] **Launch helper** — `node server.js --launch` starts Chrome with CDP flag if not already running
+- [ ] **Graceful shutdown** — save state on SIGTERM/SIGINT, clean disconnect
+- [ ] **Tab restore on Chrome restart** — detect Chrome restart, reopen saved tabs
+- [ ] **Error messages that help** — "Chrome not running with CDP" → "Run: /Applications/Google Chrome.app/... --remote-debugging-port=9222"
+
+## P2: Nice to Have
+- [ ] **File-based output** — `?output=file` saves snapshot to disk, returns path. Agent reads only if needed (Playwright CLI approach, 4x token savings)
+- [ ] **Compact format** — YAML or indented text instead of JSON for snapshots
+- [ ] **Action chaining** — `POST /actions` batch multiple actions in one call
+- [ ] **Docker image** — `docker run browser-bridge` with bundled Chromium
+- [ ] **Config file** — `~/.browser-bridge/config.json` for port, Chrome path, auth token
+- [ ] **LaunchAgent/systemd** — auto-start on boot
+
+## Not Doing
+- Plugin system
+- Proxy rotation / anti-detection
+- Session isolation / multi-tenant
+- Selenium compatibility
+- React UI
+- Cloud anything
+- MCP protocol (HTTP is the interface)
diff --git a/docs/RESEARCH.md b/docs/RESEARCH.md
new file mode 100644
index 00000000..e94da03b
--- /dev/null
+++ b/docs/RESEARCH.md
@@ -0,0 +1,111 @@
+# Browser Bridge — Interface Research
+
+## The Question: Why Screenshots?
+
+Screenshots are the worst way for an AI agent to interact with a browser. Here's why, and what's better.
+
+## Three Approaches Compared
+
+### 1. Screenshots (Vision-based)
+**How it works:** Render page → PNG → base64 → send to vision model → model interprets pixels
+
+**Problems:**
+- **Expensive:** A single screenshot = ~1,000-2,000 tokens (image tokens). A 10-step task burns 10-20k tokens just on screenshots
+- **Slow:** Render → encode → transfer → vision model inference. Each step adds latency
+- **Unreliable:** Vision models hallucinate button positions, misread text, can't see off-screen content
+- **No element refs:** Model says "click the blue button at (342, 187)" — coordinates drift between renders
+- **Requires vision model:** Not all LLMs have vision. Limits which models can use the bridge
+
+**When it's actually useful:**
+- Visual verification (does this page *look* right?)
+- CAPTCHA solving
+- Canvas/WebGL content (no DOM equivalent)
+- Debugging — human wants to see what the agent sees
+
+### 2. Accessibility Tree Snapshots (What we already have)
+**How it works:** CDP `Accessibility.getFullAXTree()` → structured tree → flat JSON with refs
+
+**Advantages:**
+- **~4x cheaper than screenshots** (Playwright team benchmarks: ~27k vs ~114k tokens for same task via MCP)
+- **Fast:** Pure data, no rendering/encoding
+- **Deterministic refs:** `e0`, `e1`, `e2`... — stable element references the agent can click/type
+- **Works with any LLM:** Text-only, no vision required
+- **Semantic:** Role + name + value tells the agent what things *are*, not what they look like
+
+**Limitations:**
+- Doesn't capture visual layout (relative positioning, colors, spacing)
+- Custom widgets with poor ARIA labeling become invisible
+- Very large pages = very large trees (need pruning)
+
+### 3. Playwright CLI Approach (Files on Disk) — NEW
+**How it works:** Snapshots/screenshots saved to disk files, agent reads only what it needs
+
+**Key insight from Playwright CLI (Microsoft, Feb 2026):**
+- MCP returns full snapshot inline → bloats context window
+- CLI saves to `.playwright-cli/snapshot.yaml` → agent reads if needed
+- **4x token reduction** vs MCP for same tasks (27k vs 114k tokens)
+- Screenshots never enter context unless agent explicitly reads the file
+
+**Implication for Browser Bridge:**
+- Add `/snapshot?format=file` — save to disk, return path only
+- Add `/screenshot?save=true` — save PNG to disk, return path
+- Agent decides whether to read the file or just act on previous knowledge
+
+## Hybrid Strategy (Recommended)
+
+The best approach combines methods based on the task:
+
+| Task | Best Method |
+|------|------------|
+| Navigate + interact | Accessibility snapshot (default) |
+| Verify visual appearance | Screenshot (on demand) |
+| Fill forms, click buttons | Snapshot refs (`e0`, `e1`) |
+| Read page content | Snapshot + `/evaluate` for innerText |
+| Debug / human review | Screenshot saved to disk |
+
+### Cost Comparison (Estimated per 10-step task)
+
+| Method | Tokens | Cost (Claude) | Latency |
+|--------|--------|---------------|---------|
+| Screenshot every step | ~20,000 | ~$0.06 | ~500ms/step |
+| A11y snapshot every step (inline) | ~5,000 | ~$0.015 | ~100ms/step |
+| A11y snapshot (file, read 2 of 10) | ~1,500 | ~$0.005 | ~80ms/step |
+| Hybrid (snapshot + 1 screenshot) | ~7,000 | ~$0.02 | ~150ms avg |
+
+## What the Industry Is Doing
+
+### Playwright MCP (Microsoft)
+- **Default:** Accessibility snapshots, no screenshots
+- "Bypasses the need for screenshots or visually-tuned models"
+- Flat YAML format with element refs
+- Vision mode available but opt-in
+
+### Browser Use (open source, 8k+ stars)
+- Uses accessibility tree + optional screenshots
+- Their benchmark: 100 hard tasks, best models hit ~60% success
+- Cost: $10-100 per 100-task evaluation run depending on model
+- Key finding: structured data >> pixel interpretation for reliability
+
+### OpenClaw (what we use)
+- Already does this! `browser` tool uses accessibility snapshots by default
+- `refs="aria"` for stable cross-call references
+- Screenshots available but secondary
+
+### Computer Use (Anthropic/OpenAI)
+- Full screenshot-based approach (most expensive)
+- Works for anything but costs ~10x more tokens
+- Designed for general computer control, not browser-specific tasks
+
+## Key Takeaways
+
+1. **Accessibility tree is the primary interface** — already implemented in our `/snapshot`
+2. **Screenshots should be opt-in, not default** — keep `/screenshot` but don't use it as the main interaction loop
+3. **File-based output reduces tokens dramatically** — add save-to-disk option for both snapshots and screenshots
+4. **Ref resolution is the hardest part** — our current `resolveRef()` uses heuristics. Need to improve this
+5. **Pruning large trees** — add depth/filter params to `/snapshot` to keep token count low
+
+## Sources
+- Playwright MCP: github.com/microsoft/playwright-mcp
+- Playwright CLI benchmarks: testcollab.com/blog/playwright-cli (Feb 2026)
+- Browser Use benchmark: browser-use.com/posts/ai-browser-agent-benchmark
+- "Building Browser Agents" paper: arxiv.org/abs/2511.19477 (Vardanyan, 2025)
diff --git a/docs/STEEL_ANALYSIS.md b/docs/STEEL_ANALYSIS.md
new file mode 100644
index 00000000..ee94f667
--- /dev/null
+++ b/docs/STEEL_ANALYSIS.md
@@ -0,0 +1,120 @@
+# Steel Browser Analysis
+
+**Repo:** github.com/steel-dev/steel-browser
+**Codebase:** ~12,000 lines TypeScript (API only), plus React UI
+**Stack:** Fastify + Puppeteer-core + LevelDB + DuckDB + React
+
+## What Steel Actually Does
+
+Steel is a **scraping/extraction** service that happens to use a browser. It is NOT an agent interaction layer.
+
+### Their 4 Endpoints (that's it)
+1. `POST /scrape` — Navigate to URL, extract HTML/markdown/readability/cleaned_html
+2. `POST /screenshot` — Navigate to URL, return JPEG screenshot
+3. `POST /pdf` — Navigate to URL, return PDF
+4. `POST /search` — Scrape Brave Search results for a query
+
+### What They DON'T Have
+- ❌ **No accessibility tree / snapshot** — Zero references to `accessibility`, `snapshot`, `a11y`, or `AXTree` in the entire codebase
+- ❌ **No element interaction** — No click, type, fill, hover, select
+- ❌ **No action API** — Can't interact with pages at all
+- ❌ **No JS evaluation** — Can't run arbitrary JavaScript
+- ❌ **No tab management** — Single primary page, not multi-tab
+
+### What They DO Have (that we don't)
+- ✅ Plugin system (BasePlugin with lifecycle hooks)
+- ✅ Session management (isolated browser contexts, cookies, localStorage persistence via LevelDB)
+- ✅ Proxy chain support (per-request proxy rotation)
+- ✅ Anti-detection / stealth (fingerprinting, user-agent management)
+- ✅ Selenium WebDriver compatibility layer
+- ✅ File upload/download management
+- ✅ Request logging with DuckDB storage
+- ✅ PDF-to-HTML conversion
+- ✅ HTML-to-Markdown (Turndown + Readability/Defuddle)
+- ✅ React UI for session monitoring
+- ✅ OpenAPI spec (Scalar docs)
+- ✅ Docker packaging
+
+## Architecture Issues
+
+### Overengineered for what it does
+- 12,000 lines of TypeScript for 4 endpoints
+- Plugin system with 7 lifecycle hooks — but ships with no plugins
+- DuckDB + LevelDB + in-memory storage abstractions — for request logs
+- Selenium compatibility layer — adds complexity for legacy support
+- WebSocket proxy infrastructure — for live viewing, not agent control
+
+### Missing the core problem
+Steel solves "how do I scrape web pages reliably" — which is a solved problem (Firecrawl, Crawlee, etc). It does NOT solve "how does an AI agent interact with a web page" — which is the actual hard problem.
+
+**No accessibility tree = no agent interaction.** An agent can't fill a form, click a button, or navigate a SPA with Steel. It can only fetch content.
+
+### Cloud-first mindset baked in
+- Session management designed for multi-tenant cloud (session IDs, isolation)
+- Proxy support for bypassing rate limits at scale
+- Anti-detection for scraping hostile sites
+- All of this is irrelevant for local agent use
+
+## What Browser Bridge Should Be (First Principles)
+
+### The actual problem
+An AI agent needs to:
+1. **See** what's on a page (cheaply, structured)
+2. **Act** on elements (click, type, select)
+3. **Navigate** between pages
+4. **Extract** specific data
+5. **Verify** results
+
+### Minimum viable surface
+```
+GET /tabs # What's open
+GET /snapshot?tabId=X # Accessibility tree (primary interface)
+POST /action {kind, ref, text} # Click/type/fill by a11y ref
+POST /navigate {url} # Go somewhere
+POST /evaluate {expression} # Run JS (escape hatch)
+GET /screenshot?tabId=X # Visual verification (opt-in)
+GET /text?tabId=X # Readable text extraction
+```
+
+That's 7 endpoints. Not 4 wrong ones + 30 supporting files.
+
+### What we should steal from Steel
+1. **HTML-to-Markdown extraction** — Useful for content reading. But as a `/text` endpoint, not the primary interface
+2. **Docker packaging** — Single `docker run` to start
+3. **OpenAPI spec** — Good for any HTTP client to auto-discover
+
+### What we should NOT copy
+1. Session management (overkill for local use)
+2. Plugin system (YAGNI — add when needed)
+3. Selenium compatibility (legacy baggage)
+4. Proxy chains (not our problem)
+5. Anti-detection (not our problem)
+6. React UI (curl is the UI)
+
+## Competitive Position
+
+| Feature | Steel | Browser Bridge | Playwright MCP |
+|---------|-------|---------------|----------------|
+| A11y tree snapshot | ❌ | ✅ | ✅ |
+| Element interaction | ❌ | ✅ | ✅ |
+| Content extraction | ✅ | ⚡ TODO | ❌ |
+| Screenshot | ✅ | ✅ | ✅ (opt-in) |
+| JS evaluation | ❌ | ✅ | ✅ |
+| Multi-tab | ❌ | ✅ | ❌ |
+| Protocol | HTTP | HTTP | MCP (JSON-RPC) |
+| Any agent can use | ✅ | ✅ | ❌ (MCP only) |
+| Docker | ✅ | TODO | ❌ |
+| Lines of code | ~12,000 | ~350 | ~5,000 |
+| Zero config | ❌ | ✅ | ❌ |
+
+**Browser Bridge is already more useful for AI agents than Steel, in 350 lines vs 12,000.**
+
+Steel is a scraping tool marketed as a browser API. We're building an actual agent-browser interface.
+
+## Conclusion
+
+Don't copy Steel. Don't compete with Steel. They solve a different problem (web scraping infrastructure) and solve it with 30x more code than necessary.
+
+Our angle: **the simplest possible bridge between any AI agent and a real browser.** Accessibility-first, HTTP API, zero config, works with curl.
+
+The closest competitor is actually **Playwright MCP** — but that requires MCP protocol support. We're HTTP, which means anything can use us.
diff --git a/go.mod b/go.mod
new file mode 100644
index 00000000..c71221da
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,14 @@
+module github.com/luigi-agosti/pinchtab
+
+go 1.25.0
+
+require (
+ github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d // indirect
+ github.com/chromedp/chromedp v0.14.2 // indirect
+ github.com/chromedp/sysutil v1.1.0 // indirect
+ github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
+ github.com/gobwas/httphead v0.1.0 // indirect
+ github.com/gobwas/pool v0.2.1 // indirect
+ github.com/gobwas/ws v1.4.0 // indirect
+ golang.org/x/sys v0.34.0 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 00000000..69af4558
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,17 @@
+github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d h1:ZtA1sedVbEW7EW80Iz2GR3Ye6PwbJAJXjv7D74xG6HU=
+github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k=
+github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM=
+github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
+github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
+github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
+github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9pEquQS5jTGkh4AqeeHCMbfbjeb0zMt0aEFzs=
+github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M=
+github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
+github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
+github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
+github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
+github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
+github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
+golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
diff --git a/main.go b/main.go
new file mode 100644
index 00000000..bcfb4e4b
--- /dev/null
+++ b/main.go
@@ -0,0 +1,915 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "os/signal"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/cdproto/target"
+ "github.com/chromedp/chromedp"
+ gojson "encoding/json"
+)
+
+// ── Config ─────────────────────────────────────────────────
+
+var (
+ port = envOr("BRIDGE_PORT", "18800")
+ cdpURL = os.Getenv("CDP_URL") // empty = launch Chrome ourselves
+ token = os.Getenv("BRIDGE_TOKEN")
+ stateDir = envOr("BRIDGE_STATE_DIR", filepath.Join(homeDir(), ".browser-bridge"))
+ headless = os.Getenv("BRIDGE_HEADLESS") == "true"
+ profileDir = envOr("BRIDGE_PROFILE", filepath.Join(homeDir(), ".browser-bridge", "chrome-profile"))
+)
+
+// ── State ──────────────────────────────────────────────────
+
+type TabState struct {
+ ID string `json:"id"`
+ URL string `json:"url"`
+ Title string `json:"title"`
+}
+
+type SessionState struct {
+ Tabs []TabState `json:"tabs"`
+ SavedAt string `json:"savedAt"`
+}
+
+type TabEntry struct {
+ ctx context.Context
+ cancel context.CancelFunc
+}
+
+type Bridge struct {
+ allocCtx context.Context
+ browserCtx context.Context // persistent browser context
+ tabs map[string]*TabEntry
+ mu sync.RWMutex
+}
+
+var bridge Bridge
+
+// ── A11y Node (flat) ───────────────────────────────────────
+
+type A11yNode struct {
+ Ref string `json:"ref"`
+ Role string `json:"role"`
+ Name string `json:"name"`
+ Depth int `json:"depth"`
+ Value string `json:"value,omitempty"`
+ Disabled bool `json:"disabled,omitempty"`
+ Focused bool `json:"focused,omitempty"`
+ NodeID int64 `json:"nodeId,omitempty"` // backend DOM node ID for action resolution
+}
+
+// ── Main ───────────────────────────────────────────────────
+
+func main() {
+ os.MkdirAll(stateDir, 0755)
+
+ var allocCancel context.CancelFunc
+
+ if cdpURL != "" {
+ // Remote mode: connect to existing Chrome
+ log.Printf("Connecting to Chrome at %s", cdpURL)
+ bridge.allocCtx, allocCancel = chromedp.NewRemoteAllocator(context.Background(), cdpURL)
+ } else {
+ // Local mode: launch Chrome ourselves
+ os.MkdirAll(profileDir, 0755)
+ log.Printf("Launching Chrome (profile: %s, headless: %v)", profileDir, headless)
+
+ opts := append(chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.UserDataDir(profileDir),
+ chromedp.Flag("disable-background-networking", false),
+ chromedp.Flag("enable-features", "NetworkService,NetworkServiceInProcess"),
+ chromedp.Flag("disable-default-apps", false),
+ chromedp.Flag("no-first-run", true),
+ chromedp.Flag("disable-popup-blocking", true),
+ )
+
+ if headless {
+ opts = append(opts, chromedp.Headless)
+ } else {
+ opts = append(opts, chromedp.Flag("headless", false))
+ }
+
+ bridge.allocCtx, allocCancel = chromedp.NewExecAllocator(context.Background(), opts...)
+ }
+ defer allocCancel()
+
+ // Create persistent browser context (launches Chrome in local mode)
+ browserCtx, browserCancel := chromedp.NewContext(bridge.allocCtx)
+ defer browserCancel()
+
+ // Navigate initial tab to about:blank to initialize
+ if err := chromedp.Run(browserCtx); err != nil {
+ log.Fatalf("Cannot start Chrome: %v", err)
+ }
+ bridge.browserCtx = browserCtx
+ bridge.tabs = make(map[string]*TabEntry)
+
+ // Register the initial tab
+ initTargetID := chromedp.FromContext(browserCtx).Target.TargetID
+ bridge.tabs[string(initTargetID)] = &TabEntry{ctx: browserCtx}
+ log.Printf("Initial tab: %s", initTargetID)
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /health", handleHealth)
+ mux.HandleFunc("GET /tabs", handleTabs)
+ mux.HandleFunc("GET /snapshot", handleSnapshot)
+ mux.HandleFunc("GET /screenshot", handleScreenshot)
+ mux.HandleFunc("GET /text", handleText)
+ mux.HandleFunc("POST /navigate", handleNavigate)
+ mux.HandleFunc("POST /action", handleAction)
+ mux.HandleFunc("POST /evaluate", handleEvaluate)
+ mux.HandleFunc("POST /tab", handleTab)
+
+ // Wrap with auth + CORS
+ handler := corsMiddleware(authMiddleware(mux))
+
+ // Graceful shutdown — save state
+ srv := &http.Server{Addr: ":" + port, Handler: handler}
+ go func() {
+ sig := make(chan os.Signal, 1)
+ signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
+ <-sig
+ log.Println("Shutting down, saving state...")
+ saveState()
+ srv.Shutdown(context.Background())
+ }()
+
+ log.Printf("🌉 Browser Bridge running on http://localhost:%s", port)
+ log.Printf(" CDP target: %s", cdpURL)
+ if token != "" {
+ log.Println(" Auth: Bearer token required")
+ } else {
+ log.Println(" Auth: none (set BRIDGE_TOKEN to enable)")
+ }
+
+ if err := srv.ListenAndServe(); err != http.ErrServerClosed {
+ log.Fatal(err)
+ }
+}
+
+// ── GET /health ────────────────────────────────────────────
+
+func handleHealth(w http.ResponseWriter, r *http.Request) {
+ targets, err := listTargets()
+ if err != nil {
+ jsonResp(w, 200, map[string]any{"status": "disconnected", "error": err.Error(), "cdp": cdpURL})
+ return
+ }
+ jsonResp(w, 200, map[string]any{"status": "ok", "tabs": len(targets), "cdp": cdpURL})
+}
+
+// ── GET /tabs ──────────────────────────────────────────────
+
+func handleTabs(w http.ResponseWriter, r *http.Request) {
+ targets, err := listTargets()
+ if err != nil {
+ jsonErr(w, 500, err)
+ return
+ }
+
+ tabs := make([]map[string]any, 0, len(targets))
+ for _, t := range targets {
+ tabs = append(tabs, map[string]any{
+ "id": string(t.TargetID),
+ "url": t.URL,
+ "title": t.Title,
+ "type": t.Type,
+ })
+ }
+ jsonResp(w, 200, map[string]any{"tabs": tabs})
+}
+
+// ── Raw a11y tree types (to avoid cdproto deserialization issues) ──
+
+type rawAXNode struct {
+ NodeID string `json:"nodeId"`
+ Ignored bool `json:"ignored"`
+ Role *rawAXValue `json:"role"`
+ Name *rawAXValue `json:"name"`
+ Value *rawAXValue `json:"value"`
+ Properties []rawAXProp `json:"properties"`
+ ChildIDs []string `json:"childIds"`
+ BackendDOMNodeID int64 `json:"backendDOMNodeId"`
+}
+
+type rawAXValue struct {
+ Type string `json:"type"`
+ Value gojson.RawMessage `json:"value"`
+}
+
+type rawAXProp struct {
+ Name string `json:"name"`
+ Value *rawAXValue `json:"value"`
+}
+
+func (v *rawAXValue) String() string {
+ if v == nil || v.Value == nil {
+ return ""
+ }
+ var s string
+ if err := gojson.Unmarshal(v.Value, &s); err == nil {
+ return s
+ }
+ // Try number/bool
+ return strings.Trim(string(v.Value), `"`)
+}
+
+// ── GET /snapshot ──────────────────────────────────────────
+
+func handleSnapshot(w http.ResponseWriter, r *http.Request) {
+ tabID := r.URL.Query().Get("tabId")
+ filter := r.URL.Query().Get("filter")
+ maxDepthStr := r.URL.Query().Get("depth")
+ maxDepth := -1
+ if maxDepthStr != "" {
+ if d, err := strconv.Atoi(maxDepthStr); err == nil {
+ maxDepth = d
+ }
+ }
+
+ ctx, cancel, err := tabContext(tabID)
+ if err != nil {
+ jsonErr(w, 404, err)
+ return
+ }
+ defer cancel()
+
+ // Use raw CDP call to avoid cdproto deserialization issues
+ var rawResult gojson.RawMessage
+ if err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx,
+ "Accessibility.getFullAXTree", nil, &rawResult)
+ }),
+ ); err != nil {
+ jsonErr(w, 500, err)
+ return
+ }
+
+ // Parse raw response
+ var treeResp struct {
+ Nodes []rawAXNode `json:"nodes"`
+ }
+ if err := gojson.Unmarshal(rawResult, &treeResp); err != nil {
+ jsonErr(w, 500, fmt.Errorf("parse a11y tree: %v", err))
+ return
+ }
+
+ interactiveRoles := map[string]bool{
+ "button": true, "link": true, "textbox": true, "searchbox": true,
+ "combobox": true, "listbox": true, "option": true, "checkbox": true,
+ "radio": true, "switch": true, "slider": true, "spinbutton": true,
+ "menuitem": true, "menuitemcheckbox": true, "menuitemradio": true,
+ "tab": true, "treeitem": true,
+ }
+
+ // Build parent map for depth
+ parentMap := make(map[string]string)
+ for _, n := range treeResp.Nodes {
+ for _, childID := range n.ChildIDs {
+ parentMap[childID] = n.NodeID
+ }
+ }
+ depthOf := func(nodeID string) int {
+ d := 0
+ cur := nodeID
+ for {
+ p, ok := parentMap[cur]
+ if !ok { break }
+ d++
+ cur = p
+ }
+ return d
+ }
+
+ flat := make([]A11yNode, 0)
+ refID := 0
+
+ for _, n := range treeResp.Nodes {
+ if n.Ignored { continue }
+
+ role := n.Role.String()
+ name := n.Name.String()
+
+ if role == "none" || role == "generic" || role == "InlineTextBox" { continue }
+ if name == "" && role == "StaticText" { continue }
+
+ depth := depthOf(n.NodeID)
+ if maxDepth >= 0 && depth > maxDepth { continue }
+ if filter == "interactive" && !interactiveRoles[role] { continue }
+
+ entry := A11yNode{
+ Ref: fmt.Sprintf("e%d", refID),
+ Role: role,
+ Name: name,
+ Depth: depth,
+ }
+
+ if v := n.Value.String(); v != "" {
+ entry.Value = v
+ }
+ if n.BackendDOMNodeID != 0 {
+ entry.NodeID = n.BackendDOMNodeID
+ }
+
+ for _, prop := range n.Properties {
+ if prop.Name == "disabled" && prop.Value.String() == "true" {
+ entry.Disabled = true
+ }
+ if prop.Name == "focused" && prop.Value.String() == "true" {
+ entry.Focused = true
+ }
+ }
+
+ flat = append(flat, entry)
+ refID++
+ }
+
+ var url, title string
+ chromedp.Run(ctx,
+ chromedp.Location(&url),
+ chromedp.Title(&title),
+ )
+
+ jsonResp(w, 200, map[string]any{
+ "url": url,
+ "title": title,
+ "nodes": flat,
+ "count": len(flat),
+ })
+}
+
+// ── GET /screenshot ────────────────────────────────────────
+
+func handleScreenshot(w http.ResponseWriter, r *http.Request) {
+ tabID := r.URL.Query().Get("tabId")
+
+ ctx, cancel, err := tabContext(tabID)
+ if err != nil {
+ jsonErr(w, 404, err)
+ return
+ }
+ defer cancel()
+
+ var buf []byte
+ quality := 80
+ if q := r.URL.Query().Get("quality"); q != "" {
+ if qn, err := strconv.Atoi(q); err == nil {
+ quality = qn
+ }
+ }
+
+ if err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ var err error
+ buf, err = page.CaptureScreenshot().
+ WithFormat(page.CaptureScreenshotFormatJpeg).
+ WithQuality(int64(quality)).
+ Do(ctx)
+ return err
+ }),
+ ); err != nil {
+ jsonErr(w, 500, err)
+ return
+ }
+
+ // Return raw image if requested
+ if r.URL.Query().Get("raw") == "true" {
+ w.Header().Set("Content-Type", "image/jpeg")
+ w.Write(buf)
+ return
+ }
+
+ jsonResp(w, 200, map[string]any{
+ "format": "jpeg",
+ "base64": buf, // encoding/json will base64-encode []byte
+ })
+}
+
+// ── GET /text ──────────────────────────────────────────────
+
+func handleText(w http.ResponseWriter, r *http.Request) {
+ tabID := r.URL.Query().Get("tabId")
+
+ ctx, cancel, err := tabContext(tabID)
+ if err != nil {
+ jsonErr(w, 404, err)
+ return
+ }
+ defer cancel()
+
+ var text string
+ if err := chromedp.Run(ctx,
+ chromedp.Evaluate(`document.body.innerText`, &text),
+ ); err != nil {
+ jsonErr(w, 500, err)
+ return
+ }
+
+ var url, title string
+ chromedp.Run(ctx,
+ chromedp.Location(&url),
+ chromedp.Title(&title),
+ )
+
+ jsonResp(w, 200, map[string]any{
+ "url": url,
+ "title": title,
+ "text": text,
+ })
+}
+
+// ── POST /navigate ─────────────────────────────────────────
+
+func handleNavigate(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ TabID string `json:"tabId"`
+ URL string `json:"url"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ jsonErr(w, 400, err)
+ return
+ }
+ if req.URL == "" {
+ jsonResp(w, 400, map[string]string{"error": "url required"})
+ return
+ }
+
+ ctx, cancel, err := tabContext(req.TabID)
+ if err != nil {
+ jsonErr(w, 404, err)
+ return
+ }
+ defer cancel()
+
+ if err := chromedp.Run(ctx, chromedp.Navigate(req.URL)); err != nil {
+ jsonErr(w, 500, err)
+ return
+ }
+
+ var url, title string
+ chromedp.Run(ctx,
+ chromedp.Location(&url),
+ chromedp.Title(&title),
+ )
+
+ jsonResp(w, 200, map[string]any{"url": url, "title": title})
+}
+
+// ── POST /action ───────────────────────────────────────────
+
+func handleAction(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ TabID string `json:"tabId"`
+ Kind string `json:"kind"`
+ Ref string `json:"ref"`
+ Selector string `json:"selector"`
+ Text string `json:"text"`
+ Key string `json:"key"`
+ NodeID int64 `json:"nodeId"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ jsonErr(w, 400, err)
+ return
+ }
+
+ ctx, cancel, err := tabContext(req.TabID)
+ if err != nil {
+ jsonErr(w, 404, err)
+ return
+ }
+ defer cancel()
+
+ // Resolve target: prefer nodeId > selector > ref-based lookup
+ var sel string
+ if req.Selector != "" {
+ sel = req.Selector
+ } else if req.NodeID > 0 {
+ // Use JS to find element by backend node ID — chromedp resolves via DOM.resolveNode
+ sel = fmt.Sprintf(`[data-bridge-node="%d"]`, req.NodeID)
+ // For nodeId-based actions, we use chromedp's built-in node resolution
+ }
+
+ var result map[string]any
+
+ switch req.Kind {
+ case "click":
+ if sel != "" {
+ err = chromedp.Run(ctx, chromedp.Click(sel, chromedp.ByQuery))
+ } else if req.Ref != "" {
+ err = clickByRef(ctx, req.Ref)
+ } else {
+ jsonResp(w, 400, map[string]string{"error": "need selector, ref, or nodeId"})
+ return
+ }
+ result = map[string]any{"clicked": true}
+
+ case "type":
+ if req.Text == "" {
+ jsonResp(w, 400, map[string]string{"error": "text required for type"})
+ return
+ }
+ if sel != "" {
+ err = chromedp.Run(ctx,
+ chromedp.Click(sel, chromedp.ByQuery),
+ chromedp.SendKeys(sel, req.Text, chromedp.ByQuery),
+ )
+ } else if req.Ref != "" {
+ err = typeByRef(ctx, req.Ref, req.Text)
+ }
+ result = map[string]any{"typed": req.Text}
+
+ case "fill":
+ if sel != "" {
+ err = chromedp.Run(ctx,
+ chromedp.SetValue(sel, req.Text, chromedp.ByQuery),
+ )
+ }
+ result = map[string]any{"filled": req.Text}
+
+ case "press":
+ if req.Key == "" {
+ jsonResp(w, 400, map[string]string{"error": "key required for press"})
+ return
+ }
+ err = chromedp.Run(ctx, chromedp.KeyEvent(req.Key))
+ result = map[string]any{"pressed": req.Key}
+
+ case "focus":
+ if sel != "" {
+ err = chromedp.Run(ctx, chromedp.Focus(sel, chromedp.ByQuery))
+ }
+ result = map[string]any{"focused": true}
+
+ default:
+ jsonResp(w, 400, map[string]string{"error": fmt.Sprintf("unknown action: %s", req.Kind)})
+ return
+ }
+
+ if err != nil {
+ jsonErr(w, 500, err)
+ return
+ }
+
+ jsonResp(w, 200, result)
+}
+
+// ── POST /evaluate ─────────────────────────────────────────
+
+func handleEvaluate(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ TabID string `json:"tabId"`
+ Expression string `json:"expression"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ jsonErr(w, 400, err)
+ return
+ }
+ if req.Expression == "" {
+ jsonResp(w, 400, map[string]string{"error": "expression required"})
+ return
+ }
+
+ ctx, cancel, err := tabContext(req.TabID)
+ if err != nil {
+ jsonErr(w, 404, err)
+ return
+ }
+ defer cancel()
+
+ var result any
+ if err := chromedp.Run(ctx,
+ chromedp.Evaluate(req.Expression, &result),
+ ); err != nil {
+ jsonErr(w, 500, err)
+ return
+ }
+
+ jsonResp(w, 200, map[string]any{"result": result})
+}
+
+// ── POST /tab ──────────────────────────────────────────────
+
+func handleTab(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Action string `json:"action"` // "new" or "close"
+ TabID string `json:"tabId"`
+ URL string `json:"url"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ jsonErr(w, 400, err)
+ return
+ }
+
+ switch req.Action {
+ case "new":
+ ctx, cancel := chromedp.NewContext(bridge.browserCtx)
+
+ url := "about:blank"
+ if req.URL != "" {
+ url = req.URL
+ }
+ if err := chromedp.Run(ctx, chromedp.Navigate(url)); err != nil {
+ cancel()
+ jsonErr(w, 500, err)
+ return
+ }
+
+ // Register in tab registry
+ newTargetID := string(chromedp.FromContext(ctx).Target.TargetID)
+ bridge.mu.Lock()
+ bridge.tabs[newTargetID] = &TabEntry{ctx: ctx, cancel: cancel}
+ bridge.mu.Unlock()
+
+ var curURL, title string
+ chromedp.Run(ctx, chromedp.Location(&curURL), chromedp.Title(&title))
+ jsonResp(w, 200, map[string]any{"tabId": newTargetID, "url": curURL, "title": title})
+
+ case "close":
+ if req.TabID == "" {
+ jsonResp(w, 400, map[string]string{"error": "tabId required"})
+ return
+ }
+ ctx, cancel := chromedp.NewContext(bridge.browserCtx,
+ chromedp.WithTargetID(target.ID(req.TabID)),
+ )
+ defer cancel()
+ if err := chromedp.Run(ctx, page.Close()); err != nil {
+ jsonErr(w, 500, err)
+ return
+ }
+ jsonResp(w, 200, map[string]any{"closed": true})
+
+ default:
+ jsonResp(w, 400, map[string]string{"error": "action must be 'new' or 'close'"})
+ }
+}
+
+// ── Ref-based actions ──────────────────────────────────────
+
+func clickByRef(ctx context.Context, ref string) error {
+ nodeID, err := resolveRefToNodeID(ctx, ref)
+ if err != nil {
+ return err
+ }
+ return chromedp.Run(ctx,
+ chromedp.Evaluate(fmt.Sprintf(`
+ (function() {
+ const node = document.querySelector('[data-bridge-ref="%s"]');
+ if (node) { node.click(); return true; }
+ // Fallback: find by walking
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
+ let n, i = 0;
+ while (n = walker.nextNode()) {
+ if (n.getAttribute && n.getAttribute('data-bridge-nid') === '%d') {
+ n.click(); return true;
+ }
+ }
+ return false;
+ })()
+ `, ref, nodeID), nil),
+ )
+}
+
+func typeByRef(ctx context.Context, ref string, text string) error {
+ _, err := resolveRefToNodeID(ctx, ref)
+ if err != nil {
+ return err
+ }
+ // Focus then type via keyboard
+ return chromedp.Run(ctx,
+ chromedp.Evaluate(fmt.Sprintf(`
+ (function() {
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
+ let n;
+ while (n = walker.nextNode()) {
+ if (n.getAttribute && n.getAttribute('data-bridge-ref') === '%s') {
+ n.focus(); return true;
+ }
+ }
+ return false;
+ })()
+ `, ref), nil),
+ chromedp.KeyEvent(text),
+ )
+}
+
+func resolveRefToNodeID(ctx context.Context, ref string) (int64, error) {
+ refNum := 0
+ fmt.Sscanf(strings.TrimPrefix(ref, "e"), "%d", &refNum)
+
+ var rawResult gojson.RawMessage
+ if err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx,
+ "Accessibility.getFullAXTree", nil, &rawResult)
+ }),
+ ); err != nil {
+ return 0, err
+ }
+
+ var treeResp struct {
+ Nodes []rawAXNode `json:"nodes"`
+ }
+ if err := gojson.Unmarshal(rawResult, &treeResp); err != nil {
+ return 0, err
+ }
+
+ idx := 0
+ for _, n := range treeResp.Nodes {
+ if n.Ignored { continue }
+ role := n.Role.String()
+ if role == "none" || role == "generic" || role == "InlineTextBox" { continue }
+ name := n.Name.String()
+ if name == "" && role == "StaticText" { continue }
+
+ if idx == refNum {
+ if n.BackendDOMNodeID != 0 {
+ return n.BackendDOMNodeID, nil
+ }
+ return 0, fmt.Errorf("node at ref %s has no backend DOM node", ref)
+ }
+ idx++
+ }
+
+ return 0, fmt.Errorf("ref %s not found (max: e%d)", ref, idx-1)
+}
+
+// ── Tab context helper ─────────────────────────────────────
+
+func tabContext(tabID string) (context.Context, context.CancelFunc, error) {
+ bridge.mu.RLock()
+ defer bridge.mu.RUnlock()
+
+ if tabID == "" {
+ // Use first page target
+ targets, err := listTargets()
+ if err != nil {
+ return nil, nil, err
+ }
+ if len(targets) == 0 {
+ return nil, nil, fmt.Errorf("no tabs open")
+ }
+ tabID = string(targets[0].TargetID)
+ }
+
+ // Check registry first
+ if entry, ok := bridge.tabs[tabID]; ok {
+ noop := func() {}
+ return entry.ctx, noop, nil
+ }
+
+ // Create new context for this target
+ ctx, cancel := chromedp.NewContext(bridge.browserCtx,
+ chromedp.WithTargetID(target.ID(tabID)),
+ )
+ if err := chromedp.Run(ctx); err != nil {
+ cancel()
+ return nil, nil, fmt.Errorf("tab %s not found: %v", tabID, err)
+ }
+
+ // Don't cancel — store in registry (caller gets noop cancel)
+ bridge.mu.RUnlock()
+ bridge.mu.Lock()
+ bridge.tabs[tabID] = &TabEntry{ctx: ctx, cancel: cancel}
+ bridge.mu.Unlock()
+ bridge.mu.RLock()
+
+ noop := func() {}
+ return ctx, noop, nil
+}
+
+func listTargets() ([]*target.Info, error) {
+ var targets []*target.Info
+ if err := chromedp.Run(bridge.browserCtx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ var err error
+ targets, err = target.GetTargets().Do(ctx)
+ return err
+ }),
+ ); err != nil {
+ return nil, err
+ }
+
+ // Filter to page targets only
+ pages := make([]*target.Info, 0)
+ for _, t := range targets {
+ if t.Type == "page" {
+ pages = append(pages, t)
+ }
+ }
+ return pages, nil
+}
+
+// ── Session persistence ────────────────────────────────────
+
+func saveState() {
+ targets, err := listTargets()
+ if err != nil {
+ log.Printf("Failed to save state: %v", err)
+ return
+ }
+
+ tabs := make([]TabState, 0, len(targets))
+ for _, t := range targets {
+ if t.URL != "" && t.URL != "about:blank" && t.URL != "chrome://newtab/" {
+ tabs = append(tabs, TabState{
+ ID: string(t.TargetID),
+ URL: t.URL,
+ Title: t.Title,
+ })
+ }
+ }
+
+ state := SessionState{
+ Tabs: tabs,
+ SavedAt: time.Now().UTC().Format(time.RFC3339),
+ }
+
+ data, _ := json.MarshalIndent(state, "", " ")
+ path := filepath.Join(stateDir, "sessions.json")
+ if err := os.WriteFile(path, data, 0644); err != nil {
+ log.Printf("Failed to write state: %v", err)
+ } else {
+ log.Printf("Saved %d tabs to %s", len(tabs), path)
+ }
+}
+
+func loadState() *SessionState {
+ path := filepath.Join(stateDir, "sessions.json")
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return nil
+ }
+ var state SessionState
+ if err := json.Unmarshal(data, &state); err != nil {
+ return nil
+ }
+ return &state
+}
+
+// ── Middleware ──────────────────────────────────────────────
+
+func authMiddleware(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if token != "" {
+ auth := r.Header.Get("Authorization")
+ if auth != "Bearer "+token {
+ jsonResp(w, 401, map[string]string{"error": "unauthorized"})
+ return
+ }
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+func corsMiddleware(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Access-Control-Allow-Origin", "*")
+ w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
+ w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
+ if r.Method == "OPTIONS" {
+ w.WriteHeader(204)
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+// ── Helpers ────────────────────────────────────────────────
+
+func jsonResp(w http.ResponseWriter, code int, data any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(code)
+ json.NewEncoder(w).Encode(data)
+}
+
+func jsonErr(w http.ResponseWriter, code int, err error) {
+ jsonResp(w, code, map[string]string{"error": err.Error()})
+}
+
+func envOr(key, fallback string) string {
+ if v := os.Getenv(key); v != "" {
+ return v
+ }
+ return fallback
+}
+
+func homeDir() string {
+ h, _ := os.UserHomeDir()
+ return h
+}