Skip to content

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

docs: add comprehensive CLI design and quick reference guides

Mario851ec1dbd340
diff --git a/docs/index.json b/docs/index.json
index e587a98a..e87f96a0 100644
--- a/docs/index.json
+++ b/docs/index.json
@@ -8,9 +8,11 @@
"showcase.md"
],
"references": [
- "references/endpoints.md",
+ "references/api-reference.json",
"references/configuration.md",
- "references/api-reference.json"
+ "references/cli-design.md",
+ "references/cli-implementation.md",
+ "references/cli-quick-reference.md"
],
"architecture": [
"architecture/architecture-overview.md",
diff --git a/docs/references/cli-design.md b/docs/references/cli-design.md
new file mode 100644
index 00000000..240bf425
--- /dev/null
+++ b/docs/references/cli-design.md
@@ -0,0 +1,366 @@
+# PinchTab CLI Design Guide
+
+## Principles
+
+1. **Hierarchical path mirroring** — CLI command structure mirrors HTTP endpoints
+2. **Resource-oriented** — `pinchtab <resource> <action>` not `pinchtab <action>`
+3. **Consistent argument order** — `<resource> <id> <sub-resource> <sub-id> <action> [flags] [payload]`
+4. **Smart payload handling** — Flags for simple cases, stdin/JSON for complex payloads
+5. **No breaking changes** — Always maintain backward compatibility
+
+## Command Structure
+
+### Pattern 1: List Resources
+```
+pinchtab <resource> List all resources
+```
+
+**Examples:**
+```bash
+pinchtab instances # GET /instances
+pinchtab profiles # GET /profiles
+```
+
+**Output:** JSON array (auto-formatted)
+
+### Pattern 2: Manage Resource (Orchestrator)
+```
+pinchtab <resource> <action> Orchestrator-level actions
+pinchtab <resource> <id> <action> Instance-scoped actions
+```
+
+**Examples:**
+```bash
+pinchtab instance launch --mode headed --port 9869
+pinchtab instance <id> logs
+pinchtab instance <id> stop
+```
+
+**HTTP mapping:**
+- `pinchtab instance launch [flags]` → `POST /instances/launch {mode, port}`
+- `pinchtab instance <id> logs` → `GET /instances/<id>/logs`
+- `pinchtab instance <id> stop` → `POST /instances/<id>/stop`
+
+### Pattern 3: Browser Control (Instance-scoped)
+```
+pinchtab [--instance <id>] <action> [args] [flags]
+```
+
+**Examples:**
+```bash
+# Default instance (auto-detected from PINCHTAB_INSTANCE env or from running instance)
+pinchtab nav https://example.com
+pinchtab snap -i -c
+pinchtab click e5
+
+# Explicit instance
+pinchtab --instance inst_abc123 nav https://example.com
+pinchtab --instance inst_abc123 snap
+```
+
+**HTTP mapping:**
+- `pinchtab nav <url>` → `POST /navigate {url}`
+- `pinchtab --instance <id> snap` → `POST /instances/<id>/snapshot`
+- `pinchtab --instance <id> click <ref>` → `POST /instances/<id>/action {kind: "click", ref}`
+
+### Pattern 4: Nested Resources (Tabs within Instance)
+```
+pinchtab --instance <id> tab <action> [args] List/manage tabs
+pinchtab --instance <id> tab <tabId> <action> Operate on specific tab
+```
+
+**Examples:**
+```bash
+# List tabs
+pinchtab --instance inst_abc123 tabs # GET /instances/<id>/tabs
+
+# Create tab
+pinchtab --instance inst_abc123 tab create https://example.com
+ # POST /instances/<id>/tab {url}
+
+# Navigate tab
+pinchtab --instance inst_abc123 tab <tabId> navigate https://example.com
+ # POST /instances/<id>/tab/navigate {tabId, url}
+
+# Close tab
+pinchtab --instance inst_abc123 tab <tabId> close
+ # POST /instances/<id>/tab/close {tabId}
+
+# Lock tab
+pinchtab --instance inst_abc123 tab <tabId> lock --owner agent1 --ttl 60
+ # POST /instances/<id>/tab/lock {tabId, owner, ttl}
+```
+
+### Pattern 5: Complex Payloads
+
+#### Option A: Flags (simple cases)
+```bash
+pinchtab --instance <id> navigate https://example.com --block-images --block-ads --timeout 30
+```
+
+Maps to:
+```json
+POST /instances/<id>/navigate
+{
+ "url": "https://example.com",
+ "blockImages": true,
+ "blockAds": true,
+ "timeout": 30
+}
+```
+
+#### Option B: JSON stdin (complex cases)
+```bash
+cat << 'EOF' | pinchtab --instance <id> action
+{
+ "kind": "select",
+ "ref": "e5",
+ "value": "option2",
+ "waitNav": true
+}
+EOF
+```
+
+Or:
+```bash
+pinchtab --instance <id> action -f payload.json
+pinchtab --instance <id> action --json '{...}'
+```
+
+#### Option C: Shell-friendly formats
+```bash
+# String payload (auto-quoted)
+pinchtab --instance <id> evaluate 'document.title'
+
+# File reference
+pinchtab --instance <id> upload --file screenshot.png --to /form/input
+
+# Multi-line (heredoc)
+pinchtab --instance <id> action << 'EOF'
+{
+ "kind": "actions",
+ "actions": [
+ {"kind": "click", "ref": "e5"},
+ {"kind": "type", "ref": "e12", "text": "hello"}
+ ]
+}
+EOF
+```
+
+## Mapping: Endpoints → CLI Commands
+
+### Instance Management
+| Endpoint | HTTP | CLI Command |
+|----------|------|-------------|
+| `/instances` | GET | `pinchtab instances` |
+| `/instances/launch` | POST | `pinchtab instance launch --mode headed --port 9869` |
+| `/instances/{id}/logs` | GET | `pinchtab instance <id> logs` |
+| `/instances/{id}/stop` | POST | `pinchtab instance <id> stop` |
+
+### Browser Control (Single Instance)
+| Endpoint | HTTP | CLI Command |
+|----------|------|-------------|
+| `/navigate` | POST | `pinchtab nav https://example.com` |
+| `/snapshot` | GET | `pinchtab snap -i -c` |
+| `/screenshot` | GET | `pinchtab ss -o out.png` |
+| `/action` | POST | `pinchtab click e5` |
+| `/actions` | POST | `pinchtab action -f actions.json` |
+| `/tab` | POST | `pinchtab tab create https://example.com` |
+| `/tabs` | GET | `pinchtab tabs` |
+| `/evaluate` | POST | `pinchtab eval "document.title"` |
+| `/pdf` | GET | `pinchtab pdf -o out.pdf --landscape` |
+| `/text` | GET | `pinchtab text` |
+| `/text` | GET | `pinchtab text --raw` |
+| `/cookies` | GET | `pinchtab cookies` |
+| `/cookies` | POST | `pinchtab cookies --set 'name=value; domain=.example.com'` |
+
+### Orchestrator Proxying (Instance-scoped)
+| Endpoint | HTTP | CLI Command |
+|----------|------|-------------|
+| `/instances/{id}/navigate` | POST | `pinchtab --instance <id> nav https://example.com` |
+| `/instances/{id}/snapshot` | GET | `pinchtab --instance <id> snap -i` |
+| `/instances/{id}/screenshot` | GET | `pinchtab --instance <id> ss` |
+| `/instances/{id}/action` | POST | `pinchtab --instance <id> action -k click -r e5` |
+| `/instances/{id}/tab` | POST | `pinchtab --instance <id> tab create https://example.com` |
+| `/instances/{id}/tabs` | GET | `pinchtab --instance <id> tabs` |
+| `/instances/{id}/evaluate` | POST | `pinchtab --instance <id> eval 'code'` |
+| `/instances/{id}/pdf` | GET | `pinchtab --instance <id> pdf -o out.pdf` |
+
+## Real-World Examples
+
+### Example 1: Launch instance and navigate
+```bash
+# Start dashboard (separate terminal)
+pinchtab
+
+# In another terminal:
+INST=$(pinchtab instance launch --mode headed --port 9869 | jq -r .id)
+echo "Started instance: $INST"
+
+# Navigate in that instance
+pinchtab --instance $INST nav https://github.com/pinchtab/pinchtab
+```
+
+### Example 2: Snapshot and click
+```bash
+# See page structure
+pinchtab --instance inst_abc123 snap -i -c | jq .
+
+# Click a button
+pinchtab --instance inst_abc123 click e5
+
+# See what changed
+pinchtab --instance inst_abc123 snap -d
+```
+
+### Example 3: Multi-step workflow
+```bash
+# Get instances
+pinchtab instances
+
+# Check instance status
+pinchtab instance inst_abc123 logs
+
+# Run actions on instance
+cat << 'EOF' | pinchtab --instance inst_abc123 action
+{
+ "kind": "actions",
+ "actions": [
+ {"kind": "click", "ref": "e1"},
+ {"kind": "type", "ref": "e2", "text": "search query"},
+ {"kind": "press", "key": "Enter"},
+ {"kind": "wait", "time": 2000}
+ ]
+}
+EOF
+
+# Capture result
+pinchtab --instance inst_abc123 snap -c > page.json
+```
+
+### Example 4: Tab management
+```bash
+# List tabs
+pinchtab --instance inst_abc123 tabs
+
+# Create new tab
+TAB_ID=$(pinchtab --instance inst_abc123 tab create https://example.com | jq -r .id)
+
+# Lock tab (prevent other agents from using it)
+pinchtab --instance inst_abc123 tab $TAB_ID lock --owner my-agent --ttl 60
+
+# Navigate in locked tab
+pinchtab --instance inst_abc123 tab $TAB_ID navigate https://google.com
+
+# Unlock
+pinchtab --instance inst_abc123 tab $TAB_ID unlock --owner my-agent
+
+# Close tab
+pinchtab --instance inst_abc123 tab $TAB_ID close
+```
+
+## Environment Variables
+
+```bash
+# Default instance for commands without --instance flag
+export PINCHTAB_INSTANCE=inst_abc123
+
+# Server URL/port
+export PINCHTAB_URL=http://localhost:9867
+export BRIDGE_PORT=9867
+
+# Authentication
+export PINCHTAB_TOKEN=sk_...
+
+# Default behavior
+export PINCHTAB_FORMAT=json # json, text, table
+export PINCHTAB_NO_COLOR=1 # Disable colored output
+export PINCHTAB_TIMEOUT=30 # Request timeout in seconds
+```
+
+## Flag Conventions
+
+### Common Flags (all commands)
+```
+--instance <id> Target instance (overrides PINCHTAB_INSTANCE)
+--tab <id> Target tab within instance
+--timeout N Request timeout in seconds (default: 30)
+--raw Raw output (no formatting)
+--json Output as JSON
+```
+
+### Snapshot Flags
+```
+-i, --interactive Interactive elements only
+-c, --compact Compact format (most token-efficient)
+-d, --diff Only changes since last snapshot
+-s, --selector CSS Scope to CSS selector
+--max-tokens N Truncate to ~N tokens
+--depth N Max tree depth
+```
+
+### Screenshot Flags
+```
+-o, --output FILE Output filename
+-q, --quality 0-100 JPEG quality (default: 80)
+--format png|jpeg Output format
+```
+
+### PDF Flags
+```
+-o, --output FILE Output filename
+--landscape Landscape orientation
+--paper-width N Width in inches (default: 8.5)
+--paper-height N Height in inches (default: 11)
+--margin-top/bottom/left/right N
+--scale N Print scale 0.1-2.0
+--page-ranges "1-3,5" Pages to export
+```
+
+### Navigation Flags
+```
+--block-images Skip loading images
+--block-ads Block ad requests
+--block-media Skip media (video, audio)
+--timeout N Navigation timeout in seconds
+--new-tab Open in new tab (for orchestrator)
+```
+
+## Error Handling
+
+All commands follow this pattern:
+```
+exit 0 — Success
+exit 1 — User error (bad args, file not found)
+exit 2 — Server error (500, connection refused)
+exit 3 — Timeout
+exit 4 — Instance/resource not found
+```
+
+Error messages always printed to stderr:
+```bash
+pinchtab --instance nonexistent snap 2>&1
+# Error: instance not found: nonexistent
+# exit: 4
+```
+
+## Future Extensibility
+
+This design scales to:
+- **Three-level nesting**: `pinchtab instance <id> tab <tabId> screencast <action>`
+- **Bulk operations**: `pinchtab instances exec 'snap -c' --all`
+- **Piping**: `pinchtab instances | jq '.[] | .id' | xargs -I {} pinchtab instance {} snap`
+- **Streaming**: `pinchtab --instance <id> screencast --stream` (server-sent events)
+- **REPL mode**: `pinchtab repl --instance <id>` (interactive shell)
+
+## Implementation Checklist
+
+- [ ] Implement `pinchtab instance <id> navigate <url>` (proxy to instance)
+- [ ] Implement `pinchtab --instance <id> tab <tabId> navigate <url>`
+- [ ] Add `--instance` flag to all browser control commands
+- [ ] Support stdin JSON for complex payloads
+- [ ] Support `-f` flag for reading payload from file
+- [ ] Add error handling with proper exit codes
+- [ ] Add `PINCHTAB_INSTANCE` environment variable support
+- [ ] Document in help (`pinchtab help`)
+- [ ] Add shell completion (`_bash`, `_zsh`)
diff --git a/docs/references/cli-implementation.md b/docs/references/cli-implementation.md
new file mode 100644
index 00000000..fdb2cc0e
--- /dev/null
+++ b/docs/references/cli-implementation.md
@@ -0,0 +1,469 @@
+# PinchTab CLI Implementation Guide
+
+## Payload Handling Patterns
+
+### Pattern 1: Simple Flags → JSON Body
+
+**CLI:**
+```bash
+pinchtab instance launch --mode headed --port 9869
+```
+
+**Implementation:**
+```go
+func cliInstanceLaunch(client *http.Client, base, token string, args []string) {
+ body := map[string]any{}
+
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "--mode":
+ if i+1 < len(args) {
+ body["mode"] = args[i+1]
+ i++
+ }
+ case "--port":
+ if i+1 < len(args) {
+ body["port"] = args[i+1]
+ i++
+ }
+ }
+ }
+
+ doPost(client, base, token, "/instances/launch", body)
+}
+```
+
+**Result:** `POST /instances/launch {"mode": "headed", "port": "9869"}`
+
+---
+
+### Pattern 2: Positional Arguments → Path Params
+
+**CLI:**
+```bash
+pinchtab instance inst_abc123 stop
+pinchtab instance inst_abc123 logs
+```
+
+**Implementation:**
+```go
+func cliInstanceStop(client *http.Client, base, token string, args []string) {
+ if len(args) < 1 {
+ fatal("Usage: pinchtab instance stop <instance-id>")
+ }
+
+ instID := args[0]
+ doPost(client, base, token, fmt.Sprintf("/instances/%s/stop", instID), nil)
+}
+```
+
+**Result:** `POST /instances/inst_abc123/stop`
+
+---
+
+### Pattern 3: Stdin JSON for Complex Payloads
+
+**CLI:**
+```bash
+cat << 'EOF' | pinchtab --instance inst_abc123 action
+{
+ "kind": "actions",
+ "actions": [
+ {"kind": "click", "ref": "e5"},
+ {"kind": "type", "ref": "e12", "text": "hello"}
+ ]
+}
+EOF
+```
+
+**Implementation:**
+```go
+func cliAction(client *http.Client, base, token string, cmd string, args []string) {
+ // Check if stdin has data
+ info, _ := os.Stdin.Stat()
+ if (info.Mode() & os.ModeCharDevice) == 0 {
+ // Stdin is piped - read JSON from stdin
+ body := readJSONFromStdin()
+ instanceID := getInstanceID(args)
+ doPost(client, base, token, fmt.Sprintf("/instances/%s/action", instanceID), body)
+ return
+ }
+
+ // Otherwise, parse from flags/args
+ body := parseActionFlags(cmd, args)
+ instanceID := getInstanceID(args)
+ doPost(client, base, token, fmt.Sprintf("/instances/%s/action", instanceID), body)
+}
+
+func readJSONFromStdin() map[string]any {
+ decoder := json.NewDecoder(os.Stdin)
+ var body map[string]any
+ if err := decoder.Decode(&body); err != nil {
+ fatal("Invalid JSON from stdin: %v", err)
+ }
+ return body
+}
+```
+
+**Result:** `POST /instances/inst_abc123/action` with JSON body from stdin
+
+---
+
+### Pattern 4: File Input via Flag
+
+**CLI:**
+```bash
+pinchtab --instance inst_abc123 action -f actions.json
+pinchtab --instance inst_abc123 action --json '{"kind": "click", "ref": "e5"}'
+```
+
+**Implementation:**
+```go
+func cliAction(client *http.Client, base, token string, cmd string, args []string) {
+ var body map[string]any
+
+ // Check for file input
+ for i := 0; i < len(args); i++ {
+ if args[i] == "-f" || args[i] == "--file" {
+ if i+1 < len(args) {
+ data, err := os.ReadFile(args[i+1])
+ if err != nil {
+ fatal("Failed to read file: %v", err)
+ }
+ if err := json.Unmarshal(data, &body); err != nil {
+ fatal("Invalid JSON in file: %v", err)
+ }
+ instanceID := getInstanceID(args)
+ doPost(client, base, token, fmt.Sprintf("/instances/%s/action", instanceID), body)
+ return
+ }
+ } else if args[i] == "--json" {
+ if i+1 < len(args) {
+ if err := json.Unmarshal([]byte(args[i+1]), &body); err != nil {
+ fatal("Invalid JSON: %v", err)
+ }
+ instanceID := getInstanceID(args)
+ doPost(client, base, token, fmt.Sprintf("/instances/%s/action", instanceID), body)
+ return
+ }
+ }
+ }
+
+ // Fall back to regular flag parsing
+ body = parseActionFlags(cmd, args)
+ instanceID := getInstanceID(args)
+ doPost(client, base, token, fmt.Sprintf("/instances/%s/action", instanceID), body)
+}
+```
+
+**Result:** JSON loaded from file or string
+
+---
+
+### Pattern 5: Nested Resources (Tabs)
+
+**CLI:**
+```bash
+# List tabs
+pinchtab --instance inst_abc123 tabs
+
+# Create tab
+pinchtab --instance inst_abc123 tab create https://example.com
+
+# Navigate specific tab
+pinchtab --instance inst_abc123 tab tab_xyz navigate https://google.com
+
+# Lock tab
+pinchtab --instance inst_abc123 tab tab_xyz lock --owner agent1 --ttl 60
+```
+
+**Implementation:**
+```go
+func cliTabs(client *http.Client, base, token string, args []string) {
+ if len(args) == 0 {
+ // pinchtab --instance <id> tabs → List tabs
+ instanceID := getInstanceID(args)
+ doGet(client, base, token, fmt.Sprintf("/instances/%s/tabs", instanceID))
+ return
+ }
+
+ action := args[0]
+ subArgs := args[1:]
+ instanceID := getInstanceID(args[2:]) // Skip 'tab' and action
+
+ switch action {
+ case "create":
+ if len(subArgs) < 1 {
+ fatal("Usage: pinchtab tab create <url>")
+ }
+ body := map[string]any{"url": subArgs[0]}
+ doPost(client, base, token, fmt.Sprintf("/instances/%s/tab", instanceID), body)
+
+ case "close":
+ if len(subArgs) < 1 {
+ fatal("Usage: pinchtab tab <tabId> close")
+ }
+ tabID := subArgs[0]
+ body := map[string]any{"tabId": tabID}
+ doPost(client, base, token, fmt.Sprintf("/instances/%s/tab/close", instanceID), body)
+
+ case "navigate":
+ if len(subArgs) < 2 {
+ fatal("Usage: pinchtab tab <tabId> navigate <url>")
+ }
+ tabID := subArgs[0]
+ url := subArgs[1]
+ body := map[string]any{"tabId": tabID, "url": url}
+ doPost(client, base, token, fmt.Sprintf("/instances/%s/tab/navigate", instanceID), body)
+
+ case "lock":
+ if len(subArgs) < 1 {
+ fatal("Usage: pinchtab tab <tabId> lock [--owner name] [--ttl seconds]")
+ }
+ tabID := subArgs[0]
+ body := map[string]any{"tabId": tabID}
+
+ // Parse flags
+ for i := 1; i < len(subArgs); i++ {
+ switch subArgs[i] {
+ case "--owner":
+ if i+1 < len(subArgs) {
+ body["owner"] = subArgs[i+1]
+ i++
+ }
+ case "--ttl":
+ if i+1 < len(subArgs) {
+ ttl, _ := strconv.Atoi(subArgs[i+1])
+ body["ttl"] = ttl
+ i++
+ }
+ }
+ }
+
+ doPost(client, base, token, fmt.Sprintf("/instances/%s/tab/lock", instanceID), body)
+ }
+}
+```
+
+**Result:**
+- `GET /instances/inst_abc123/tabs`
+- `POST /instances/inst_abc123/tab {"url": "..."}`
+- `POST /instances/inst_abc123/tab/navigate {"tabId": "...", "url": "..."}`
+- `POST /instances/inst_abc123/tab/lock {"tabId": "...", "owner": "...", "ttl": 60}`
+
+---
+
+## Global Flag Handling
+
+### Instance Selection
+
+**Goals:**
+1. Support explicit `--instance <id>` flag
+2. Fallback to `PINCHTAB_INSTANCE` env var
+3. Fallback to single running instance (if only one)
+
+**Implementation:**
+```go
+func getInstanceID(args []string) string {
+ // Check for explicit --instance flag
+ for i := 0; i < len(args)-1; i++ {
+ if args[i] == "--instance" {
+ return args[i+1]
+ }
+ }
+
+ // Check env var
+ if id := os.Getenv("PINCHTAB_INSTANCE"); id != "" {
+ return id
+ }
+
+ // For bridge mode (single instance), instances list will have exactly 1
+ // and we can use it if no explicit instance was provided
+ // This is optional - caller can still require --instance
+
+ fatal("instance not specified: use --instance <id> or set PINCHTAB_INSTANCE")
+ return ""
+}
+
+func removeInstanceFlag(args []string) []string {
+ result := []string{}
+ skip := false
+
+ for i, arg := range args {
+ if skip {
+ skip = false
+ continue
+ }
+ if arg == "--instance" && i+1 < len(args) {
+ skip = true
+ continue
+ }
+ result = append(result, arg)
+ }
+
+ return result
+}
+```
+
+---
+
+## Error Handling
+
+**Standard Exit Codes:**
+```go
+const (
+ ExitOK = 0 // Success
+ ExitUserError = 1 // Bad arguments, file not found
+ ExitServerError = 2 // Server 5xx or connection refused
+ ExitTimeout = 3 // Request timed out
+ ExitNotFound = 4 // Resource not found (404)
+ ExitUnauthorized = 5 // Auth failed (401)
+ ExitConflict = 6 // Conflict (409)
+)
+
+func doPost(client *http.Client, base, token, path string, body any) error {
+ // ... make request ...
+
+ resp, err := client.Do(req)
+ if err != nil {
+ // Network error
+ fmt.Fprintf(os.Stderr, "Error: %v\n", err)
+ os.Exit(ExitServerError)
+ }
+
+ defer resp.Body.Close()
+ responseBody, _ := io.ReadAll(resp.Body)
+
+ switch resp.StatusCode {
+ case 200, 201:
+ // Success - print response
+ fmt.Println(string(responseBody))
+ case 400:
+ fmt.Fprintf(os.Stderr, "Error: invalid request\n")
+ fmt.Fprintf(os.Stderr, "%s\n", string(responseBody))
+ os.Exit(ExitUserError)
+ case 404:
+ fmt.Fprintf(os.Stderr, "Error: not found\n")
+ os.Exit(ExitNotFound)
+ case 409:
+ fmt.Fprintf(os.Stderr, "Error: conflict (resource already exists or in use)\n")
+ os.Exit(ExitConflict)
+ case 500, 503:
+ fmt.Fprintf(os.Stderr, "Error: server error (%d)\n", resp.StatusCode)
+ fmt.Fprintf(os.Stderr, "%s\n", string(responseBody))
+ os.Exit(ExitServerError)
+ default:
+ fmt.Fprintf(os.Stderr, "Error: HTTP %d\n", resp.StatusCode)
+ os.Exit(ExitServerError)
+ }
+
+ return nil
+}
+
+func fatal(format string, args ...any) {
+ fmt.Fprintf(os.Stderr, "Error: "+format+"\n", args...)
+ os.Exit(ExitUserError)
+}
+```
+
+---
+
+## Testing CLI Commands
+
+### Unit Test Example
+```go
+func TestCliInstanceLaunch(t *testing.T) {
+ // Mock server
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "POST" || r.URL.Path != "/instances/launch" {
+ t.Errorf("expected POST /instances/launch, got %s %s", r.Method, r.URL.Path)
+ }
+
+ var body map[string]any
+ json.NewDecoder(r.Body).Decode(&body)
+
+ if body["mode"] != "headed" || body["port"] != "9869" {
+ t.Errorf("unexpected body: %v", body)
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusCreated)
+ json.NewEncoder(w).Encode(map[string]string{"id": "inst_123"})
+ }))
+ defer server.Close()
+
+ client := &http.Client{}
+ args := []string{"--mode", "headed", "--port", "9869"}
+
+ // Should not panic
+ cliInstanceLaunch(client, server.URL, "", args)
+}
+```
+
+### Integration Test Example
+```bash
+#!/bin/bash
+# test-cli.sh
+
+set -e
+
+# Start server
+./pinchtab &
+SERVER_PID=$!
+sleep 2
+
+trap "kill $SERVER_PID" EXIT
+
+# Test instance launch
+RESP=$(./pinchtab instance launch --mode headed --port 9999)
+INST_ID=$(echo "$RESP" | jq -r .id)
+echo "✓ Launched instance: $INST_ID"
+
+# Test with --instance flag
+./pinchtab --instance $INST_ID snap -c > /tmp/snap.json
+echo "✓ Snapshot with --instance flag"
+
+# Test JSON stdin
+echo '{"kind": "click", "ref": "e5"}' | ./pinchtab --instance $INST_ID action
+echo "✓ Action with stdin JSON"
+
+# Test file input
+echo '{"kind": "navigate", "url": "https://example.com"}' > /tmp/nav.json
+./pinchtab --instance $INST_ID action -f /tmp/nav.json
+echo "✓ Action with file input"
+
+echo "All tests passed!"
+```
+
+---
+
+## Documentation
+
+Update help text:
+```go
+case "instance":
+ if len(args) < 1 {
+ fmt.Print(`Instance management:
+
+Usage: pinchtab instance <command> [options]
+
+Commands:
+ launch [--mode headed|headless] [--port N] Create new instance
+ logs <id> Show instance logs
+ stop <id> Stop instance
+ <id> navigate <url> Navigate in instance
+ <id> snap [flags] Snapshot instance
+ <id> tab create <url> Create tab in instance
+ <id> tab <tabId> navigate <url> Navigate specific tab
+ <id> tab <tabId> lock [--owner name] [--ttl N] Lock tab
+ <id> tab <tabId> unlock [--owner name] Unlock tab
+
+Examples:
+ pinchtab instance launch --mode headed
+ pinchtab instance inst_abc123 logs
+ pinchtab --instance inst_abc123 snap -i -c
+ pinchtab --instance inst_abc123 tab create https://example.com
+`)
+ return
+ }
+```
diff --git a/docs/references/cli-quick-reference.md b/docs/references/cli-quick-reference.md
new file mode 100644
index 00000000..21c3c30a
--- /dev/null
+++ b/docs/references/cli-quick-reference.md
@@ -0,0 +1,483 @@
+# PinchTab CLI Quick Reference
+
+**Legend:**
+- `inst_abc123` — Instance ID
+- `tab_xyz789` — Tab ID
+- `e5` — Element reference (from snapshot)
+
+## Instance Management
+
+### Launch an instance
+```bash
+# Headless (default)
+pinchtab instance launch
+
+# Headed (with window)
+pinchtab instance launch --mode headed
+
+# On specific port
+pinchtab instance launch --port 9868
+
+# Get instance ID
+INST=$(pinchtab instance launch --mode headed | jq -r .id)
+echo $INST # inst_abc123
+```
+
+### List running instances
+```bash
+pinchtab instances
+
+# Get just IDs
+pinchtab instances | jq -r '.[] | .id'
+
+# Get specific instance
+pinchtab instances | jq '.[] | select(.id == "inst_abc123")'
+```
+
+### Instance logs
+```bash
+pinchtab instance inst_abc123 logs
+
+# Follow logs (continuous)
+pinchtab instance inst_abc123 logs | tail -f
+
+# Last 100 lines
+pinchtab instance inst_abc123 logs | tail -100
+```
+
+### Stop instance
+```bash
+pinchtab instance inst_abc123 stop
+```
+
+---
+
+## Browser Control (Single Instance)
+
+### Navigate
+```bash
+# Default instance
+pinchtab nav https://example.com
+
+# Specific instance
+pinchtab --instance inst_abc123 nav https://example.com
+
+# Open in new tab
+pinchtab --instance inst_abc123 nav https://example.com --new-tab
+
+# Without images (faster)
+pinchtab --instance inst_abc123 nav https://example.com --block-images
+```
+
+### Snapshot page
+```bash
+# Full page
+pinchtab --instance inst_abc123 snap
+
+# Interactive elements only
+pinchtab --instance inst_abc123 snap -i
+
+# Compact (token-efficient)
+pinchtab --instance inst_abc123 snap -c
+
+# Interactive + compact (best for AI)
+pinchtab --instance inst_abc123 snap -i -c
+
+# Only changes since last snapshot
+pinchtab --instance inst_abc123 snap -d
+
+# Save to file
+pinchtab --instance inst_abc123 snap > page.json
+
+# Parse in script
+pinchtab --instance inst_abc123 snap -c | jq '.elements[] | .ref' | head -5
+```
+
+### Click element
+```bash
+pinchtab --instance inst_abc123 click e5
+```
+
+### Type text
+```bash
+pinchtab --instance inst_abc123 type e12 "hello world"
+```
+
+### Fill input (directly, no events)
+```bash
+pinchtab --instance inst_abc123 fill e12 "value"
+```
+
+### Press key
+```bash
+pinchtab --instance inst_abc123 press Enter
+pinchtab --instance inst_abc123 press Tab
+pinchtab --instance inst_abc123 press Escape
+```
+
+### Scroll
+```bash
+pinchtab --instance inst_abc123 scroll down
+pinchtab --instance inst_abc123 scroll up
+pinchtab --instance inst_abc123 scroll 500 # pixels
+```
+
+### Get page text
+```bash
+pinchtab --instance inst_abc123 text
+
+# Raw text (no JSON wrapper)
+pinchtab --instance inst_abc123 text --raw
+```
+
+### Screenshot
+```bash
+# To stdout (PNG)
+pinchtab --instance inst_abc123 ss > screenshot.png
+
+# To file
+pinchtab --instance inst_abc123 ss -o out.png
+
+# JPEG with quality
+pinchtab --instance inst_abc123 ss -o out.jpg -q 85
+```
+
+### PDF export
+```bash
+# Default (A4 portrait)
+pinchtab --instance inst_abc123 pdf -o out.pdf
+
+# Landscape
+pinchtab --instance inst_abc123 pdf -o out.pdf --landscape
+
+# Letter size
+pinchtab --instance inst_abc123 pdf -o out.pdf --paper-width 8.5 --paper-height 11
+
+# Specific pages
+pinchtab --instance inst_abc123 pdf -o out.pdf --page-ranges "1-3,5"
+```
+
+### Run JavaScript
+```bash
+pinchtab --instance inst_abc123 eval "document.title"
+
+# JSON result
+pinchtab --instance inst_abc123 eval "document.querySelectorAll('a').length"
+
+# Complex script
+pinchtab --instance inst_abc123 eval '
+ JSON.stringify({
+ title: document.title,
+ url: location.href,
+ links: document.querySelectorAll("a").length
+ })
+'
+```
+
+---
+
+## Tab Management
+
+### List tabs
+```bash
+pinchtab --instance inst_abc123 tabs
+
+# Get tab IDs
+pinchtab --instance inst_abc123 tabs | jq -r '.tabs[] | .id'
+
+# Count tabs
+pinchtab --instance inst_abc123 tabs | jq '.tabs | length'
+```
+
+### Create tab
+```bash
+# Create and get ID
+TAB=$(pinchtab --instance inst_abc123 tab create https://example.com | jq -r .id)
+echo $TAB # tab_xyz789
+```
+
+### Navigate specific tab
+```bash
+pinchtab --instance inst_abc123 tab tab_xyz789 navigate https://google.com
+```
+
+### Close tab
+```bash
+pinchtab --instance inst_abc123 tab tab_xyz789 close
+```
+
+### Lock tab (prevent concurrent access)
+```bash
+# Lock for 60 seconds
+pinchtab --instance inst_abc123 tab tab_xyz789 lock --owner my-agent --ttl 60
+
+# After work, unlock
+pinchtab --instance inst_abc123 tab tab_xyz789 unlock --owner my-agent
+```
+
+---
+
+## Complex Actions
+
+### Multi-step workflow (JSON stdin)
+```bash
+cat << 'EOF' | pinchtab --instance inst_abc123 action
+{
+ "kind": "actions",
+ "actions": [
+ {"kind": "click", "ref": "e1"},
+ {"kind": "type", "ref": "e2", "text": "search query"},
+ {"kind": "press", "key": "Enter"},
+ {"kind": "wait", "time": 2000},
+ {"kind": "click", "ref": "e5"}
+ ]
+}
+EOF
+```
+
+### From file
+```bash
+# Create actions file
+cat > actions.json << 'EOF'
+{
+ "kind": "actions",
+ "actions": [
+ {"kind": "click", "ref": "e1"},
+ {"kind": "type", "ref": "e2", "text": "hello"},
+ {"kind": "press", "key": "Enter"}
+ ]
+}
+EOF
+
+# Run it
+pinchtab --instance inst_abc123 action -f actions.json
+```
+
+### From inline JSON
+```bash
+pinchtab --instance inst_abc123 action --json '{"kind":"click","ref":"e5"}'
+```
+
+---
+
+## Typical Workflow
+
+### 1. Start orchestrator
+```bash
+# Terminal 1: Start the dashboard/orchestrator
+pinchtab
+# Now listening on http://localhost:9867
+```
+
+### 2. Launch instance
+```bash
+# Terminal 2: Launch a headed instance
+INST=$(pinchtab instance launch --mode headed | jq -r .id)
+echo "Instance: $INST"
+```
+
+### 3. Navigate and interact
+```bash
+# Navigate to website
+pinchtab --instance $INST nav https://github.com/pinchtab/pinchtab
+
+# See page structure
+pinchtab --instance $INST snap -i -c | jq .
+
+# Click button (find e5 from snapshot)
+pinchtab --instance $INST click e5
+
+# See result
+pinchtab --instance $INST snap -i -c | jq '.elements[] | select(.ref == "e5")'
+```
+
+### 4. Extract data
+```bash
+# Get all visible text
+pinchtab --instance $INST text --raw
+
+# Count links
+pinchtab --instance $INST eval 'document.querySelectorAll("a").length'
+
+# Export page
+pinchtab --instance $INST pdf -o page.pdf
+```
+
+### 5. Cleanup
+```bash
+# Stop instance
+pinchtab instance $INST stop
+
+# Verify stopped
+pinchtab instances
+```
+
+---
+
+## Scripting Examples
+
+### Batch instances
+```bash
+# Launch 3 instances
+for i in {1..3}; do
+ PORT=$((9868 + i))
+ INST=$(pinchtab instance launch --mode headed --port $PORT | jq -r .id)
+ echo "Instance $i: $INST"
+done
+```
+
+### Parallel navigation
+```bash
+# Navigate multiple instances concurrently
+for inst in $(pinchtab instances | jq -r '.[] | .id'); do
+ (pinchtab --instance $inst nav https://example.com) &
+done
+wait
+
+echo "All instances navigated"
+```
+
+### Monitor instances
+```bash
+# Watch instance status
+while true; do
+ clear
+ pinchtab instances | jq -r '.[] | "\(.id) (\(.mode)): \(.status)"'
+ sleep 2
+done
+```
+
+### Cleanup all instances
+```bash
+# Stop all instances
+pinchtab instances | jq -r '.[] | .id' | xargs -I {} pinchtab instance {} stop
+```
+
+---
+
+## Troubleshooting
+
+### Check server status
+```bash
+pinchtab health
+# Should print: {"status": "ok"}
+```
+
+### View server logs
+```bash
+# If running in foreground, Ctrl+C to see logs
+# If running in background:
+jobs
+fg # bring to foreground
+```
+
+### Instance not starting?
+```bash
+# Check logs
+pinchtab instance inst_abc123 logs | tail -50
+
+# Check port availability
+lsof -i :9868
+```
+
+### Can't connect to instance?
+```bash
+# Verify instance is running
+pinchtab instances | jq '.[] | select(.id == "inst_abc123")'
+
+# Check status
+pinchtab instances | jq '.[] | select(.id == "inst_abc123") | .status'
+# Should be "running"
+```
+
+### Need to specify server address?
+```bash
+# For remote server
+export PINCHTAB_URL=http://192.168.1.100:9867
+
+# Or per-command (coming soon)
+pinchtab --server http://192.168.1.100:9867 instances
+```
+
+---
+
+## Environment Variables
+
+```bash
+# Server address (if not on localhost:9867)
+export PINCHTAB_URL=http://localhost:9867
+
+# Server port (alternative to PINCHTAB_URL)
+export BRIDGE_PORT=9868
+
+# Default instance (skip --instance flag)
+export PINCHTAB_INSTANCE=inst_abc123
+
+# Auth token
+export PINCHTAB_TOKEN=sk_xxx
+
+# Request timeout
+export PINCHTAB_TIMEOUT=30
+
+# Output format
+export PINCHTAB_FORMAT=json # json, text (coming soon)
+
+# Disable colors
+export PINCHTAB_NO_COLOR=1
+```
+
+---
+
+## Common Patterns
+
+### Wait for page load, then interact
+```bash
+pinchtab --instance inst_abc123 nav https://example.com
+sleep 2 # Wait for page
+pinchtab --instance inst_abc123 snap -i
+```
+
+### Click, wait, screenshot
+```bash
+pinchtab --instance inst_abc123 click e5
+sleep 1
+pinchtab --instance inst_abc123 ss -o result.png
+```
+
+### Form fill
+```bash
+pinchtab --instance inst_abc123 fill e1 "John Doe"
+pinchtab --instance inst_abc123 fill e2 "[email protected]"
+pinchtab --instance inst_abc123 click e3 # Submit button
+sleep 2
+pinchtab --instance inst_abc123 snap
+```
+
+### Search and verify
+```bash
+pinchtab --instance inst_abc123 nav https://google.com
+pinchtab --instance inst_abc123 fill e1 "golang"
+pinchtab --instance inst_abc123 press Enter
+sleep 2
+pinchtab --instance inst_abc123 text | grep -q "golang"
+echo "Search results found"
+```
+
+---
+
+## Exit Codes
+
+```bash
+pinchtab instance inst_abc123 logs
+echo $? # 0 = success
+
+pinchtab --instance nonexistent snap
+echo $? # 4 = not found
+
+pinchtab instance launch --invalid-flag
+echo $? # 1 = user error
+
+curl http://localhost:9867/health > /dev/null || {
+ echo "Server down" # 2 = server error
+}
+```