Skip to content

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

docs: verify readme and docs against the code, fix stale commands, endpoints, config and architecture, and index current guides

Luigi Agosti47890c2f4ec5
diff --git a/README.md b/README.md
index 9ce8c280..11068284 100644
--- a/README.md
+++ b/README.md
@@ -17,7 +17,7 @@
<td align="left" valign="middle">
<a href="https://github.com/pinchtab/pinchtab/releases/latest"><img src="https://img.shields.io/github/v/release/pinchtab/pinchtab?style=flat-square&color=FFD700" alt="Release"/></a><br/>
<a href="https://github.com/pinchtab/pinchtab/actions/workflows/ci-go.yml"><img src="https://img.shields.io/github/actions/workflow/status/pinchtab/pinchtab/ci-go.yml?branch=main&style=flat-square&label=Go%20CI" alt="Go CI"/></a><br/>
- <img src="https://img.shields.io/badge/Go-1.25+-00ADD8?style=flat-square&logo=go&logoColor=white" alt="Go 1.25+"/><br/>
+ <img src="https://img.shields.io/badge/Go-1.26+-00ADD8?style=flat-square&logo=go&logoColor=white" alt="Go 1.26+"/><br/>
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue?style=flat-square" alt="License"/></a>
</td>
</tr>
@@ -52,7 +52,7 @@ If you prefer not to run a daemon, or if you're on Windows, you can instead run:
`pinchtab server` — runs the control-plane server directly
`pinchtab bridge` — runs a single browser instance as a lightweight runtime
-PinchTab also provides a CLI with an interactive entry point for local setup and common tasks:
+Running bare `pinchtab` runs the security setup on first use, then prints server status, the security posture, and suggested next steps:
`pinchtab`
@@ -165,7 +165,7 @@ The primary user journey is:
4. let PinchTab act as your local browser service
That is the default “replace the browser runtime” scenario.
-Most users should not need to think about `pinchtab bridge` directly, and only need `pinchtab` when they want the local interactive menu.
+Most users should not need to think about `pinchtab bridge` directly, and only need bare `pinchtab` for first-run setup or a status overview.
Agent plugins (binary still installed separately):
@@ -185,7 +185,7 @@ Grok users can install from the PinchTab repository marketplace or directly from
- **Token-efficient** — 800 tokens/page with text extraction (5-13x cheaper than screenshots)
- **Headless or Headed** — Run without a window or with visible Chrome
- **Multi-instance** — Run multiple parallel Chrome processes with isolated profiles
-- **Self-contained** — ~15MB binary, no external dependencies
+- **Self-contained** — single ~30MB binary; drives a locally installed Chrome or Chromium
- **Accessibility-first** — Element refs that denote a DOM node, not a row: the same `e5` survives a change of filter, selector or depth (filtered views are sparse), and expires only on navigation to a new document
- **ARM64-optimized** — First-class Raspberry Pi support with automatic Chromium detection
- **CloakBrowser support** — Optional drop-in provider for sites that fingerprint stock Chromium. PinchTab launches a user-supplied CloakBrowser binary; no CloakBrowser is bundled in released artifacts. See [docs/guides/cloakbrowser.md](docs/guides/cloakbrowser.md).
@@ -305,28 +305,34 @@ pinchtab click e5
pinchtab text
```
-Or use the HTTP API directly:
+Or use the HTTP API directly (every request needs the server token):
```bash
+export PINCHTAB_TOKEN=$(pinchtab config token --stdout)
+
# Create a profile first (returns profile id)
PROF=$(curl -s -X POST http://localhost:9867/profiles \
+ -H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"work"}' | jq -r '.id')
# Start an instance for that profile (returns instance id)
INST=$(curl -s -X POST http://localhost:9867/instances/start \
+ -H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"profileId\":\"$PROF\",\"mode\":\"headless\"}" | jq -r '.id')
# Open a tab in that instance
TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \
+ -H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d '{"url":"https://pinchtab.com"}' | jq -r '.tabId')
# Get snapshot
-curl "http://localhost:9867/tabs/$TAB/snapshot?filter=interactive"
+curl -H "Authorization: Bearer $PINCHTAB_TOKEN" "http://localhost:9867/tabs/$TAB/snapshot?filter=interactive"
# Click element
curl -X POST "http://localhost:9867/tabs/$TAB/action" \
+ -H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d '{"kind":"click","ref":"e5"}'
```
@@ -384,7 +390,7 @@ methodology, per-run tables, and raw logs.
## Privacy
-PinchTab is a fully open-source, local-first tool. No telemetry, no analytics, and no required outbound service dependency. The binary binds to `127.0.0.1` by default. Persistent profiles store browser sessions locally on your machine, similar to how a human reuses their browser. Remote and distributed deployments are available for advanced use cases, but they are explicit operator-managed setups rather than the default posture. The single Go binary (~16 MB) is fully verifiable: build from source at [github.com/pinchtab/pinchtab](https://github.com/pinchtab/pinchtab).
+PinchTab is a fully open-source, local-first tool. No telemetry, no analytics, and no required outbound service dependency. The binary binds to `127.0.0.1` by default. Persistent profiles store browser sessions locally on your machine, similar to how a human reuses their browser. Remote and distributed deployments are available for advanced use cases, but they are explicit operator-managed setups rather than the default posture. The single Go binary (~30 MB) is fully verifiable: build from source at [github.com/pinchtab/pinchtab](https://github.com/pinchtab/pinchtab).
---
@@ -416,17 +422,19 @@ pinchtab text # ~800 tokens instead of 10,000
### Multi-Instance Workflows
```bash
-# Run multiple instances in parallel
+# Run multiple instances in parallel (profiles "alice" and "bob" must already exist — see POST /profiles above)
curl -s -X POST http://localhost:9867/instances/start \
+ -H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d '{"profileId":"alice","mode":"headless"}'
curl -s -X POST http://localhost:9867/instances/start \
+ -H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d '{"profileId":"bob","mode":"headless"}'
# Each instance is isolated
-curl http://localhost:9867/instances
+curl -H "Authorization: Bearer $PINCHTAB_TOKEN" http://localhost:9867/instances
```
See [chrome-files.md](docs/implementations/chrome-files.md) for technical details on how PinchTab manages Chrome user data directories and ensures isolation between parallel instances.
diff --git a/docs/architecture/autosolver.md b/docs/architecture/autosolver.md
index c2afb634..d3f459a0 100644
--- a/docs/architecture/autosolver.md
+++ b/docs/architecture/autosolver.md
@@ -58,26 +58,28 @@ internal/autosolver/
├── autosolver.go # Core orchestrator with fallback chain
├── challenge_detection.go # Shared challenge classification (title/URL/HTML)
├── heuristics.go # Title-based intent detection fallback
+├── keygated.go # Solvers that register only once their API key is set
├── registry.go # Instance-level solver registry with priority ordering
-├── autosolver_test.go # Core loop tests
-├── challenge_detection_test.go
-├── registry_test.go
├── adapters/
│ └── pinchtab.go # Bridge adapter (ONLY chromedp import)
+├── catalog/
+│ └── catalog.go # Single owner of the names autoSolver.solvers accepts
├── semantic/
│ └── adapter.go # Wraps pinchtab/semantic ElementMatcher
├── external/
+│ ├── external.go # Shared external-solver wrapper
│ ├── capsolver.go # Capsolver API skeleton
│ └── twocaptcha.go # 2Captcha API skeleton
├── llm/
-│ ├── llm.go # LLM provider skeleton with structured prompts
-│ └── trim.go # HTML trimming for token efficiency
+│ └── llm.go # LLM provider skeleton with structured prompts
└── solvers/
├── cloudflare.go # Cloudflare Turnstile solver
- ├── jschallenge.go # Generic JavaScript challenge/interstitial solver
- └── jschallenge_test.go
+ └── jschallenge.go # Generic JavaScript challenge/interstitial solver
```
+Tests sit next to each file (`*_test.go`). HTML trimming for the LLM prompt
+lives in the shared `internal/htmltrim` package.
+
## Core Interfaces
### Page
@@ -89,6 +91,7 @@ type Page interface {
URL() string
Title() string
HTML() (string, error)
+ HTMLWithin(timeout time.Duration) (string, error)
Screenshot() ([]byte, error)
}
```
@@ -130,17 +133,18 @@ type Solver interface {
## Fallback Chain
-The core loop executes this chain per attempt:
+Intent is detected once, before the first attempt; the core loop then executes
+the rest of this chain per attempt:
```
-1. Detect intent (semantic engine → title heuristics)
+1. Detect intent (semantic engine, or title heuristics when none is configured)
2. If intent = normal → return solved
3. Try semantic-first action planning (`/find` + self-healing)
4. If still unresolved, find matching solvers (CanHandle = true)
5. Execute solvers in configured order (`autoSolver.solvers`), falling back to
priority order when configuration does not match available solvers
6. If all fail AND LLM enabled:
- a. Trim HTML to ~4KB
+ a. Trim HTML to ~4KB (`htmltrim.TrimHTML`, 4000-byte cap)
b. Build structured prompt with attempt history
c. Execute LLM-suggested action
7. Retry with exponential backoff (500ms → 10s cap)
diff --git a/docs/architecture/browser-abstraction.md b/docs/architecture/browser-abstraction.md
index dac32d59..19775c50 100644
--- a/docs/architecture/browser-abstraction.md
+++ b/docs/architecture/browser-abstraction.md
@@ -20,7 +20,7 @@ abstraction each:
| Config validation | `internal/config/browser_targets.go` | registry-driven (`browsers.Get`/`browsers.IDs`) |
| Lifecycle cleanup | `internal/browsers/providerhooks/` | registered `Hooks` (decorate, cleanup, shutdown) |
-`Engine` (`chrome` / `lite` / `auto`) — **deprecated**; replaced by the browser provider model (`chrome` / `cloak` / `ghost-chrome`). See [routing-contract.md](routing-contract.md) and [terminology.md](terminology.md) for the canonical provider definitions. `Capabilities` are additional concepts layered on top, partially wired.
+`Engine` (`chrome` / `lite` / `auto`) — **removed** from config (`server.engine` now fails validation); replaced by the browser provider model (`chrome` / `cloak` / `ghost-chrome`). See [routing-contract.md](routing-contract.md) and [terminology.md](terminology.md) for the canonical provider definitions. `Capabilities` are additional concepts layered on top, partially wired.
## Goal
@@ -42,9 +42,12 @@ internal/browsers/
browser.go // Browser interface + registry
config.go // LaunchConfig, GeoConfig, TargetConfig (provider-neutral)
capabilities.go // CapabilitySet (moved from config/)
- common/ // shared chrome-family helpers (proxy auth, profile, CDP url discovery)
+ runtimekit/ // shared launch-plan resolution (ResolveProviderLaunchPlan)
+ providerhooks/ // optional bridge decoration + cleanup/shutdown hooks
+ all/, builtin/ // barrel packages that blank-import every built-in provider
chrome/ // chrome implementation, registers itself
cloak/ // cloak implementation, composes chrome
+ ghostchrome/ // static-first provider (staticfetch + bridgekit adapter)
lightpanda/ // future
brave/ // future
```
@@ -72,6 +75,10 @@ type Browser interface {
// Strategy hooks
GeoAlignment(geo GeoConfig) GeoStrategy
ValidateTarget(cfg TargetConfig) error
+ ClassifyLaunchError(f LaunchFailure) LaunchErrorKind
+
+ // Request routing (see routing-contract.md)
+ CanHandle(intent RequestIntent) HandleDecision
}
type GeoStrategy struct {
@@ -82,7 +89,7 @@ type GeoStrategy struct {
var registry = map[string]Browser{}
-func Register(b Browser) { registry[b.ID()] = b }
+func Register(b Browser) { registry[b.ID()] = b } // panics on duplicate ID
func Get(id string) (Browser, bool) { b, ok := registry[id]; return b, ok }
func IDs() []string { /* sorted list */ }
```
@@ -98,32 +105,29 @@ Importers wire providers via a barrel file (e.g. `internal/browsers/all/all.go`)
### Launch mode
-`LaunchMode` controls **headed vs headless** browser launch state. It is
-purely about the display mode of the browser process — not about which
-provider handles a request (that is the provider model's job).
-
-> **Deprecation note:** The `chrome` / `lite` / `auto` engine values that
-> previously occupied this field are fully superseded by the browser provider
-> model (`chrome` / `cloak` / `ghost-chrome`). The `Engine` field is
-> deprecated and will be removed. See [terminology.md](terminology.md).
+`LaunchMode` (`internal/browsers/config.go`) is internal only: `chrome`,
+`lite`, or `auto`. `runtimekit` derives it from the configured default browser,
+and `ResolveLaunchMode` maps `auto` (and unknown values) to `chrome`. It is not
+public config — public selection uses browser provider names
+(`chrome` / `cloak` / `ghost-chrome`); the old public `Engine` field was removed.
+See [terminology.md](terminology.md).
-`Mode` is a field on `LaunchConfig`:
+Headed vs headless is a separate `Headless` bool on `LaunchConfig`:
```go
type LaunchConfig struct {
- Mode LaunchMode // headed | headless (internal only)
- Binary string
- UserDir string
- Proxy ProxyConfig
+ Mode LaunchMode // chrome | lite | auto (internal only)
+ Binary string
+ ProfileDir string
+ Proxy ProxyConfig
ExtraFlags []string
+ Headless bool // true → --headless=new + swiftshader flags
// ...
}
```
-- `headed`: full headful Chromium with GUI.
-- `headless`: headless Chromium (`--headless=new` + lightweight flags).
-
-A provider may reject a mode it cannot serve (e.g. a future `lightpanda` rejects `headed` mode).
+A provider may reject a mode it cannot serve: `chrome` and `cloak` both
+return an error for `lite`.
### Cloak as composition over Chrome
@@ -155,19 +159,26 @@ func (b Browser) DiscoverBinary() browsers.BinaryDiscovery {
### Doctor
-`doctor/runner.go` becomes a thin orchestrator:
+`doctor/runner.go` is a thin orchestrator that pulls checks from the
+configured browser only:
```go
-func Registry(cfg config.Config) []Check {
- base := []Check{configFileCheck, binaryExistsCheck, binaryExecutableCheck, binaryStartsCheck}
- for _, id := range browsers.IDs() {
- b, _ := browsers.Get(id)
- base = append(base, b.DoctorChecks(cfg.ResolveTarget())...)
+func Registry(cfg *config.RuntimeConfig) []CheckEntry {
+ entries := []CheckEntry{{Name: "config_file", Fn: checkConfigFile}}
+ browserID := config.NormalizeBrowser(browserFromCfg(cfg))
+ if b, ok := browsers.Get(browserID); ok {
+ for _, dc := range b.DoctorChecks(browsers.TargetConfig{Provider: browserID}) {
+ entries = append(entries, /* CheckEntry wrapping dc */)
+ }
}
- return base
+ // then binary_exists, binary_executable, binary_starts
+ return entries
}
```
+`internal/doctor/browsers.go` (`ReportBrowsers`) separately walks every
+registered browser for the multi-browser report.
+
Provider-specific checks (`cdp_reachable`, `fingerprint_flags_accepted`, `linux_fonts_present`) move into `browsers/cloak/doctor.go`.
### Config validation
@@ -306,7 +317,7 @@ The target architecture is implemented through Phase 6. Key components:
and signals `*bridge.StaticEscalateError` instead of escalating internally,
so Chrome is launched only when actually needed. Phase 2 re-runs with
`SkipStatic`. The timeout budget is per phase (each phase gets
- `NavigateTimeout`, default 30s), so a navigate that escalates can take up
+ `NavigateTimeout`, default 60s), so a navigate that escalates can take up
to twice the configured timeout.
- **Route metadata** — `usedProvider` is consistently `"ghost-chrome"` for all
adapter paths. Static vs Chrome routing recorded in `Attempts[]`.
@@ -331,14 +342,14 @@ The target architecture is implemented through Phase 6. Key components:
lives inside the adapter.
4. **No separate routing package for browsers.** The `routing.Route()`
- function and its `ghostchrome.StaticFetcher` adapter exist only
- because handlers can't call `Browser.Route()` through BridgeAPI. Once
+ function and its `ghostchrome.StaticFetcher` adapter existed only
+ because handlers couldn't call `Browser.Route()` through BridgeAPI. Once
BridgeAPI has Navigate/Snapshot/Text, routing decisions happen inside
the adapter.
-5. **The server layer is thin wiring.** `configureBridgeRouter` creates
- the adapter and sets `h.Bridge = adapter`. Nothing else. No
- `h.StaticBrowser = ...`.
+5. **The server layer is thin wiring.** `configureBridgeRouter` asks
+ `providerhooks.DecorateBridge` for the configured browser and sets
+ `h.Bridge` to the result. Nothing else. No `h.StaticBrowser = ...`.
### Violations
@@ -392,7 +403,8 @@ Incremental. Each phase lands independently.
`bridgekit.BridgeAdapter` (`internal/browsers/ghostchrome/bridgekit/bridge_adapter.go`)
wraps `bridge.BridgeAPI` and a `ghostchrome.BridgeProxy`. All
ghost-chrome static-vs-Chrome routing decisions are encapsulated here.
-Server layer creates the adapter via `bridgekit.NewBridgeAdapter(chromeBridge, cfg)`.
+`bridgekit`'s `init()` registers a `providerhooks.Hooks.DecorateBridge` for
+`ghost-chrome` that calls `bridgekit.NewBridgeAdapter(chromeBridge, cfg)`.
**Phase 3 — Remove StaticBrowser from Handlers.** COMPLETE
`StaticBrowser` field, `useStaticBrowser()`, `shouldUseStaticAction()`,
@@ -410,10 +422,11 @@ zero ghost-chrome awareness.
```go
func configureBridgeRouter(h *handlers.Handlers, cfg *config.RuntimeConfig) {
- if cfg.DefaultBrowser != config.BrowserGhostChrome {
+ decorated := providerhooks.DecorateBridge(config.NormalizeBrowser(cfg.DefaultBrowser), h.Bridge, cfg)
+ if decorated == h.Bridge {
return
}
- h.Bridge = bridgekit.NewBridgeAdapter(h.Bridge, cfg)
+ h.Bridge = decorated
}
```
diff --git a/docs/architecture/browser-runtime.md b/docs/architecture/browser-runtime.md
index 2c994624..240ae0fd 100644
--- a/docs/architecture/browser-runtime.md
+++ b/docs/architecture/browser-runtime.md
@@ -6,7 +6,7 @@ Related: [browser-abstraction.md](browser-abstraction.md), [routing-contract.md]
## Overview
Handlers have zero chromedp/cdproto imports. All browser operations go
-through BridgeAPI (~40 methods). CDP usage is contained in the bridge
+through BridgeAPI (~75 methods). CDP usage is contained in the bridge
layer and the cdptk shared toolkit. Post-launch behavior belongs to the
Bridge; providers shape it declaratively through `Capabilities()`.
@@ -14,7 +14,7 @@ Bridge; providers shape it declaratively through `Capabilities()`.
```
┌─────────────────────────────────────────────────────────┐
-│ Handlers (54 files) │
+│ Handlers (internal/handlers) │
│ │
│ Zero chromedp imports. Zero cdproto imports. │
│ All operations via bridge.BridgeAPI. │
@@ -34,7 +34,7 @@ Bridge; providers shape it declaratively through `Capabilities()`.
│ BridgeAPI (domain types, no CDP types)
▼
┌─────────────────────────────────────────────────────────┐
-│ Bridge (BridgeAPI — ~40 methods) │
+│ Bridge (BridgeAPI — ~75 methods) │
│ │
│ Owns: lifecycle, tab routing, locks, auto-close, │
│ network monitoring, CDP connection │
@@ -69,12 +69,13 @@ Bridge; providers shape it declaratively through `Capabilities()`.
│ Pure functions. No state. No browser ownership. │
│ Takes a chromedp context, returns data. │
│ │
-│ cdptk.CaptureScreenshot(ctx, format, quality, clip) │
-│ cdptk.ClipForNode(ctx, backendNodeID) → *ScreenshotClip│
-│ cdptk.ScreencastRepaintLoop(ctx) (start/stop) │
-│ cdptk.AnnotatedScreenshot(ctx, ...) → []byte │
+│ cdptk.CaptureWithSurfaceFallback(fromSurface, capture) │
+│ cdptk.ClipForNode(ctx, nodeID, css1x) → *ScreenshotClip│
+│ cdptk.StartRepaintLoop(ctx) → stop func │
+│ cdptk.InjectInteractiveOverlay / AnnotationRectForNode │
│ │
-│ Used by the bridge. Never by handlers. │
+│ Used by the bridge; handlers call it only for the │
+│ screenshot/annotate overlay helpers. │
└─────────────────────────────────────────────────────────┘
```
@@ -144,7 +145,7 @@ browser's capability set.
| bridge/ | Page, DOM, Runtime, Network, Fetch, Emulation, Input, Target | All browser operations delegated from handlers |
| cdptk/ | Page, DOM, Runtime | Shared pure-function CDP wrappers |
| browsers/chrome/ | Runtime (via `chromedp.Evaluate`) | Launch-probe diagnostics only; no post-launch operations |
-| handlers/ | None | All operations via BridgeAPI |
+| handlers/ | None directly | All operations via BridgeAPI; annotation overlays via cdptk helpers |
## Non-goals
diff --git a/docs/architecture/extract.md b/docs/architecture/extract.md
index ae6862a9..feabf997 100644
--- a/docs/architecture/extract.md
+++ b/docs/architecture/extract.md
@@ -81,10 +81,12 @@ above the threshold (default `0.3`, same as `find`):
`x-pinchtab-hint` accepts either a bare query or a selector, restricted to the
kinds a node list can answer without a browser:
-- a bare string → used verbatim as the query,
+- a bare string → used verbatim as the query (except a bare `eN`, which is a
+ ref, and a bare `//…` XPath, which is rejected),
- `find:` → the natural-language query,
-- `role:`, `label:`, `placeholder:`, `alt:`, `title:`, `testid:` → routed
- through `selector.SemanticQuery` so the grammar stays single-sourced with the
+- `role:`, `label:`, `placeholder:`, `alt:`, `title:`, `testid:`, and
+ `first:` / `last:` / `nth:` wrapping one of those → routed through
+ `selector.SemanticQuery` so the grammar stays single-sourced with the
action and `find` paths,
- `text:` → the text as a query,
- `ref:` (or a bare `eN`) → selects that node verbatim; a ref that is not in the
@@ -94,6 +96,14 @@ kinds a node list can answer without a browser:
A hint that resolves beats the name-based query, so an agent can pin an ambiguous
field (e.g. a sale price among several prices) without renaming the schema.
+### Request scope
+
+`POST /extract` also takes an optional top-level `scope`, parsed with the same
+grammar as a hint (`Schema.WithScope`). When set, it is resolved once over the
+whole node list and the entire schema then resolves inside the matched node's
+subtree only. A scope that matches nothing reports every field with reason
+`scope_not_found` and lists the required ones in `missing`.
+
## Arrays of objects
An `array` property resolves to one object per repeated group in the snapshot.
diff --git a/docs/architecture/find.md b/docs/architecture/find.md
index 52bb6d8e..2a7e2e47 100644
--- a/docs/architecture/find.md
+++ b/docs/architecture/find.md
@@ -19,6 +19,7 @@ The implementation is designed to stay:
accessibility snapshot
-> DOM metadata enrichment
-> element descriptors
+ -> IDPI scan of the candidate text (when enabled)
-> lexical matcher
-> embedding matcher
-> combined score
diff --git a/docs/architecture/geo-provider.md b/docs/architecture/geo-provider.md
index 59ac1ff1..59b7d7b0 100644
--- a/docs/architecture/geo-provider.md
+++ b/docs/architecture/geo-provider.md
@@ -6,7 +6,7 @@ The geo provider (`internal/config/geo`) resolves geographic information for a
proxy egress IP so users can wire "automatic" geo alignment without supplying
`browser.proxy.geo.*` by hand.
-P4b ships only the `Noop` and `Static` providers. This note captures the
+The package currently ships only the `Noop` and `Static` providers. This note captures the
proposed contract for a future HTTP-backed provider so the design lives in
documentation rather than as ballast in the compiled package.
diff --git a/docs/architecture/index.md b/docs/architecture/index.md
index d86a6261..53e351e9 100644
--- a/docs/architecture/index.md
+++ b/docs/architecture/index.md
@@ -17,7 +17,7 @@ Today, the main production shape is:
PinchTab also supports an advanced attach path:
-- the server can register an externally managed Chrome instance through `POST /instances/attach`
+- the server can front an externally managed Chrome instance through `POST /instances/attach` (it launches a child `pinchtab bridge --cdp-attach` against the CDP URL), or register an already running bridge through `POST /instances/attach-bridge`
- attach is policy-gated by `security.attach.enabled`, `security.attach.allowHosts`, and `security.attach.allowSchemes`
The current managed implementation is bridge-backed. Any direct-CDP-only managed model is architectural discussion elsewhere, not the default runtime path in this codebase.
@@ -62,18 +62,19 @@ For the normal multi-instance server path, the flow is:
```mermaid
flowchart LR
R["HTTP Request"] --> M["Auth + Middleware"]
- M --> P["Policy Checks"]
- P --> X["Routing / Instance Resolution"]
+ M --> X["Routing / Instance Resolution"]
X --> B["Bridge Handler"]
- B --> C["Chrome via CDP"]
+ B --> P["Handler Policy Checks"]
+ P --> C["Chrome via CDP"]
C --> O["JSON / Text / PDF / Image Response"]
```
Important details:
- auth and common middleware run at the HTTP layer
-- policy checks include attach policy and, when enabled, IDPI protections
+- attach policy is enforced on the attach routes in the server
- tab-scoped routes are resolved to the owning instance before execution
+- browser-facing checks (open-dialog guard, domain policy, and IDPI when enabled) run in the bridge handlers, before any CDP work
- the bridge runtime performs the actual CDP work
In bridge-only mode, the orchestrator and multi-instance routing layers are skipped, but the same browser handler model still applies.
@@ -107,7 +108,7 @@ When `security.idpi` is enabled, the current implementation can:
Architecturally, this keeps policy separate from routing and execution:
```text
-request -> middleware/policy -> routing -> execution -> response
+request -> middleware -> routing -> handler policy -> execution -> response
```
## Design Principles
@@ -124,7 +125,9 @@ The most important packages for the current architecture are:
- `cmd/pinchtab`: process startup modes and CLI entrypoints
- `internal/orchestrator`: instance lifecycle, attach, and tab-to-instance proxying
+- `internal/instance`: tab-to-instance locator cache and instance allocation used by the orchestrator
- `internal/bridge`: browser runtime, tab state, and CDP execution
+- `internal/browsers`: browser provider registry (`chrome`, `cloak`, `ghost-chrome`)
- `internal/handlers`: single-instance HTTP handlers
- `internal/profiles`: persistent profile management
- `internal/strategy`: server-side routing behavior for shorthand requests
diff --git a/docs/architecture/instance-charts.md b/docs/architecture/instance-charts.md
index d72ec5ee..c22678b8 100644
--- a/docs/architecture/instance-charts.md
+++ b/docs/architecture/instance-charts.md
@@ -12,14 +12,15 @@ flowchart TD
I --> A["Attached"]
M --> MB["Bridge-backed"]
- A --> EX["External Chrome registration"]
+ A --> EX["External Chrome via child bridge (cdp-bridge)"]
+ A --> EB["External bridge registration (bridge)"]
```
Current meaning:
- **managed** means PinchTab launches and owns the runtime lifecycle
-- **attached** means PinchTab registers an already running external Chrome
-- **bridge-backed** means the server reaches the browser through a `pinchtab bridge` runtime
+- **attached** means PinchTab fronts something it did not launch: an already running external Chrome (`POST /instances/attach`, through a child `pinchtab bridge --cdp-attach`) or an already running bridge server (`POST /instances/attach-bridge`)
+- **bridge-backed** means the server reaches the browser through a `pinchtab bridge` runtime; that holds for every instance type
## Chart 2: Managed Instance Shape
@@ -44,16 +45,19 @@ For managed instances today:
```mermaid
flowchart LR
S["PinchTab Server"] --> O["Orchestrator"]
- O -. "attach via CDP URL" .-> E["External Chrome"]
+ O --> B["pinchtab bridge --cdp-attach child"]
+ B -. "CDP URL" .-> E["External Chrome"]
E --> T["Tabs"]
+ O -. "attach-bridge" .-> XB["External pinchtab bridge"]
```
For attached instances today:
- PinchTab does not launch the browser
+- for a CDP attach, PinchTab launches and stops a child bridge that connects to the external browser; for `attach-bridge` it only registers the remote bridge's URL
- PinchTab stores registration metadata in the instance registry
- ownership of the external browser process stays outside PinchTab
-- attached registration exists today, but the normal managed-instance tab proxy path is still centered on bridge-backed instances
+- both attach types expose a bridge URL, so tab-scoped routes proxy to them the same way as to managed instances
## Chart 4: Ownership Model
@@ -85,7 +89,7 @@ flowchart TD
The important runtime rule is:
- tabs belong to one instance
-- for managed bridge-backed instances, tab-scoped server routes are resolved to the owning instance before proxying
+- tab-scoped server routes are resolved to the owning instance before proxying, for managed and attached instances alike
## Current Instance Fields
@@ -102,13 +106,16 @@ The main instance fields surfaced by the current API are:
- `startTime`
- `error`
- `attached`
-- `attachType` (`cdp` or `bridge`, for attached instances)
+- `attachType` (`cdp-bridge` or `bridge`, for attached instances)
- `cdpUrl`
- `securityPolicy`
+- `browser`
+- `responsiveness`
+- `crashes`, `fallbackFrom`, `fallbackReason` (when present)
Useful interpretation:
- `attached: false` usually means a managed bridge-backed instance
- `attached: true` means an externally registered instance
-- `port` is relevant for managed bridge-backed instances
-- `cdpUrl` is relevant for attached instances
+- `port` is relevant for managed and CDP-attached instances (the child bridge's port)
+- `cdpUrl` is relevant for CDP-attached instances
diff --git a/docs/architecture/mcp.md b/docs/architecture/mcp.md
index cca788df..be71c761 100644
--- a/docs/architecture/mcp.md
+++ b/docs/architecture/mcp.md
@@ -33,9 +33,10 @@ pinchtab mcp
├── reads config port (default http://127.0.0.1:9867)
├── --server flag (override for remote servers)
├── reads PINCHTAB_TOKEN (env or config)
+ ├── ensureServerForCLI (auto-starts a local server when allowed)
│
├── creates internal/mcp.Client (HTTP client with 120 s timeout)
- ├── registers 38 MCP tools via mcp-go SDK
+ ├── registers 47 MCP tools via mcp-go SDK
└── calls server.ServeStdio() (blocking read loop)
```
@@ -46,15 +47,23 @@ The process exits when stdin is closed by the client.
```
internal/mcp/
├── server.go # NewServer() wires tools → handlers; Serve() starts stdio
-├── tools.go # allTools() — JSON-schema tool definitions for all 38 tools
-├── handlers.go # handlerMap() — registers each tool's handler
+├── tools.go # allTools() — JSON-schema tool definitions for all 47 tools
+├── tools_params.go # shared parameter builders (tabId, browser, snap, …)
+├── tools_a11y.go # a11y_audit tool + handler
+├── tools_memory.go # memory, memory_snapshot, memory_compare tools + handlers
+├── handlers.go # handlerMap() — wraps each tool's handler with argument checks
+├── argcheck.go # declared-argument + typed-argument validation from the tool schema
+├── routing.go # routedQuery/routedPath — puts `browser` where the router reads it
├── handlers_helpers.go # shared argument parsing / response helpers
-├── handlers_navigation.go # navigate, snapshot, frame, screenshot, get_text
-├── handlers_interaction.go # click, type, press, hover, focus, select, scroll(_into_view), fill
-├── handlers_content.go # eval, pdf, find
-├── handlers_tabs.go # list_tabs, close_tab, health, cookies, connect_profile
-├── handlers_wait.go # wait, wait_for_selector/text/url/load/function
-├── handlers_network.go # network, network_detail/clear/route/unroute
+├── handlers_navigation.go # navigate, back/forward/reload, snapshot, frame, screenshot, capture, get_text
+├── handlers_interaction.go # click, type, hover, focus, select, scroll(_into_view), fill, key
+├── handlers_content.go # eval, pdf, find, extract
+├── handlers_tabs.go # list_tabs, close_tab, health, handoff/resume/handoff_status, cookies(_set), connect_profile
+├── handlers_wait.go # wait (fixed ms or selector/text/url/load/function condition)
+├── handlers_network.go # network, network_detail/clear/route/unroute/rules
+├── handlers_diagnostics.go # console, errors
+├── handlers_record.go # record
+├── handlers_scrape.go # scrape
├── handlers_dialog.go # dialog
└── client.go # Client — thin HTTP wrapper for PinchTab REST API
@@ -76,13 +85,13 @@ cmd/pinchtab/
- a human-readable description used by the LLM to select the right tool
- typed parameter schemas with `Required()` / `Description()` annotations
-The declarations are grouped by category: Navigation, Interaction, Keyboard, Content, Tab Management, Wait utilities, Network, and Dialog.
+The declarations are ordered roughly by category: Navigation, Interaction, Keyboard, Content, Tab Management, Wait utilities, Network, Diagnostics, Dialog, and Scrape.
### handlers.go
-Each handler is a factory function returning a `func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error)` closure. Handlers:
+Each handler is a factory function returning a `func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error)` closure. `handlerMap` wraps every handler in `withTypedArgChecks`, which first rejects any argument the tool's schema does not declare (naming the closest declared argument) and any declared number/integer/boolean argument whose value has the wrong type, returning a tool error before the handler runs. Handlers then:
-1. Extract and validate arguments from `r.GetArguments()`
+1. Extract arguments from `r.GetArguments()`
2. Build the corresponding PinchTab REST payload
3. Call `c.Get` or `c.Post` with the request context
4. Return `mcp.NewToolResultText` on success or `mcp.NewToolResultError` on HTTP 4xx/5xx
@@ -103,14 +112,16 @@ URL validation lives in `handleNavigate` (`handlers_navigation.go`), which calls
| Category | Count | REST Endpoints Used |
|----------|-------|---------------------|
-| Navigation | 5 | `/navigate`, `/snapshot`, `/frame`, `/screenshot`, `/text` |
+| Navigation | 9 | `/navigate`, `/back`, `/forward`, `/reload`, `/snapshot`, `/frame`, `/screenshot`, `/capture`, `/text` |
| Interaction | 8 | `/action` |
| Keyboard | 1 | `/action` |
-| Content | 3 | `/evaluate`, `/pdf`, `/find` |
-| Tab Management | 5 | `/tabs`, `/health`, `/cookies`, `/profiles/{id}/instance` |
+| Content | 4 | `/evaluate`, `/pdf`, `/find`, `/extract` |
+| Tab Management | 9 | `/tabs`, `/close`, `/health`, `/tabs/{id}/handoff`, `/tabs/{id}/resume`, `/cookies`, `/profiles/{name}/instance` |
| Wait utilities | 1 | `/wait` |
-| Network | 5 | `/network`, `/network/route` (POST/DELETE) |
+| Network | 6 | `/network`, `/network/{requestId}`, `/network/clear`, `/tabs/{id}/network/route` (POST/GET/DELETE) |
+| Diagnostics | 7 | `/console`, `/errors`, `/record/*`, `/a11y/audit`, `/memory`, `/memory/snapshot`, `/memory/compare` |
| Dialog | 1 | `/dialog` |
+| Scrape | 1 | `/scrape` |
## Security Considerations
diff --git a/docs/architecture/orchestration.md b/docs/architecture/orchestration.md
index ced73407..8fb302c3 100644
--- a/docs/architecture/orchestration.md
+++ b/docs/architecture/orchestration.md
@@ -60,22 +60,27 @@ What the code does today:
## Attach Flow
-Attach is a separate path for an already running browser.
+Attach is a separate path for an already running browser or bridge.
```mermaid
flowchart LR
R["POST /instances/attach"] --> P["Validate attach policy"]
- P --> A["Register external instance"]
- A --> L["Add to instance registry"]
+ P --> B["Spawn pinchtab bridge --cdp-attach child"]
+ B --> H{"Child healthy before timeout?"}
+ H -->|Yes| L["Registry: attached, attachType cdp-bridge"]
+ H -->|No| X["Stop child, return error"]
+ RB["POST /instances/attach-bridge"] --> PB["Validate attach policy"]
+ PB --> LB["Health-check + registry: attached, attachType bridge"]
```
Current attach behavior:
- requires `security.attach.enabled`
-- validates the CDP URL against `security.attach.allowSchemes`
+- validates the URL against `security.attach.allowSchemes`
- validates the host against `security.attach.allowHosts`
-- registers the instance as `attached: true`
-- does not start or stop an external Chrome process
+- `POST /instances/attach` (CDP URL) launches a child `pinchtab bridge --cdp-attach <url>` on an allocated port, waits for its `/health`, and registers it as `attached: true`, `attachType: "cdp-bridge"`
+- `POST /instances/attach-bridge` registers an already running bridge server as `attachType: "bridge"` (upserted by name when the token matches)
+- never starts or kills the external Chrome process itself
## Routing Model
@@ -83,26 +88,27 @@ The orchestrator is also the routing layer for multi-instance server mode.
```mermaid
flowchart LR
- R["Tab-scoped request"] --> T["Resolve tab owner"]
- T --> C["Locator cache"]
- C -->|hit| P["Proxy to instance port"]
- C -->|miss| F["Fetch /tabs from running instances"]
- F --> P
+ R["Tab-scoped request"] --> C["Locator (cache, then /tabs scan)"]
+ C -->|found| P["Proxy to owning instance URL"]
+ C -->|miss| F["Scan running instances: /tabs?includeTransient=1"]
+ F -->|found| P
+ F -->|not found| S{"Exactly one running instance?"}
+ S -->|Yes| P
+ S -->|No| N["404 tab not found"]
```
-Today, tab routing works like this:
+Today, tab routing (`routeByTabOwner` in `internal/orchestrator/route.go`) works like this:
- for routes such as `/tabs/{id}/navigate` and `/tabs/{id}/action`, the server resolves which instance owns the tab
-- it first tries the instance locator cache
-- on cache miss, it falls back to scanning running instances through `/tabs`
-- after resolution, it proxies the request to the owning bridge instance
+- it first asks the instance locator (`internal/instance`), which checks its tab→instance cache and on a miss scans each running instance's user-facing `/tabs` list
+- if that misses, the orchestrator scans running instances with `/tabs?includeTransient=1`, the unfiltered list that also contains tabs the UI list hides (for example `about:blank`, `file://`, or the instance's own port), and records the owner in the locator
+- if no owner is found and exactly one instance is running, the request falls through to it; otherwise it returns 404
+- a `browser` that conflicts with the owner's browser is rejected before proxying
+- after resolution, it proxies the request to the owning instance's URL
-This keeps the public server API stable while the bridge instances remain isolated.
+Requests without a tab id go to the instance bound to the caller's session or agent identity when there is one, and otherwise to the active strategy's fallback, which targets the earliest-started running instance matching the requested or default browser (the `simple` strategy launches one when none is running). With no browser requested, that is the same instance `/health` reports as `defaultInstance` (`DefaultInstance()`).
-Important limitation:
-
-- this routing path is fully shaped around managed bridge-backed instances that expose loopback HTTP ports
-- attached instances are registered and surfaced in the instance registry, but the normal tab-owner proxy path is not yet equally first-class for them
+This keeps the public server API stable while the bridge instances remain isolated. Attached instances (both attach types) expose a bridge HTTP URL, so they use the same proxy path.
## Stop Flow
@@ -129,7 +135,7 @@ Current stop behavior:
- releases the allocated port
- removes the instance from the registry and locator cache
-For attached instances, there is no child process to kill; the orchestrator only removes its own registration state.
+For CDP-attached instances, the child bridge is stopped the same way; the external Chrome is left running. For `attach-bridge` instances there is no child process: the orchestrator sends `POST /shutdown` to the registered bridge, waits for its endpoint to go away, and then removes the registration.
## Instance States
@@ -143,10 +149,14 @@ The main statuses surfaced today are:
The orchestrator also emits lifecycle events such as:
+- `instance.launched`
- `instance.started`
- `instance.stopped`
- `instance.error`
- `instance.attached`
+- `instance.reattached`
+
+`Orchestrator.List()` returns instances ordered by start time (ties broken by ID), so listings are stable across calls.
## Relationship To Other Layers
diff --git a/docs/architecture/routing-contract.md b/docs/architecture/routing-contract.md
index 35f1170c..dfd49503 100644
--- a/docs/architecture/routing-contract.md
+++ b/docs/architecture/routing-contract.md
@@ -28,7 +28,7 @@ Each shape constant classifies the kind of work a request represents:
### StateChanging Flag
-When `RequestIntent.StateChanging` is true, the request mutates browser state. Providers that only handle read-only operations (e.g. ghost-chrome lite) should return `DecisionSkip` for state-changing requests even if the shape would otherwise be acceptable.
+When `RequestIntent.StateChanging` is true, the request mutates browser state. Providers that only handle read-only operations (e.g. ghost-chrome's static fetch) should return `DecisionSkip` for state-changing requests even if the shape would otherwise be acceptable.
## Security Invariant
@@ -48,20 +48,20 @@ Security denials (domain block, IDPI content block, private/internal IP block, r
## Ghost-Chrome Escalation
-- Ghost-chrome has a special internal `Route()` method that implements lite-first-then-Chrome escalation
+- Ghost-chrome's escalation lives in `bridgekit.BridgeAdapter` (`internal/browsers/ghostchrome/bridgekit/`), which wraps the Chrome `BridgeAPI` and implements static-first-then-Chrome for `Navigate`, `Snapshot`, and `Text`
- This is NOT a general multi-browser fallback — it's hardcoded ghost-to-chrome escalation within one provider
-- When ghost-chrome's lite attempt produces low-quality results (SPA markers, thin content), it escalates to Chrome automatically
+- When ghost-chrome's static attempt fails the quality gate (`ghostchrome.AssessContent`: SPA markers, thin content), it escalates to Chrome automatically
## Fallback Policy (current vs future)
-- **Current**: `DecisionSkip` returns HTTP 400 immediately. No multi-browser fallback exists in the handler layer.
+- **Current**: `DecisionSkip` downgrades the request to `chrome` (`resolveBrowserForRequest` in `internal/handlers/browser_routing.go`). There is no ordered multi-provider fallback; `chrome` is the only fallback target.
- **Future**: `DecisionSkip` should trigger fallback to the next available provider in priority order. Security denials must remain non-fallback-able.
## Routing Order
-1. Resolve browser provider from request (query param `?browser=`) or config default
+1. Resolve browser provider (`config.ResolveBrowser`): request (`?browser=` query or body `browser`), then session browser, then the tab's owning instance browser, then `browsers.default`, then the first of `browsers.available`, else `chrome`. An unknown provider returns 400
2. Call `CanHandle(intent)` on the resolved provider
-3. If `DecisionSkip` — return 400 (future: try next provider)
+3. If `DecisionSkip` — downgrade to `chrome` (future: try next provider)
4. If `DecisionFail` — return 400 with error
5. If `DecisionHandle` — proceed to security checks
6. Apply security policy (domain, IDPI, IP, redirects)
diff --git a/docs/architecture/scheduler.md b/docs/architecture/scheduler.md
index aabea42b..b78ec000 100644
--- a/docs/architecture/scheduler.md
+++ b/docs/architecture/scheduler.md
@@ -16,7 +16,7 @@ It does not replace the direct action endpoints.
## Runtime Placement
-In dashboard mode, the scheduler is created only when `scheduler.enabled` is true. It is registered directly on the main mux and exposes:
+In server mode, the scheduler is created only when `scheduler.enabled` is true. It is registered directly on the main mux and exposes:
- `POST /tasks`
- `GET /tasks`
@@ -135,7 +135,7 @@ The scheduler stores the corresponding cancel function so that:
Two deadline paths exist:
-- queued task expiry: a background reaper scans queued tasks every second and marks expired ones as failed
+- queued task expiry: a background reaper scans queued tasks every 5 seconds and marks expired ones as failed
- running task deadline: the per-task context deadline is enforced by the HTTP request to the executor
Queued expiry currently records:
@@ -245,7 +245,7 @@ Custom headers are sent: `X-PinchTab-Event: task.completed` and `X-PinchTab-Task
### Batch Submission
-`POST /tasks/batch` accepts an array of task definitions (up to 50) sharing a single `agentId` and optional `callbackUrl`. Each task is submitted individually through `Submit()`, so queue admission limits apply per-task.
+`POST /tasks/batch` accepts an array of task definitions (up to `scheduler.maxBatchSize`, default 50) sharing a single `agentId` and optional `callbackUrl`. Each task is submitted individually through `Submit()`, so queue admission limits apply per-task.
The batch endpoint supports partial failure: if some tasks are rejected (queue full), the accepted tasks are still submitted and the response includes per-task status.
diff --git a/docs/architecture/terminology.md b/docs/architecture/terminology.md
index c4fa23a1..1dd22e98 100644
--- a/docs/architecture/terminology.md
+++ b/docs/architecture/terminology.md
@@ -10,8 +10,8 @@ and provider routing.
| **browser** | Public | The user-facing selection concept. Users choose a browser in config, CLI flags, and API calls. Replaces "engine" in all user-facing contexts. |
| **provider** | Public | One of `chrome | cloak | ghost-chrome`. The implementation behind a browser selection. Each provider maps to a distinct launch and routing strategy. |
| **static fetch**| Public | The lightweight HTTP+DOM path used by `ghost-chrome` before escalating to Chrome. Replaces "lite engine" in user-facing language. |
-| **engine** | Internal | DEPRECATED as a public concept. Kept internally in `internal/engine/` as an implementation detail. Will be removed from public config in a future phase. |
-| **target** | Internal | A named profile for launch settings (binary path, proxy, flags, etc.). Not exposed publicly through API, CLI, or docs. |
+| **engine** | Removed | No longer a public concept: `server.engine` in a config file fails validation. The old `chrome` / `lite` / `auto` values survive only as the internal `browsers.LaunchMode` (`internal/browsers/config.go`). |
+| **target** | Config | A named launch profile under `browser.targets` in the config file (provider, binary path, proxy, flags, etc.), with `browser.defaultTarget` naming the default. Where a `browser` value is accepted (e.g. `POST /instances/attach`), a target name may be given instead of a provider. |
## Provider descriptions
@@ -33,9 +33,11 @@ requires JavaScript execution.
## Migration notes
-- The `engine` field in `ServerConfig` and `RuntimeConfig` is deprecated.
- Use `browsers.default` in the config file instead.
-- The `provider` field inside `browser {}` config blocks is deprecated in
- favor of the top-level `browsers.default` key.
+- The `engine` field in `ServerConfig` is no longer supported: it is parsed
+ only so config validation can reject it. Use `browsers.default` in the
+ config file instead. `RuntimeConfig` has no engine field.
+- The `provider` field inside `browser {}` config blocks is no longer
+ supported (validation error); use the top-level `browsers.default` key.
+ Per-target `browser.targets.<name>.provider` is still required.
- Public documentation, CLI help text, and API responses should use
"browser" and "provider" — never "engine" or "lite engine".
diff --git a/docs/audit.md b/docs/audit.md
index 218ecde4..103752cb 100644
--- a/docs/audit.md
+++ b/docs/audit.md
@@ -86,7 +86,7 @@ summaryScore # mean accessibility score of enriched pages;
# broken assets, failed requests and uncaught
# JS errors do not move it
pages[]:
- url, title, error? # error set when the page failed to load
+ url, title, statusCode?, error? # error set when the page failed to load
seaportal? # HTTP-extraction summary when ingested
securityFindings[]? # ruleId, severity, detail, url
browser:
@@ -191,11 +191,13 @@ build against it if you need one.
## HTTP API
-The CLI is a thin client over two endpoints:
+The CLI is a thin client over these endpoints (`pinchtab audit` calls `POST /audit`):
-- `POST /audit/page {"url", "options"}` → single-page `BrowserPageData`
+- `POST /audit/page {"url", "options"}` → single-page `PageAudit` (`url`, `title`,
+ `error`, `screenshot`, `a11yFindings`, `securityFindings`, plus the
+ `BrowserPageData` fields inline)
- `POST /audit {"urls" | "sitemapUrl" | "seaportalResults", "options",
- "concurrency", "sampleSize", "enrichAll"}` → `AuditReport`
+ "seaportalFile", "concurrency", "sampleSize", "enrichAll"}` → `AuditReport`
## Docker / CI
diff --git a/docs/commands.md b/docs/commands.md
index 48e7077d..c1c84d85 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -12,6 +12,11 @@ pinchtab server restart # Stop + restart in background (applies
pinchtab bridge # Start the bridge-only runtime
pinchtab bridge --log-level debug # Bridge threshold (same precedence as server)
pinchtab mcp # Start the MCP stdio server
+pinchtab dashboard # Open the dashboard in your browser (--no-open prints the URL)
+pinchtab session create --agent-id <id> # Create an agent session (--grant limits it to capability groups)
+pinchtab session list # List agent sessions
+pinchtab session info # Show the current agent session
+pinchtab session revoke <session-id> # Revoke an agent session
pinchtab daemon # Show daemon status
pinchtab daemon install # Install as a background service
pinchtab daemon start # Start the background service
@@ -107,6 +112,7 @@ pinchtab tab # List tabs
pinchtab tab <id> # Focus a tab by ID or 1-based index
pinchtab nav <url> --new-tab # Open a new tab and navigate it
pinchtab tab close <id> # Close a tab
+pinchtab close <id> # Same as tab close
```
Use top-level commands with `--tab` for tab-scoped work:
@@ -163,6 +169,7 @@ pinchtab mouse down [selector] # Press a mouse button
pinchtab mouse up [selector] # Release a mouse button
pinchtab mouse wheel [dy|selector] # Dispatch wheel deltas
pinchtab drag <from> <to> # Drag between targets (selector/ref or x,y)
+pinchtab drag <selector> --drag-x <n> --drag-y <n> # Drag by a pixel offset
pinchtab focus [selector] # Focus an element
pinchtab scroll <selector|pixels> # Scroll an element or the page
pinchtab scroll down --snap # Scroll and output snapshot
@@ -200,6 +207,17 @@ pinchtab text --raw # Raw extraction
pinchtab text --markdown # Markdown (preserves links, tables)
pinchtab text --markdown --output page.md # Write Markdown to a file (one-line confirmation)
pinchtab text --frame <frameId> # Read text from one iframe
+pinchtab html [selector] # Document or element HTML (--max-chars, --frame)
+pinchtab styles [selector] # Computed styles (root element when omitted; --prop for one)
+pinchtab title # Current tab title
+pinchtab url # Current tab URL
+pinchtab value <ref> # Current value of a form element
+pinchtab attr <ref> <name> # Value of one HTML attribute
+pinchtab box <ref> # Bounding box of an element
+pinchtab checked <ref> # Whether an element is checked
+pinchtab enabled <ref> # Whether an element is enabled
+pinchtab visible <ref> # Whether an element is rendered
+pinchtab count <selector> # Count elements matching a CSS selector
pinchtab find <query> # Semantic element search
pinchtab find --threshold <0-1> # Minimum similarity score
pinchtab find --explain # Include score breakdown
@@ -231,7 +249,7 @@ See [reference/memory.md](reference/memory.md).
[reference/a11y.md](reference/a11y.md)) in the page's isolated world, so page
script cannot tamper with the result. Each violation node that maps to a
snapshot ref carries it, so a failing element can be actioned directly with
-`pinchtab action`.
+`pinchtab click` and the other element commands.
`pinchtab eval` is intentionally not frame-scoped. Current `pinchtab frame`
state affects selector-based commands such as `snap`, `click`, `fill`, and
@@ -279,13 +297,16 @@ pinchtab wait --url <glob> # Wait for URL match (glob: **, *, ?)
pinchtab wait --load <state> # state: ready-state | content-loaded | network-idle
# ready-state → document.readyState === 'complete'
# content-loaded → readyState in {interactive, complete}
- # network-idle → 0 in-flight requests for 500ms (override with --idle-for)
+ # network-idle → 0 in-flight requests for 500ms (HTTP `idleFor` overrides; no CLI flag)
pinchtab wait --fn <expression> # Wait for JS to become truthy
pinchtab wait ... --timeout-ms <ms> # Override timeout in ms (default 10000, max 30000); --timeout is a deprecated alias
pinchtab network # List captured network requests
pinchtab network <requestId> # Show one request in detail
pinchtab network --stream # Stream network entries
pinchtab network --clear # Clear captured network data
+pinchtab network route <url> --abort # Block matching requests (--body '<json>' fulfills instead)
+pinchtab network unroute [url] # Remove one interception rule, or all of them
+pinchtab network rules # List interception rules
# HAR / NDJSON export is available over HTTP (no dedicated CLI subcommand):
# curl http://127.0.0.1:9867/network/export → HAR 1.2 archive
# curl http://127.0.0.1:9867/network/export?format=ndjson → NDJSON (one entry per line)
@@ -314,6 +335,8 @@ pinchtab tab handoff-status <tabId>
pinchtab tab resume <tabId> --status completed
```
+`pinchtab handoff`, `pinchtab handoff-status` and `pinchtab resume` are top-level spellings of the same three commands.
+
API equivalents:
Paused handoff state blocks action execution routes (`/action`, `/actions`, `/macro`) with `409 tab_paused_handoff`
@@ -387,12 +410,36 @@ pinchtab state load <name> # Restore a saved state; <name> may be a
pinchtab state show <name> # Print a saved state file
pinchtab state delete <name> # Delete a saved state file
pinchtab state clean --older-than <h> # Remove state files older than <h> hours (default 24)
+pinchtab cookies get # Cookies for the tab's current page (--name, --url)
+pinchtab cookies set <name> <value> # Set a cookie (--domain, --path, --secure, --http-only, --same-site)
+pinchtab cookies clear # Clear ALL browser cookies, every origin
```
`storage delete` never wipes a store: a bare `pinchtab storage delete` is refused and names
`storage clear`, the one wipe verb. Every storage verb takes `--tab <id>`, as do `state`,
`state save` and `state load`. The `state` family requires `security.allowStateExport`.
+## Emulation
+
+```bash
+pinchtab set viewport <w> <h> # Viewport size (--dpr, --mobile)
+pinchtab set geo <lat> <lon> # Geolocation (--accuracy)
+pinchtab set media <feature> <value> # CSS media feature, e.g. prefers-color-scheme dark
+pinchtab set offline <true|false> # Toggle offline mode
+pinchtab set headers '<json>' # Extra HTTP headers ({} clears them)
+pinchtab set credentials <user> <pass> # HTTP auth credentials
+```
+
+## Site Audit, Compare, And Scrape
+
+```bash
+pinchtab audit <url> # Browser-enriched page audit (see audit.md)
+pinchtab compare <live-url> <staging-url> # Visual + data diff of two site versions
+pinchtab scrape <url> # HTTP crawl, browser-render only thin pages (see scrape.md)
+```
+
+See [audit.md](audit.md) and [scrape.md](scrape.md) for flags and report shapes.
+
## Instances, Profiles, And Activity
```bash
@@ -403,9 +450,11 @@ pinchtab instance start --mode headed
pinchtab instance start --port <n>
pinchtab instance start --extension /path/to/ext
pinchtab instance stop <id> # Stop an instance
+pinchtab instance restart <id> # Soft-restart an instance's browser process
pinchtab instance logs <id> # Show instance logs
pinchtab instance navigate <id> <url> # Open a tab in an instance already on <url> (one step)
pinchtab profiles # List profiles
+pinchtab profiles create <name> # Create a profile for human setup and login
pinchtab profiles prune # List reclaimable quarantined profiles (removes nothing)
pinchtab profiles prune --confirm # Remove them and report the disk freed
pinchtab profiles prune --profile <dir> # Reclaim just one quarantined directory
@@ -468,12 +517,17 @@ pinchtab config token # Copy server.token to the clipboard wit
pinchtab config token --stdout # Print server.token to stdout (headless hosts, $(...) capture)
pinchtab config path # Print config file path
pinchtab config validate # Validate the current config file
+pinchtab config schema # Print the config JSON Schema URL (--print for the schema)
pinchtab config get <path> # Read one file-config value
pinchtab config set <path> <val> # Set one file-config value
pinchtab config patch <json> # Merge JSON into the config file
pinchtab security # Interactive security overview
pinchtab security up # Apply stricter defaults
pinchtab security down # Apply documented guards-down preset
+pinchtab doctor # Read-only install and browser checks (--json, --check <name>)
+pinchtab doctor browsers # Configured and known browsers with availability
+pinchtab doctor browser [name] # Browser availability, or checks for one target
+pinchtab version # Print the PinchTab version
```
## Global Flags
@@ -528,6 +582,13 @@ Commands with `--tab` currently include:
- `dialog dismiss`
- `console`
- `errors`
+- `frame`, `html`, `styles`, `title`, `url`
+- `value`, `attr`, `box`, `checked`, `enabled`, `visible`, `count`
+- `drag`, `download`, `upload`, `annotate`
+- `a11y audit`, `memory`, `memory snapshot`, `record start`
+- `network route`, `network unroute`, `network rules`
+- `cookies get`, `cookies set`, `set` (every subcommand)
+- `storage` (every subcommand), `state`, `state save`, `state load`
## Output Format
diff --git a/docs/core-concepts.md b/docs/core-concepts.md
index 62ea68a1..8da4b810 100644
--- a/docs/core-concepts.md
+++ b/docs/core-concepts.md
@@ -9,11 +9,13 @@ The **server** is the main PinchTab process.
Start it with:
```bash
-pinchtab
-# or explicitly
pinchtab server
+# or run it in the background
+pinchtab daemon install
```
+Bare `pinchtab` does not start a server: it prints whether one is running, the security posture, and next steps (and runs the security setup on first use).
+
What the server does:
- exposes the main HTTP API and dashboard on port `9867` by default
@@ -21,6 +23,9 @@ What the server does:
- proxies tab-scoped requests to the correct managed instance
- can expose shorthand routes such as `/navigate`, `/snapshot`, and `/action`
+The HTTP API requires the server token. The `curl` examples on this page omit it for brevity;
+add `-H "Authorization: Bearer $PINCHTAB_TOKEN"` after `export PINCHTAB_TOKEN=$(pinchtab config token --stdout)`.
+
Important clarification:
- the server is the public entry point
@@ -271,7 +276,7 @@ These route to the "current" or first running instance.
For most users, this is the right sequence:
-1. start the server with `pinchtab`
+1. start the server with `pinchtab server` (or `pinchtab daemon install`)
2. create a profile if you need persistence
3. start an instance from that profile
4. open one or more tabs in that instance
diff --git a/docs/dashboard.md b/docs/dashboard.md
index 9adb4c29..1eba2400 100644
--- a/docs/dashboard.md
+++ b/docs/dashboard.md
@@ -4,7 +4,7 @@ PinchTab includes a built-in web dashboard for monitoring instances, managing pr
The dashboard is part of the full server:
-- `pinchtab` or `pinchtab server` starts the full server and serves the dashboard
+- `pinchtab server` (or the daemon from `pinchtab daemon install`) starts the full server and serves the dashboard
- `pinchtab bridge` does not serve the dashboard
You can open the dashboard at:
@@ -19,11 +19,12 @@ You can open the dashboard at:
## Dashboard overview
-The current dashboard exposes three main pages:
+The current dashboard exposes four main pages:
1. **Monitoring**
-2. **Profiles**
-3. **Settings**
+2. **Agents**
+3. **Profiles**
+4. **Settings**
The UI is a React SPA served by the Go server.
@@ -59,6 +60,12 @@ Operational data comes from:
---
+## Agents page
+
+The Agents page lists agents known to the server (from `GET /api/agents`) and shows the selected agent's recorded activity, updated live over `GET /api/agents/{id}/events`.
+
+---
+
## Profiles page
![Dashboard Profiles](media/dashboard-profiles.jpeg)
@@ -78,12 +85,13 @@ What you can do:
- stop the running instance for a profile
- edit profile metadata
- delete a profile
-- open a profile details modal
+- open a profile's details panel
The launch flow uses the server APIs behind the scenes:
```bash
curl -X POST http://localhost:9867/profiles \
+ -H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"work","useWhen":"Team account workflows"}'
# Response
@@ -96,6 +104,7 @@ curl -X POST http://localhost:9867/profiles \
```bash
curl -X POST http://localhost:9867/instances/start \
+ -H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d '{"profileId":"prof_278be873","mode":"headed"}'
# CLI Alternative
@@ -114,14 +123,15 @@ pinchtab instance start --profile prof_278be873 --mode headed
---
-## Profile details modal
+## Profile details panel
-Profile details are shown in a modal, not as a separate top-level page.
+Profile details are shown in a panel beside the profile list, not as a separate top-level page.
-The modal currently includes tabs for:
+The panel currently includes tabs for:
- **Profile**
- **Live**
+- **Tabs**
- **Logs**
From there you can:
@@ -150,6 +160,8 @@ It includes sections for:
- Network & Attach
- Browser Runtime
- Timeouts
+- AutoSolver
+- Observability
What you can do:
@@ -172,10 +184,10 @@ The Security IDPI section is focused on content-protection behavior:
- `security.idpi.wrapContent`
- `security.idpi.customPatterns`
-The health payload also surfaces summary info:
+The health payload also surfaces summary info (the API requires the server token; see `pinchtab config token --stdout`):
```bash
-curl http://localhost:9867/health | jq .
+curl -H "Authorization: Bearer $PINCHTAB_TOKEN" http://localhost:9867/health | jq .
# Response
{
"status": "ok",
@@ -196,7 +208,7 @@ The dashboard uses Server-Sent Events, not WebSockets.
Primary stream endpoint:
```bash
-curl http://localhost:9867/api/events
+curl -H "Authorization: Bearer $PINCHTAB_TOKEN" http://localhost:9867/api/events
```
This stream carries:
@@ -219,7 +231,7 @@ If the React dashboard assets are not built into the binary, the server serves a
### Dashboard not loading
```bash
-curl http://localhost:9867/health
+pinchtab health
```
If the server is up, try:
@@ -233,6 +245,7 @@ Start one:
```bash
curl -X POST http://localhost:9867/instances/start \
+ -H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d '{"mode":"headless"}'
# CLI Alternative
@@ -241,4 +254,4 @@ pinchtab instance start
### No live profile preview
-The profile must have a running instance before the Live tab in the profile details modal can show live tab data.
+The profile must have a running instance before the Live tab in the profile details panel can show live tab data.
diff --git a/docs/deep-dive/benchmark.md b/docs/deep-dive/benchmark.md
index 74cadad9..e362d83d 100644
--- a/docs/deep-dive/benchmark.md
+++ b/docs/deep-dive/benchmark.md
@@ -44,17 +44,18 @@ lane-specific task overrides.
### Environment
-Every run is executed inside Docker Compose (`tests/tools/docker-compose.yml`)
-with three services:
+Every run is executed against Docker Compose (`tests/tools/docker-compose.yml`)
+plus a host-side runner:
- `fixtures` — the benchmark web server hosting the test pages
(`/`, `/wiki.html`, `/articles.html`, `/search.html`, `/form.html`,
`/dashboard.html`, `/ecommerce.html`, `/spa.html`, `/login.html`, etc.).
- `pinchtab` or `agent-browser` — the browser surface being measured.
- PinchTab is built from `tests/tools/config/pinchtab-benchmark.json`
+ PinchTab is configured from `tests/tools/config/pinchtab-benchmark.json`
(IDPI `wrapContent=false`, to match agent-browser's unwrapped output).
- `runner` — the Go program at `tests/tools/runner/` that drives the LLM
- agent loop.
+ agent loop. It is not a Compose service: `./dev bench` runs it on the host
+ with `go run`, and the lane wrappers `docker exec` into the containers.
### Agent loop
@@ -103,7 +104,7 @@ deliberate, to keep the comparison fair:
size ≈ **58.5 KB**.
- **PinchTab in the benchmark** = just `SKILL.md` (~14.5 KB). The reference
subfolder is not inlined.
-- **agent-browser full skill** comes from `agent-browwser skills get
+- **agent-browser full skill** comes from `agent-browser skills get
agent-browser --full`. In the benchmark the runner extracts only the
header plus `references/commands.md` and `references/snapshot-refs.md`
and drops the rest (see
@@ -123,7 +124,7 @@ the tool surface itself*, re-run with `--full` skills on both lanes.
## Results: 2026-04-20 runs (n=5 each)
All ten runs scored 10/10 passes on the same 10-step set. Anthropic
-`claude-haiku-4-5-20251001`, `--max-turns 120`.
+`claude-haiku-4-5-20251001`, `--max-turns 100` (la1: 120).
### Raw per-run totals
@@ -274,7 +275,7 @@ stronger model close the gap by using fewer turns on agent-browser's
click→snapshot pattern? — we re-ran the 24-step extended scope with
`claude-sonnet-4-6`, n=2 per lane. Two runs per lane is too few for a
confident headline, but enough to spot whether the ratio between lanes
-changes vs Haiku. Logs prefixed `lae-sonnet46-*` (agent-browser) and
+changes vs Haiku. Logs prefixed `lae*-sonnet46-*` (agent-browser) and
`lpe-sonnet46-*` (PinchTab).
### Raw per-run totals
diff --git a/docs/deep-dive/lite-engin-prototype.md b/docs/deep-dive/lite-engin-prototype.md
index bc980d8b..e1cfec35 100644
--- a/docs/deep-dive/lite-engin-prototype.md
+++ b/docs/deep-dive/lite-engin-prototype.md
@@ -4,6 +4,7 @@
> The engine has been replaced by the **browser provider** model. Use `browsers.default`
> in your config with providers: `chrome`, `cloak`, or `ghost-chrome`.
> See [terminology](../architecture/terminology.md) for details.
+> None of the code below exists at HEAD: `internal/engine` (Router, rules, `LiteEngine`), the `server.engine` key (now a config validation error) and the `X-Engine` header were removed. The Gost-DOM static path now lives in `internal/browsers/ghostchrome/staticfetch`, used by the `ghost-chrome` provider before it escalates to Chrome.
**Branch:** `feat/lite-engine-gostdom`
**Issue:** [#201](https://github.com/pinchtab/pinchtab/issues/201)
diff --git a/docs/endpoints.md b/docs/endpoints.md
index 377c1da4..cc0e6870 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -2,11 +2,20 @@
This page summarizes the live HTTP surface exposed by PinchTab. Some routes are only available in bridge mode, some only in full server mode, and some are gated by security settings.
+Most browser routes also answer at a tab-scoped `/tabs/{id}/...` form (for example
+`GET /tabs/{id}/html`), and the blocks below list only the common ones. The routes with no
+tab form are `POST /tab`, console and errors, clipboard, `/stealth/status`,
+`/fingerprint/rotate`, `/solvers`, `/config/autosolver`, cache, the `/state` family, `/macro`,
+screencast and record, memory summary and compare, `/audit`, `/audit/page`, `/scrape` and
+`POST /network/clear`. Handoff and resume exist only in their tab form. The route catalog
+lives in `internal/routes/routes.go`.
+
## Health And Server Metadata
```text
GET /health
POST /ensure-browser
+POST /ensure-chrome (legacy alias for /ensure-browser)
POST /browser/restart
GET /openapi.json
GET /help (alias for /openapi.json)
@@ -51,6 +60,7 @@ POST /api/auth/elevate
POST /api/auth/logout
GET /api/config
PUT /api/config
+GET /dashboard (dashboard UI; also served at / and /login)
```
Notes:
@@ -110,6 +120,7 @@ Navigation request fields:
- `timeout` optional
- `blockImages`, `blockMedia`, `blockAds` optional
- `waitFor`, `waitSelector`, `waitTitle` optional
+- `dismissBanners`, `dispatchOnly` optional
Important behavior:
@@ -172,8 +183,20 @@ GET /snapshot
GET /tabs/{id}/snapshot
GET /text
GET /tabs/{id}/text
+GET /title
+GET /url
+GET /html
+GET /styles
+GET /value
+GET /attr
+GET /count
+GET /box
GET /visible
GET /tabs/{id}/visible
+GET /enabled
+GET /checked
+GET /timing
+GET /a11y/audit
POST /find
POST /tabs/{id}/find
POST /extract
@@ -184,8 +207,19 @@ GET /memory
POST /memory/snapshot
GET /memory/snapshot/{snapshotId}/summary
GET /memory/compare?base=<id>&head=<id>
+POST /emulation/viewport
+POST /emulation/geolocation
+POST /emulation/offline
+POST /emulation/headers
+POST /emulation/credentials
+POST /emulation/media
+GET /stealth/status
+POST /fingerprint/rotate
```
+The `/emulation/*` routes back the CLI's `pinchtab set` subcommands. `/a11y/audit` is
+described in [reference/a11y.md](reference/a11y.md).
+
`/memory` reads the tab's JavaScript heap and DOM counters; the snapshot, summary and
compare routes need `security.allowMemory` — see [reference/memory.md](reference/memory.md).
@@ -213,7 +247,10 @@ cardinality, and zero is the honest answer to "how many".
`/evaluate` is intentionally separate from selector frame scope. `GET/POST /frame` only affects selector-based `/snapshot` and `/action` calls, not arbitrary JavaScript evaluation.
-`GET /action` decodes a subset of the action fields and refuses, with `400` naming the field, any parameter it cannot express rather than silently dropping it — so a modifier chord, a drag, `waitNav` or `humanize` must be sent as `POST /action` with a JSON body. A parameter the action request does not declare at all is refused the same way, with a `did you mean` hint for a near miss, so `?modifers=8` or `?Modifiers=8` no longer dispatches a plain click and answers `200`. The accepted set is the action request's own fields plus the parameters only the GET form carries, which today is `timeout` — a per-request action timeout in seconds, clamped to 0–60, that the POST form sends in its body instead. Cache-busters and stray parameters must be dropped from the URL.
+`GET /action` decodes a subset of the action fields and refuses, with `400` naming the field, any parameter it cannot express rather than silently dropping it — so a modifier chord, a drag, `waitNav` or `humanize` must be sent as `POST /action` with a JSON body. A parameter the action request does not declare at all is refused the same way, with a `did you mean` hint for a near miss, so `?modifers=8` or `?Modifiers=8` no longer dispatches a plain click and answers `200`. The accepted set is the action request's own fields plus the parameters only the GET form carries, which today is `timeout`.
+`timeout` is a per-request action timeout in seconds, honoured when it is above 0 and at most
+60 (any other value falls back to the configured action timeout). The POST body has no
+equivalent field, so a POST action always uses the configured action timeout. Cache-busters and stray parameters must be dropped from the URL.
`GET /snapshot` validates its cost controls the same way but resolves the unknown-parameter
question differently, and the difference is deliberate. A bad VALUE is refused with a `400`
@@ -280,6 +317,8 @@ Action targeting fields:
- `waitNav`
- `dialogAction` and `dialogText`
- `humanize`
+- `toSelector`, `toX`/`toY` and `dragX`/`dragY` (drag)
+- `submit`, `mode` and `modifiers` (click)
`fill` and `type` write the string in `text`; `fill` also accepts it as `value`, which is the
field `select` reads. A `fill` carrying neither is rejected — send `"text": ""` to clear a
@@ -320,7 +359,8 @@ Snapshot query parameters:
- `depth`
- `format`
- `noAnimations`
-- `output`
+- `output` (with `path` when `output=file`)
+- `tabId`
`selector` on `/snapshot` follows the same rule: it only searches the current frame scope. It does not automatically pierce into iframes, and cross-origin iframe descendants are not inlined.
@@ -330,6 +370,8 @@ Text query parameters:
- `format`
- `maxChars`
- `frameId`
+- `selector` or `ref` to read one element
+- `tabId`
`/text` default mode picks the first **visible** `<article>` / `[role="main"]` /
`<main>` (skips `display:none`) and strips nav/footer/ads. Use `mode=raw` for
@@ -445,6 +487,9 @@ Screenshot query parameters:
- `raw=true`
- `output=file`
- `noAnimations=true`
+- `selector` — capture one element
+- `annotate=true` — bake numbered ref boxes into the image
+- `beyondViewport=true` — capture the full document (ignored with `selector`)
- `scale=<float>` — rescale the output bitmap (e.g. `0.5` = half size,
`0.25` = quarter). Default `1`.
@@ -587,6 +632,19 @@ Notes:
- `.gif` format uses pure Go encoding (always available).
- Only one recording per bridge instance.
+## Site Audit And Scrape
+
+```text
+POST /audit/page
+POST /audit
+POST /scrape
+```
+
+`POST /audit/page` audits one `url`; `POST /audit` takes `urls`, a `sitemapUrl` or SeaPortal
+results; `POST /scrape` takes the crawl root `url`. These back `pinchtab audit` and
+`pinchtab scrape` — see [audit.md](audit.md) and [scrape.md](scrape.md) for the bodies and
+report shapes.
+
## Downloads, Uploads, Cookies, And Clipboard
```text
@@ -615,7 +673,7 @@ Notes:
- download automatically decompresses `.gz` files and returns the decompressed content
- `security.downloadAllowedDomains` can whitelist specific domains (bypasses SSRF checks for matching domains). Setting `["*"]` matches every host and disables private-IP protection for this endpoint, including loopback. Naming a loopback host (`127.0.0.1`, `localhost`) or using `"*"` lets the download endpoint reach services on the server's own machine, including PinchTab's own local endpoints. A host that is neither matched nor public is refused with code `download_host_blocked`, and the response carries the `config set` line that names it.
- clipboard endpoints are gated by `security.allowClipboard`
-- upload uses a JSON body with `selector`, `files`, and optional `fileNames`
+- upload uses a JSON body with `selector` (default `input[type=file]`), `files` (base64) and/or `paths` (files already inside `<stateDir>/uploads`), and optional `fileNames`
- `fileNames` is index-aligned with `files` and sets the name the page sees in `file.name` — send it, or every upload arrives as `upload-<i>.bin` and forms gating on `accept=".csv"` or `file.name.endsWith(...)` reject it. Without a name the extension is sniffed from content, which cannot identify text formats (`.csv`, `.json`, `.txt`, `.md`, `.html`) because they have no magic bytes. A supplied name wins over the sniffed type even when the two disagree, matching what a browser sends. Only the basename is used: any directory part is dropped.
## Storage
@@ -646,10 +704,10 @@ POST body fields:
- `type` — `local` or `session` (required)
- `tabId` — optional
-DELETE body fields:
+DELETE body fields (the body itself is optional):
-- `type` — `local` or `session` (required)
-- `key` — optional (if omitted, clears entire storage)
+- `type` — `local`, `session` or `all` (default `all`, both stores)
+- `key` — optional (if omitted, clears the whole store); refused together with `type: all`
- `tabId` — optional
## State
@@ -731,6 +789,12 @@ GET /tabs/{id}/network/stream
GET /tabs/{id}/network/export
GET /tabs/{id}/network/export/stream
GET /tabs/{id}/network/{requestId}
+GET /network/route
+POST /network/route
+DELETE /network/route
+GET /tabs/{id}/network/route
+POST /tabs/{id}/network/route
+DELETE /tabs/{id}/network/route
POST /dialog
POST /tabs/{id}/dialog
GET /console
@@ -766,6 +830,7 @@ Network query parameters:
- `type`
- `limit`
- `bufferSize`
+- `broken=true` — answer with the broken-asset list (`broken`, `count`) instead of entries
- `body=true` on detail requests
- `bodyMode=auto|retained-preferred|retained-only|live-only` on detail requests to choose how response bodies are resolved
- `timeoutMs` on detail requests to bound the retained-body wait window (default 2000, max 30000)
@@ -801,6 +866,12 @@ Network export query parameters:
The `/export` endpoint returns the full capture as a single response. The `/export/stream` endpoint writes entries to a file as they arrive (SSE progress events sent to the caller). The streamed file is atomically renamed on completion.
+Interception rules (`/network/route`, gated by `security.allowNetworkIntercept`): `POST` takes
+`pattern` (substring or `*`/`?` glob), `action` (`continue`, `abort` or `fulfill`), and for a
+fulfill `body`, `contentType` and `status`, plus optional `resourceType` and `method`. `DELETE`
+takes `pattern` in the query or body and removes every rule when it is omitted; `GET` lists the
+tab's rules.
+
Dialog body fields:
- `action`: `accept` or `dismiss`
@@ -888,6 +959,7 @@ POST /profiles/{id}/reset
GET /profiles/{id}/logs
GET /profiles/{id}/analytics
POST /profiles/import
+POST /profiles/prune
PATCH /profiles/meta
GET /instances
GET /instances/{id}
@@ -906,6 +978,12 @@ GET /instances/{id}/logs/stream
GET /instances/{id}/tabs
POST /instances/{id}/tabs/open
POST /instances/{id}/tab
+POST /instances/{id}/close
+POST /instances/{id}/cookies
+POST /instances/{id}/audit
+POST /instances/{id}/scrape
+POST /instances/{id}/cache/clear
+GET /instances/{id}/cache/status
```
Notes:
@@ -919,6 +997,8 @@ Notes:
- create profiles explicitly with `POST /profiles`; `name` is no longer supported on `/instances/launch`
- `/profiles/{id}/start` uses `headless`
- attach routes are gated by `security.attach`
+- `POST /profiles/prune` removes quarantined profile directories; see the `pinchtab profiles prune` section of [commands.md](commands.md)
+- `/instances/{id}/close|cookies|audit|scrape|cache/*` proxy the same route to that instance
## Activity And Scheduler
@@ -947,7 +1027,6 @@ Activity query parameters include:
- `profileName`
- `tabId`
- `action`
-- `engine`
- `pathPrefix`
Activity attribution and source behavior:
@@ -962,7 +1041,7 @@ Scheduler routes are only present when `scheduler.enabled` is true.
| Method | Path | Description |
|--------|------|-------------|
-| `POST` | `/sessions` | Create a new agent session (body: `{agentId, label?}`) |
+| `POST` | `/sessions` | Create a new agent session (body: `{agentId, label?, grants?, browser?}`) |
| `GET` | `/sessions` | List all agent sessions |
| `GET` | `/sessions/me` | Get current session (requires `Authorization: Session` auth) |
| `GET` | `/sessions/{id}` | Get session details by ID |
@@ -987,13 +1066,17 @@ Some endpoints are intentionally disabled unless the matching config allows them
These gates are not ordinary feature toggles. Enabling them is a documented, non-default, security-reducing choice that widens the control surface available to callers.
- `/evaluate` and `/tabs/{id}/evaluate` -> `security.allowEvaluate`
+- `/macro` -> `security.allowMacro`
+- `GET /network/{requestId}`, `POST /network/clear` and the `/network/route` family (plus tab-scoped variants) -> `security.allowNetworkIntercept`
+- `/memory/snapshot`, `/memory/snapshot/{snapshotId}/summary` and `/memory/compare` -> `security.allowMemory`
- `/download` and `/tabs/{id}/download` -> `security.allowDownload`
- `GET/POST/DELETE /cookies` and `GET/POST/DELETE /tabs/{id}/cookies` -> `security.allowCookies`
- `/upload` and `/tabs/{id}/upload` -> `security.allowUpload`
- clipboard routes -> `security.allowClipboard`
- attach routes -> `security.attach`
- screencast routes -> `security.allowScreencast`
-- storage routes (`/storage`, `/tabs/{id}/storage`) and the full state-management family (`/state/list`, `/state/show`, `/state/save`, `/state/load`, `DELETE /state`, `POST /state/clean`) -> `security.allowStateExport`
+- storage routes (`/storage`, `/tabs/{id}/storage`) and the full state-management family
+ (`GET /state`, `/state/list`, `/state/show`, `/state/save`, `/state/load`, `DELETE /state`, `POST /state/clean`) -> `security.allowStateExport`
## Error Response Format
diff --git a/docs/get-started.md b/docs/get-started.md
index 832da5bf..d65a1c68 100644
--- a/docs/get-started.md
+++ b/docs/get-started.md
@@ -36,13 +36,13 @@ pinchtab --version
**Requires:** Docker
```bash
-docker run -d -p 127.0.0.1:9867:9867 pinchtab/pinchtab
-curl http://localhost:9867/health
+docker run -d --name pinchtab -p 127.0.0.1:9867:9867 pinchtab/pinchtab
+docker exec pinchtab pinchtab health
```
### Option 4: build from source
-**Requires:** Go 1.25+, Git, Chrome/Chromium
+**Requires:** Go 1.26+, Git, Chrome/Chromium
```bash
git clone https://github.com/pinchtab/pinchtab.git
@@ -92,18 +92,25 @@ The normal flow is:
```bash
pinchtab server
-# Response
-🦀 PinchTab port=9867
-dashboard ready url=http://localhost:9867
+# Response (log lines)
+time=... level=INFO msg=orchestration strategy=always-on allocation=fcfs
+time=... level=INFO msg="dashboard started" port=9867
```
The server runs on `http://127.0.0.1:9867`.
You can open the dashboard at `http://127.0.0.1:9867` or `http://127.0.0.1:9867/dashboard`.
+The HTTP API requires the server token (`server.token`, generated on first run). Export it once for the `curl` examples below:
+
+```bash
+export PINCHTAB_TOKEN=$(pinchtab config token --stdout)
+```
+
### Step 2: start your first instance
```bash
curl -s -X POST http://127.0.0.1:9867/instances/start \
+ -H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d '{"mode":"headless"}' | jq .
# CLI Alternative
@@ -112,7 +119,7 @@ pinchtab instance start
{
"id": "inst_0a89a5bb",
"profileId": "prof_278be873",
- "profileName": "instance-1741400000000000000",
+ "profileName": "instance-1741400000000000000-9f3c2a1b",
"port": "9868",
"mode": "headless",
"headless": true,
@@ -124,6 +131,7 @@ pinchtab instance start
```bash
curl -s -X POST http://127.0.0.1:9867/navigate \
+ -H "Authorization: Bearer $PINCHTAB_TOKEN" \
-H "Content-Type: application/json" \
-d '{"url":"https://github.com/pinchtab/pinchtab"}' | jq .
# CLI Alternative
@@ -139,7 +147,7 @@ pinchtab nav https://github.com/pinchtab/pinchtab
### Step 4: inspect the page
```bash
-curl -s "http://127.0.0.1:9867/snapshot?filter=interactive" | jq .
+curl -s -H "Authorization: Bearer $PINCHTAB_TOKEN" "http://127.0.0.1:9867/snapshot?filter=interactive" | jq .
# CLI Alternative
pinchtab snap -i -c
# Response
@@ -160,7 +168,7 @@ You now have a working PinchTab server, a running browser instance, and a naviga
### Connection refused
```bash
-curl http://localhost:9867/health
+pinchtab health
```
If that fails, start the server:
diff --git a/docs/guides/agent-identity.md b/docs/guides/agent-identity.md
index b398dc78..e18b0c5c 100644
--- a/docs/guides/agent-identity.md
+++ b/docs/guides/agent-identity.md
@@ -6,11 +6,7 @@ PinchTab offers three levels of agent identification, from simple to fully manag
Every PinchTab server has a bearer token configured in `server.token`. This is the baseline authentication method — it proves the caller is authorized to use the server, but says nothing about *which* agent is making the request.
-```bash
-pinchtab --token "your-server-token" nav https://example.com
-```
-
-Or via environment variable:
+The CLI reads it from the local config automatically. To supply it explicitly (for example against another server), use the environment variable — there is no `--token` flag:
```bash
export PINCHTAB_TOKEN=your-server-token
@@ -77,7 +73,7 @@ Modes:
|------|----------|
| `off` | Agent sessions disabled |
| `preferred` | Both bearer and session auth accepted (default when enabled) |
-| `required` | Only session auth accepted for agents |
+| `required` | Not implemented; refused at config load (see [Configuration](#configuration)) |
### Create a Session
diff --git a/docs/guides/annotate-for-llm-fixes.md b/docs/guides/annotate-for-llm-fixes.md
index f9a9dba8..ba524c82 100644
--- a/docs/guides/annotate-for-llm-fixes.md
+++ b/docs/guides/annotate-for-llm-fixes.md
@@ -18,7 +18,8 @@ This guide shows the full loop.
Annotation is a *human-facing* overlay, so run a headed instance you can actually look at. See [Headed mode](./headed-mode.md) for details.
```bash
-# start a visible browser and open your site
+# start a visible browser (drop --browser cloak if CloakBrowser is not installed)
+# and open your site; 9870 stands for the "port" in the instance start reply
pinchtab instance start --browser cloak --mode headed
pinchtab --server http://127.0.0.1:9870 nav https://your-site.com
```
diff --git a/docs/guides/attach-chrome.md b/docs/guides/attach-chrome.md
index c6c9aecd..2caea528 100644
--- a/docs/guides/attach-chrome.md
+++ b/docs/guides/attach-chrome.md
@@ -51,17 +51,16 @@ The attach request body is:
{
"name": "shared-chrome",
"cdpUrl": "ws://127.0.0.1:9222/devtools/browser/...",
- "provider": "chrome",
- "browser": "chrome-local"
+ "browser": "chrome"
}
```
-`browser` is optional and accepts a provider name (`chrome`, `cloak`) or a
-configured target name from `browser.targets`. When `browser.targets` is
-configured, an omitted value attaches to the configured default target and the
-target's browser is used. If you also pass `provider`, it must agree with the
-`browser` value. Without browser targets,
-`provider` defaults to `chrome`; use `cloak` for a CloakBrowser endpoint
+`browser` (or its alias `provider`) is optional and takes a provider name
+(`chrome`, `cloak`, `ghost-chrome`), not a target name. When `browser.targets`
+is configured, the provider must have at least one configured target, and an
+omitted value attaches with the default target's provider. If you pass both
+`browser` and `provider`, they must agree. Without browser targets, the
+provider defaults to `chrome`; use `cloak` for a CloakBrowser endpoint
(equivalent to `--browser cloak` on the CLI).
Accepted `cdpUrl` shapes:
@@ -143,22 +142,25 @@ The value of `webSocketDebuggerUrl` is the `cdpUrl` you pass to PinchTab.
```bash
curl -X POST http://localhost:9867/instances/attach \
+ -H "Authorization: Bearer $(pinchtab config token --stdout)" \
-H "Content-Type: application/json" \
-d '{
"name": "shared-chrome",
"cdpUrl": "ws://127.0.0.1:9222/devtools/browser/abc123",
- "browser": "chrome-local"
+ "browser": "chrome"
}'
-# Response
+# Response (201, abridged)
{
"id": "inst_0a89a5bb",
"profileId": "prof_278be873",
"profileName": "shared-chrome",
- "port": "",
+ "port": "9868",
+ "url": "http://127.0.0.1:9868",
"mode": "headed",
"headless": false,
"status": "running",
"attached": true,
+ "attachType": "cdp-bridge",
"cdpUrl": "ws://127.0.0.1:9222/devtools/browser/abc123",
"browser": "chrome"
}
@@ -167,14 +169,15 @@ curl -X POST http://localhost:9867/instances/attach \
Notes:
- `name` is optional; if omitted, the server generates one like `attached-...`
-- the server validates the URL against `security.attach.allowHosts` and `security.attach.allowSchemes`
+- the server validates the URL against `security.attach.allowHosts` and `security.attach.allowSchemes` (a rejected URL answers `403`)
+- `port` and `url` belong to the child bridge PinchTab spawned from the instance port range, not to Chrome
---
## Step 5: confirm it is registered
```bash
-curl -s http://localhost:9867/instances | jq .
+curl -s -H "Authorization: Bearer $(pinchtab config token --stdout)" http://localhost:9867/instances | jq .
# CLI Alternative
pinchtab instance list
```
@@ -182,6 +185,7 @@ pinchtab instance list
An attached instance appears in the normal instance list with:
- `attached: true`
+- `attachType: "cdp-bridge"`
- `cdpUrl: ...`
- `status: "running"`
@@ -265,6 +269,7 @@ then managed instance start via:
```bash
curl -X POST http://localhost:9867/instances/start \
+ -H "Authorization: Bearer $(pinchtab config token --stdout)" \
-H "Content-Type: application/json" \
-d '{"mode":"headless"}'
# CLI Alternative
diff --git a/docs/guides/cloakbrowser.md b/docs/guides/cloakbrowser.md
index 0583031d..404b37f8 100644
--- a/docs/guides/cloakbrowser.md
+++ b/docs/guides/cloakbrowser.md
@@ -215,7 +215,7 @@ pinchtab doctor --check binary_exists # run a single check by name
```
Exit codes: `0` all checks passed or skipped, `1` at least one check failed,
-`2` config or usage error. See the [Troubleshooting](#troubleshooting) section
+`2` usage error (for example an unknown check name). See the [Troubleshooting](#troubleshooting) section
below for how to react to specific failures.
## Verify CloakBrowser Is Active
@@ -223,7 +223,7 @@ below for how to react to specific failures.
Check `/stealth/status` after the managed browser instance starts:
```bash
-TOKEN="$(pinchtab config get server.token)"
+TOKEN="$(pinchtab config token --stdout)"
curl -sS -H "Authorization: Bearer ${TOKEN}" \
http://127.0.0.1:9867/stealth/status
```
@@ -329,10 +329,10 @@ Project maintainers can validate the Docker integration with:
That command swaps the runtime browser to `browsers.default=cloak`
(`/opt/cloakbrowser/chrome`, `fingerprintSeed=42069`,
-`disableDefaultStealthArgs=true`), reuses the prebuilt
-`pinchtab-cloakbrowser:test` image (build it once via
-`tests/tools/docker/cloakbrowser-smoke.Dockerfile` — the runner does not
-auto-build it), asserts `/stealth/status` reports
+`disableDefaultStealthArgs=true`), builds the
+`pinchtab-cloakbrowser:test` image from
+`tests/tools/docker/cloakbrowser-smoke.Dockerfile` (set `SKIP_BUILD=1` to
+reuse an existing image instead), asserts `/stealth/status` reports
`provider=cloak, native=true, pinchtabOverlaysDisabled=true,
fingerprintSeed=42069`, and runs the full E2E suite against the cloak
container.
@@ -351,19 +351,19 @@ around the external endpoint and exposes the standard API on a local port.
```bash
curl -X POST http://localhost:9867/instances/attach \
+ -H "Authorization: Bearer $(pinchtab config token --stdout)" \
-H "Content-Type: application/json" \
-d '{
"name": "cloak-manager-profile",
"cdpUrl": "ws://127.0.0.1:9222/devtools/browser/abc123",
- "provider": "cloak",
- "browser": "cloak-1"
+ "browser": "cloak"
}'
```
For a remote CloakBrowser attach:
-- `browser` should name a CloakBrowser target (or the `cloak` provider) when `browser.targets` is configured; if omitted, the configured default target is used
-- `provider` in the JSON body must be `cloak` when no browser target is configured, or must match the selected target when both fields are present
+- `browser` (or its alias `provider`) takes the provider name `cloak`, not a target name; when `browser.targets` is configured there must be a target with provider `cloak`, and an omitted value attaches with the default target's provider
+- without `browser` or `provider` and without targets, the attach defaults to `chrome`; if you pass both fields they must agree
- `/stealth/status` reports `provider=cloak`, `launchMode=remote-cdp`,
`native=true`, and `pinchtabOverlaysDisabled=true` — PinchTab does not inject
its JS fingerprint overlays, on the assumption the external browser owns
@@ -395,8 +395,10 @@ pinchtab config set browser.binary /absolute/path/to/cloakbrowser/chrome
pinchtab config set browser.targets.cloak-eu.binary /absolute/path/to/cloakbrowser/chrome
```
-PinchTab does not search `$PATH` for CloakBrowser. Use the absolute path
-reported by `python -m cloakbrowser info` or `cloakbrowser.binaryInfo()`.
+Discovery only looks for an executable named `cloakbrowser` on `$PATH`, then
+`/opt/cloakbrowser/chrome` and `~/.cloakbrowser/chrome` (Linux and macOS). An
+installer that puts `chrome` anywhere else is not found, so use the absolute
+path reported by `python -m cloakbrowser info` or `cloakbrowser.binaryInfo()`.
### Unsupported platform build
@@ -419,18 +421,19 @@ x86_64 (or vice versa) the inner CloakBrowser binary will fail the same way.
Symptom: launch fails with `profile in use`, or PinchTab logs a warning that
the profile lock is held.
-PinchTab's stale-`SingletonLock` recovery (P3b) automatically removes the
-lock when the owning PID no longer exists:
+PinchTab's stale-`SingletonLock` recovery automatically clears the lock when
+no running PinchTab owns the profile:
-- if the lock points to a live non-PinchTab process, PinchTab refuses to
- steal the profile and logs `chrome profile lock appears active and owned by another pinchtab; leaving singleton files in place`
-- if the lock points to a dead process, PinchTab logs `chrome profile lock appears active but pinchtab owner is dead` and cleans up the stale files
-- if the lock points to a live process owned by another PinchTab, PinchTab
- refuses to steal it
+- if a running PinchTab owns the profile, PinchTab refuses to steal it and logs
+ `browser profile lock appears active and owned by another pinchtab; leaving singleton files in place`
+- if the lock PID is alive but its PinchTab owner is gone, PinchTab logs
+ `browser profile lock appears active but pinchtab owner is dead; proceeding with stale cleanup`
+- if browser processes still hold the profile with no PinchTab owner, PinchTab
+ logs `browser profile lock appears active but no pinchtab owner found; killing stale processes`
+ and then removes the singleton files
If recovery does not happen automatically, check the container or host
-logs for the `chrome profile lock appears active but pinchtab owner is dead`
-line:
+logs for those `browser profile lock` lines:
```bash
docker logs pinchtab-cloak | grep "profile lock"
diff --git a/docs/guides/contributing.md b/docs/guides/contributing.md
index e8c451e7..09b88835 100644
--- a/docs/guides/contributing.md
+++ b/docs/guides/contributing.md
@@ -8,7 +8,7 @@ This is the canonical contributor and development guide for PinchTab.
| Requirement | Version | Purpose |
|------------|---------|---------|
-| Go | 1.25+ | Build language |
+| Go | 1.26+ (`go.mod`) | Build language |
| golangci-lint | Latest | Linting (required for pre-commit hooks) |
| Chrome/Chromium | Latest | Browser automation |
| macOS, Linux, or WSL2 | Current | OS support |
@@ -38,7 +38,7 @@ cd pinchtab
# 3. Build and run
go build ./cmd/pinchtab
-./pinchtab
+./pinchtab server
```
**Example output:**
@@ -79,7 +79,7 @@ If you decline, it shows the manual install command instead.
**macOS (Homebrew):**
```bash
brew install go
-go version # Verify: go version go1.25.0
+go version # Verify: go1.26.0 or newer
```
**Linux (Ubuntu/Debian):**
@@ -152,7 +152,7 @@ cd pinchtab
```
Doctor checks your environment and **asks before installing** anything:
-- Go 1.25+ and golangci-lint (offers `brew install` or `go install`)
+- Go 1.26+ and golangci-lint (offers `brew install` or `go install`)
- Git hooks (copies pre-commit hook)
- Go dependencies (`go mod download`)
- Node.js, Bun, and dashboard deps (optional, for dashboard development)
@@ -196,11 +196,7 @@ ls -la pinchtab
./pinchtab server
```
-**Expected output:**
-```
-🦀 PINCH! PINCH! port=9867
-auth disabled (set PINCHTAB_TOKEN to enable)
-```
+The server listens on `127.0.0.1:9867` and requires the `server.token` from your config on every request (`./pinchtab config token --stdout` prints it). Add `-v` for the full startup banner.
### Start (Headed Mode)
@@ -229,7 +225,9 @@ URL/token without log scraping. For a longer-lived install, use
### Health Check
```bash
-curl http://localhost:9867/health
+./pinchtab health
+# or, with the token:
+curl -H "Authorization: Bearer $(./pinchtab config token --stdout)" http://localhost:9867/health
```
### Try CLI
@@ -252,7 +250,7 @@ go test ./... -v -coverprofile=coverage.out
go tool cover -html=coverage.out # View coverage
./dev e2e # Run the default extended E2E suite
./dev e2e basic # Run API + CLI + Infra basic tests
-./dev smoke ci # Run CI smoke scenarios + host Docker smoke checks
+./dev e2e smoke # Run CI smoke scenarios + host Docker smoke checks
./dev smoke # Run all local smoke categories
./dev smoke --browser=cloak # Run all local CloakBrowser smoke categories
./dev e2e api # Run API basic tests
@@ -442,7 +440,7 @@ This will tell you exactly what's missing or misconfigured.
### Common Issues
**"Go version too old"**
-- Install Go 1.25+ from https://go.dev/dl/
+- Install Go 1.26+ from https://go.dev/dl/
- Verify: `go version`
**"golangci-lint: command not found"**
@@ -474,6 +472,6 @@ Issues? Check:
1. Run `./dev doctor` first
2. All dependencies installed and correct versions?
3. Port 9867 available?
-4. Check logs: `tail -f pinchtab.log`
+4. Check logs: a foreground server logs to its terminal; `pinchtab server --background` writes `<server.stateDir>/server.log`; the daemon writes `~/.pinchtab/logs/daemon.err.log`
See `docs/` for guides and examples.
diff --git a/docs/guides/daemon.md b/docs/guides/daemon.md
index 886fd2f9..02b24a18 100644
--- a/docs/guides/daemon.md
+++ b/docs/guides/daemon.md
@@ -4,29 +4,22 @@ PinchTab can run as a user-level background service (daemon) on macOS (`launchd`
This workflow is not currently provided on Windows. Windows binaries are available, but Windows support is limited and best-effort; on Windows, prefer running `pinchtab server` or `pinchtab bridge` directly.
-![Daemon Status & Picker](../media/daemon-status.png)
-
## Quick Start
-The normal entrypoints are:
-
-```bash
-pinchtab
-```
-
-Then choose `Daemon` from the menu, or manage the service directly:
+Check the service, then install it:
```bash
pinchtab daemon
+pinchtab daemon install
```
-When run without arguments in an interactive terminal, this command shows the current status and opens a picker for common actions.
+Without an action, `pinchtab daemon` prints the current status, the commands that apply to that state, and recent logs. It does not open a picker; run the action you want directly. `pinchtab daemon --json` prints the status as JSON.
## Daemon Commands
| Command | Description |
|---------|-------------|
-| `pinchtab daemon` | Show status summary, recent logs, and open interactive picker. |
+| `pinchtab daemon` | Show status summary, next commands, and recent logs (`status` is an alias). |
| `pinchtab daemon install` | Create and enable the background service file. |
| `pinchtab daemon start` | Start the background service if it is stopped. |
| `pinchtab daemon stop` | Stop the background service. |
@@ -38,10 +31,10 @@ When run without arguments in an interactive terminal, this command shows the cu
The `pinchtab daemon` command provides a comprehensive overview of the service:
- **Service Status**: Shows if the `.plist` (macOS) or `.service` (Linux) file is installed.
-- **State**: Indicates if the process is `active (running)` or `stopped`.
+- **State**: Indicates if the process is `running` or `stopped`.
- **PID**: The Process ID of the running server.
- **Path**: The exact location of the service configuration file on your system.
-- **Recent Logs**: The last few lines of output from the server to help diagnose issues.
+- **Recent Logs**: The last few lines of output from the server to help diagnose issues (the full logs are `~/.pinchtab/logs/daemon.out.log` and `daemon.err.log`).
## Manual Installation
@@ -59,7 +52,7 @@ In those cases, use the manual steps below or run `pinchtab server` in the foreg
### macOS (launchd)
Service file: `~/Library/LaunchAgents/com.pinchtab.pinchtab.plist`
-1. Create the plist file (PinchTab will provide the content on error).
+1. Create the plist file (the error output names the path to create).
2. Register and start:
```bash
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.pinchtab.pinchtab.plist
diff --git a/docs/guides/data-storage.md b/docs/guides/data-storage.md
index c6a49c5c..56e804c0 100644
--- a/docs/guides/data-storage.md
+++ b/docs/guides/data-storage.md
@@ -12,16 +12,28 @@ PinchTab stores configuration, profiles, session state, and usage logs on local
| `activity/events-YYYY-MM-DD.jsonl` | Primary daily request/activity log for `/api/activity`, CLI activity, and dashboard activity views | `server.stateDir`, `observability.activity.retentionDays` |
| `activity/events-<source>-YYYY-MM-DD.jsonl` | Source-specific daily activity log for named sources such as `dashboard` or `orchestrator` | `server.stateDir`, `observability.activity.retentionDays` |
| `<profile>/.pinchtab-state/config.json` | Child instance config written by the orchestrator | generated automatically for managed instances |
+| `server.log` | Output of a server started with `pinchtab server --background` | `server.stateDir` |
+| `heapsnapshots/<id>.heapsnapshot` | V8 heap snapshots from `POST /memory/snapshot` | `server.stateDir` |
+| `logs/daemon.out.log`, `logs/daemon.err.log` | Output of the background service (`pinchtab daemon`), always under `~/.pinchtab/logs/` | not configurable |
+
+## CLI State
+
+The command line keeps its own per-user scratch state outside the server's `stateDir`: the current-tab file per server (`current-tab-<host>-<port>`), the ref-vocabulary cache (`vocab-<host>-<port>`), the active recording marker (`current-recording`), and the once-per-run advisory markers (`advisories/`). It lives in:
+
+- `$XDG_STATE_HOME/pinchtab/`, if `XDG_STATE_HOME` is set
+- otherwise `~/.local/state/pinchtab/`
+
+Deleting it only resets CLI conveniences; it holds no browser data.
## Default Storage Location
-PinchTab uses the OS config directory:
+PinchTab keeps config and server state under one base directory. `server.stateDir` defaults to that directory, and `profiles.baseDir` defaults to `<server.stateDir>/profiles`:
| OS | Default Base Directory |
| --- | --- |
| Linux | `~/.pinchtab/` |
| macOS | `~/.pinchtab/` |
-| Windows | `%APPDATA%\\pinchtab\\` |
+| Windows | `%APPDATA%\pinchtab\` |
Typical layout:
@@ -39,7 +51,7 @@ pinchtab/
On macOS and Linux, `~/.pinchtab/` is the default base directory.
-On Windows, PinchTab uses the OS-native config directory under `%APPDATA%\\pinchtab\\`.
+On Windows, PinchTab uses the OS-native config directory under `%APPDATA%\pinchtab\`.
## Profiles
@@ -93,7 +105,7 @@ Bridge session restore data is stored as:
<server.stateDir>/sessions.json
```
-This file is used for tab/session restoration when restore behavior is enabled.
+This file is used for tab/session restoration when restore behavior is enabled (`instanceDefaults.tabPolicy.restore`, default `false`).
## Activity Logs
@@ -109,13 +121,13 @@ Named sources also get their own daily files:
<server.stateDir>/activity/events-<source>-YYYY-MM-DD.jsonl
```
-By default PinchTab keeps 1 day of activity data and prunes older daily files when new activity is recorded. You can change that with:
+By default PinchTab keeps 30 days of activity data and prunes older daily files when new activity is recorded. You can change that with:
```json
{
"observability": {
"activity": {
- "retentionDays": 1,
+ "retentionDays": 30,
"sessionIdleSec": 1800,
"events": {
"dashboard": false,
@@ -156,7 +168,7 @@ Profile `logs` and `analytics` endpoints are derived from the activity store rat
```bash
export PINCHTAB_CONFIG=/etc/pinchtab/config.json
-pinchtab
+pinchtab server
```
### Choose Different Profile And State Paths
@@ -175,7 +187,7 @@ pinchtab
## Container Use
-For Docker or other containers, persist both config and profile data with a mounted volume and point `PINCHTAB_CONFIG` at a file inside that volume.
+For Docker or other containers, persist both config and profile data with a mounted volume and point `PINCHTAB_CONFIG` at a file inside that volume. A config selected through `PINCHTAB_CONFIG` must carry `server.token` (or the container must set `PINCHTAB_TOKEN`); PinchTab will not generate one into an operator-supplied file.
Example layout inside the volume:
diff --git a/docs/guides/docker.md b/docs/guides/docker.md
index d715c45e..4f76f44e 100644
--- a/docs/guides/docker.md
+++ b/docs/guides/docker.md
@@ -1,7 +1,7 @@
# Docker Deployment
PinchTab can run in Docker with a mounted data volume for config, profiles, and state.
-The bundled image now manages its default config under `/data/.config/pinchtab/config.json`.
+The bundled image manages its default config under `/data/.pinchtab/config.json` (the image sets `HOME=/data`, and PinchTab keeps config in `~/.pinchtab` on Linux).
If you want full control over the config file path, you can still mount your own file and point `PINCHTAB_CONFIG` at it.
## Quick Start
@@ -23,7 +23,7 @@ docker run -d \
pinchtab
```
-On first boot, the image creates `/data/.config/pinchtab/config.json` with `bind: 0.0.0.0` (required for Docker port publishing) and generates a token if needed.
+On first boot, the image creates `/data/.pinchtab/config.json` with `bind: 0.0.0.0` (required for Docker port publishing) and generates a token if needed. Read it with `docker exec pinchtab pinchtab config token --stdout`; every API call, `/health` included, needs it as `Authorization: Bearer <token>`.
If you inspect the startup security summary from inside Docker, the loopback bind check will still report the effective runtime bind as non-loopback. That is expected: the process is listening on `0.0.0.0` inside the container so Docker port publishing can forward traffic to it.
@@ -47,11 +47,11 @@ With the `always-on` strategy (default), PinchTab launches a managed Chrome inst
### Docker Compose Healthcheck
-The standard healthcheck marks the container as "healthy" when the dashboard responds:
+The image's built-in `HEALTHCHECK` runs `pinchtab health`, which reads the token from the container's config, and marks the container "healthy" when the dashboard responds. In Compose the equivalent is:
```yaml
healthcheck:
- test: ["CMD-SHELL", "wget -q -O /dev/null http://localhost:9867/health"]
+ test: ["CMD-SHELL", "pinchtab health >/dev/null"]
interval: 3s
timeout: 10s
retries: 20
@@ -66,7 +66,7 @@ If your application needs Chrome to be ready before making requests, poll `/heal
```bash
# Wait for browser to be ready
-until curl -sf http://localhost:9867/health | jq -e '.defaultInstance.status == "running"' > /dev/null 2>&1; do
+until curl -sf -H "Authorization: Bearer $PINCHTAB_TOKEN" http://localhost:9867/health | jq -e '.defaultInstance.status == "running"' > /dev/null 2>&1; do
sleep 1
done
echo "Browser ready"
@@ -75,11 +75,13 @@ echo "Browser ready"
Or in code:
```javascript
-async function waitForBrowser(baseUrl, timeoutMs = 60000) {
+async function waitForBrowser(baseUrl, token, timeoutMs = 60000) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
try {
- const res = await fetch(`${baseUrl}/health`);
+ const res = await fetch(`${baseUrl}/health`, {
+ headers: { Authorization: `Bearer ${token}` },
+ });
const data = await res.json();
if (data.defaultInstance?.status === "running") return;
} catch {}
@@ -97,6 +99,7 @@ async function waitForBrowser(baseUrl, timeoutMs = 60000) {
"mode": "dashboard",
"version": "0.8.0",
"uptime": 12345,
+ "authRequired": true,
"profiles": 1,
"instances": 1,
"defaultInstance": {
@@ -126,6 +129,7 @@ Example `docker-data/config.json`:
"server": {
"bind": "0.0.0.0",
"port": "9867",
+ "token": "replace-with-a-generated-token",
"stateDir": "/data/state"
},
"profiles": {
@@ -139,6 +143,8 @@ Example `docker-data/config.json`:
}
```
+PinchTab will not write a token into a file you supplied through `PINCHTAB_CONFIG`, so either set `server.token` as above or pass `-e PINCHTAB_TOKEN=...`; with neither, the server refuses to start.
+
Run with an explicit config file:
```bash
@@ -155,8 +161,8 @@ docker run -d \
Check it:
```bash
-curl http://localhost:9867/health
-curl http://localhost:9867/instances
+curl -H "Authorization: Bearer $PINCHTAB_TOKEN" http://localhost:9867/health
+curl -H "Authorization: Bearer $PINCHTAB_TOKEN" http://localhost:9867/instances
```
## What To Persist
@@ -202,7 +208,7 @@ services:
command:
- |
export PINCHTAB_TOKEN="$(cat /run/secrets/pinchtab_token)"
- exec /usr/local/bin/docker-entrypoint.sh pinchtab
+ exec /usr/local/bin/docker-entrypoint.sh pinchtab server
```
Secrets mounted at `/run/secrets/...` are read-only and never appear in `docker ps` or logs.
@@ -212,7 +218,7 @@ Secrets mounted at `/run/secrets/...` are read-only and never appear in `docker
The repository includes a `docker-compose.yml` that follows the managed-config pattern:
1. mount a persistent `/data` volume
-2. let the entrypoint create and maintain `/data/.config/pinchtab/config.json`
+2. let the entrypoint create and maintain `/data/.pinchtab/config.json`
3. optionally pass `PINCHTAB_TOKEN`
If you prefer a fully user-managed config file, mount it separately and set `PINCHTAB_CONFIG`.
@@ -279,7 +285,7 @@ This image is local-only:
- it is not pushed to any registry
- it is not produced by `./dev binaries`
-- `./dev smoke cloakbrowser` reuses it when present; set `SKIP_BUILD=0` or remove the image to force a rebuild
+- `./dev smoke cloakbrowser` builds its own copy from the same Dockerfile, tagged `pinchtab-cloakbrowser:test`, on every run; set `SKIP_BUILD=1` to reuse an existing image instead
### Run a CloakBrowser-backed container locally
diff --git a/docs/guides/headed-mode.md b/docs/guides/headed-mode.md
index 8cf70863..aa78dc91 100644
--- a/docs/guides/headed-mode.md
+++ b/docs/guides/headed-mode.md
@@ -44,10 +44,14 @@ work too because Chrome falls back to XWayland.
### Linux over SSH with X forwarding
```bash
-ssh -X user@workstation 'DISPLAY=:0 pinchtab instance start --mode headed'
+ssh -X user@workstation
+# in that SSH session, DISPLAY already points at the forwarded display
+pinchtab server --headed
```
-Forwarding works but is laggy for interactive use; prefer running PinchTab on
+Chrome inherits `DISPLAY` from the `pinchtab server` process, not from the
+client that calls `pinchtab instance start`, so the server has to be started
+inside the forwarded session. Forwarding works but is laggy for interactive use; prefer running PinchTab on
the workstation itself.
### Docker with X11 forwarding (manual, Linux host only)
diff --git a/docs/guides/identifying-instances.md b/docs/guides/identifying-instances.md
index 0451a376..1bc1800c 100644
--- a/docs/guides/identifying-instances.md
+++ b/docs/guides/identifying-instances.md
@@ -71,7 +71,9 @@ The dashboard and instance APIs show:
If you need an API-based view instead of the UI:
```bash
-curl http://localhost:9867/instances
+curl -H "Authorization: Bearer $(pinchtab config token --stdout)" http://localhost:9867/instances
+# CLI Alternative
+pinchtab instance list
```
## Practical Combination
diff --git a/docs/guides/mcp-agents.md b/docs/guides/mcp-agents.md
index b94c6ee6..04fa7948 100644
--- a/docs/guides/mcp-agents.md
+++ b/docs/guides/mcp-agents.md
@@ -12,7 +12,7 @@ This guide walks through setting up PinchTab as an MCP tool server for AI coding
## What is MCP?
-The [Model Context Protocol](https://modelcontextprotocol.io/) is an open standard for connecting AI models to external tools. PinchTab implements an MCP server that exposes 38 browser-control tools — navigation, interaction, screenshot, PDF export, waits, network inspection, and more — over a simple stdio interface that every major AI client supports.
+The [Model Context Protocol](https://modelcontextprotocol.io/) is an open standard for connecting AI models to external tools. PinchTab implements an MCP server that exposes 47 browser-control tools — navigation, interaction, screenshot, PDF export, waits, network inspection, and more — over a simple stdio interface that every major AI client supports.
## Prerequisites
@@ -24,16 +24,16 @@ The [Model Context Protocol](https://modelcontextprotocol.io/) is an open standa
The MCP server is a thin adapter — it needs a running PinchTab instance to delegate to.
-**Headless mode (recommended for agents):**
+**Single-instance bridge (headless by default, recommended for agents):**
```bash
-pinchtab bridge --headless
+pinchtab bridge
```
**Normal server mode (if you want the dashboard too):**
```bash
-pinchtab
+pinchtab server
```
PinchTab listens on `http://127.0.0.1:9867` by default.
@@ -231,9 +231,11 @@ The `pinchtab mcp` process runs locally (on the agent machine) and makes HTTP ca
PinchTab is not running, or is on a different port. Check:
```bash
-curl http://127.0.0.1:9867/health
+pinchtab health
```
+(A raw `curl http://127.0.0.1:9867/health` also proves the port answers, but it returns `401` without `-H "Authorization: Bearer <token>"`.)
+
**"HTTP 401" from tools**
Token mismatch. Set `PINCHTAB_TOKEN` to match `server.token` in your PinchTab config.
diff --git a/docs/guides/memory-monitoring.md b/docs/guides/memory-monitoring.md
index c58b6966..55c2bef6 100644
--- a/docs/guides/memory-monitoring.md
+++ b/docs/guides/memory-monitoring.md
@@ -39,16 +39,18 @@ Important limitation:
## Instance Metrics
-For a single running browser:
+For a single running browser, read the instance's own `/metrics`. Against `pinchtab bridge` that is the bridge port; behind `pinchtab server`, go through the instance route, because the server's own `GET /metrics` answers the front door's counters (`"layer": "frontDoor"`) with no `memory` block:
```bash
-curl http://localhost:9867/metrics
+curl http://localhost:9867/metrics # pinchtab bridge
+curl http://localhost:9867/instances/<instanceId>/metrics # pinchtab server
```
-Example shape:
+Example shape (abridged; `failures` and `crashes` omitted):
```json
{
+ "layer": "instance",
"metrics": {
"goHeapAllocMB": 12.5,
"goHeapSysMB": 24.0,
@@ -100,6 +102,18 @@ curl http://localhost:9867/instances/metrics
This returns one metrics object per running instance — `instanceId`, `profileName`, `memoryMB`, `renderers`, `page` and `unreadableTargets` — which is the best API for comparing memory across a fleet.
+## Page Heap And Leak Hunting
+
+The figures above are instance-wide. For one tab's JavaScript heap, heap snapshots, and snapshot comparison, use the `/memory` endpoints and `pinchtab memory` instead:
+
+```bash
+pinchtab memory --gc # GET /memory?gc=true: heap usage and DOM counters
+pinchtab memory snapshot # POST /memory/snapshot (needs security.allowMemory)
+pinchtab memory compare <base> <head>
+```
+
+`GET /memory` is always available; snapshot, summary and compare need `security.allowMemory` (default off). See [Memory](../reference/memory.md) for the endpoints, response shapes and a leak-hunting walkthrough.
+
## Dashboard Monitoring
The dashboard consumes monitoring snapshots from:
diff --git a/docs/guides/multi-instance.md b/docs/guides/multi-instance.md
index 4944228f..057271be 100644
--- a/docs/guides/multi-instance.md
+++ b/docs/guides/multi-instance.md
@@ -15,7 +15,7 @@ PinchTab can run multiple isolated Chrome instances at the same time. Each runni
pinchtab server
```
-By default the orchestrator listens on `http://localhost:9867`.
+By default the orchestrator listens on `http://localhost:9867`. Every API call below needs the server token; the examples assume `export PINCHTAB_TOKEN=$(pinchtab config token --stdout)` and send it as `-H "Authorization: Bearer $PINCHTAB_TOKEN"` (omitted for brevity). The CLI alternatives pick the token up automatically.
## Start An Instance
@@ -43,8 +43,8 @@ Notes:
- `POST /instances/launch` still exists as a compatibility endpoint, but it now follows the same semantics as `POST /instances/start`.
- If you omit `profileId`, PinchTab creates a managed instance with an auto-generated profile name.
-- `securityPolicy.allowedDomains` lets you widen IDPI/domain trust for just that instance. This is additive over the server baseline, so one instance can use `["*"]` while the rest stay on the default allowlist.
-- Starting an instance is only optional in workflows that use shorthand routes with auto-launch behavior, such as the `simple` strategy. In `explicit`, you should assume you need to start one yourself.
+- `securityPolicy.allowedDomains` lets you widen IDPI/domain trust for just that instance. This is merged with the server's `security.allowedDomains`, so with a local-only server allowlist one instance can use `["*"]` while the rest stay restricted. The server default leaves `allowedDomains` unset, so passing a list to an instance on a default server restricts that instance to the list.
+- Starting an instance is only optional in workflows that use shorthand routes with auto-launch behavior, such as the default `always-on` strategy or `simple`. In `explicit`, you should assume you need to start one yourself.
## Open A Tab In A Specific Instance
@@ -85,9 +85,9 @@ Then start an instance for a known profile:
```bash
curl -X POST http://localhost:9867/instances/start \
-H "Content-Type: application/json" \
- -d '{"profileId":"278be873adeb","mode":"headless"}'
+ -d '{"profileId":"prof_278be873","mode":"headless"}'
# CLI Alternative
-pinchtab instance start --profile 278be873adeb --mode headless
+pinchtab instance start --profile prof_278be873 --mode headless
```
Because a profile can have only one active managed instance, starting the same profile again while it is already active returns an error instead of creating a duplicate browser.
diff --git a/docs/guides/raspberry-pi.md b/docs/guides/raspberry-pi.md
index add58443..210e427a 100644
--- a/docs/guides/raspberry-pi.md
+++ b/docs/guides/raspberry-pi.md
@@ -72,12 +72,14 @@ Example:
}
```
-Run with it:
+Save it as `/home/pi/.pinchtab/config.json` (the default path, so no `PINCHTAB_CONFIG` is needed) and run:
```bash
-PINCHTAB_CONFIG=/home/pi/.pinchtab/config.json ./pinchtab
+./pinchtab server
```
+The first start generates `server.token` into that file. If you instead point `PINCHTAB_CONFIG` at a file elsewhere, add `server.token` yourself: PinchTab refuses to start rather than write a token into an operator-supplied file.
+
## Headless Vs Headed
For most Raspberry Pi workloads, keep the default:
@@ -133,7 +135,7 @@ After=network.target
Type=simple
User=pi
WorkingDirectory=/home/pi
-ExecStart=/home/pi/pinchtab
+ExecStart=/home/pi/pinchtab server
Environment=PINCHTAB_CONFIG=/home/pi/.pinchtab/config.json
Restart=always
RestartSec=10
diff --git a/docs/guides/security.md b/docs/guides/security.md
index 21659a6e..9ca53df3 100644
--- a/docs/guides/security.md
+++ b/docs/guides/security.md
@@ -21,13 +21,18 @@ The default security posture is:
- `security.allowDownload = false`
- `security.allowCookies = false`
- `security.allowUpload = false`
+- `security.allowStateExport = false`
+- `security.allowNetworkIntercept = false`
+- `security.allowMemory = false`
+- `security.allowClipboard = false`
+- `security.allowFileScheme = false`
- `autoSolver.enabled = false`
- `instanceDefaults.stealthLevel = "light"` (minimal fingerprint normalization only; anti-bot bypass requires explicit opt-in to `medium` or `full`)
- `security.attach.enabled = false`
- `security.attach.allowHosts = ["127.0.0.1", "localhost", "::1"]`
- `security.attach.allowSchemes = ["ws", "wss", "http", "https"]`
- `security.attach.forwardProxyAuth = false`
-- `security.allowedDomains = ["127.0.0.1", "localhost", "::1"]`
+- `security.allowedDomains` unset (no domain restriction; the SSRF/private-IP guard still applies)
- `security.trustedProxyCIDRs = []`
- `security.trustedResolveCIDRs = []`
- `security.idpi.enabled = true`
@@ -35,7 +40,7 @@ The default security posture is:
- `security.idpi.scanContent = true`
- `security.idpi.wrapContent = true`
-Use `pinchtab security` to review the current posture and restore the recommended defaults.
+Use `pinchtab security` to review the current posture and `pinchtab security up` to restore the recommended defaults (loopback bind, every capability off, local-only attach, IDPI on). `security up` resets the whole `security` block to the defaults above, so it also clears `security.allowedDomains`; set a local-only allowlist separately if you want one (see [IDPI](#idpi)).
## Security Philosophy
@@ -164,7 +169,7 @@ Recommended practice:
pinchtab config init
```
-The dashboard Settings page does not expose or rotate `server.token`. Use `pinchtab config token` to copy the current token (or `pinchtab config token --stdout` to print it where there is no clipboard), or let `pinchtab security` restore or create one if `server.token` is empty.
+The dashboard Settings page does not expose or rotate `server.token`. Use `pinchtab config token` to copy the current token (or `pinchtab config token --stdout` to print it where there is no clipboard), or let `pinchtab security up` create one if `server.token` is empty.
If you are calling the API manually:
@@ -195,6 +200,10 @@ Some endpoint families expose much more power than normal navigation and inspect
- `security.allowDownload`
- `security.allowCookies`
- `security.allowUpload`
+- `security.allowStateExport`
+- `security.allowNetworkIntercept`
+- `security.allowMemory`
+- `security.allowClipboard`
- `security.allowFileScheme`
Why they are considered dangerous:
@@ -205,6 +214,10 @@ Why they are considered dangerous:
- `download` can fetch and persist remote content. When `security.downloadAllowedDomains` is set, matching domains bypass private-IP SSRF checks (intended for internal hosts such as Docker services). A bare `"*"` matches every host and therefore disables private-IP protection for this endpoint, including loopback. Naming a loopback host (`127.0.0.1`, `localhost`) or using `"*"` lets the download endpoint reach services on the server's own machine, including PinchTab's own local endpoints, so treat either configuration the way you treat `allowFileScheme`.
- `cookies` can read, write, or clear browser session tokens for the current page
- `upload` can push local files into browser flows
+- `stateExport` writes cookies and browser storage to disk and loads them back (`/state/*`, `/storage`)
+- `networkIntercept` can rewrite, block, or mock requests and read full request details (`/network/route`, `/network/{requestId}`)
+- `memory` writes V8 heap snapshots, which hold every string on the page, tokens included (`/memory/snapshot`, `/memory/compare`)
+- `clipboard` can read and write the browser clipboard (`/clipboard/*`)
- `allowFileScheme` permits navigation to `file://` URLs. Because a `file://` URL has no host, it is **not** subject to `allowedDomains` or the SSRF/private-IP guard, so enabling it grants read access (via snapshot/screenshot/scrape) to any local file the server process can read. It stays blocked when a strict-mode `allowedDomains` allowlist is active. Enable only on trusted, single-tenant hosts. `javascript:`, `chrome://`, and `data:` remain rejected regardless.
These are not the same as authentication.
@@ -214,7 +227,7 @@ These are not the same as authentication.
For example, a token-protected server with `security.allowEvaluate = true` is still intentionally exposing JavaScript execution to any caller that has the token.
-When disabled, these routes are locked and return a `403` explaining that the endpoint family is disabled in config.
+When disabled, these routes are locked and return a `403` explaining that the endpoint family is disabled in config (codes such as `evaluate_disabled`, `upload_disabled`, `memory_disabled`).
## Attach Policy
@@ -277,7 +290,7 @@ PinchTab's IDPI layer currently does four things:
- scans extracted content for suspicious prompt-injection patterns
- wraps text output so downstream systems can treat it as untrusted content
-The default local-only IDPI config is:
+IDPI is on by default, but `allowedDomains` is unset, so navigation is not domain-restricted until you set it. A local-only IDPI config looks like this:
```json
{
@@ -303,7 +316,7 @@ Important notes:
keeps refusing private and internal addresses exactly as it does with IDPI off.
(Enabling IDPI with an empty list used to *remove* that protection, because "the
scanner found nothing suspicious" was read as "the operator allowed this host".)
-- listing a private or internal host explicitly — `["10.0.0.5"]`, or the default
+- listing a private or internal host explicitly — `["10.0.0.5"]`, or the local-only
`["127.0.0.1", "localhost", "::1"]` — is what permits navigation to it. That is the
only way the private-IP guard is relaxed, and it is a positive match by an entry
that **denotes a host**, never the absence of a list and never a bare `"*"`.
@@ -415,7 +428,7 @@ For short-lived or one-off usage, prefer `pinchtab server` (foreground process,
Agent session credentials auto-expire after **30 minutes of idle** (`sessions.agent.idleTimeoutSec: 1800`) and have a **24-hour max lifetime** (`sessions.agent.maxLifetimeSec: 86400`) by default.
-## Agent Sessions
+## Agent Session Tokens
For automated agents, use **agent sessions** instead of sharing the server bearer token. Each agent gets a dedicated session token (`PINCHTAB_SESSION`) that:
diff --git a/docs/guides/tailscale-bridge-orchestrator.md b/docs/guides/tailscale-bridge-orchestrator.md
index 07ea03d3..a39a1045 100644
--- a/docs/guides/tailscale-bridge-orchestrator.md
+++ b/docs/guides/tailscale-bridge-orchestrator.md
@@ -10,8 +10,6 @@ There is a simple distributed PinchTab shape that turns out to be very practical
That gives you one control plane and multiple places where browser execution can live.
-![Placeholder diagram for a Tailscale-connected orchestrator and remote bridge](../media/tailscale-bridge-topology-placeholder.svg)
-
```mermaid
flowchart LR
Agent["Agent / client"] --> AAPI
diff --git a/docs/headless-vs-headed.md b/docs/headless-vs-headed.md
index d56ca396..fb52c83b 100644
--- a/docs/headless-vs-headed.md
+++ b/docs/headless-vs-headed.md
@@ -5,7 +5,10 @@ PinchTab instances can run Chrome in two modes:
- **Headless**: no visible browser window
- **Headed**: visible browser window
-You usually run one server with `pinchtab`, then start instances in either mode through the API or CLI.
+You usually run one server with `pinchtab server`, then start instances in either mode through the API or CLI.
+
+The HTTP API requires the server token. The `curl` examples on this page omit it for brevity;
+add `-H "Authorization: Bearer $PINCHTAB_TOKEN"` after `export PINCHTAB_TOKEN=$(pinchtab config token --stdout)`.
---
@@ -23,7 +26,7 @@ pinchtab instance start
{
"id": "inst_0a89a5bb",
"profileId": "prof_278be873",
- "profileName": "instance-1741400000000000000",
+ "profileName": "instance-1741400000000000000-9f3c2a1b",
"port": "9868",
"mode": "headless",
"headless": true,
@@ -59,7 +62,7 @@ pinchtab instance start --mode headed
{
"id": "inst_1b9a5dcc",
"profileId": "prof_278be873",
- "profileName": "instance-1741400000000000001",
+ "profileName": "instance-1741400000000000001-4d7e0c52",
"port": "9869",
"mode": "headed",
"headless": false,
@@ -191,7 +194,7 @@ curl http://localhost:9867/tabs/CDP_TARGET_ID/text | jq .
```
```bash
-curl http://localhost:9867/tabs/CDP_TARGET_ID/screenshot > page.jpg
+curl "http://localhost:9867/tabs/CDP_TARGET_ID/screenshot?raw=true" > page.jpg
```
---
@@ -207,10 +210,10 @@ Headed mode works with the native desktop session.
### Linux
Headless works anywhere.
-Headed mode needs X11 or Wayland.
+Headed mode needs X11 or Wayland. Chrome is launched by the server, so the display must be available to `pinchtab server`, not to the CLI that starts the instance:
```bash
-ssh -X user@server 'pinchtab instance start --mode headed'
+ssh -X user@server 'pinchtab server'
```
### Windows
@@ -224,7 +227,7 @@ Prefer direct local runs with `pinchtab server` or `pinchtab bridge`; the daemon
Headless is the normal choice in containers:
```bash
-docker run -d -p 9867:9867 pinchtab/pinchtab
+docker run -d -p 127.0.0.1:9867:9867 pinchtab/pinchtab
curl -X POST http://localhost:9867/instances/start \
-H "Content-Type: application/json" \
-d '{"mode":"headless"}'
diff --git a/docs/implementations/chrome-files.md b/docs/implementations/chrome-files.md
index 3126382a..38413d0e 100644
--- a/docs/implementations/chrome-files.md
+++ b/docs/implementations/chrome-files.md
@@ -4,11 +4,12 @@ PinchTab manages Chrome instances using dedicated **User Data Directories** (pro
## Profile Resolution
-PinchTab determines the Chrome `--user-data-dir` (profile) using the following precedence:
+PinchTab derives the Chrome `--user-data-dir` (profile) as `profiles.baseDir` joined with `profiles.defaultProfile` (`finalizeProfileConfig` in `internal/config/config_load.go`):
-1. **Explicit `ProfileDir`**: If a specific path is provided in the configuration or as a flag, PinchTab uses that exact directory.
-2. **Named Profile**: If a profile name is provided (e.g., via the dashboard or CLI), PinchTab resolves it to a subdirectory within the `ProfilesBaseDir`.
-3. **Default Profile**: If no profile is specified, it defaults to `~/.pinchtab/profiles/default` (on Linux/macOS).
+1. **Named Profile**: When an instance is started for a named profile (dashboard, `pinchtab instance start --profile <name>`, or the API), the orchestrator writes the child's config with `profiles.baseDir` / `profiles.defaultProfile` pointing at that profile's directory (`buildChildFileConfig` in `internal/orchestrator/child_config.go`).
+2. **Default Profile**: Otherwise `profiles.baseDir` defaults to `<server.stateDir>/profiles` and `profiles.defaultProfile` to `default`, giving `~/.pinchtab/profiles/default` on Linux/macOS.
+
+There is no config key for an arbitrary profile path, and `--user-data-dir` in `browser.extraFlags` is rejected by config validation.
## The Singleton Model
@@ -26,13 +27,13 @@ With the introduction of **New Headless mode** (`--headless=new`), Chrome's prof
### Headless Auto-Fallback
To support parallel automation tasks, PinchTab implements an **automatic fallback for headless instances**:
-1. If a headless instance tries to start using a profile that is already locked by another PinchTab process, it will **automatically create a unique temporary directory** (e.g., `/tmp/pinchtab-profile-*`).
+1. If a headless instance tries to start using a profile that is already locked by another PinchTab process, it will **automatically create a unique temporary directory** (`pinchtab-profile-*` under the system temp directory, e.g. `/tmp`).
2. This allows you to run multiple headless tasks in parallel without manually managing profile paths.
### Manual Parallelism (Headed Mode)
In **headed mode**, PinchTab does *not* automatically fall back to a temporary directory (to avoid losing user session data unexpectedly). If you need to run multiple headed browsers in parallel, you must:
-* Use different named profiles.
-* Explicitly provide a unique `--user-data-dir` for each instance.
+* Use a different named profile for each instance, or
+* point `profiles.baseDir` / `profiles.defaultProfile` at a separate directory for each server.
## Best Practices for AI Agents
@@ -46,7 +47,7 @@ When building agents that use PinchTab, follow these guidelines:
If you see the error `"The profile appears to be in use by another Chromium process"`:
1. **Check for active instances**: Ensure you don't have another PinchTab or Chrome process already using that profile.
-2. **Stale Locks**: If no process is active, PinchTab will attempt to automatically clear stale `SingletonLock` files on the next startup.
+2. **Stale Locks**: If no process is active, PinchTab automatically clears the stale `SingletonLock` / `SingletonSocket` / `SingletonCookie` files when browser startup fails with this error, then retries once.
3. **Manual Fix**: In rare cases, you may need to manually remove the `SingletonLock` file from the profile directory.
For more details on how PinchTab recovers from crashes, see [Chrome Profile Lock Recovery](./chrome-profile-lock-recovery.md).
diff --git a/docs/implementations/chrome-profile-lock-recovery.md b/docs/implementations/chrome-profile-lock-recovery.md
index 5cb74f9c..e50668bc 100644
--- a/docs/implementations/chrome-profile-lock-recovery.md
+++ b/docs/implementations/chrome-profile-lock-recovery.md
@@ -12,10 +12,10 @@ The recovery process follows a multi-layered approach to distinguish between a t
### 1. Detection
-During initialization in `internal/bridge/runtime/init.go` (with bridge wiring in `internal/bridge/bridge_lifecycle.go`), if browser startup fails, PinchTab checks the error message for signatures of a profile lock:
+During initialization, `startBrowserWithRecovery` in `internal/bridge/runtime/recovery.go` (called from `InitBrowser` in `internal/bridge/runtime/init.go`) checks the startup error message via `isProfileLockError` for signatures of a profile lock:
- `The profile appears to be in use by another Chromium process`
- `The profile appears to be in use by another Chrome process`
-- `process_singleton_posix.cc` (indicating a failure in the ProcessSingleton logic)
+- `process_singleton` (e.g. `process_singleton_posix.cc`, indicating a failure in the ProcessSingleton logic)
### 2. Validation & PinchTab PID Lock
@@ -25,6 +25,7 @@ To safely clear a lock, PinchTab must be certain no *other* active PinchTab inst
- **Ownership Check**: Before clearing any browser locks, PinchTab reads this file.
- If the PID in the file is still running **and** is verified to be a `pinchtab` process (by inspecting its command-line arguments), it assumes another PinchTab instance is active and **does not** touch the locks.
- This verification prevents issues with PID reuse where a dead PinchTab instance's PID is reassigned to a different process.
+ - Outside a startup grace window (`lockStartupGrace`, 2 minutes) after the PID file is written, a live PinchTab owner with no browser process using the profile is also treated as stale.
- If the PID is not running or is not a PinchTab process, the previous instance is considered "dead," and the profile is eligible for recovery.
### 3. Headless Fallback
@@ -47,16 +48,16 @@ Once stale processes are terminated, PinchTab removes the following files from t
### 5. Automatic Retry
-After clearing the stale state, `InitBrowser` automatically retries the startup sequence once. This makes the recovery transparent to the user and the API caller (e.g., the first `/health` check will succeed after a brief internal recovery delay).
+After clearing the stale state, `startBrowserWithRecovery` automatically retries the startup sequence once. This makes the recovery transparent to the user and the API caller (e.g., the first `/health` check will succeed after a brief internal recovery delay).
## Implementation Details
The logic is distributed across these components:
-- **`internal/bridge/profile_lock.go`**: Core logic for detection, PID lock management (`AcquireProfileLock`), and stale file removal.
-- **`internal/bridge/profile_lock_pid_*.go`**: Platform-specific implementations for PID probing and process killing (supports Unix-like systems and Windows).
-- **`internal/bridge/runtime/init.go`**: Orchestrates the retry logic within `startBrowserWithRecovery`.
-- **`internal/bridge/bridge_lifecycle.go`**: Calls `AcquireProfileLock` and `EnsureBrowser` during bridge startup.
+- **`internal/bridge/profile_lock.go`**: Core logic for detection (`isProfileLockError`), PID lock management (`AcquireProfileLock`), and stale process/file cleanup (`clearStaleProfileLocks`).
+- **`internal/bridge/profile_lock_pid_other.go`** / **`profile_lock_pid_windows.go`**: Platform-specific implementations for PID probing and process killing (Unix-like systems and Windows).
+- **`internal/bridge/runtime/recovery.go`**: Orchestrates the retry logic within `startBrowserWithRecovery` (the detection and cleanup functions are passed in as runtime hooks).
+- **`internal/bridge/bridge_lifecycle.go`**: `EnsureBrowser` calls `AcquireProfileLock` (with the headless temp-dir fallback) before `InitBrowser`.
- **`internal/server/bridge.go`**: Ensures clean shutdown via signal handling to prevent locks from being left behind in the first place.
## Multi-Instance Safety
diff --git a/docs/implementations/docker-local-testing.md b/docs/implementations/docker-local-testing.md
index 62f1f535..765de026 100644
--- a/docs/implementations/docker-local-testing.md
+++ b/docs/implementations/docker-local-testing.md
@@ -4,7 +4,7 @@ This page is a practical checklist for testing the current Docker setup locally.
It covers two paths:
-- the default managed-config flow, where the container owns `/data/.config/pinchtab/config.json`
+- the default managed-config flow, where the container owns `/data/.pinchtab/config.json` (`HOME=/data`; on Linux the default config lives under `~/.pinchtab`)
- the explicit-config flow, where you mount your own `config.json` and set `PINCHTAB_CONFIG`
## Managed Config Flow
@@ -20,13 +20,13 @@ Inspect the effective config path and persisted config:
```bash
docker exec pinchtab pinchtab config path
-docker exec pinchtab sh -lc 'cat /data/.config/pinchtab/config.json'
+docker exec pinchtab sh -lc 'cat /data/.pinchtab/config.json'
```
Expected results:
-- the config path is `/data/.config/pinchtab/config.json`
-- `server.bind` in the persisted config remains `127.0.0.1`
+- the config path is `/data/.pinchtab/config.json`
+- `server.bind` in the persisted config is `0.0.0.0` (the entrypoint sets it so port publishing works)
- a token is present if one was generated on first boot or passed in
Verify the config bind address:
@@ -42,7 +42,7 @@ Verify persistence across restart:
```bash
docker compose down
docker compose up -d
-docker exec pinchtab sh -lc 'cat /data/.config/pinchtab/config.json'
+docker exec pinchtab sh -lc 'cat /data/.pinchtab/config.json'
```
## Explicit `PINCHTAB_CONFIG` Flow
@@ -59,7 +59,7 @@ Create a local config file, for example `./tmp/config.json`:
}
```
-Run the container with that config mounted read-only:
+Run the container with that config mounted read-only (to test a local build instead of the published image, first run `docker build -t pinchtab/pinchtab .`):
```bash
docker run --rm -d \
@@ -105,9 +105,22 @@ docker exec pinchtab-test pinchtab config path
Persisted config content:
```bash
-docker exec pinchtab sh -lc 'cat /data/.config/pinchtab/config.json'
+docker exec pinchtab sh -lc 'cat /data/.pinchtab/config.json'
```
-## Current Caveat
+## Automated Docker E2E
-The Docker runtime path owns `--no-sandbox` compatibility now. Do not put it in `browser.extraFlags`.
+The E2E stack (`tests/e2e/docker-compose.yml`, `tests/e2e/docker-compose-multi.yml`) builds this same `Dockerfile` and runs `docker-entrypoint.sh`, but always with `PINCHTAB_CONFIG` set — so it exercises the explicit-config flow only. The managed-config flow above is covered only by this manual checklist.
+
+```bash
+./dev e2e # extended suite (go run ./tests/tools/runner e2e --suite extended)
+./dev e2e smoke # smoke tier
+./dev e2e api <text> # one suite, filtered by scenario file name (--suite api --filter <text>)
+./dev e2e test "<name>" # runs only the first start_test whose name contains <name>
+```
+
+## Current Caveats
+
+The Docker runtime path owns `--no-sandbox` compatibility now (added at launch when a container is detected). Do not put it in `browser.extraFlags`; config validation rejects it.
+
+`docker-entrypoint.sh` checks for an existing config at `$XDG_CONFIG_HOME/pinchtab/config.json` (`/data/.config/...`), but the binary reads and writes `/data/.pinchtab/config.json`, so the "first boot" block runs on every start: `server.bind` is re-set to `0.0.0.0` and, when `PINCHTAB_TOKEN` is set, `server.token` is overwritten with it.
diff --git a/docs/implementations/index.md b/docs/implementations/index.md
index c01bdba0..84e9fb93 100644
--- a/docs/implementations/index.md
+++ b/docs/implementations/index.md
@@ -4,9 +4,9 @@ This section covers implementation-focused documents: how specific subsystems wo
Use these pages when you want lower-level detail than the architecture overview, but do not need full API reference material.
-- [Static Fetch (Lite Engine)](./lite-engine.md) — Chrome-free DOM capture using Gost-DOM (the lightweight HTTP+DOM path used by the `ghost-chrome` provider before escalating to Chrome; "lite engine" is deprecated terminology — see [terminology](../architecture/terminology.md))
+- [Lite Engine (historical)](./lite-engine.md) — the removed `chrome`/`lite`/`auto` engine router; its Gost-DOM path survives as the static fetch used by the `ghost-chrome` provider (`internal/browsers/ghostchrome/staticfetch`) — see [terminology](../architecture/terminology.md)
- [Managed Bridge vs Managed Direct CDP](./managed-bridge-vs-managed-direct-cdp.md)
- [Chrome Profile Lock Recovery](./chrome-profile-lock-recovery.md)
- [Chrome Files](./chrome-files.md)
-- [Parallel Tab Execution](./parallel-tab-execution.md)
+- [Parallel Tab Execution (design write-up)](./parallel-tab-execution.md)
- [Docker Local Testing](./docker-local-testing.md)
diff --git a/docs/implementations/lite-engine.md b/docs/implementations/lite-engine.md
index bb57ce53..ab876c25 100644
--- a/docs/implementations/lite-engine.md
+++ b/docs/implementations/lite-engine.md
@@ -4,6 +4,7 @@
> The engine has been replaced by the **browser provider** model. Use `browsers.default`
> in your config with providers: `chrome`, `cloak`, or `ghost-chrome`.
> See [terminology](../architecture/terminology.md) for details.
+> None of the code below exists at HEAD: `internal/engine` (Router, rules, `LiteEngine`), the `server.engine` key (now a config validation error) and the `X-Engine` header were removed. The Gost-DOM static path now lives in `internal/browsers/ghostchrome/staticfetch`, used by the `ghost-chrome` provider before it escalates to Chrome.
PinchTab includes a **Lite Engine** that performs DOM capture — navigate, snapshot,
text extraction, click, and type — without requiring Chrome or Chromium. It is
diff --git a/docs/implementations/managed-bridge-vs-managed-direct-cdp.md b/docs/implementations/managed-bridge-vs-managed-direct-cdp.md
index 6af60a03..c6f5d456 100644
--- a/docs/implementations/managed-bridge-vs-managed-direct-cdp.md
+++ b/docs/implementations/managed-bridge-vs-managed-direct-cdp.md
@@ -155,6 +155,6 @@ direct-cdp = better efficiency
Today, the intended architecture is:
- `managed + bridge` for PinchTab-launched instances
-- `attached + direct-cdp` for externally managed browsers
+- `attached + bridge` for externally managed browsers: `POST /instances/attach` spawns a `pinchtab bridge --cdp-attach <cdpUrl>` child (`attachType: cdp-bridge`), and `POST /instances/attach-bridge` registers an already running bridge (`attachType: bridge`) — see [Orchestration](../architecture/orchestration.md#attach-flow)
-`managed + direct-cdp` is a useful future model, but it is primarily an architectural option, not the default implementation.
+`managed + direct-cdp` is not implemented; it is an architectural option only. Every instance, managed or attached, is reached through a bridge.
diff --git a/docs/implementations/parallel-tab-execution.md b/docs/implementations/parallel-tab-execution.md
index 39a877be..b4fac66d 100644
--- a/docs/implementations/parallel-tab-execution.md
+++ b/docs/implementations/parallel-tab-execution.md
@@ -1,5 +1,7 @@
# Parallel Tab Execution
+> **Status:** design write-up from the original TabExecutor PR (March 2026), including its test logs. `TabExecutor` exists at HEAD (`internal/bridge/tabs/tab_executor.go`) and is constructed per `TabManager` with `instanceDefaults.maxParallelTabs`, but no HTTP handler calls `Bridge.Execute`, so the request flow below is not how `/action`, `/navigate`, `/find` or `/snapshot` are served today. The "Observed results" log lines (`tab_executor: executing task`, `semaphore acquired`, `tab_XXXXXX` IDs) are not emitted by the code.
+
PinchTab supports safe parallel execution across browser tabs. Multiple tabs can
execute actions concurrently while each tab remains sequential internally, preventing
resource exhaustion and race conditions.
@@ -108,7 +110,7 @@ return te.safeRun(ctx, tabID, task) // Execute with panic recovery
| `TabManager.Execute()` | `internal/bridge/tab_manager.go` | Integration point for handlers |
| `Bridge.Execute()` | `internal/bridge/bridge.go` | BridgeAPI interface method |
| `LockManager` | `internal/bridge/tabs/lock.go` (re-exported via `internal/bridge/tabs_facade.go`) | Per-tab ownership locks with TTL |
-| `TabEntry` | `internal/bridge/bridge.go` | Per-tab chromedp context + metadata |
+| `TabEntry` | `internal/bridge/bridge_types.go` | Per-tab chromedp context + metadata |
### How It Works
diff --git a/docs/index.json b/docs/index.json
index 1f6ca24f..90d5e8c2 100644
--- a/docs/index.json
+++ b/docs/index.json
@@ -15,21 +15,27 @@
"guides/contributing.md",
"guides/security.md",
"guides/mcp-agents.md",
+ "guides/agent-identity.md",
"guides/cloakbrowser.md",
"guides/attach-chrome.md",
"guides/remote-bridge-orchestrator.md",
"guides/tailscale-bridge-orchestrator.md",
+ "guides/daemon.md",
"guides/multi-instance.md",
"guides/identifying-instances.md",
"guides/memory-monitoring.md",
"guides/data-storage.md",
"guides/docker.md",
+ "implementations/docker-local-testing.md",
"guides/headed-mode.md",
"guides/annotate-for-llm-fixes.md",
"guides/raspberry-pi.md"
],
"architecture": [
- "*"
+ "*",
+ "implementations/chrome-files.md",
+ "implementations/chrome-profile-lock-recovery.md",
+ "implementations/managed-bridge-vs-managed-direct-cdp.md"
],
"reference": [
"*"
diff --git a/docs/pinchtab-scrape-audit-spec.md b/docs/pinchtab-scrape-audit-spec.md
index 2c5d5409..15dce609 100644
--- a/docs/pinchtab-scrape-audit-spec.md
+++ b/docs/pinchtab-scrape-audit-spec.md
@@ -1,5 +1,10 @@
# PinchTab Scraping & Audit Spec
+> **Status at HEAD:** this is the original design spec. Most of it shipped as `pinchtab audit`,
+> `pinchtab compare` and `pinchtab scrape` — see [audit.md](audit.md) and [scrape.md](scrape.md)
+> for the shipped contract. Items marked *(not shipped)* below describe behaviour the code
+> does not implement.
+
## Overview
PinchTab serves as the **deep browser enhancement layer** on top of SeaPortal's discovery and HTTP extraction. It adds visual, interactive, performance, and security capabilities that pure HTTP scraping cannot provide.
@@ -20,13 +25,16 @@ pinchtab compare <live-url> <staging-url> [flags]
## Input
-- SeaPortal `SiteReport` JSON (or direct URL + sitemap data)
-- Optional: authentication details (cookies, login flow)
+- SeaPortal `SiteReport` JSON (or direct URL + sitemap data) — *shipped as a JSON array of
+ SeaPortal `Result` objects (`--seaportal-report`), a URL, or a sitemap (`--sitemap`)*
+- Optional: authentication details (cookies, login flow) — *cookies and `--profile` shipped;
+ login flow not shipped*
- Comparison baseline (for diff mode)
## Output
-Enhanced `SiteReport` with browser-enriched fields per page.
+Enhanced `SiteReport` with browser-enriched fields per page. *Shipped as a versioned
+`AuditReport` (`internal/audit/types.go`), not an extended `SiteReport`.*
## Page Enhancement Fields (PinchTab)
@@ -44,10 +52,13 @@ type BrowserPageData struct {
}
```
+*Shipped with an extra `JSErrors []JSError` field. `FullPageScreenshot` exists but is never
+set: audit screenshots cover the viewport.*
+
## Key Features
### 1. Visual Analysis
-- Full-page screenshots
+- Full-page screenshots *(not shipped: audit screenshots are viewport-only)*
- Image diffing (for compare mode)
- Highlighted diff images with annotations
@@ -63,15 +74,15 @@ type BrowserPageData struct {
### 4. Performance (Browser-level)
- Core Web Vitals (via CDP)
- Navigation timing
-- Resource loading breakdown
+- Resource loading breakdown *(not shipped as a breakdown; per-request `duration` is in `networkRequests`)*
### 5. Usability & Accessibility
- Basic a11y checks
- Missing form labels, alt texts
-- Navigation flow validation
+- Navigation flow validation *(not shipped)*
### 6. Security Surface (optional)
-- Integration point for Nuclei or similar
+- Integration point for Nuclei or similar *(not shipped; built-in rules only)*
- Exposed endpoints detection
- Mixed content warnings
@@ -80,7 +91,8 @@ type BrowserPageData struct {
- Respect SeaPortal's page groups and samples
- Allow overriding sample size
- Parallel processing with configurable concurrency
-- Smart prioritization (homepage, key flows first)
+- Smart prioritization (homepage, key flows first) — *shipped as: entry URL first, ungrouped
+ pages before template-group samples; no key-flow detection*
### Preview → Expand (large sites)
@@ -125,7 +137,8 @@ the same SSRF/redirect vetting as browser navigation.
## Integration Points
-- Library mode: `pinchtab.EnrichWithBrowser(seaPortalReport)`
+- Library mode: `pinchtab.EnrichWithBrowser(seaPortalReport)` — *shipped as
+ `pinchtabaudit.New(baseURL, token).EnrichWithBrowser(ctx, AuditInput, opts)` in `pkg/pinchtabaudit`*
- CLI for standalone use
- Docker-friendly for CI/CD
- Output formats: JSON (for LLM), Markdown/HTML report, PDF
@@ -133,8 +146,8 @@ the same SSRF/redirect vetting as browser navigation.
## Authentication Support
- Cookie injection
-- Login flow recording/replay
-- Headless + stealth options
+- Login flow recording/replay *(not shipped)*
+- Headless + stealth options *(no audit-specific flags for these)*
## Flags (examples)
@@ -142,12 +155,12 @@ the same SSRF/redirect vetting as browser navigation.
- `--screenshot`
- `--network-monitor`
- `--visual-diff`
-- `--llm-refine`
+- `--llm-refine` *(not shipped)*
- `--output-dir`
- `--concurrency int`
---
-**Status**: Ready for implementation planning.
+**Status**: Ready for implementation planning. *(Superseded: see the status note at the top.)*
This complements the SeaPortal spec perfectly.
diff --git a/docs/pinchtab.md b/docs/pinchtab.md
index 65dd446f..78cd32fe 100644
--- a/docs/pinchtab.md
+++ b/docs/pinchtab.md
@@ -36,6 +36,9 @@ Start `pinchtab server` or even better `pinchtab daemon install` and leave it ru
pinchtab server
```
+The HTTP API requires the server token. The `curl` examples below omit it for brevity;
+add `-H "Authorization: Bearer $PINCHTAB_TOKEN"` after `export PINCHTAB_TOKEN=$(pinchtab config token --stdout)`. The CLI alternatives read the token from your config.
+
### 2. Start an instance
By default we use always-on strategy. This is optional now and not necessary.
@@ -50,7 +53,7 @@ pinchtab instance start
{
"id": "inst_0a89a5bb",
"profileId": "prof_278be873",
- "profileName": "instance-1741400000000000000",
+ "profileName": "instance-1741400000000000000-9f3c2a1b",
"port": "9868",
"mode": "headless",
"headless": true,
diff --git a/docs/reference/a11y.md b/docs/reference/a11y.md
index 558d47c7..dc47fcc3 100644
--- a/docs/reference/a11y.md
+++ b/docs/reference/a11y.md
@@ -32,6 +32,8 @@ default tag set is WCAG conformance tags only.
```json
{
+ "tabId": "...",
+ "vocabularyToken": "...",
"engine": "axe",
"version": "4.13.0",
"url": "https://example.com/",
@@ -55,17 +57,21 @@ default tag set is WCAG conformance tags only.
"passes": 9,
"incomplete": 0,
"inapplicable": 51,
- "score": 70
+ "score": 90
}
```
- `version` echoes the vendored axe-core version (see `THIRD_PARTY_LICENSES.md`).
- `ref` is filled when the failing element maps to a snapshot ref, so an agent
- can fall straight to `/action` on it.
+ can fall straight to `/action` on it. Only single-hop targets (top-frame
+ elements) get a ref; a node inside an iframe is left without one.
+- The axe run publishes the tab's ref cache, so it returns a fresh
+ `vocabularyToken` (also sent as the `X-PinchTab-Vocab` header); echo it as
+ `vocab` on the follow-up action or a ref from an older read is refused `409`.
- `incompleteViolations` (details) is included only when `includeIncomplete=true`;
the `incomplete` count is always present.
- `score` reuses the native 0–100 scale (`100` minus severity-weighted violation
- counts, floored at `0`) so axe and native scores stay comparable on a
+ counts — serious/critical `10`, moderate `5`, minor `2` per node — floored at `0`) so axe and native scores stay comparable on a
dashboard.
The script runs in PinchTab's **isolated world**, so a page that overrides
@@ -85,6 +91,16 @@ pinchtab a11y audit --axe
pinchtab a11y audit --axe --tags wcag2a,wcag2aa --json
```
+CLI flags: `--axe` (same as `--engine axe`), `--engine`, `--tags`, `--rules`,
+`--include-incomplete`, `--selector`, `--tab`, `--json`.
+
+MCP: `pinchtab_a11y_audit` takes `tabId`, `engine`, `tags`, `rules`,
+`includeIncomplete` and `browser` (no `selector`).
+
+Covered by `tests/e2e/scenarios/api/a11y-axe-basic.sh`,
+`tests/e2e/scenarios/api/a11y-audit-basic.sh` and
+`tests/e2e/scenarios/cli/a11y-axe-basic.sh`.
+
## Native Response
With `engine` omitted the response is the native report unchanged:
diff --git a/docs/reference/capture.md b/docs/reference/capture.md
index efc819f1..548a78df 100644
--- a/docs/reference/capture.md
+++ b/docs/reference/capture.md
@@ -79,9 +79,12 @@ calls"** — `pairing.navigated` flips to `true` when the main frame's
document (React re-renders, `IntersectionObserver` mutations) is not
detected; `wait=stable` reduces but does not eliminate it.
-`epoch.domEpoch` is an opaque server-minted token cached on the tab's
-ref-cache alongside the snapshot refs. Future action endpoints will accept
-an `expectedEpoch` query param to reject stale refs at use time.
+`epoch.domEpoch` is the tab's ref vocabulary token — the same opaque value
+`/snapshot` returns as `vocabularyToken` — and is also set on the
+`X-PinchTab-Vocab` response header. It is kept while the new nodes share refs
+with the previous vocabulary and re-minted when they do not. Echo it as `vocab`
+on ref-based actions: a ref action under a token other than the tab's current
+one is refused with `409 vocab_superseded`.
## Bounding boxes and coordinate space
@@ -157,13 +160,13 @@ above.
| `selector` | Scope: clips image and filters snapshot subtree to the same element |
| `filter` | `interactive` (default) or `all` |
| `format` | `jpeg` (default) or `png` |
-| `quality` | JPEG quality 0-100 |
-| `depth` | Snapshot tree depth limit |
+| `quality` | JPEG quality 0-100 (default `80`) |
+| `depth` | Snapshot tree depth limit (default `-1`, full tree) |
| `output` | `file` (default), `inline` (base64 in JSON), or `raw` (bytes only — drops the snapshot) |
| `wait` | `stable` (default) waits for `Page.lifecycleEvent` quiescence (250ms silence / 750ms ceiling); `load` polls `document.readyState` until `complete` (2s ceiling); `none` skips the wait |
| `withBounds` | `true` (default) — populate `boundingBox` (the border box) + `visible` on every measurable snapshot node; `false` omits both keys everywhere |
| `beyondViewport` | `true` — capture the full scrollable document; coordinate space becomes `document` |
-| `scale` | Rescale the output bitmap. Default `1`. `0.5` halves each axis (quarter the pixels) |
+| `scale` | Rescale the output bitmap. Default `1`. `0.5` halves each axis (quarter the pixels); out-of-range values are clamped |
| `requirePair` | `true` returns 409 if `pairing.navigated` would be true |
| `noAnimations` | `true` — inject `prefers-reduced-motion` CSS for the capture window |
@@ -174,7 +177,7 @@ above.
| `-o <path>` | Save the captured image locally (default: `capture-<ts>.jpg`) |
| `-s <selector>` | Scope: clips image and filters snapshot subtree |
| `--filter <name>` | Snapshot filter |
-| `--format <fmt>` | `jpeg` or `png` |
+| `--format <fmt>` | `jpeg` or `png` (default: `png` when `-o` ends in `.png`, otherwise `jpeg`) |
| `-q <0-100>` | JPEG quality |
| `--depth <n>` | Snapshot depth limit |
| `--wait <mode>` | `stable` (default) / `load` / `none` |
@@ -183,6 +186,11 @@ above.
| `--scale <f>` | Bitmap rescale (e.g. `0.5`) |
| `--require-pair` | Fail with 409 on mid-capture navigation |
| `--tab <id>` | Target a specific tab |
+| `--json` | Print the full JSON response instead of the terse summary |
+
+`GET /tabs/{id}/capture` is the same handler with the tab in the path. An
+unknown `output` value is a 400; `requirePair` failing is a 409, as is a pending
+JavaScript dialog (`409 dialog_blocked`).
## Related Pages
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index a4879e2e..9af0c1c4 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -1,37 +1,35 @@
# CLI Overview
-`pinchtab` has two normal usage styles:
-
-- interactive menu mode
-- direct command mode
-
-Use the menu when you want a guided local control surface. Use direct commands when you want shell history, scripts, or remote targeting with `--server`.
+`pinchtab` is driven by direct commands. Running it with no subcommand prints a
+status summary and next-step hints.
When you target a remote server with `--server`, the CLI is exercising the same privileged control plane as the dashboard and HTTP API. Do not use it as an access path for untrusted users or untrusted systems. For deployment guidance, see [Security](../guides/security.md).
-## Interactive Menu
+## Bare `pinchtab`
-Running `pinchtab` with no subcommand in an interactive terminal opens the menu. It does not immediately start the server.
-
-Typical flow:
+Running `pinchtab` with no subcommand does not start the server. When the config file
+is new or its `configVersion` is older than this build, it first runs the security
+setup (generating `server.token` if missing; the prompts only appear in an interactive
+terminal). It then prints the server state, where logs go, `allowedDomains`, IDPI
+state, and suggested next commands, for example:
```text
-listen running 127.0.0.1:9867
-str,plc simple,fcfs
-daemon ok
-security [■■■■■■■■■■] LOCKED
-
-Main Menu
- 1. Start server
- 2. Daemon
- 3. Start bridge
- 4. Start MCP server
- 5. Config
- 6. Security
- 7. Help
- 8. Exit
+PinchTab dev
+
+ server protected listener
+ logs stdout/stderr of the terminal running `pinchtab server`
+ allowedDomains a.com, b.com
+ idpi enabled
+
+Next steps:
+ pinchtab config token --stdout # print the API token (capture with $(...))
+ pinchtab health --json # retry health with the current token
+ pinchtab config show # inspect configured port and token
```
+Advisory hints about a steady state you may have chosen print once per run; set
+`PINCHTAB_HINTS=off` to silence them.
+
## Direct Commands
Use direct commands when you already know the action you want:
@@ -63,7 +61,8 @@ CLI requests carry agent identity over the `X-Agent-Id` request header.
- `--agent-id <value>` sets the header explicitly for that command
- `PINCHTAB_AGENT_ID` sets the default agent ID for the current shell or script
-- if neither is set, the CLI uses `cli`
+- if neither is set, the CLI sends no `X-Agent-Id`; a request authenticated with an
+ agent session (`PINCHTAB_SESSION`) is attributed to that session's agent ID
That agent ID is what appears as `agentId` in `/api/activity`, the Agents page, and scheduler-driven activity.
@@ -102,7 +101,8 @@ exit=1
```
Two commands take an argument rather than a subcommand and are unaffected: `pinchtab tab
-<id>` focuses a tab, and `pinchtab network <filter>` filters the network log. An unknown
+<id>` focuses a tab, and `pinchtab network <requestId>` inspects one captured request (filters use
+`--filter`, `--method`, `--status`, `--type`). An unknown
value there is data the server rejects, not a typo the CLI can catch.
## Core Commands
@@ -115,9 +115,10 @@ value there is data the server rejects, not a typo the CLI can catch.
| `pinchtab bridge` | Start the single-instance bridge runtime |
| `pinchtab mcp` | Start the stdio MCP server |
| `pinchtab daemon` | Show daemon status and manage the background service |
-| `pinchtab config` | Open the interactive config overview/editor |
-| `pinchtab security` | Open the interactive security overview |
+| `pinchtab config` | Print the config overview (read-only) |
+| `pinchtab security` | Print the runtime security posture |
| `pinchtab completion <shell>` | Generate shell completion scripts |
+| `pinchtab version` | Print the PinchTab version (same as `--version`) |
### Server Flags
@@ -127,9 +128,15 @@ pinchtab server [flags]
| Flag | Short | Purpose |
| --- | --- | --- |
-| `--yolo` | `-y` | Apply guards down preset (enables evaluate, macro, download, cookies) |
-| `--headed` | `-H` | Start browser instances in headed (visible) mode |
+| `--yolo` | `-y` | Apply the guards-down preset for this run only; the config file is unchanged (every capability gate except state export on, attach on, IDPI off) |
+| `--headed` | `-H` | Start the default instance in headed (visible) mode |
| `--extension <path>` | `-e` | Load browser extension (repeatable) |
+| `--browser <name>` | | `chrome`, `cloak`, or `ghost-chrome` (overrides config) |
+| `--bind <addr>` | | HTTP bind address (overrides `server.bind`) |
+| `--port <port>` | | HTTP port (overrides `server.port`) |
+| `--log-level <level>` | | `debug`, `info` (default), `warn`, or `error` |
+| `--verbose` | `-v` | Full startup banner; logs at debug only when neither `--log-level` nor `server.logLevel` is set |
+| `--background` | `-b` | Spawn the server detached and print JSON with pid/url/token |
Examples:
@@ -170,7 +177,7 @@ Common commands:
| `pinchtab capture` | Paired screenshot + accessibility snapshot from the same DOM epoch (`--scale`, `--beyond-viewport`, `--require-pair`, `--with-bounds`) |
| `pinchtab pdf` | Export the page as PDF |
| `pinchtab network` | Inspect captured network requests |
-| `pinchtab wait ...` | Wait for selector, text, URL, JS, or time |
+| `pinchtab wait ...` | Wait for selector, text, URL, network idle, JS, or time |
| `pinchtab console` | Show browser console logs |
| `pinchtab errors` | Show browser error logs |
@@ -231,7 +238,7 @@ pinchtab pdf --tab <id> -o page.pdf
## Config From The CLI
-`pinchtab config` shows:
+`pinchtab config` prints a read-only overview:
- `multiInstance.strategy`
- `multiInstance.allocationPolicy`
@@ -239,15 +246,15 @@ pinchtab pdf --tab <id> -o page.pdf
- `instanceDefaults.tabEvictionPolicy`
- `instanceDefaults.tabPolicy.lifecycle`
- the active config file path
-- the dashboard URL when the server is running
- the masked server token
-- a `Copy token` action
+- the dashboard URL when the server is running
+- hints for `config get/set/show`, `config token` and `pinchtab security`
For file schema details and `config get/set/patch`, see [Config](./config.md).
## Security From The CLI
-`pinchtab security` is the interactive security screen.
+`pinchtab security` prints the runtime security posture and recommended defaults.
Direct subcommands:
diff --git a/docs/reference/click.md b/docs/reference/click.md
index 4790ffe8..694f9118 100644
--- a/docs/reference/click.md
+++ b/docs/reference/click.md
@@ -74,6 +74,8 @@ depends on the new page having loaded.
| `--text` | Output page text after click |
| `--dialog-action` | Auto-handle JS dialog: `accept` or `dismiss` |
| `--dialog-text` | Prompt response text (with `--dialog-action accept`) |
+| `--dismiss-banners` | Dismiss cookie/consent banners after a `--wait-nav` click (no-op without `--wait-nav`) |
+| `--dismiss-known-interstitials` | Dismiss a recognized portal interstitial before resolving the click target (refused with `known_interstitial_not_dismissed` when it cannot) |
| `--x`, `--y` | Click at specific coordinates |
| `--humanize` | Use humanized bezier+jitter input path (overrides instance config) |
| `--submit` | Use the once-only submit-click path and include bounded post-submit state in the response |
@@ -106,9 +108,12 @@ pinchtab click --x 100 --y 200 # Click at coordinates
- The API also accepts `selector` field: `{"kind":"click","selector":"#login"}`
- Click behavior works like this: omit `mode` for the normal click path, use `mode:"dom"` for `element.click()`, or `mode:"dispatch"` for synthetic click events.
- Treat `mode` as a broad, low-level escape hatch for click delivery. Occlusion bypass is the common case, but it can also help with pages that need a non-default click path.
-- `mode` and `humanize:true` are mutually exclusive.
+- `mode` and humanize are mutually exclusive — whether humanize comes from `humanize:true` on the request or from `instanceDefaults.humanize:true`.
- To opt a click into the slower humanized path for a page that needs it, pass `humanize:true` in the action JSON or set `instanceDefaults.humanize:true`.
- `submit:true` is for terminal form actions where retrying could submit twice. For clicks it sends exactly one DOM click, disables recovery/retry delivery, and reports a bounded `postState` result (`succeeded` when the URL changes or an open modal closes; otherwise `pending`). It requires an element target and cannot be combined with coordinates, `waitNav`, `mode`, or `humanize:true`. It is accepted only on a single `/action` request, not a batch or macro.
+- Ref vocabulary: an action that targets a ref may echo the snapshot's `X-PinchTab-Vocab` token as `vocab` in the body (or the `X-PinchTab-Vocab` request header), with `vocabTab` naming its tab. If a newer snapshot has renumbered that tab's refs, `/action` refuses with a `vocab_superseded` conflict instead of acting on the wrong node — re-snapshot and use the new refs. The CLI attaches the token from your last snapshot automatically. When an action re-epochs the tab's refs, the response carries the new `X-PinchTab-Vocab` header.
+- While a JavaScript dialog is open on the tab, `/action` refuses with a `dialog_blocked` conflict (details carry `dialogType` and `dialogMessage`); answer it with `pinchtab dialog accept|dismiss`, or pass `--dialog-action` on the click that opens it. See [Dialog](./dialog.md).
+- A ref that cannot be resolved answers `404 ref_not_found` with `details.dispatched: false`.
## Related Pages
diff --git a/docs/reference/config.md b/docs/reference/config.md
index 41fd1f21..ea28a06a 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -8,22 +8,23 @@ For security posture, token usage, sensitive endpoint policy, and IDPI guidance,
### `pinchtab config`
-Opens the interactive config overview/editor.
+Prints a read-only config overview. It is not an editor; change values with
+`config set`, `config patch`, or by editing the file.
-It currently exposes these high-signal settings directly:
+It shows these high-signal effective settings:
- `multiInstance.strategy`
- `multiInstance.allocationPolicy`
- `instanceDefaults.stealthLevel`
- `instanceDefaults.tabEvictionPolicy`
-- `instanceDefaults.tabPolicy.lifecycle`
+- `instanceDefaults.tabPolicy.lifecycle` (with the close delay when an idle lifecycle is on)
It also shows:
- the active config file path
-- the dashboard URL when the server is running
- the masked server token
-- a `Copy token` action
+- the dashboard URL when the server is running, otherwise `not running`
+- hints for `config get`, `config set`, `config show`, `config token` and `pinchtab security`
```bash
pinchtab config
@@ -40,13 +41,16 @@ pinchtab config init
`config init` respects `PINCHTAB_CONFIG`. If that environment variable is set, the file is created there.
Generated config files include a `$schema` URL for IDE completion and validation.
+The new file gets a generated `server.token`, reported on stderr. If a file already
+exists at that path, `config init` asks before overwriting it.
### `pinchtab config schema`
Prints the JSON Schema URL for this PinchTab build. Source builds, development
builds, and versions without a published schema use the `main` schema URL.
-When a matching release schema is known, PinchTab uses that release tag; when a
-newer matching schema is known, PinchTab uses the closest newer tag.
+For a release build PinchTab uses the closest published schema tag at or below its
+own version, so a generated config never points at rules from a newer release; with
+no such tag it uses `main`.
```bash
pinchtab config schema
@@ -154,6 +158,8 @@ Supported environment variables:
(default 3000, sized for agent-driven snapshot/action bursts). Lower it
(e.g. to 300) when exposing the port beyond localhost. Child instances
inherit it from the orchestrator's environment.
+- `PINCHTAB_STATE_KEY`: state-file encryption key; when set it wins over
+ `security.stateEncryptionKey`
For remote CLI targeting, use the root `--server` flag instead of config.
@@ -212,6 +218,9 @@ Current nested file-config shape:
},
"extensionPaths": ["/path/to/pinchtab/extensions"]
},
+ "browsers": {
+ "default": "chrome"
+ },
"instanceDefaults": {
"mode": "headless",
"noRestore": false,
@@ -240,6 +249,7 @@ Current nested file-config shape:
"allowScreencast": false,
"allowDownload": false,
"allowCookies": false,
+ "allowNetworkIntercept": false,
"allowMemory": false,
"allowFileScheme": false,
"allowedDomains": ["127.0.0.1", "localhost", "::1"],
@@ -248,6 +258,8 @@ Current nested file-config shape:
"memorySnapshotMaxBytes": 536870912,
"allowUpload": false,
"allowClipboard": false,
+ "allowStateExport": false,
+ "stateEncryptionKey": null,
"uploadMaxRequestBytes": 10485760,
"uploadMaxFiles": 8,
"uploadMaxFileBytes": 5242880,
@@ -255,6 +267,7 @@ Current nested file-config shape:
"maxRedirects": -1,
"trustedProxyCIDRs": [],
"trustedResolveCIDRs": [],
+ "trustLoopbackProxy": false,
"attach": {
"enabled": false,
"allowHosts": ["127.0.0.1", "localhost", "::1"],
@@ -337,10 +350,31 @@ Current nested file-config shape:
"other": false
}
}
+ },
+ "sessions": {
+ "dashboard": {
+ "persist": true,
+ "idleTimeoutSec": 604800,
+ "maxLifetimeSec": 604800,
+ "elevationWindowSec": 900,
+ "persistElevationAcrossRestart": false,
+ "requireElevation": false
+ },
+ "agent": {
+ "enabled": true,
+ "mode": "preferred",
+ "idleTimeoutSec": 1800,
+ "maxLifetimeSec": 86400
+ }
}
}
```
+`sessions.agent.*` is described in [Agent Identity](../guides/agent-identity.md);
+`sessions.agent.mode` accepts `off` or `preferred`. `browser.proxy`,
+`browser.targets`, `browser.defaultTarget` and `browser.fallbackOrder` are covered
+under Browser Selection below.
+
`autoSolver.external` is config-file-only. Capsolver and 2Captcha credentials
are stored there.
@@ -534,8 +568,9 @@ Rationale: humanized input is useful for compatibility with pages that react poo
| Section | Purpose |
| --- | --- |
-| `server` | HTTP server settings, engine selection, proxy trust, and network buffer defaults |
-| `browser` | Chrome executable, version pin, extra flags, and extension paths |
+| `server` | HTTP server settings, log level, proxy trust, cookie transport, and network buffer defaults |
+| `browser` | Chrome executable, version pin, extra flags, extension paths, CloakBrowser flags, proxy, and named targets |
+| `browsers` | Default browser selection and the optional `available` allowlist |
| `instanceDefaults` | Default behavior for managed instances |
| `security` | Sensitive feature gates, transfer limits, attach policy, and IDPI |
| `profiles` | Profile storage defaults |
@@ -543,13 +578,17 @@ Rationale: humanized input is useful for compatibility with pages that react poo
| `timeouts` | Action, navigation, shutdown, and navigation wait delays |
| `scheduler` | Optional task queue |
| `observability` | Activity logging, source selection, and retention |
+| `sessions` | Dashboard session cookies and agent sessions |
+| `autoSolver` | Challenge auto-solver behavior, provider keys, and credentials |
## `config get` And `config set` Support
-`pinchtab config get` and `pinchtab config set` only support these top-level sections:
+`pinchtab config get` and `pinchtab config set` accept a `section.field` dotted path in
+these top-level sections:
- `server`
- `browser`
+- `browsers`
- `instanceDefaults`
- `security`
- `profiles`
@@ -557,19 +596,18 @@ Rationale: humanized input is useful for compatibility with pages that react poo
- `timeouts`
- `scheduler`
- `observability`
+- `sessions`
+- `autoSolver`
-They do not expose every field in those sections.
+Every leaf in those sections is reachable, with these exceptions:
-Use `pinchtab config patch` or edit `config.json` directly for fields such as:
+- `server.engine` and `browser.provider` are removed settings; setting them is refused
+- `instanceDefaults.headless` is superseded by `instanceDefaults.mode`
+- `browsers.config.*` is a retired block, superseded by `browser.targets`
+- `observability.activity.stateDir` can be read but not set (see Activity Retention)
-- `server.networkBufferSize`
-- `browser.extensionPaths`
-- `instanceDefaults.dialogAutoAccept`
-- `instanceDefaults.tabPolicy.*`
-- `security.allowClipboard`
-- `security.idpi.scanTimeoutSec`
-- `security.idpi.shieldThreshold`
-- `observability.activity.events.*`
+List values such as `security.allowedDomains` or `browser.extensionPaths` are set as a
+comma-separated string. `$schema` and `configVersion` are document metadata, not settings.
## Common Examples
@@ -774,9 +812,14 @@ Use `pinchtab config init` to create the current nested format.
- `multiInstance.instancePortStart <= multiInstance.instancePortEnd`
- `multiInstance.restart.initBackoffSec <= multiInstance.restart.maxBackoffSec`
- non-negative timeout values
-- non-negative `server.networkBufferSize`
+- `server.networkBufferSize` between 1 and 10000
+- `server.retainNetworkBodyMaxBytes` between 0 and 10 MiB
+- `security.downloadMaxBytes`, `memorySnapshotMaxBytes` and the `upload*` limits between 1 and their caps,
+ with `uploadMaxFileBytes <= uploadMaxTotalBytes`
- non-negative `security.idpi.scanTimeoutSec`
-- positive `observability.activity.sessionIdleSec` and `retentionDays`
+- non-negative `observability.activity.sessionIdleSec` and positive `retentionDays`
+- valid `sessions.agent.mode` and positive `sessions.dashboard.*Sec` values
+- `server.engine` and `browser.provider` are rejected as removed settings
Valid enum values:
@@ -791,6 +834,7 @@ Valid enum values:
| `multiInstance.allocationPolicy` | `fcfs`, `round_robin`, `random` |
| `security.attach.allowSchemes` | `ws`, `wss`, `http`, `https` |
| `security.attach.forwardProxyAuth` | `true`, `false` |
+| `sessions.agent.mode` | `off`, `preferred` |
## Notes
diff --git a/docs/reference/dialog.md b/docs/reference/dialog.md
new file mode 100644
index 00000000..8c92b96b
--- /dev/null
+++ b/docs/reference/dialog.md
@@ -0,0 +1,50 @@
+# Dialog
+
+Accept or dismiss the JavaScript dialog (`alert`, `confirm`, `prompt`) open on a tab.
+
+```bash
+curl -X POST http://localhost:9867/dialog \
+ -H "Content-Type: application/json" \
+ -d '{"action":"accept"}'
+# CLI Alternative
+pinchtab dialog accept
+# Response (use --json for full JSON)
+OK
+```
+
+JSON response:
+
+```json
+{"type": "alert", "message": "Hello", "handled": true}
+```
+
+`type` is `unknown` and `message` empty when PinchTab missed the dialog-open event but a dialog was still answered.
+
+## CLI
+
+| Command | Description |
+|---------|-------------|
+| `pinchtab dialog accept [text]` | Accept (OK); `text` is the prompt response |
+| `pinchtab dialog dismiss` | Dismiss (Cancel) |
+
+Both take `--tab <id>` and `--json`.
+
+## HTTP
+
+`POST /dialog` or `POST /tabs/{id}/dialog`:
+
+| Field | Description |
+|-------|-------------|
+| `action` | Required: `accept` or `dismiss` |
+| `text` | Prompt response, used with `accept` |
+| `tabId` | Target tab (default: current tab) |
+
+Errors: `400` for a missing or unknown `action`, or when no dialog is open on the tab (`no dialog open on tab <id>`); `409 tab_paused_handoff` while the tab is paused for handoff.
+
+## Dialog-blocked tabs
+
+While a dialog is open, routes that drive the page — navigate, back/forward/reload, wait, find, evaluate, element reads such as `attr` and `count`, `/action` and `/actions`, storage, and state save — answer `409 dialog_blocked` immediately instead of hanging. The error `details` carry `hint`, `remedy`, `tabId`, `dialogType` and `dialogMessage`. A batch whose step opens a dialog stops with a failed step carrying code `dialog_blocked`, even with `stopOnError:false`. Answer the dialog with `pinchtab dialog accept|dismiss`, or pass `--dialog-action accept|dismiss` (API `dialogAction`) on the click that opens it — see [Click](./click.md).
+
+Tested by `tests/e2e/scenarios/api/dialog-guard-basic.sh`, `tests/e2e/scenarios/cli/dialog-guard-basic.sh` and `tests/e2e/scenarios/api/actions-extended.sh`.
+
+MCP: `pinchtab_dialog` with `action` (required), `text`, `tabId`.
diff --git a/docs/reference/eval.md b/docs/reference/eval.md
index e10c33e2..ec8225e9 100644
--- a/docs/reference/eval.md
+++ b/docs/reference/eval.md
@@ -31,6 +31,23 @@ pinchtab eval "fetch('/api/data').then(r => r.json())" --await-promise
pinchtab eval "document.title" --json # {"result":"Example Domain"}
```
+## API Body Fields
+
+| Field | Description |
+|-------|-------------|
+| `expression` | JavaScript to evaluate (required; `400` when empty) |
+| `awaitPromise` | Resolve a returned Promise before responding |
+| `tabId` | Target a specific tab |
+
+Response: `{"result": <value>}`. A Promise returned without `awaitPromise`
+yields `{}` plus a `hint` field naming the flag.
+
+Errors: `403 evaluate_disabled` when `security.allowEvaluate` is off;
+`500 evaluate_null_ref` (with a `hint`) when the expression dereferences a
+null element; `409 dialog_blocked` while a JavaScript dialog is open.
+
+MCP: `pinchtab_eval` takes `expression` (required), `awaitPromise`, `tabId`.
+
## Notes
- Requires `security.allowEvaluate: true`
diff --git a/docs/reference/extract.md b/docs/reference/extract.md
index ae272b9b..9c3a018e 100644
--- a/docs/reference/extract.md
+++ b/docs/reference/extract.md
@@ -22,7 +22,7 @@ route the request to the instance that owns it.
| --- | --- | --- | --- | --- |
| `schema` | object or string | yes | - | JSON schema describing the data; see [Schema Subset](#schema-subset) |
| `tabId` | string | no | active tab | Tab ID when using `POST /extract` |
-| `scope` | string | no | whole page | Confine every field to the subtree of one element: a ref (`e12`), `role:`, `text:` or a plain query. CSS and XPath are refused |
+| `scope` | string | no | whole page | Confine every field to the subtree of one element: a bare ref (`e12`), `role:`, `text:` or a plain query. CSS and XPath are refused (`400`) |
| `threshold` | float | no | `0.3` | Minimum match score per field |
| `maxItems` | int | no | `100` | Cap on items per array |
@@ -141,5 +141,5 @@ pinchtab click e7
| `400` | invalid JSON, missing `schema`, or an unsupported schema or `scope` (the message names the path) |
| `403` | blocked by IDPI in strict mode |
| `404` | tab not found |
-| `409` | a JavaScript dialog is blocking the tab |
-| `500` | Chrome not initialized or snapshot unavailable |
+| `409` | `dialog_blocked`: a JavaScript dialog is blocking the tab (answer it with `pinchtab dialog`) |
+| `500` | Chrome not initialized, snapshot unavailable, or the snapshot has no elements |
diff --git a/docs/reference/fill.md b/docs/reference/fill.md
index a71f530e..02d55ce9 100644
--- a/docs/reference/fill.md
+++ b/docs/reference/fill.md
@@ -16,6 +16,7 @@ OK
| Flag | Description |
|------|-------------|
+| `--submit` | Press Enter after filling the field (`submit:true` in the action JSON) |
| `--snap` | Output interactive snapshot after fill |
| `--snap-diff` | Output snapshot diff after fill |
| `--text` | Output page text after fill |
@@ -39,6 +40,7 @@ pinchtab fill e8 "value" --snap # Fill and show snapshot
- Use [`/frame`](./frame.md) before selector-based iframe fills
- Missing selectors fail immediately; use `pinchtab wait` first for async fields (see [`commands.md`](../commands.md))
- For API, use `selector` field for CSS/XPath/text selectors
+- The API reads `text`, falling back to `value`. A fill with neither is refused with `400 missing_fill_text`; send `"text":""` to clear the field
## Related Pages
diff --git a/docs/reference/find.md b/docs/reference/find.md
index 371aad41..f2b071cb 100644
--- a/docs/reference/find.md
+++ b/docs/reference/find.md
@@ -164,9 +164,11 @@ curl -X POST http://localhost:9867/tabs/<tabId>/action \
## Operational Notes
- `/find` uses the tab's accessibility snapshot, not raw DOM selectors.
-- Structured `/find` queries such as `role:button Save`, `text:Submit`, `label:Email`, `placeholder:Search`, `alt:Logo`, `title:Close`, `testid:submit`, `first:role:button`, `last:text:Submit`, and `nth:2:label:Email` are matched by the semantic engine against enriched descriptors. A wrapper index is zero-based here too, exactly as it is over `css:`/`xpath:`/`text:` — `nth:0:label:Email` is the first match in document order — and an index past the last match refuses by saying so rather than reporting that nothing matched.
+- The query is natural language, not a selector: CSS, XPath and refs are not resolved, only scored as text. Prefix a query with `find:` or `semantic:` to force natural-language matching.
+- Structured `/find` queries such as `role:button Save`, `text:Submit`, `label:Email`, `placeholder:Search`, `alt:Logo`, `title:Close`, `testid:submit`, `first:role:button`, `last:text:Submit`, and `nth:2:label:Email` are matched by the semantic engine against enriched descriptors. `/find` hands the query to the matcher unchanged, so its `nth:` index counts from 1 (`nth:1:label:Email` is the first match); `nth:0` or an index past the last match returns `200` with an empty `best_ref`. The zero-based index and the out-of-range refusal apply to `nth:` in action selectors, not to `/find`.
- In action commands, `role:`, `label:`, `placeholder:`, `alt:`, `title:`, `testid:`, and wrappers around those forms use semantic matching. CSS, XPath, refs, the existing `text:` action selector, and bare CSS/text wrappers such as `first:button` remain browser-side selector resolution.
- If there is no cached snapshot, PinchTab tries to refresh it automatically before matching.
+- Every successful response carries the tab's ref vocabulary token in the `X-PinchTab-Vocab` header; the CLI and MCP capture it, so a returned ref can be acted on without a snapshot in between.
- Successful matches are useful inputs to `/action`, `/actions`, and higher-level recovery logic.
- A `200` response can still return an empty `best_ref` if nothing met the threshold.
@@ -177,4 +179,5 @@ curl -X POST http://localhost:9867/tabs/<tabId>/action \
| `400` | invalid JSON or missing `query` |
| `403` | blocked by IDPI in strict mode |
| `404` | tab not found |
-| `500` | Chrome not initialized, snapshot unavailable, or matcher failure |
+| `409` | `dialog_blocked`: a JavaScript dialog is blocking the tab |
+| `500` | Chrome not initialized, no elements in the snapshot, or matcher failure |
diff --git a/docs/reference/frame.md b/docs/reference/frame.md
index 87e9daa7..c6cf9ce2 100644
--- a/docs/reference/frame.md
+++ b/docs/reference/frame.md
@@ -31,7 +31,15 @@ Targets accepted by `POST /frame` and `pinchtab frame`:
- a selector for an iframe element
- a frame name or frame URL
-Typical iframe flow:
+Response: `{tabId, scoped, target, current}` — unscoped, `target` and `current`
+are `"main"`; scoped, `target` is the frame ID and `current`/`frame` carry
+`{frameId, frameUrl, frameName, ownerRef}`. `POST` without `target` returns `400`;
+a target that is not an iframe or frame returns `400`.
+
+MCP: `pinchtab_frame` takes `target` (omit to read the current scope), `tabId`,
+`browser`.
+
+Typical iframe flow (API form exercised in `tests/e2e/scenarios/api/actions-extended.sh`):
```bash
pinchtab snap -i
@@ -47,7 +55,8 @@ Notes:
- selector scope is explicit; unscoped selectors do not automatically pierce into iframes
- same-origin iframe content is supported; cross-origin iframe descendants are not currently exposed as frame scopes
- nested iframes usually require multiple `frame` hops
-- the same frame scope applies to selector-based `/snapshot` and `/action` calls, and also to `/text` when `frameId` is not provided explicitly
+- the frame scope applies to `/snapshot`, `/capture`, selector-based `/action` calls, and `/text` when `frameId` is not provided explicitly
+- a read served from a frame scope carries a `frame` object (`frameId`, `frameUrl`, `frameName`, `ownerRef`, `frameTitle`) so a later reader can tell the content is not the top document
- `/evaluate` is separate and does not inherit frame scope
## Related Pages
diff --git a/docs/reference/handoff.md b/docs/reference/handoff.md
index e5c67b1a..819aacb7 100644
--- a/docs/reference/handoff.md
+++ b/docs/reference/handoff.md
@@ -10,6 +10,13 @@ pinchtab tab handoff-status <tabId>
pinchtab tab resume <tabId> --status completed
```
+The same commands exist top-level (`pinchtab handoff`, `pinchtab handoff-status`,
+`pinchtab resume`); each defaults to the current tab when `<tabId>` is omitted.
+`--reason` defaults to `manual_handoff`.
+
+MCP: `pinchtab_handoff` (`tabId` required, `reason`, `timeoutMs`),
+`pinchtab_handoff_status` (`tabId`), `pinchtab_resume` (`tabId`, `status`).
+
API equivalents:
When a tab is in `paused_handoff`, action execution routes reject with `409 tab_paused_handoff`
@@ -33,7 +40,9 @@ Notes:
- `GET /tabs/{id}/handoff` returns the current handoff state, or `active` when no handoff is set
- when a timeout is set, status also includes `expiresAt` and `timeoutMs`
- `POST /tabs/{id}/resume` clears the handoff state and can carry resume metadata such as `status` or `resolvedData`
-- paused tabs reject `/action`, `/actions`, and `/macro` requests with `tab_paused_handoff`
+- paused tabs reject mutating routes — `/action`, `/navigate`, `/back`, `/forward`, `/reload`, `/evaluate`, `/dialog`, `/cookies`, `/storage`, `/upload`, `/download`, `/solve`, `/emulation/*`, `/network/route`, `/fingerprint/rotate`, `/state/load` — with `409 tab_paused_handoff`; `/actions` and `/macro` answer `200` and report `tab_paused_handoff` on each step
+- `POST /tabs/{id}/handoff` returns `{tabId, status, reason, timeoutMs, hint, remedy}` (plus `expiresAt` with a timeout); a negative `timeoutMs` is `400`, a tab leased to another owner is `423 tab_locked`
+- `POST /tabs/{id}/resume` returns `{tabId, status:"active", resumeStatus, resolvedData}`
- use this for CAPTCHA, 2FA, login approval, or other human-only steps
## Related Pages
diff --git a/docs/reference/health.md b/docs/reference/health.md
index 886ccf7b..b4c50320 100644
--- a/docs/reference/health.md
+++ b/docs/reference/health.md
@@ -17,18 +17,22 @@ curl http://localhost:9867/health
# CLI Alternative (human-readable by default)
pinchtab health
-# Output: ok
+# Output: ok (followed by next-step hints)
pinchtab health --json # Full JSON response
```
+`tabs` counts every browser target, including ones `GET /tabs` hides (such as `about:blank`).
Bridge-mode health also reports `version`, and may include:
- `crashLogs`
- `failures`
- `crashes`
-In error cases it returns `503` with `status: "error"` and a `reason`.
+In error cases it returns `503` with `status: "error"`, a `reason` and an error `code`
+(`bridge_unavailable`, `browser_init_failed`, `list_targets_failed`). While the browser is
+restarting it returns `503` `browser_draining` with `status: "draining"`, `retryAfterSeconds`
+and a `Retry-After` header.
## Server Mode (Dashboard)
@@ -44,10 +48,13 @@ curl http://localhost:9867/health
"uptime": 12345,
"authRequired": true,
"profiles": 1,
+ "temporaryProfiles": 0,
+ "quarantinedProfiles": 0,
"instances": 1,
"defaultInstance": {
"id": "inst_abc12345",
- "status": "running"
+ "status": "running",
+ "responsiveness": "responsive"
},
"agents": 0,
"restartRequired": false
@@ -61,18 +68,22 @@ curl http://localhost:9867/health
| `version` | PinchTab version |
| `uptime` | Milliseconds since server start |
| `authRequired` | `true` when a server token is configured |
-| `profiles` | Number of configured profiles |
+| `profiles` | Number of profiles `GET /profiles` lists (neither temporary nor quarantined) |
+| `temporaryProfiles` | Number of temporary auto-generated instance profiles |
+| `quarantinedProfiles` | Number of quarantined profiles |
| `instances` | Number of managed instances |
-| `defaultInstance` | The instance shorthand (non-`/instances`) routes use, when present: `id`, `status` and `responsiveness`. With no running routable instance it is the earliest-started one |
+| `defaultInstance` | The instance shorthand (non-`/instances`) routes use: `id`, `status`, `responsiveness`. See note below |
| `agents` | Connected agent count |
| `restartRequired` | `true` when file-based config changes need restart |
| `restartReasons` | Restart reason list when required |
+| `security` | Only for requests authenticated by bearer token or dashboard cookie: `level`, `bind`, `allowedDomains`, `idpiEnabled`, `enabledSensitiveEndpoints`, `guardsDown` |
| `crashes` | Present once any instance's browser has crashed: `total` and `recent`, the same block bridge `/health` carries, each event naming its `instanceId` |
| `unresponsiveInstances` | Present while any instance answers its own `/health` but not its browser routes: the ids of those instances |
Notes:
-- `defaultInstance` is present when at least one instance exists
+- `defaultInstance` is present when at least one instance exists. It is the earliest-started running instance of the
+ default browser target; with none, it falls back to the earliest-started instance of any status
- use `defaultInstance.status == "running"` when you want to confirm Chrome is ready
- strategies such as `always-on` can create an instance automatically at startup
- `status` does not degrade on a browser crash: the instance is relaunched and is serving again. The crash is history, so it rides beside `status` as `crashes`; a crashed-then-relaunched instance differs from one that never crashed by that key alone. Every tab the dead browser held is gone, and a call to one answers `404` with code `browser_crashed` and a `hint` saying so
diff --git a/docs/reference/index.md b/docs/reference/index.md
index accf6940..a81239c0 100644
--- a/docs/reference/index.md
+++ b/docs/reference/index.md
@@ -5,10 +5,12 @@ Reference pages for the current PinchTab CLI and closely related command-facing
Note: this index is generated and should be checked against the code when commands change.
- [CLI Overview](./cli.md)
+- [A11y](./a11y.md)
- [Cache](./cache.md)
- [Capture](./capture.md)
- [Click](./click.md)
- [Config](./config.md)
+- [Dialog](./dialog.md)
- [Eval](./eval.md)
- [Extract](./extract.md)
- [Frame](./frame.md)
diff --git a/docs/reference/instances.md b/docs/reference/instances.md
index d15165e3..441893a8 100644
--- a/docs/reference/instances.md
+++ b/docs/reference/instances.md
@@ -18,7 +18,7 @@ curl http://localhost:9867/instances
# CLI Alternative (human-readable by default)
pinchtab instance list
-# Output: inst_0a89 9999 headed running
+# Output (tab-separated): inst_0a89a5bb 9999 headed running
pinchtab instance list --json # Full JSON response
```
@@ -32,11 +32,13 @@ Response shape:
{
"id": "inst_0a89a5bb",
"profileId": "prof_278be873",
- "profileName": "instance-1741410000000",
+ "profileName": "instance-1741410000000000000-3fa9c2d1",
"port": "9999",
"mode": "headed",
"headless": false,
"status": "running",
+ "startTime": "2026-03-08T05:00:00Z",
+ "attached": false,
"responsiveness": "responsive",
"securityPolicy": {
"allowedDomains": ["127.0.0.1", "localhost", "::1", "wikipedia.org"]
@@ -46,6 +48,8 @@ Response shape:
```
`GET /instances` returns a bare JSON array, not an envelope like `{"instances":[...]}`. Each instance response includes both `mode` (`"headless"` or `"headed"`) and the legacy-compatible `headless` boolean.
+Optional fields appear when they apply: `url` (bridge-backed instances), `error` (when `status` is `error`), `attachType` and `cdpUrl`
+(attached instances), `browser`, `fallbackFrom`/`fallbackReason` (a launch that fell back to another target), and `crashes`.
## Start An Instance
@@ -67,6 +71,10 @@ Request body:
- `mode`: optional; use `headed` for a visible browser, anything else is treated as headless
- `port`: optional
- `securityPolicy.allowedDomains`: optional additive instance-scoped IDPI/domain allowlist entries
+- `browser`: optional provider or `browser.targets` name (CLI `--browser`)
+- `fallbackTargets`: optional ordered target names to try if the first launch fails (CLI `--browser-fallback`, repeatable)
+
+The response is `201` with the instance object.
Notes:
@@ -75,7 +83,8 @@ Notes:
- the CLI flag is `--profile`, even though the API field is `profileId`
- `securityPolicy.allowedDomains` is merged with the server-level `security.allowedDomains` baseline for that instance only
- you can widen a single instance without changing the server default. For example, `{"securityPolicy":{"allowedDomains":["*"]}}` makes that instance unrestricted while other instances still use the server baseline
-- request-supplied extension paths are rejected; configure `browser.extensionPaths` on the server instead. By default, PinchTab uses the local `extensions/` directory under its state/config folder.
+- request-supplied extension paths are rejected (so `pinchtab instance start --extension` fails with `400`);
+ configure `browser.extensionPaths` on the server instead. By default, PinchTab uses the local `extensions/` directory under its state/config folder.
### `POST /instances/launch`
@@ -93,6 +102,7 @@ Request body:
- `mode`: optional; `headed` or headless by default
- `port`: optional
- `securityPolicy.allowedDomains`: optional additive instance-scoped IDPI/domain allowlist entries
+- `browser`, `fallbackTargets`: optional, as for `/instances/start`
Important:
@@ -139,6 +149,21 @@ pinchtab instance stop inst_ea2e747f
```
Stopping an instance preserves the profile unless it was a temporary auto-generated profile.
+The response is `{"status":"stopped","id":"<instanceId>"}`.
+
+## Restart Or Start An Instance By ID
+
+```bash
+curl -X POST http://localhost:9867/instances/inst_ea2e747f/restart
+# CLI Alternative
+pinchtab instance restart inst_ea2e747f
+```
+
+`POST /instances/{id}/restart` soft-restarts the browser process of a running instance
+(`503` when it is not running). `POST /instances/{id}/start` starts a known, stopped
+instance again with its previous profile, port and mode (`201` with the instance), or
+ensures the browser of one that is still active; attached CDP instances cannot be started
+this way (`409`).
## Start By Profile
@@ -151,6 +176,8 @@ curl -X POST http://localhost:9867/profiles/prof_278be873/start \
```
This route accepts a profile ID or profile name in the path. Unlike `/instances/start` and `/instances/launch`, its request body uses `headless` instead of `mode`.
+`headless` defaults to `false`, so a request without it starts a headed browser. The body also accepts
+`browser` and `fallbackTargets`.
## Open A Tab In An Instance
@@ -182,12 +209,18 @@ curl http://localhost:9867/instances/tabs
This is the fleet-wide tab listing endpoint. It is different from `GET /tabs`, which is shorthand or bridge scoped.
+Both routes return a bare JSON array of `{"id","instanceId","url","title"}` objects, cached per
+instance; add `?fresh=1` to refetch. `GET /instances/{id}/tabs` answers `503` when the instance is not running.
+
## List Metrics Across Instances
```bash
curl http://localhost:9867/instances/metrics
```
+`GET /instances/{id}/metrics` returns one instance's own request counters; the bare
+`GET /metrics` on the server answers with the server's counters (see [Metrics](./metrics.md)).
+
## Attach An Existing Browser (CDP)
```bash
diff --git a/docs/reference/keyboard.md b/docs/reference/keyboard.md
index cc9acd96..285313f8 100644
--- a/docs/reference/keyboard.md
+++ b/docs/reference/keyboard.md
@@ -36,12 +36,15 @@ Hold or release individual keys. Useful for modifier keys (Shift, Ctrl, Alt) or
```bash
pinchtab keydown Shift
-pinchtab keyboard type "abc" # Types "ABC" (shift held)
pinchtab keyup Shift
```
+`keyboard type` sends each character's text as given and sets no modifier flags on its key events, so do not rely on a held `keydown Shift` to change the typed text. For a modified key, use a [`press`](./press.md) chord such as `Shift+ArrowLeft`.
+
## API Equivalent
+`keydown` and `keyup` are the `keydown` / `keyup` action kinds with a `key` field.
+
```bash
curl -X POST http://localhost:9867/action \
-H "Content-Type: application/json" \
diff --git a/docs/reference/mcp-tools.md b/docs/reference/mcp-tools.md
index 44d05c66..885c9021 100644
--- a/docs/reference/mcp-tools.md
+++ b/docs/reference/mcp-tools.md
@@ -1,6 +1,6 @@
# MCP Tool Reference
-PinchTab currently exposes 36 MCP tools. All tool names are prefixed with `pinchtab_` and are served over stdio JSON-RPC.
+PinchTab currently exposes 47 MCP tools. All tool names are prefixed with `pinchtab_` and are served over stdio JSON-RPC.
For selector-based interaction tools, prefer `selector`. `ref`, `element` and `target` are still accepted as deprecated aliases, and `query` as a fallback, on the element-action tools (`query` is shorthand for `find:<text>`).
@@ -23,16 +23,23 @@ Positional wrappers index the candidates in **document order** for every selecto
Structured semantic locators are matched by the semantic engine; CSS, XPath, refs, the existing `text:` action selector, and bare CSS/text wrappers stay browser-side.
+Most browser-facing tools also declare an optional `browser` argument (e.g. `chrome`, `cloak`, `ghost-chrome`) that selects the browser for that one request; the tables below list it only where it changes behaviour.
+
+Ref vocabulary: the MCP server remembers the `X-PinchTab-Vocab` token returned by `pinchtab_snapshot`, `pinchtab_find`, `pinchtab_extract`, `pinchtab_a11y_audit` and any `snap=true` follow-up snapshot, keyed by the `tabId` argument, and sends it as `vocab` on the element-action tools (`pinchtab_click`, `pinchtab_type`, `pinchtab_hover`, `pinchtab_focus`, `pinchtab_select`, `pinchtab_scroll`, `pinchtab_scroll_into_view`, `pinchtab_fill`). A ref from a snapshot that a newer one has renumbered is refused with `409 vocab_superseded`; re-snapshot and use the new refs.
+
## Navigation
| Tool | Key Parameters | Notes |
| --- | --- | --- |
-| `pinchtab_navigate` | `url` required, `tabId`, `newTab`, `snap` | Uses `/navigate`; reuses the current tab, and `newTab=true` opens one (as does a first navigate with no tab yet). The returned `tabId` targets the new tab in later tools. `snap=true` returns an interactive compact snapshot in the same response |
+| `pinchtab_navigate` | `url` required, `tabId`, `newTab`, `snap`, `browser` | Uses `/navigate`; reuses the current tab, and `newTab=true` opens one (as does a first navigate with no tab yet). The returned `tabId` targets the new tab in later tools. `snap=true` returns an interactive compact snapshot in the same response |
+| `pinchtab_back` | `tabId`, `snap`, `browser` | Uses `/back` (or `/tabs/{id}/back`); returns `{tabId, url}` with the URL the tab landed on; `snap=true` appends an interactive compact snapshot |
+| `pinchtab_forward` | `tabId`, `snap`, `browser` | Uses `/forward`; same response shape as `pinchtab_back` |
+| `pinchtab_reload` | `tabId`, `snap`, `browser` | Uses `/reload`; same response shape as `pinchtab_back` |
| `pinchtab_snapshot` | `tabId`, `interactive`, `compact`, `format`, `diff`, `selector`, `maxTokens`, `depth`, `noAnimations` | Returns compact by default — the tool asks `/snapshot` for `format=compact` unless `format` says otherwise or `compact=false` asks for the JSON tree. `selector` scopes the snapshot; `format` is limited to `compact` or `text` |
| `pinchtab_frame` | `tabId`, `target` | Get or set the frame scope for selector-based actions on the tab; `target` accepts `main`, a snapshot ref, an iframe selector, or a frame name/URL |
| `pinchtab_screenshot` | `tabId`, `selector`, `scale`, `format`, `quality`, `annotate`, `beyondViewport`, `browser` | `selector` captures a specific element in current frame scope; `scale` rescales the output bitmap (e.g. `0.5` = half size); `format` is `jpeg` or `png`; `annotate=true` overlays numbered ref boxes and populates the annotations envelope; `beyondViewport=true` captures the full scrollable document (ignored when `selector` is set) — box coords are document-relative in that mode; `browser` selects the browser (e.g. `chrome`, `cloak`) for this request |
| `pinchtab_capture` | `tabId`, `selector`, `filter`, `format`, `quality`, `depth`, `scale`, `wait`, `withBounds`, `beyondViewport`, `requirePair`, `noAnimations`, `browser` | Paired screenshot + accessibility snapshot from the same DOM epoch. Returns an image content block plus a JSON envelope with `epoch`, `pairing.navigated`, per-node `boundingBox`, and `image.coordinateSpace` (`viewport`, `document`, or selector `clip`). `browser` selects the browser (e.g. `chrome`, `cloak`); the static ghost-chrome runtime cannot paint, so it falls back to chrome. Use when the model reads pixels AND acts on refs in the same turn. |
-| `pinchtab_get_text` | `tabId`, `raw`, `format`, `maxChars` | `raw=true` maps to `/text?mode=raw`; `format=text/plain` returns plain text; inherits the current `pinchtab_frame` scope for that tab |
+| `pinchtab_get_text` | `tabId`, `mode`, `raw`, `format`, `maxChars` | `mode` is `readability` (default), `raw` or `markdown` and supersedes `raw`; `raw=true` alone maps to `/text?mode=raw`; `format=text/plain` returns plain text; inherits the current `pinchtab_frame` scope for that tab |
## Interaction
@@ -40,9 +47,9 @@ All element-action tools accept the unified `selector`, its deprecated aliases `
| Tool | Key Parameters | Notes |
| --- | --- | --- |
-| `pinchtab_click` | `selector`, `ref`, `query`, `tabId`, `x`, `y`, `nodeId`, `dialogAction`, `dialogText`, `waitNav`, `mode`, `snap` | Click element by selector or coordinate; `mode` accepts `dom` or `dispatch` as a broad low-level escape hatch for click delivery; `mode` and `humanize` are mutually exclusive; `dialogAction` handles a dialog opened by the click; `waitNav=true` waits for navigation; `snap=true` returns a snapshot |
+| `pinchtab_click` | `selector`, `ref`, `query`, `tabId`, `x`, `y`, `nodeId`, `dialogAction`, `dialogText`, `waitNav`, `mode`, `humanize`, `snap` | Click element by selector or coordinate; `mode` accepts `dom` or `dispatch` as a broad low-level escape hatch for click delivery; `humanize` overrides the instance default for this click (omit to inherit it); `mode` and `humanize=true` are mutually exclusive; `dialogAction` handles a dialog opened by the click; `waitNav=true` waits for navigation; `snap=true` returns a snapshot |
| `pinchtab_type` | `selector`, `ref`, `query`, `nodeId`, `text` required, `tabId` | Sends key events at the targeted input; target with `selector` or `nodeId` |
-| `pinchtab_hover` | `selector`, `ref`, `query`, `tabId`, `x`, `y`, `nodeId` | Hover an element or coordinate |
+| `pinchtab_hover` | `selector`, `ref`, `query`, `tabId`, `x`, `y`, `nodeId`, `humanize` | Hover an element or coordinate; `humanize` overrides the instance default for this hover |
| `pinchtab_focus` | `selector`, `ref`, `query`, `tabId`, `nodeId` | Focus element |
| `pinchtab_select` | `selector`, `ref`, `query`, `nodeId`, `value` required, `tabId`, `snap` | Select `<option>` by value or visible text; target with `selector` or `nodeId` |
| `pinchtab_scroll` | `selector`, `ref`, `query`, `nodeId`, `pixels`, `deltaX`, `deltaY`, `direction`, `steps`, `x`, `y`, `tabId` | Omit every target to scroll the page; element + `pixels` uses wheel semantics; `direction` accepts `down`/`left`/`right`/`up` and moves 800px per step — the same distance as the CLI's `pinchtab scroll <direction>`, multiplied by `steps` or overridden by `pixels` |
@@ -59,11 +66,22 @@ All element-action tools accept the unified `selector`, its deprecated aliases `
| Tool | Key Parameters | Notes |
| --- | --- | --- |
-| `pinchtab_eval` | `expression` required, `tabId` | Requires `security.allowEvaluate` (documented non-default JS-execution opt-in). Not frame-scoped — current `pinchtab_frame` state does not change evaluation context |
+| `pinchtab_eval` | `expression` required, `awaitPromise`, `tabId` | `awaitPromise=true` resolves a returned Promise (without it a Promise returns `{}` with a hint). Requires `security.allowEvaluate` (documented non-default JS-execution opt-in). Not frame-scoped — current `pinchtab_frame` state does not change evaluation context |
| `pinchtab_pdf` | `tabId`, `landscape`, `scale`, `pageRanges` | Returns base64-encoded PDF content |
-| `pinchtab_find` | `query` required, `tabId` | Semantic element search; returns `best_ref` and selector hints to reuse in action tools |
+| `pinchtab_find` | `query` required, `tabId` | Natural-language element search via `/find`; the result adds `bestRef`, `selector` (both the `best_ref`) and a `nextActionHint` to reuse in action tools |
| `pinchtab_extract` | `schema` (object) required, `tabId`, `scope`, `maxItems` | Schema-typed data via `/extract`: `data` plus a per-field `ref`, `score` and `confidence`; the refs are usable in action tools straight away. Prefer it over snapshot-then-parse for structured values; pin a `low` field with `x-pinchtab-hint`. See [Extract](./extract.md) |
+## Diagnostics
+
+| Tool | Key Parameters | Notes |
+| --- | --- | --- |
+| `pinchtab_console` | `tabId`, `clear` | Reads the tab's captured console logs via `/console`; `clear=true` posts `/console/clear` instead of reading |
+| `pinchtab_errors` | `tabId`, `clear` | Reads the tab's uncaught JavaScript errors via `/errors`; `clear=true` posts `/errors/clear` instead of reading |
+| `pinchtab_a11y_audit` | `tabId`, `engine`, `tags`, `rules`, `includeIncomplete`, `browser` | Accessibility audit via `/a11y/audit`. `engine` is `native` (default) or `axe` (any other value is a 400); `tags`, `rules` and `includeIncomplete` apply to `axe` only, and `rules` wins over `tags`. See [A11y](./a11y.md) |
+| `pinchtab_memory` | `tabId`, `gc`, `browser` | JS heap usage and DOM counters via `/memory`; `gc=true` collects garbage first |
+| `pinchtab_memory_snapshot` | `tabId`, `top`, `browser` | Takes a V8 heap snapshot (`POST /memory/snapshot`) and returns `{id, path, bytes, summary}`; `top` rows per summary table (default 20). Needs `security.allowMemory`. See [Memory](./memory.md) |
+| `pinchtab_memory_compare` | `base` required, `head` required, `top`, `retained`, `browser` | Diffs two `pinchtab_memory_snapshot` ids via `/memory/compare`: per-constructor count and self-size deltas plus new duplicate strings; `top` rows (default 20); `retained=true` adds retained sizes (slower). Needs `security.allowMemory` |
+
## Site
| Tool | Key Parameters | Notes |
@@ -93,7 +111,7 @@ All element-action tools accept the unified `selector`, its deprecated aliases `
| Tool | Key Parameters | Notes |
| --- | --- | --- |
-| `pinchtab_wait` | `for` required, `value` required, `timeoutMs`, `state`, `tabId` | One wait tool: `for` names the condition and `value` carries it. `timeoutMs` bounds a browser-backed condition (default 10000, max 30000); `timeout` is its deprecated alias. `for=ms` is a fixed-duration wait capped at 30000 ms; `selector` waits for an element (`state` is `visible` (default) or `hidden`); `text` waits for body text; `url` is a URL glob match; `load` is `ready-state` (`readyState=complete`), `content-loaded` (`readyState` in `{interactive, complete}`), or `network-idle` (0 in-flight requests for 500 ms); `function` waits for a JS expression to become truthy |
+| `pinchtab_wait` | `for` required, `value` required, `timeoutMs`, `state`, `tabId`, `browser` | One wait tool: `for` names the condition and `value` carries it. `timeoutMs` bounds a browser-backed condition (default 10000, max 30000); `timeout` is its deprecated alias. `for=ms` is a fixed-duration wait capped at 30000 ms; `selector` waits for an element (`state` is `visible` (default) or `hidden`); `text` waits for body text; `url` is a URL glob match; `load` is `ready-state` (`readyState=complete`), `content-loaded` (`readyState` in `{interactive, complete}`), or `network-idle` (0 in-flight requests for 500 ms); `function` waits for a JS expression to become truthy |
## Network
@@ -110,7 +128,7 @@ All element-action tools accept the unified `selector`, its deprecated aliases `
| Tool | Key Parameters | Notes |
| --- | --- | --- |
-| `pinchtab_record` | `action` required, `file`, `fps`, `quality`, `scale`, `tabId` | One recording tool. `action=start` starts recording (format inferred from the `file` extension — `.gif`, `.webm`, `.mp4`; requires `security.allowScreencast`; GIF works without ffmpeg); `stop` encodes and saves to `file`, which may take a while for long recordings; `status` returns the active recording status (format, fps, duration, frame count) |
+| `pinchtab_record` | `action` required, `file`, `fps`, `quality`, `scale`, `tabId` | One recording tool. `fps` 1-30 (default 5), `quality` 1-100 (default 80), `scale` up to 1.0 (default 1.0). `action=start` starts recording (format inferred from the `file` extension — `.gif`, `.webm`, `.mp4`; requires `security.allowScreencast`; GIF works without ffmpeg); `stop` encodes and saves to `file` (the same path given to `start`), which may take a while for long recordings; `status` returns the active recording status (format, fps, duration, frame count) |
## Dialog
diff --git a/docs/reference/memory.md b/docs/reference/memory.md
index 1ce84d6c..5ab46d92 100644
--- a/docs/reference/memory.md
+++ b/docs/reference/memory.md
@@ -19,31 +19,39 @@ heap snapshot holds every string on the page, tokens included.
## Usage
-`GET /memory?tabId=<id>&gc=true` returns `usedJSHeapSize`, `totalJSHeapSize`,
-`jsHeapSizeLimit`, `documents`, `nodes`, `listeners` and `frames`. `gc=true` runs a
-garbage collection first so two reads compare live memory only.
+`GET /memory?tabId=<id>&gc=true` returns `tabId`, `usedJSHeapSize`, `totalJSHeapSize`,
+`jsHeapSizeLimit`, `documents`, `nodes`, `listeners`, `frames` and `gc`. `gc=true` runs a
+garbage collection first so two reads compare live memory only; a `gc` value that is
+not a boolean is `400 bad_gc`.
```bash
-pinchtab memory --gc
+pinchtab memory --gc # --tab <id>, --json
```
+MCP `pinchtab_memory` takes `tabId`, `gc` and `browser`.
+
## Snapshot
`POST /memory/snapshot` with an optional `{"tabId": "..."}` streams the snapshot to
`<stateDir>/heapsnapshots/<id>.heapsnapshot` and returns
`{id, path, bytes, nodeCount, durationMs, tabId}`. The file loads in the Chrome
DevTools Memory panel. A snapshot larger than `security.memorySnapshotMaxBytes`
-(default 512 MB) is discarded and answered `413 memory_snapshot_too_large`.
+(default 512 MB, capped at 4 GB) is discarded and answered
+`413 memory_snapshot_too_large` (details carry `maxBytes`).
```bash
pinchtab memory snapshot # prints the id and path
pinchtab memory snapshot --out app.heapsnapshot # also copy it locally
```
+MCP `pinchtab_memory_snapshot` takes `tabId`, `top` and `browser`; it takes the
+snapshot and returns `{id, path, bytes, summary}` in one call.
+
## Summary
-`GET /memory/snapshot/{snapshotId}/summary?top=20` returns `nodeCount`, `edgeCount`,
-`totalSelfSize`, `topBySize`, `topByCount` (constructor rows of `name`, `count`,
+`GET /memory/snapshot/{snapshotId}/summary?top=20` returns `id`, `path`, `top`,
+`nodeCount`, `edgeCount`, `totalSelfSize`, `constructors` (distinct constructor
+count), `topBySize`, `topByCount` (constructor rows of `name`, `count`,
`selfSize`) and `duplicateStrings` (`value`, `length`, `count`, `selfSize`).
```bash
@@ -63,7 +71,7 @@ growing array shows its bytes under `(array)` while `Array` itself stays small.
| --- | --- | --- |
| `base` | required | The earlier snapshot id |
| `head` | required | The later snapshot id |
-| `top` | `20` | Rows in `constructors` and `newDuplicateStrings` (max 200) |
+| `top` | `20` | Rows in `constructors` and `newDuplicateStrings`; values above 200 are clamped to 200, a non-positive or non-integer value is `400 bad_top` |
| `retained` | `false` | Add `retainedSize` to each returned row, from a dominator tree of `head` |
```json
@@ -99,7 +107,8 @@ growing array shows its bytes under `(array)` while `Array` itself stays small.
- Parsed snapshots are cached in memory per snapshot file for the process lifetime,
so comparing the same ids again, or summarizing one you compared, does not reparse.
-Errors: `400 bad_snapshot_id` (missing or malformed id), `400 bad_top`,
+Snapshot ids match `^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$`; the server names them
+`heap_<YYYYMMDD_HHMMSS>`. Errors: `400 bad_snapshot_id` (missing or malformed id), `400 bad_top`,
`400 bad_retained`, `404 memory_snapshot_not_found` (details name the `id`),
`422 memory_snapshot_invalid` (details name the `id` and the broken `section`),
`403 memory_disabled`.
@@ -111,7 +120,12 @@ pinchtab memory compare <base> <head> --top 5
pinchtab memory compare <base> <head> --retained --json
```
-MCP `pinchtab_memory_compare` takes `base`, `head`, `top` and `retained`.
+MCP `pinchtab_memory_compare` takes `base` and `head` (both required), `top`,
+`retained` and `browser`.
+
+Covered by `tests/e2e/scenarios/api/memory-basic.sh`,
+`tests/e2e/scenarios/api/memory-extended.sh` and
+`tests/e2e/scenarios/cli/memory-basic.sh`.
## Walkthrough: find a leak
diff --git a/docs/reference/metrics.md b/docs/reference/metrics.md
index 40163c19..2088a9b0 100644
--- a/docs/reference/metrics.md
+++ b/docs/reference/metrics.md
@@ -33,6 +33,10 @@ Every response says which layer its numbers describe:
}
```
+`metrics` carries `requestsTotal`, `requestsFailed`, `avgLatencyMs`, `rateLimited`,
+`staleRefRetries`, `rateBucketHosts` and the Go runtime figures `goHeapAllocMB`, `goHeapSysMB`,
+`goNumGoroutine` and `goHeapObjects`. A failure event carries `code` and `message` when it has a reason.
+
A failure is not always a 4xx. `POST /actions` and `POST /macro` answer 200 with per-item
results by design, so a run whose steps failed publishes a failure reason instead of a
status: it counts in `requestsFailed`, appears in `failures.recent` with the run's path,
diff --git a/docs/reference/mouse.md b/docs/reference/mouse.md
index 4b4ecbf4..e6a068e4 100644
--- a/docs/reference/mouse.md
+++ b/docs/reference/mouse.md
@@ -42,7 +42,7 @@ pinchtab drag e5 400,320
Notes:
-- All `mouse` subcommands and `drag` accept `--humanize` to opt the action into the humanized bezier+jitter input path (overrides `instanceDefaults.humanize`).
+- All `mouse` subcommands accept `--humanize` to opt the action into the humanized bezier+jitter input path (overrides `instanceDefaults.humanize`). `drag` has no `--humanize` flag.
- `mouse move` accepts either coordinates or a unified selector.
- `mouse down` and `mouse up` accept an optional selector. Without one, they use the current pointer position.
- `mouse wheel` accepts either a delta form (`<dy> [--dx <n>]`) or an optional selector. Without a selector, it uses the current pointer position.
@@ -140,7 +140,7 @@ curl -X POST http://localhost:9867/tabs/<tabId>/action \
- POST coordinate bodies work with plain `x` and `y`; no extra `hasXY` flag is required.
- `mouse-down`, `mouse-up`, and `mouse-wheel` use per-tab current-pointer state when you omit a fresh target.
- If no current pointer position is known yet, `mouse-down` and `mouse-up` fail with a clear error. Use `mouse-move` first or pass an explicit target.
-- If no current pointer position is known yet, `mouse-wheel` and page `scroll` use the viewport center as a deterministic fallback.
+- If no current pointer position is known yet, `mouse-wheel` uses the viewport center as a deterministic fallback. Page `scroll` without `x`/`y` always targets the viewport center.
- `mouse-wheel` defaults to vertical scrolling when only `deltaY` is provided.
- The CDP-to-DOM move fallback only handles renderer acknowledgement timeouts. Other CDP errors and caller cancellation are returned to the caller.
diff --git a/docs/reference/navigate.md b/docs/reference/navigate.md
index 090e3aa6..59b46b22 100644
--- a/docs/reference/navigate.md
+++ b/docs/reference/navigate.md
@@ -8,10 +8,13 @@ curl -X POST http://localhost:9867/navigate \
-d '{"url":"https://pinchtab.com"}'
# CLI Alternative
pinchtab nav https://pinchtab.com
-# Response (default is tab ID; use --json for full JSON)
+# Response (terminal: tab ID, then the landed URL; piped: tab ID only; --json for full JSON)
8f9c7d4e1234567890abcdef12345678
+https://pinchtab.com/
```
+API response: `{"tabId":"...","url":"<landed URL>","title":"...","route":...}`.
+
## CLI Flags
`pinchtab nav <url>` auto-starts the default local server when it is not already running. When `--server` or `PINCHTAB_SERVER` targets another server, PinchTab connects to that server without auto-starting a new process.
@@ -26,9 +29,12 @@ Hidden aliases: `goto`, `navigate`, `open`.
| `--new-tab` | Force new tab |
| `--block-images` | Block image loading |
| `--block-ads` | Block ads |
+| `--dismiss-banners` | After landing, click a visible cookie/consent dismissal button or remove obvious overlays |
+| `--timeout` | Navigation timeout in seconds (max 120); overrides the 30s new-tab ceiling |
| `--snap` | Output snapshot after navigation |
| `--snap-diff` | Output snapshot diff after navigation |
-| `--print-tab-id` | Print only tab ID (auto when piped) |
+| `--text` | Output page text after navigation |
+| `--print-tab-id` | Print only tab ID (auto when piped); with `--snap`/`--text` the tab ID goes to stderr |
| `--json` | Full JSON response |
## Examples
@@ -50,20 +56,29 @@ pinchtab nav https://example.com --block-images # Skip images
| `tabId` | Reuse existing tab |
| `newTab` | Force new tab |
| `blockImages` | Block image loading |
+| `blockMedia` | Block media loading |
| `blockAds` | Block ads |
-| `timeout` | Navigation timeout |
-| `waitFor` | Wait condition |
-| `waitSelector` | Wait for selector |
+| `dismissBanners` | Dismiss cookie/consent banners after landing |
+| `timeout` | Navigation timeout in seconds (capped at 120) |
+| `waitTitle` | Wait up to N seconds for a title (capped at 30) |
+| `waitFor` | Wait condition: `none` (default), `dom`, `selector`, `networkidle` |
+| `waitSelector` | Selector to wait for; required when `waitFor` is `selector` |
+| `dispatchOnly` | Return `{tabId,url,dispatched:true}` once the navigation is dispatched, without waiting for load |
+| `browser` | Browser to route the request to |
+
+`GET /navigate?url=...` accepts the same fields as query parameters, except `blockImages`, `blockMedia` and `blockAds`.
## Behavior
-- Top-level `POST /navigate` opens a new tab when no `tabId` is provided.
+- Top-level `POST /navigate` opens a new tab when no `tabId` is provided, unless the caller is identified (session or agent id) and has a current tab, which is reused. Under the strict empty-pointer policy an identified caller with no current tab gets `409 no_current_tab`.
- `pinchtab nav <url>` uses the current tracked tab when one is available; otherwise it opens a new tab.
- `POST /tabs/{id}/navigate`, `POST /navigate` with `tabId`, and `pinchtab nav <url> --tab <id>` reuse the specified tab and make it the current tab for later unscoped operations.
- `--new-tab` and `newTab:true` force a new tab even if another tab is current.
- Commands that operate without `--tab` use the current tracked tab. Focusing or using a tab updates that current-tab pointer; if the pointer is stale, PinchTab falls back to the most recently used tracked tab.
- When the saved current-tab pointer names a tab the server no longer has, `pinchtab nav` retries the navigation without the tab id. For a session or agent-id caller — by `--agent-id` or `PINCHTAB_AGENT_ID`, either one — that retry reuses that scope's current tab, and the CLI stays silent because nothing was created. For a caller with neither, the server opens a **new** tab — the documented anonymous contract — so the CLI prints a `HINT` on stderr naming both the tab that was gone and the new one, rather than reporting plain success while leaving you with two tabs on one URL. Run with `PINCHTAB_SESSION` set to keep a single work surface. An explicit `--tab` never retries: it surfaces the 404.
+Errors: `400` for an invalid URL, `400 bad_wait_for` when the `waitFor` condition is unsupported or does not hold, `403` when the target is blocked (IDPI domain policy or a private/internal address), `409 dialog_blocked` when a JavaScript dialog is open on the tab, `409 tab_paused_handoff` while the tab is paused for [handoff](./handoff.md), `422` on a redirect loop.
+
Rationale: the CLI keeps one obvious work surface by default. Use `--new-tab` when you intentionally want another tab, or `--tab`/`tabId` when you need a specific tab.
## Related Pages
diff --git a/docs/reference/pdf.md b/docs/reference/pdf.md
index 5dc4676c..baa7d3a9 100644
--- a/docs/reference/pdf.md
+++ b/docs/reference/pdf.md
@@ -30,17 +30,32 @@ pinchtab pdf # Auto-generates filename: page-20260308-120
| `--margin-*` | Margins (top, bottom, left, right) |
| `--generate-tagged-pdf` | Generate tagged PDF |
| `--generate-document-outline` | Generate document outline |
+| `--file-output` | Save server-side (`output=file`) instead of streaming bytes |
+| `--path` | Server-side output path (under the state directory) |
| `--tab` | Target specific tab |
## API Parameters
+`GET /pdf` and `POST /pdf` read query parameters; `POST /tabs/{id}/pdf` also
+accepts them as JSON body fields.
+
| Parameter | Description |
|-----------|-------------|
-| `output` | `file` to save server-side |
-| `raw` | `true` for raw PDF bytes |
+| `output` | `file` to save server-side; response is `{path, size}` |
+| `path` | Server-side path for `output=file`; must stay inside the state directory (else `400`) |
+| `raw` | `true` for raw PDF bytes; otherwise the response is `{"format":"pdf","base64":"..."}` |
| `landscape` | Landscape orientation |
-| `scale` | Page scale |
-| `paperWidth`, `paperHeight` | Paper dimensions |
+| `scale` | Page scale (default `1`) |
+| `paperWidth`, `paperHeight` | Paper dimensions in inches (default `8.5` x `11`) |
+| `marginTop`, `marginBottom`, `marginLeft`, `marginRight` | Margins in inches (default `0.4`) |
+| `pageRanges` | Pages to export, e.g. `1-3,5` |
+| `preferCSSPageSize`, `displayHeaderFooter`, `generateTaggedPDF`, `generateDocumentOutline` | Booleans |
+| `headerTemplate`, `footerTemplate` | HTML templates; a template containing `<script`, `javascript:` or an `on*=` handler is rejected with `400` |
+| `tabId` | Target a specific tab |
+
+With IDPI content scanning enabled, a page that trips the scanner returns `403`.
+
+MCP: `pinchtab_pdf` takes `tabId`, `landscape`, `scale`, `pageRanges` and returns the base64 PDF.
## Related Pages
diff --git a/docs/reference/press.md b/docs/reference/press.md
index 5b26eebe..e08e50a0 100644
--- a/docs/reference/press.md
+++ b/docs/reference/press.md
@@ -1,6 +1,6 @@
# Press
-Send a keyboard key to the current tab.
+Send a keyboard key or chord to the current tab, optionally focusing an element first.
```bash
curl -X POST http://localhost:9867/action \
@@ -16,11 +16,18 @@ OK
| Flag | Description |
|------|-------------|
+| `--snap` | Output interactive snapshot after key press |
+| `--snap-diff` | Output snapshot diff after key press |
+| `--text` | Output page text after key press |
| `--json` | Full JSON response |
| `--tab` | Target specific tab |
Common keys include `Enter`, `Tab`, `Escape`, `ArrowDown`, `ArrowUp`, `Backspace`, `Delete`.
+CLI usage is `pinchtab press [ref] <key|chord>`: with two arguments the first is a selector or ref that is focused before the key is sent (API: `ref` or `selector`).
+
+A chord joins modifiers and a key with `+`, for example `Ctrl+A` or `Shift+ArrowLeft`. Modifiers are `Ctrl`/`Control`, `Alt`/`Option`, `Shift`, and `Meta`/`Cmd`/`Command`/`Super`/`Win` (case-insensitive); an unknown or repeated modifier is refused. The API alternatively takes the CDP bitmask `modifiers` (Alt=1, Ctrl=2, Meta=4, Shift=8) with a plain `key`, but not both forms at once.
+
## Related Pages
- [Click](./click.md)
diff --git a/docs/reference/profiles.md b/docs/reference/profiles.md
index c51d0b86..1f603af7 100644
--- a/docs/reference/profiles.md
+++ b/docs/reference/profiles.md
@@ -16,25 +16,35 @@ curl http://localhost:9867/profiles
# CLI Alternative (human-readable by default)
pinchtab profiles
-# Output: prof_278be873 work
+# Output (tab-separated): prof_278be873 work
pinchtab profiles --json # Full JSON response
```
-`pinchtab profiles` is the simplest way to see available profiles from the CLI.
+`pinchtab profiles` is the simplest way to see available profiles from the CLI. Quarantined
+profiles are listed separately after the live ones, with their size.
-Response shape:
+Response shape (every field is always present; the same object is returned by `GET /profiles/{id}`):
```json
[
{
"id": "prof_278be873",
"name": "work",
+ "path": "/path/to/profiles/work",
+ "pathExists": true,
"created": "2026-02-27T20:37:13.599055326Z",
+ "lastUsed": "2026-03-01T09:12:44Z",
"diskUsage": 534952089,
"sizeMB": 510.17,
"running": false,
+ "quarantined": false,
+ "temporary": false,
"source": "created",
+ "chromeProfileName": "",
+ "accountEmail": "",
+ "accountName": "",
+ "hasAccount": false,
"useWhen": "Use for work accounts",
"description": ""
}
@@ -44,7 +54,7 @@ Response shape:
Notes:
- `GET /profiles` excludes temporary auto-generated instance profiles by default
-- use `GET /profiles?all=true` to include temporary profiles
+- use `GET /profiles?all=true` to include temporary profiles (`"temporary": true`)
## Get One Profile
@@ -57,8 +67,12 @@ curl http://localhost:9867/profiles/prof_278be873
"path": "/path/to/profiles/work",
"pathExists": true,
"created": "2026-02-27T20:37:13.599055326Z",
+ "lastUsed": "2026-03-01T09:12:44Z",
"diskUsage": 534952089,
"sizeMB": 510.17,
+ "running": false,
+ "quarantined": false,
+ "temporary": false,
"source": "created",
"chromeProfileName": "Your Chrome",
"accountEmail": "[email protected]",
@@ -87,8 +101,9 @@ curl -X POST http://localhost:9867/profiles \
Notes:
-- there is no `pinchtab profile create` CLI command
+- `name` is required; `description` and `useWhen` are optional
- both `POST /profiles` and `POST /profiles/create` work for creating profiles
+- the CLI form is `pinchtab profiles create <name>`, which prints the new `id` and `name`
## Update A Profile
@@ -118,6 +133,9 @@ Important:
- using the profile name in that path returns an error
- a rename changes the generated profile ID because IDs are derived from the name
+`PATCH /profiles/meta` updates `description` and/or `useWhen` for the profile named by `name`
+in the body, and answers `{"status":"updated","name":"..."}`.
+
## Delete A Profile
```bash
@@ -130,7 +148,8 @@ curl -X DELETE http://localhost:9867/profiles/prof_278be873
}
```
-`DELETE /profiles/{id}` also requires the profile ID.
+`DELETE /profiles/{id}` also requires the profile ID. Add `?force=true` to delete a profile
+that still has an instance; the response then names that instance as `orphanedInstance`.
## Start Or Stop By Profile
@@ -164,7 +183,10 @@ curl -X POST http://localhost:9867/profiles/prof_278be873/stop
}
```
-For these orchestrator routes, the path can be a profile ID or profile name. The returned instance object now includes both `mode` and `headless`.
+For these orchestrator routes, the path can be a profile ID or profile name. Start answers `201` with the
+instance object (see [Instances](./instances.md)), which includes both `mode` and `headless`. Its body takes
+`headless` (default `false`, so omitting it starts a headed browser), `port`, `securityPolicy`, `browser`
+and `fallbackTargets`.
## Check Whether A Profile Has A Running Instance
@@ -173,6 +195,7 @@ curl http://localhost:9867/profiles/prof_278be873/instance
# Response
{
"name": "work",
+ "exists": true,
"running": true,
"status": "running",
"port": "9868",
@@ -180,6 +203,10 @@ curl http://localhost:9867/profiles/prof_278be873/instance
}
```
+`status` is `running` or `starting` when an instance exists (`id` is then set), `stopped` when it
+does not, and `missing` (with `exists: false` and a `message`) when the profile does not exist.
+The route always answers `200`.
+
## Additional Profile Operations
### Reset A Profile
@@ -188,7 +215,7 @@ curl http://localhost:9867/profiles/prof_278be873/instance
curl -X POST http://localhost:9867/profiles/prof_278be873/reset
```
-This route requires the profile ID.
+This route requires the profile ID and answers `{"status":"reset","id":"...","name":"..."}`.
### Import A Profile
@@ -198,6 +225,25 @@ curl -X POST http://localhost:9867/profiles/import \
-d '{"name":"imported-profile","sourcePath":"/path/to/existing/profile"}'
```
+`name` and `sourcePath` are required; `description` and `useWhen` are optional. The response is
+`{"status":"imported","name":"..."}`.
+
+### Prune Quarantined Profiles
+
+```bash
+curl -X POST http://localhost:9867/profiles/prune
+curl -X POST http://localhost:9867/profiles/prune \
+ -H "Content-Type: application/json" \
+ -d '{"confirm":true}'
+# CLI Alternative
+pinchtab profiles prune # list what would be removed
+pinchtab profiles prune --confirm # remove it
+```
+
+Without `confirm` (body or `?confirm=true`) nothing is deleted and the response lists what would be.
+`profile` (body or query) limits it to one quarantined directory. The response is
+`{"removed":<bool>,"count":N,"totalBytes":N,"profiles":[{"name","path","bytes"}]}`.
+
### Get Logs
```bash
diff --git a/docs/reference/record.md b/docs/reference/record.md
index 47ea4a74..e9f6a0ce 100644
--- a/docs/reference/record.md
+++ b/docs/reference/record.md
@@ -3,7 +3,7 @@
Record browser activity as a video file. Supports GIF (pure Go), WebM, and MP4 (require ffmpeg).
```bash
-# Start recording (format from file extension)
+# Start recording
curl -X POST http://localhost:9867/record/start \
-H "Content-Type: application/json" \
-d '{"format":"gif","fps":5,"quality":80}'
@@ -11,10 +11,18 @@ curl -X POST http://localhost:9867/record/start \
# Check status
curl http://localhost:9867/record/status
-# Stop and save
-curl -X POST http://localhost:9867/record/stop > recording.gif
+# Stop: encoding runs in the background into <stateDir>/recordings/
+curl -X POST http://localhost:9867/record/stop -d '{}'
+# {"status":"encoding","path":"<stateDir>/recordings/rec_<timestamp>.gif","format":"gif","frames":62,"hint":"..."}
+
+# Stop without encoding
+curl -X POST http://localhost:9867/record/stop -d '{"discard":true}'
+# {"status":"discarded","format":"gif","frames":62}
```
+The server chooses the output path; poll `/record/status` until `state` is
+`finished` (API flow exercised in `tests/e2e/scenarios/api/recording-smoke.sh`).
+
## Start Response
```json
@@ -32,6 +40,7 @@ curl -X POST http://localhost:9867/record/stop > recording.gif
```json
{
"active": true,
+ "state": "recording",
"format": "gif",
"durationSeconds": 12.5,
"frames": 62,
@@ -40,18 +49,30 @@ curl -X POST http://localhost:9867/record/stop > recording.gif
}
```
+`state` is one of `idle`, `recording`, `limit_reached`, `stopping`, `encoding`,
+`finished`, `aborted`. While a recording exists the body may also carry
+`stopReason` and `outputPath`; once `finished` it carries `outputPath`, and
+`error` or `warning` when encoding failed or truncated.
+
## API Body Fields (POST /record/start)
-- `format`: `gif`, `webm`, or `mp4`. Determined by file extension in CLI.
-- `fps`: Frames per second, 1-30 (default 5).
-- `quality`: JPEG capture quality 1-100 (default 80).
-- `scale`: Resolution multiplier (default 1.0). Values < 1 reduce output size.
+- `format`: `gif` (default), `webm`, or `mp4`. Determined by file extension in CLI. Anything else is `400 invalid_format`.
+- `fps`: Frames per second, capped at 30 (default 5).
+- `quality`: JPEG capture quality, capped at 100 (default 80).
+- `scale`: Resolution multiplier, capped at 1.0 (default 1.0). Values < 1 reduce output size.
- `tabId`: Target a specific tab.
+A second `start` while a recording is active returns `409 recording_error`;
+`stop` with no active recording returns `400 recording_error`.
+
+## API Body Fields (POST /record/stop)
+
+- `discard`: `true` to drop the frames without encoding.
+
## CLI
- `record start <file>`: Start recording. Format from extension (.gif, .webm, .mp4).
-- `record stop`: Stop and save to the path given at start.
+- `record stop`: Stop, wait for the server to finish encoding, then move the file to the path given at start (`recording-<timestamp>.gif` if none was recorded).
- `record status`: Show active recording info.
- `--fps <n>`: Frames per second (default 5).
- `--quality <n>`: JPEG capture quality (default 80).
@@ -66,14 +87,16 @@ curl -X POST http://localhost:9867/record/stop > recording.gif
| `.webm` | `ffmpeg` | VP8 via ffmpeg pipe | Requires ffmpeg on `$PATH` |
| `.mp4` | `ffmpeg` | H.264 via ffmpeg pipe | Requires ffmpeg on `$PATH` |
-GIF encoding runs entirely in-process — no external binary needed. Dithering is CPU-bound; recordings over ~2 minutes at 10 fps can take 30-60 seconds to encode. Frames are capped at 600 (max ~2 minutes at 5 fps) and downscaled if they exceed 1280x720 pixels to limit memory usage.
+GIF encoding runs entirely in-process — no external binary needed. Dithering is CPU-bound. A GIF encodes at most 600 frames (~2 minutes at 5 fps) and at most 256 MB of in-memory frame data; frames are kept at the requested scale (no forced downscale), so larger captures fit fewer frames before truncation. Capture itself stops at 5 minutes or 9000 frames (`state: limit_reached`).
-WebM and MP4 stream frames to ffmpeg during `record stop`. If ffmpeg is not installed, `record start` returns a 400 error with a message indicating the dependency. Install ffmpeg via your package manager (`brew install ffmpeg`, `apt install ffmpeg`, etc.) or use `.gif` as a zero-dependency alternative.
+WebM and MP4 stream frames to ffmpeg after `record stop`. If ffmpeg is not installed, `record start` returns `400 ffmpeg_required`. Install ffmpeg via your package manager (`brew install ffmpeg`, `apt install ffmpeg`, etc.) or use `.gif` as a zero-dependency alternative.
## Notes
- Gated by `security.allowScreencast` (disabled by default). Enable with `pinchtab config set security.allowScreencast true` and restart the server.
- One active recording per bridge instance.
+- Recordings are owned by the caller's session (or agent id); an anonymous recording can be stopped by any caller.
+- MCP: `pinchtab_record` takes `action` (`start`|`stop`|`status`, required), `file`, `fps`, `quality`, `scale`, `tabId`.
## Related Pages
diff --git a/docs/reference/scheduler.md b/docs/reference/scheduler.md
index efa4e79b..913caf96 100644
--- a/docs/reference/scheduler.md
+++ b/docs/reference/scheduler.md
@@ -48,6 +48,9 @@ The scheduler is off by default. Dashboard mode registers the task routes only w
| `workerCount` | `4` | number of worker goroutines |
| `maxBatchSize` | `50` | max tasks one `POST /tasks/batch` may submit; a larger batch is refused with `batch_too_large` |
+A numeric knob set to `0` or below means its default, never unlimited. The scheduler reads these
+values once at startup; changing them takes a server restart.
+
## Task Object
Tasks are scheduler-owned records with these main fields:
@@ -58,7 +61,8 @@ Tasks are scheduler-owned records with these main fields:
| `agentId` | submitting agent identifier |
| `action` | action kind to run |
| `tabId` | target tab ID |
-| `ref` | optional element ref |
+| `selector` | optional element selector (ref, CSS, XPath or text) |
+| `ref` | optional element ref (deprecated; use `selector`) |
| `params` | optional action-specific request fields |
| `priority` | lower number means higher priority |
| `state` | current task state |
@@ -105,15 +109,16 @@ Request fields:
| `agentId` | yes | validated at request time |
| `action` | yes | becomes the executor `kind` |
| `tabId` | practically yes | required by the execution path |
-| `ref` | no | top-level element ref for element-targeted actions |
-| `params` | no | action-specific fields merged into the executor request body |
+| `selector` | no | top-level element selector for element-targeted actions |
+| `ref` | no | deprecated top-level element ref; use `selector` |
+| `params` | no | action-specific fields merged into the executor request body (`kind`, `ref`, `selector` and `tabId` inside `params` are ignored) |
| `priority` | no | lower number means higher priority |
| `deadline` | no | RFC3339 timestamp; defaults to `now + 60s` |
| `callbackUrl` | no | webhook URL; receives POST with task snapshot on terminal state |
Important:
-- request validation enforces only `agentId` and `action`
+- request validation enforces only `agentId` and `action` (plus a valid `callbackUrl` when one is given); other failures answer `400`
- missing `tabId` is rejected later during execution with `tabId is required for task execution`
- past deadlines are rejected at submission time
- `agentId` is also forwarded to the executor as `X-Agent-Id`, so the resulting browser action is attributed to the same agent in `/api/activity` and the dashboard Agents view
@@ -254,6 +259,7 @@ It builds the action body like this:
{
"kind": "<action>",
"ref": "<ref>",
+ "selector": "<selector>",
"...params": "..."
}
```
@@ -261,8 +267,8 @@ It builds the action body like this:
That means:
- `action` becomes `kind`
-- top-level `ref` is forwarded when present
-- every key in `params` is merged into the top-level action body
+- top-level `ref` and `selector` are forwarded when present
+- every other key in `params` is merged into the top-level action body; `params` cannot override `kind`, `ref`, `selector` or `tabId`
- `agentId` is propagated as `X-Agent-Id`
Example:
@@ -306,9 +312,9 @@ curl http://localhost:9867/scheduler/stats
"queue": {
"totalQueued": 5,
"totalInflight": 2,
- "agentCounts": {
- "agent-crawl-01": 3,
- "agent-scrape-02": 2
+ "agents": {
+ "agent-crawl-01": { "queued": 3, "inflight": 1 },
+ "agent-scrape-02": { "queued": 2, "inflight": 1 }
}
},
"metrics": {
@@ -374,7 +380,8 @@ curl -X POST http://localhost:9867/tasks \
Webhook behavior:
- delivery is best-effort: failures are logged but do not affect task state
-- only `http` and `https` schemes are allowed (SSRF protection)
+- only `http` and `https` schemes are allowed, with no credentials in the URL, and the host must resolve to a
+ public address (loopback and private/internal hosts are refused at submission with `400`)
- a dedicated HTTP client with a 10-second timeout is used
- custom headers are sent: `X-PinchTab-Event: task.completed` and `X-PinchTab-Task-ID: <taskId>`
@@ -395,9 +402,9 @@ curl -X POST http://localhost:9867/tasks/batch \
"agentId": "agent-crawl-01",
"callbackUrl": "https://pinchtab.com/hooks/batch",
"tasks": [
- { "action": "click", "tabId": "TAB_ID", "params": { "selector": "#btn" } },
+ { "action": "click", "tabId": "TAB_ID", "ref": "e5" },
{ "action": "scroll", "tabId": "TAB_ID", "params": { "scrollY": 400 } },
- { "action": "hover", "tabId": "TAB_ID", "params": { "selector": "h1" }, "priority": 1 }
+ { "action": "hover", "tabId": "TAB_ID", "ref": "e9", "priority": 1 }
]
}'
# Response (202 Accepted)
@@ -417,9 +424,11 @@ curl -X POST http://localhost:9867/tasks/batch \
| --- | --- | --- |
| `agentId` | yes | shared across all tasks in the batch |
| `callbackUrl` | no | webhook URL applied to every task |
-| `tasks` | yes | array of task definitions (1–50) |
+| `tasks` | yes | array of task definitions (1 to `scheduler.maxBatchSize`) |
-Each task definition supports the same fields as a single task submit (`action`, `tabId`, `ref`, `params`, `priority`, `deadline`) except `agentId` and `callbackUrl` which are inherited from the batch.
+Each task definition supports `action`, `tabId`, `ref`, `params`, `priority` and `deadline`; `agentId` and
+`callbackUrl` are inherited from the batch. A batch task has no `selector` field, and a `selector` inside
+`params` is dropped, so target elements in a batch by `ref`.
#### Batch Validation
@@ -430,9 +439,14 @@ Each task definition supports the same fields as a single task submit (`action`,
| more tasks than `scheduler.maxBatchSize` (default 50) | `400 Bad Request` with `batch_too_large` code |
| invalid JSON body | `400 Bad Request` |
-Partial failure: if some tasks are rejected by admission (queue full), the accepted tasks are still submitted. The response includes each task's status individually.
+Partial failure: if some tasks are rejected by admission (queue full) or validation, the accepted tasks are still
+submitted. Each rejected item comes back with `state: "rejected"` and an `error`; `submitted` is the number of items
+in the response, rejected ones included.
+
+### Config Hot-Reload (Go API only)
-### Config Hot-Reload
+These are Go APIs in `internal/scheduler` for embedders. `pinchtab server` does not start a
+`ConfigWatcher` or call `ReloadConfig`, so editing `scheduler.*` in the config file still needs a restart.
`ReloadConfig(cfg)` updates queue limits, inflight limits, and result TTL at runtime without restarting the scheduler.
diff --git a/docs/reference/screenshot.md b/docs/reference/screenshot.md
index 5a9f0b8d..0a230f68 100644
--- a/docs/reference/screenshot.md
+++ b/docs/reference/screenshot.md
@@ -26,6 +26,10 @@ curl "http://localhost:9867/screenshot?output=file"
## Response (JSON)
+Default: `{"format":"jpeg","base64":"..."}`. With `annotate=true` the body also
+carries `annotations: [{ref, role, name, tag, box:{x,y,w,h}}]`. With
+`output=file`:
+
```json
{
"path": "/path/to/state/screenshots/screenshot-20260308-120001.jpg",
@@ -35,6 +39,9 @@ curl "http://localhost:9867/screenshot?output=file"
}
```
+A `selector` that matches nothing returns the same selector-failure 404 as
+other read endpoints.
+
## Useful flags
### API Query Parameters
@@ -42,20 +49,25 @@ curl "http://localhost:9867/screenshot?output=file"
- `format`: `jpeg` (default) or `png`.
- `quality`: JPEG quality `0-100` (default: `80`). Ignored for PNG.
- `selector`: Unified selector to capture one element (e.g. `e5`, `#id`, `xpath://...`, `text:Submit`).
-- `scale`: Rescale the output bitmap. Default `1`. `0.5` halves each axis (quarter the pixels).
+- `scale`: Rescale the output bitmap. Default `1`, clamped to `0.05`–`4`. `0.5` halves each axis (quarter the pixels). Invalid `quality`/`scale` values fall back to the defaults.
- `beyondViewport`: `true` to capture the full scrollable document instead of just the visible viewport. Ignored when `selector` is set. With `annotate=true` the returned box coordinates are document-relative.
+- `annotate`: `true` to overlay numbered ref boxes on interactive elements (or on `selector` matches, which then narrows instead of clips) and return an `annotations` list.
+- `noAnimations`: `true` to disable CSS animations before capturing.
- `raw`: `true` to return image bytes directly instead of JSON.
- `output`: `file` to save to state directory.
- `tabId`: Target a specific tab.
### CLI
+Without `-o` the CLI saves to `screenshot-<timestamp>.jpg` (or `.png`) in the current directory.
+
- `-o <path>`: Save to a specific path. A `.png` extension selects PNG when `--format` is omitted; other extensions use JPEG.
- `--format <jpeg|png>`: Explicitly select the image format, overriding extension inference.
- `-q <0-100>`: Set JPEG quality.
- `-s <selector>`: Capture a specific element.
- `--scale <f>`: Bitmap rescale (e.g. `0.5`).
- `--beyond-viewport`: Capture the full scrollable document. Ignored when `--selector` is set.
+- `--annotate`: Overlay numbered ref boxes and print a `[n] ref role "name"` legend to stdout.
- `--tab <id>`: Target a specific tab.
## When to use `pinchtab capture` instead
diff --git a/docs/reference/scroll.md b/docs/reference/scroll.md
index d8dce5ce..f0a34574 100644
--- a/docs/reference/scroll.md
+++ b/docs/reference/scroll.md
@@ -6,7 +6,9 @@ Scroll the current tab or a specific element.
curl -X POST http://localhost:9867/action \
-H "Content-Type: application/json" \
-d '{"kind":"scroll","scrollY":800}'
-# Response: {"success":true,"result":{"success":true}}
+# Response: {"success":true,"result":{"scrolled":true,...},"route":{...}}
+# result also carries deltaX/deltaY (the scroll applied), targetX/targetY (the point scrolled at)
+# and legacy x/y (same as deltaX/deltaY); an element scroll returns only scrolled:true
# CLI Alternative (human-readable by default)
pinchtab scroll down
@@ -28,9 +30,11 @@ Notes:
- give either the flags or one positional, never both, and only one positional is accepted —
so `--tab` stays a flag and must not be placed after `--`, where it would be read as a
positional
-- a delta of zero on both axes is refused: it reaches the server as "no delta given", which
- scrolls down by the default 120px rather than doing nothing. An explicit zero on one axis
- (`--dy 0 --dx 500`) is a real scroll and passes through
+- a delta of zero on both axes is refused, by the CLI before sending and by the server
+ (an explicit `scrollX`/`scrollY` of zero on both axes is an error). An explicit zero on one
+ axis (`--dy 0 --dx 500`) is a real scroll and passes through. Only a request with no delta
+ and no target at all scrolls down by the default 120px
+- a direction keyword (`up`, `down`, `left`, `right`) scrolls 800px per step
- use `--snap` to output an interactive snapshot after scrolling
- use `--snap-diff` to output only the changes from the previous snapshot
diff --git a/docs/reference/select.md b/docs/reference/select.md
index e5155eff..243ba136 100644
--- a/docs/reference/select.md
+++ b/docs/reference/select.md
@@ -42,6 +42,8 @@ pinchtab select e12 "Kingdom"
Prefer the canonical option value or full visible text when disambiguation matters.
+The API reads `value`, falling back to `text`. When nothing matches, the action answers `422 option_not_found`; `details.available` lists the options as `{value, text}` and `details.hint` renders them.
+
Selector lookup is limited to current frame scope (default: `main`). Use [`/frame`](./frame.md) before iframe selects.
## Related Pages
diff --git a/docs/reference/sessions.md b/docs/reference/sessions.md
index f7221afd..50f75c57 100644
--- a/docs/reference/sessions.md
+++ b/docs/reference/sessions.md
@@ -4,7 +4,7 @@ Agent sessions provide durable, revocable authentication for automated agents. I
## Overview
-- **Session token**: `ses_<48 hex chars>` — high-entropy, never stored raw (only SHA-256 hash persisted)
+- **Session token**: `ses_<48 hex chars>` (24 random bytes) — never stored raw (only SHA-256 hash persisted)
- **Session ID**: `ses_<16 hex chars>` — public identifier for management
- **Auth header**: `Authorization: Session <token>`
- **Env var**: `PINCHTAB_SESSION` — CLI auto-detects and uses session auth
@@ -58,7 +58,7 @@ server refuses to load, so the repair does not need a hand edit.
- Tokens are never logged or persisted in plaintext
- SHA-256 hash comparison using `crypto/subtle.ConstantTimeCompare`
- Idle timeout (default 30m) and max lifetime (default 24h)
-- Sessions persisted to `agent-sessions.json` (atomic writes)
+- Sessions persisted to `<server.stateDir>/sessions.json` (atomic writes)
- Each session bound to a specific agentId for activity tracking
> **⚠️ Trusted, controlled environments only.** Agent sessions are meant for operators and automation you already trust: local machines, private networks, CI, or other controlled systems. They are not a multi-tenant isolation boundary and should not be treated as safe for untrusted users, untrusted agents, or public internet exposure.
@@ -129,4 +129,12 @@ pinchtab session revoke ses_abc123def456
## API Endpoints
-See [endpoints.md](../endpoints.md) for full API reference.
+| Route | Purpose |
+| --- | --- |
+| `POST /sessions` | Create a session; body `agentId` (required), optional `label`, `grants` and `browser` (`invalid_browser` when unknown) |
+| `GET /sessions` | List sessions |
+| `GET /sessions/me` | The session authenticating the request |
+| `GET /sessions/{id}` | One session |
+| `POST /sessions/{id}/revoke` | Revoke a session |
+
+`pinchtab session create` also takes `--label`. See [endpoints.md](../endpoints.md) for the full API reference.
diff --git a/docs/reference/snapshot.md b/docs/reference/snapshot.md
index 871eaf51..ca0006e0 100644
--- a/docs/reference/snapshot.md
+++ b/docs/reference/snapshot.md
@@ -10,10 +10,10 @@ Selector scoping is explicit. `selector=...` only searches the current frame sco
curl "http://localhost:9867/snapshot?filter=interactive"
# CLI Alternative (defaults to compact text output)
pinchtab snap -i
-# Output
-[e5] link "More information..."
+# Output: a "# <title> | <url> | <N> nodes" header line, then one node per line
+e5:link "More information..."
-# Use --full or --compact=false for JSON
+# --json (same as --compact=false) keeps the interactive filter; --full returns every node as JSON
pinchtab snap --full
```
@@ -23,10 +23,11 @@ pinchtab snap --full
|------|-------------|
| `-i`, `--interactive` | Filter to interactive elements + headings (default: true) |
| `-c`, `--compact` | Compact text output (default: true) |
+| `--json` | JSON output, keeping the interactive filter (same as `--compact=false`) |
| `-d`, `--diff` | Show diff from previous snapshot |
-| `--full` | Full JSON output (shorthand for `--interactive=false --compact=false`) |
+| `--full` | Full JSON output (shorthand for `--interactive=false --json`) |
| `--text` | Text output format |
-| `-s`, `--selector` | CSS selector to scope snapshot |
+| `-s`, `--selector` | Selector to scope the snapshot (also accepted as the positional `[selector]` argument) |
| `--max-tokens` | Maximum token budget |
| `--depth` | Tree depth limit |
| `--tab` | Target specific tab |
@@ -46,13 +47,41 @@ pinchtab snap --max-tokens 2000 # Limit output size
| Parameter | Description |
|-----------|-------------|
+| `tabId` | Target tab (defaults to the current tab) |
| `filter` | `interactive` for interactive + headings, `all` (default) for the whole tree |
| `interactive` | Boolean alias for `filter`: `true` is `filter=interactive`, `false` is `filter=all`. Contradicting an explicit `filter` is a 400 |
| `format` | `compact`, `text`, `yaml`, or default JSON. The CLI and the MCP tool both ask for `compact`; the HTTP default is unchanged |
| `diff` | `true` for diff mode |
-| `selector` | CSS selector to scope |
-| `maxTokens` | Token budget limit |
-| `depth` | Tree depth limit |
+| `selector` | Unified selector (ref, CSS, XPath, text, …) to scope |
+| `maxTokens` | Token budget limit (positive integer; anything else is a 400) |
+| `depth` | Tree depth limit (`-1` = no limit; below `-1` is a 400) |
+| `noAnimations` | `true` disables animations once before capturing |
+| `output` | `file` writes the snapshot under the state dir's `snapshots/` and returns `{path, size, format, timestamp}` |
+| `path` | With `output=file`, a file path inside the state dir (anything outside is a 400) |
+
+`GET /tabs/{id}/snapshot` is the same handler with the tab in the path.
+
+Unknown query parameters are not rejected; they are echoed back as `ignoredParams` (JSON/YAML) or a `# ignored params:` comment line (compact/text) so a mistyped flag is visible.
+
+## Response
+
+The default JSON body carries `url`, `title`, `route`, `nodes`, `count` and `vocabularyToken`,
+plus `truncated`/`maxTokens` when the budget cut the tree and `hint` when a selector matched an
+element with no accessible nodes. `vocabularyToken` names the ref vocabulary this snapshot
+issued; every snapshot also sets it on the `X-PinchTab-Vocab` response header (with
+`X-PinchTab-Tab-Id`), whatever the format. Echo it as `vocab` on ref-based actions (the CLI does this for you):
+an action that targets a ref under a token other than the tab's current one is refused with
+`409 vocab_superseded` — re-snapshot and use the new refs.
+
+When a modal dialog is open in the page, the snapshot is scoped to the topmost dialog's
+subtree. If the topmost dialog changes twice while the snapshot is being taken, the request
+fails with `409` — retry after the page settles. A pending JavaScript dialog (alert,
+confirm, prompt) blocks the read with `409 dialog_blocked` until it is answered with
+`pinchtab dialog`.
+
+A tab whose document is `hidden` (a background tab) is rendered before the accessibility read:
+PinchTab enables focus emulation and waits for a painted frame (up to 1s), so content that
+only lays out when visible still appears in the tree.
## What a format costs, and what it carries
diff --git a/docs/reference/solve.md b/docs/reference/solve.md
index 0242cf89..90c69760 100644
--- a/docs/reference/solve.md
+++ b/docs/reference/solve.md
@@ -71,7 +71,9 @@ curl -X POST http://localhost:9867/tabs/{tabId}/solve \
| `tabId` | string | — | Tab ID (optional, uses default tab) |
| `solver` | string | — | Solver name (optional, auto-detect) |
| `maxAttempts`| int | config (`autoSolver.maxAttempts`, default 8) | Maximum solve attempts |
-| `timeout` | float | auto-estimated (minimum 30000) | Overall timeout in milliseconds |
+| `timeout` | float | auto-estimated from the solver chain (never below 30000) | Overall timeout in milliseconds; an explicit value is used as-is |
+
+The path form (`/solve/{name}`) overrides a body `solver`. On `/tabs/{id}/solve`, a body `tabId` that disagrees with the path is rejected.
## Response
@@ -94,14 +96,17 @@ curl -X POST http://localhost:9867/tabs/{tabId}/solve \
| `challengeType` | string | Challenge variant (`turnstile`, `recaptcha-v2`, `hcaptcha`) or broad intent (`captcha`, `blocked`) |
| `attempts` | int | Number of attempts made |
| `title` | string | Final page title |
+| `handoff` | string | `paused_handoff` when a challenge was detected but not solved — the tab is paused for [handoff](./handoff.md) |
+| `hint` | string | Present with `handoff`: return control to the user, then resume the tab |
## Error Responses
| Code | Meaning |
|------|----------------------------------------|
-| 400 | Invalid body or unknown solver name |
+| 400 | Invalid body; `unknown_solver` for an unregistered name; `solver_key_missing` for `capsolver`/`twocaptcha` without their API key |
| 404 | Tab not found |
-| 423 | Tab locked by another owner |
+| 409 | `dialog_blocked` (a JavaScript dialog is open) or `tab_paused_handoff` |
+| 423 | `tab_locked`: tab leased by another owner |
| 500 | CDP/Chrome error |
## Built-In Solvers
@@ -131,7 +136,7 @@ Handles Cloudflare Turnstile and interstitial challenges.
**Click strategy**: The solver uses human-like mouse input (Bezier curve movement, random delays, press/release offset) to click the Turnstile checkbox. Click coordinates are computed relative to the widget dimensions (not hardcoded pixel offsets) with randomised jitter.
-**Stealth requirement**: The Cloudflare solver works best with `stealthLevel: "full"` in the PinchTab config. Cloudflare evaluates browser fingerprints (CDP detection, WebGL, canvas, navigator properties) before and after the checkbox interaction. Without full stealth, the solver may click correctly but the challenge can still fail fingerprint verification. Check stealth status with `GET /stealth/status`.
+**Stealth requirement**: The Cloudflare solver works best with `instanceDefaults.stealthLevel: "full"` in the PinchTab config. Cloudflare evaluates browser fingerprints (CDP detection, WebGL, canvas, navigator properties) before and after the checkbox interaction. Without full stealth, the solver may click correctly but the challenge can still fail fingerprint verification. Check stealth status with `GET /stealth/status`.
### External Solvers
@@ -167,4 +172,4 @@ func (s *MyGatewaySolver) Solve(ctx context.Context, page autosolver.Page, exec
}
```
-Then add it to the handler autosolver registry setup.
+Then add it to `buildAll` in `internal/autosolver/catalog/catalog.go`, which the handler registry setup reads through `catalog.Registrable`.
diff --git a/docs/reference/state.md b/docs/reference/state.md
index 7fd0d362..a2c75024 100644
--- a/docs/reference/state.md
+++ b/docs/reference/state.md
@@ -2,7 +2,7 @@
`pinchtab state` shows the current full browser state for a tab, and also manages saved browser state on disk.
-There are two related state views:
+There are three related state views:
- **full browser state** via `pinchtab state` or `GET /state`
- **live tab state** via `GET /tabs/{id}/state`
@@ -15,7 +15,7 @@ Full browser state includes:
- current-origin `sessionStorage`
- optional metadata
-All full/saved state operations require `security.allowStateExport=true`.
+All full/saved state operations require `security.allowStateExport=true`; when it is off they answer `403 state_export_disabled`.
## Commands
@@ -29,6 +29,9 @@ pinchtab state delete --name <name>
pinchtab state clean [--older-than <hours>]
```
+`save`, `load`, `show` and `delete` also accept the name as a positional
+argument (`pinchtab state load work-login`); `--name` is the same value.
+
## Show Current Browser State
```bash
@@ -66,7 +69,7 @@ Notes:
- omitting `--name` lets PinchTab auto-generate one
- `--tab <id>` captures state from a specific tab instead of the active/current one
-- `--encrypt` requires the configured state-encryption key
+- `--encrypt` requires `security.stateEncryptionKey` (or the `PINCHTAB_STATE_KEY` environment variable, which wins); without one the save is `400`
## Load A Saved State
@@ -78,9 +81,12 @@ pinchtab state load --name checkout --tab <tabId>
Notes:
-- `--name` accepts either an exact name or a prefix
+- `--name` accepts either an exact name or a prefix; an exact match wins
- prefix matching resolves to the most recent matching saved state
-- loading restores cookies plus current-origin storage into the target tab
+- loading restores the saved cookies, then writes the saved `localStorage` and
+ `sessionStorage` items into the target tab's current page, so navigate the tab
+ to the saved origin first
+- the response reports `cookiesRestored`, `storageItemsRestored` and `origins`
## Show Saved State Details
@@ -88,7 +94,7 @@ Notes:
pinchtab state show --name work-login
```
-Displays the full saved browser state record, including stored metadata and origin storage payloads.
+Displays the full saved browser state record, including stored metadata and origin storage payloads. Unlike `load`, `show` needs the exact name.
## Delete A Saved State
@@ -105,7 +111,7 @@ pinchtab state clean
pinchtab state clean --older-than 72
```
-Removes saved state files older than the given number of hours. Default is `24`.
+Removes saved state files older than the given number of hours. Default is `24` (a zero or negative value also means `24`).
## HTTP API
@@ -119,6 +125,17 @@ DELETE /state
POST /state/clean
```
+| Route | Input |
+| --- | --- |
+| `GET /state` | `?tabId=` (optional) |
+| `GET /state/show`, `DELETE /state` | `?name=` (required, else `400`) |
+| `POST /state/save` | `{"name", "encrypt", "tabId", "metadata"}`, fields optional but a JSON body (at least `{}`) is required; returns `name`, `path`, `cookies` (count), `origins`, `encrypted` |
+| `POST /state/load` | `{"name", "tabId"}`, `name` required |
+| `POST /state/clean` | `{"olderThanHours"}` (JSON body required); returns `removed`, `olderThanHours`, `sessionsDir` |
+
+`GET /state/list` returns `{states, count}`; saved files live under
+`<stateDir>/sessions/`.
+
See [Endpoints](../endpoints.md) for the short route index. Use `GET /state?tabId=<id>` for the full gated browser-state view and `GET /tabs/{id}/state` for live readiness/blocking data.
## Related
diff --git a/docs/reference/strategies.md b/docs/reference/strategies.md
index 36cd0767..77aefc03 100644
--- a/docs/reference/strategies.md
+++ b/docs/reference/strategies.md
@@ -43,8 +43,8 @@ Best fit:
Behavior:
- you start instances explicitly with `/instances/start`, `/instances/launch`, or `/profiles/{id}/start`
-- shorthand routes proxy to the first running instance only if one already exists
-- if nothing is running, shorthand routes return an error instead of launching a browser for you
+- shorthand routes proxy to the earliest-started running instance (of the default browser target) only if one already exists
+- if nothing is running, shorthand routes return `503 no running instances — launch one from the Profiles tab` instead of launching a browser for you; `GET /tabs` returns an empty list
Best fit:
@@ -61,7 +61,8 @@ Behavior:
- launches one managed instance when the strategy starts
- exposes the same shorthand routes as `simple`
- watches that managed instance and keeps restarting it after unexpected exits until the configured restart limit is reached
-- exposes `GET /always-on/status` for current managed-instance state
+- exposes `GET /always-on/status` for current managed-instance state: `instanceId`, `restartCount`, `maxRestarts`,
+ `lastCrash`, `lastStart`, and `status` (`running`, `restarting`, `crashed`, or `stopped`)
Best fit:
@@ -78,7 +79,9 @@ Behavior:
- launches one managed instance when the strategy starts
- exposes the same shorthand routes as `simple`
- watches that managed instance and tries to restart it after unexpected exits under the configured restart policy
-- exposes `GET /autorestart/status` for restart state
+- exposes `GET /autorestart/status` for restart state (same shape as `/always-on/status`)
+
+Both managed strategies take their limits from `multiInstance.restart`; `maxRestarts: -1` means unlimited.
Best fit:
@@ -111,7 +114,12 @@ Valid policies in the current implementation:
- `round_robin`
- `random`
-Allocation policy matters only when PinchTab has multiple eligible running instances and needs to choose one. If your request already targets `/instances/{id}/...`, no allocation policy is involved for that request.
+Allocation policy is meant for the case where PinchTab has multiple eligible running instances and needs to choose one.
+If your request already targets `/instances/{id}/...`, no allocation policy is involved for that request.
+
+**Current behavior:** the value is validated and loaded into the orchestrator's allocator, but no request path
+consults that allocator yet. Shorthand routes always go to the earliest-started running instance of the requested
+(or default) browser target, which is what `fcfs` describes, whichever policy is configured.
### `fcfs`
diff --git a/docs/reference/tabs.md b/docs/reference/tabs.md
index a5a3a3f0..b2508312 100644
--- a/docs/reference/tabs.md
+++ b/docs/reference/tabs.md
@@ -8,10 +8,11 @@ Use tab-scoped HTTP routes once you already have a tab ID. In the CLI, use the n
- listing tabs
- focusing a tab
-- opening a new tab
- closing a tab
+- human handoff (`handoff`, `handoff-status`, `resume`)
-There are no subcommands such as `pinchtab tab navigate` or `pinchtab tab click`.
+Open a new tab with `pinchtab nav <url> --new-tab`. There are no subcommands such as
+`pinchtab tab navigate` or `pinchtab tab click`.
## Top-Level Browser Commands
@@ -69,7 +70,8 @@ curl http://localhost:9867/tabs
"id": "8f9c7d4e1234567890abcdef12345678",
"url": "https://pinchtab.com",
"title": "PinchTab",
- "type": "page"
+ "type": "page",
+ "status": "active"
}
]
}
@@ -86,6 +88,10 @@ Notes:
- `GET /tabs` is not a fleet-wide inventory
- in bridge mode or shorthand mode it lists tabs from the active browser context
- `pinchtab tab` follows that shorthand behavior
+- the current tab is listed first
+- tabs on `about:blank`, `chrome://`, `chrome-extension://`, `devtools://`, `file://` or the server's own port are not listed
+- `status` is `active`, or `paused_handoff` with `handoffReason` and `pausedAt`; a locked tab also carries `owner` and `lockedUntil`,
+ and `browserContextId` appears when the tab has one
### Tabs For One Instance
@@ -101,6 +107,9 @@ curl http://localhost:9867/instances/tabs
Use `GET /instances/tabs` when you need the orchestrator-wide view.
+Both instance routes return a bare JSON array of `{"id","instanceId","url","title"}` objects.
+Results are cached per instance; add `?fresh=1` to refetch.
+
## Focus And Close From The CLI
```bash
@@ -285,17 +294,23 @@ Tab locking is API-only.
```bash
curl -X POST http://localhost:9867/tabs/<tabId>/lock \
-H "Content-Type: application/json" \
- -d '{"owner":"my-agent","ttl":60}'
+ -d '{"owner":"my-agent","timeoutSec":60}'
curl -X POST http://localhost:9867/tabs/<tabId>/unlock \
-H "Content-Type: application/json" \
-d '{"owner":"my-agent"}'
```
-There are also active-tab forms at `POST /lock` and `POST /unlock`.
+`owner` is required. `timeoutSec` is optional and defaults to 10 minutes. Lock answers
+`{"locked":true,"owner":"...","expiresAt":"..."}`, unlock answers `{"unlocked":true}`, and a
+conflicting owner gets `409`.
+
+There are also root forms at `POST /lock` and `POST /unlock`; they take the tab in the body
+as `tabId` (required).
## Important Limits
-- There is no `GET /tabs/{id}` endpoint for fetching single-tab metadata.
+- There is no `GET /tabs/{id}` endpoint. `GET /tabs/{id}/state` reports one tab's `tabId`, `url`, `title`,
+ `dialogPresent`/`dialog`, `load` (`readyState`, `navigationInProgress`, `networkIdle`, `state`) and `actionability`.
- `GET /tabs` and `GET /instances/tabs` serve different purposes and are not interchangeable.
- In the CLI, tab-scoped work happens through top-level commands with `--tab`, not through `pinchtab tab <subcommand>` variants — except for `handoff`, `resume`, and `handoff-status`, which are exposed both as top-level commands and as `pinchtab tab handoff|resume|handoff-status` subcommands.
diff --git a/docs/reference/text.md b/docs/reference/text.md
index f9012b62..fa24dfda 100644
--- a/docs/reference/text.md
+++ b/docs/reference/text.md
@@ -35,9 +35,17 @@ Default output is human-readable text. Use `--json` for structured output:
```bash
pinchtab text # Plain text output
-pinchtab text --json # JSON: {"url":"...","title":"...","text":"..."}
+pinchtab text --json # JSON envelope: url, title, text, truncated, extraction, textLength, rawLength, ...
```
+An element read (`selector`/`ref`) returns just `{url, title, text}` — the element's
+`innerText` — and ignores `mode`.
+
+When a modal dialog is open in the page, a whole-page read returns the topmost dialog's
+text (reported as `raw`) and element selectors resolve inside it. If the topmost dialog
+changes twice during the read the request fails with `409`; a pending JavaScript dialog
+(alert, confirm, prompt) blocks it with `409 dialog_blocked`.
+
## Extraction Mode
Readability is an article heuristic, so on a landing page, dashboard, or docs
@@ -53,7 +61,8 @@ text:
| `rawLength` | Length of `document.body.innerText`, so coverage is computable |
With `format=text` the body stays bare and the mode is reported in the
-`X-PT-Text-Extraction` response header. `mode=raw` never runs the comparison.
+`X-PT-Text-Extraction` response header (`text/markdown` content type for the
+Markdown modes). `mode=raw` never runs the comparison.
`truncated` keeps its meaning — text cut by `maxChars` — and is unaffected by a
fallback. The CLI prints a one-line note on stderr when a fallback fired; stdout
stays text-only.
@@ -113,9 +122,12 @@ curl "http://localhost:9867/text?frameId=FRAME123&format=text"
| `selector` | Element selector for text extraction |
| `ref` | Snapshot ref (e.g., `e5`) |
| `frameId` | Target iframe ID |
-| `mode` | `raw` for innerText, `markdown` for Markdown, default for Readability |
-| `maxChars` | Truncate output |
-| `format` | `text` for plain text response |
+| `tabId` | Target tab (defaults to the current tab) |
+| `mode` | `raw` or its alias `full` for innerText, `markdown` for Markdown, omitted for Readability; any other value is a 400 |
+| `maxChars` | Truncate output to this many characters (positive integer; Markdown is cut on line boundaries) |
+| `format` | `text` or `plain` for a bare text response; default is the JSON envelope |
+
+`GET /tabs/{id}/text` is the same handler with the tab in the path.
Use default mode for article-like pages. Use `--full` / `mode=raw` for UI-heavy
pages such as dashboards, SERPs, grids, pricing tables, or short log panes that
diff --git a/docs/scrape.md b/docs/scrape.md
index d5e75bb9..646f36e3 100644
--- a/docs/scrape.md
+++ b/docs/scrape.md
@@ -110,7 +110,7 @@ Each HTTP-extracted page is scored for whether the browser should re-render it:
- **thin-content** (extraction shorter than the static-ok threshold) routes: a
probable JavaScript shell.
-`--enrich-all` forces every non-404 page to the browser; `--no-browser` records
+`--enrich-all` forces every page except not-found (404 / 410) to the browser; `--no-browser` records
the verdict on each page but renders nothing.
## Report anatomy
diff --git a/docs/showcase.md b/docs/showcase.md
index b4ad0c72..8cd1e1df 100644
--- a/docs/showcase.md
+++ b/docs/showcase.md
@@ -12,6 +12,9 @@ pinchtab daemon install
Starting an instance may be optional, depending on strategy/config.
+The HTTP API requires the server token. The `curl` examples on this page omit it for brevity;
+add `-H "Authorization: Bearer $PINCHTAB_TOKEN"` after `export PINCHTAB_TOKEN=$(pinchtab config token --stdout)`. The CLI alternatives read the token from your config.
+
```bash
curl -s -X POST http://127.0.0.1:9867/instances/start \
-H "Content-Type: application/json" \
@@ -22,7 +25,7 @@ pinchtab instance start
{
"id": "inst_0a89a5bb",
"profileId": "prof_278be873",
- "profileName": "instance-1741400000000000000",
+ "profileName": "instance-1741400000000000000-9f3c2a1b",
"port": "9868",
"mode": "headless",
"headless": true,
@@ -96,7 +99,7 @@ pinchtab click e14
### Screenshot
```bash
-curl -s http://127.0.0.1:9867/screenshot > smoke.jpg
+curl -s "http://127.0.0.1:9867/screenshot?raw=true" > smoke.jpg
ls -lh smoke.jpg
# CLI Alternative
pinchtab screenshot -o smoke.jpg
@@ -107,7 +110,7 @@ Saved smoke.jpg (55876 bytes)
### Export a PDF
```bash
-curl -s http://127.0.0.1:9867/pdf > smoke.pdf
+curl -s "http://127.0.0.1:9867/pdf?raw=true" > smoke.pdf
ls -lh smoke.pdf
# CLI Alternative
pinchtab pdf -o smoke.pdf
@@ -157,7 +160,7 @@ pinchtab press Enter
### Generate artifacts
```bash
-curl -s http://127.0.0.1:9867/pdf > report.pdf
+curl -s "http://127.0.0.1:9867/pdf?raw=true" > report.pdf
ls -lh report.pdf
# CLI Alternative
pinchtab pdf -o report.pdf
@@ -166,7 +169,7 @@ Saved report.pdf (1494657 bytes)
```
```bash
-curl -s http://127.0.0.1:9867/screenshot > page.jpg
+curl -s "http://127.0.0.1:9867/screenshot?raw=true" > page.jpg
ls -lh page.jpg
# CLI Alternative
pinchtab screenshot -o page.jpg
@@ -185,6 +188,8 @@ This fits:
When Chrome is already running in remote-debugging mode, PinchTab can attach to it and expose it through the same API.
+Attach is disabled by default; enable it first with `pinchtab config set security.attach.enabled true` and restart the server.
+
### 1. Start Chrome with remote debugging
```bash