# pwapi — Playwright Chatbot API

Query web chatbots (ChatGPT, Claude, Gemini, DeepSeek, Grok, Mistral, Meta AI, Z.AI, Perplexity, Qwen, Kimi) through one HTTP API. A persistent Chromium profile holds your logins; the container reuses them.

## Quickstart (Docker)

```bash
cp .env.example .env   # optional; set BEARER_TOKEN to require auth
mkdir -p data/profiles/default

# 1. Log in on your DESKTOP (needs a display + node + playwright browsers):
npm install
node scripts/login.mjs --all   # browser opens, log in to each tab, Ctrl+C when done

# 2. Run the API (mounts ./data/profiles at /data/profiles):
docker compose up --build
# or: docker build -t pwapi . && docker run -p 3000:3000 -v ./data/profiles:/data/profiles -v ./data/failures:/data/failures pwapi
```

Open `http://localhost:3000/` for status page + test form.

## Endpoints

| Method | Path | Description |
|---|---|---|
| `GET`/`POST` | `/api/chatbot` | **The chatbot endpoint.** The `command` parameter defines what it shall do (see commands below). New chatbot functions are added as new commands. |
| `GET`/`POST` | `/api/browse` | Fetch any URL as `source`/`plain`/`pdf`/`tar`/`full`. POST additionally supports `method`, form fields (`data`) and file uploads (`files`). |
| `GET`/`POST` | `/launch:browser` | Start the persistent browser headed (watch on VNC). Optionally opens a `url`. |
| `GET`/`POST` | `/profile:unlock` | Remove stale Chromium lock files from a transferred profile. Refuses (409) while the API browser runs. |
| `GET` | `/api/failures` | List failure screenshots `{file, bytes, mtime}`. |
| `GET` | `/api/failures/<file>` | Download one screenshot (PNG). |
| `DELETE` | `/api/failures/<file>` | Delete one screenshot. |
| `DELETE` | `/api/failures` | Delete all screenshots. |
| `GET`/`POST` | `/launch:chat-login` | Open a chatbot login page in the headed browser (`chatbot` param) — log in by hand over VNC. |
| `GET` | `/api/readme` | This file as `text/markdown`. For developer agents. |
| `GET` | `/api/status` | Health, uptime, code version, profile info, defaults. |
| `GET` | `/api/health` | `{ "ok": true }`. |
| `GET` | `/` | Status dashboard: test forms, "Test all chatbots" (OK/FAILED), failure-screenshot gallery. |

| `command` | Params | Description |
|---|---|---|
| `list` | — | List `{ id, name, url }` of all chatbots. Call this first. |
| `ask` | `chatbot`, `prompt`, `timeout` | Ask a chatbot. |

### command=list

```bash
curl -s "http://localhost:3000/api/chatbot?command=list"
# {"command":"list","ok":true,"count":12,"chatbots":[{"id":"chatgpt","name":"ChatGPT (OpenAI)","url":"https://chatgpt.com/"}, ...]}
```

### command=ask (POST recommended)

```bash
curl -s -X POST http://localhost:3000/api/chatbot \
  -H 'Content-Type: application/json' \
  -d '{"command":"ask","chatbot":"chatgpt","prompt":"Say OK","timeout":"120s"}'
```

Response:

```json
{
  "command": "ask",
  "ok": true,
  "chatbot": "chatgpt",
  "prompt": "Say OK",
  "answer": "...bot reply text...",
  "elapsedMs": 12345,
  "timeoutMs": 120000
}
```

### command=ask via GET (alternative)

```bash
curl -s -G http://localhost:3000/api/chatbot \
  --data-urlencode "command=ask" \
  --data-urlencode "chatbot=claude" \
  --data-urlencode "prompt=Explain recursion in one sentence" \
  --data-urlencode "timeout=90s"
```

### Parameters

| Param | Required | Description |
|---|---|---|
| `command` | yes | What the endpoint shall do: `list` or `ask`. |
| `chatbot` | yes for `ask` | Bot id from `command=list` (aliases `bot`, `id` accepted). Case-insensitive. |
| `prompt` | yes for `ask` | The message to send (aliases `q`, `text`, `message` accepted). |
| `timeout` | no | Max wait for answer. Accepts `120s`, `2m`, `120000`, `120000ms`, bare `120` (= seconds). Default `120000` (`DEFAULT_TIMEOUT_MS`), capped at `MAX_TIMEOUT_MS` (default 600s). |
| `tempProfile` | no | `true` = launch the browser with a fresh temporary profile (no logins, no history), deleted after the call. Alias `temp`. |
| `profile` | no | Named profile to use (`work`, `private`, …). Created on demand under `data/profiles/`. Default: `default`. |
| `headless` | no | `true` = run invisibly for this call. The default is **headed** (visible; container VNC provides the display). `headed=true/false` is accepted too. |
| `linger` | no | Headed only: how long the page stays visible after the answer before closing (ms). Default `HEADED_LINGER_MS` (5000). `0` closes at once, `<0` keeps it open. |
| `diagnose` | no | `true` = include `diagnostics` (input method, submit path, per-selector match counts/text) in the response — for bots whose markup changed. |

### Known chatbot ids

`chatgpt`, `claude`, `gemini`, `deepseek`, `grok`, `mistral`, `meta`, `zai`, `perplexity`, `qwen`, `kimi`

Bots with `requireHeaded: true` (shown by `command=list`) always run headed, even when the API is headless — some sites (e.g. **ChatGPT**, behind Cloudflare) block headless browsers, so they need the display/VNC.

### /api/browse — fetch any URL

GET fetches via HTTP GET. POST additionally supports `method=get|post`, form fields (`data`) and file uploads (multipart field `files`), which are forwarded to the target URL as a multipart POST (uploaded files force POST).

| Param | Required | Description |
|---|---|---|
| `url` | yes | Target URL (aliases `u`, `link`). Only `http`/`https`. Query strings may be included for GET. |
| `format` | no | `source` \| `plain` \| `pdf` \| `tar` \| `full` (alias `mode`). Default `plain`. |
| `method` | no | `get` \| `post` (alias `httpMethod`). POST-only. Default `get`. |
| `data` | no | Form fields as object (or JSON string). Aliases `params`, `body`, `form`. POST-only. |
| `files` | no | Multipart uploads, field name `files` (max 10 × 20MB). POST-only. |
| `timeout` | no | Same syntax as `ask` timeout. |
| `wait` | no | Extra ms to let JS settle after load. Default `2000`, capped by `timeout`. |
| `tempProfile` | no | `true` = load the page with a fresh temporary profile (no logins, no cookies), deleted after the call. Alias `temp`. |
| `profile` | no | Named profile to use (`work`, `private`, …). Created on demand under `data/profiles/`. Default: `default`. |
| `headless` | no | `true` = load invisibly for this call. The default is **headed** (visible; container VNC provides the display). `headed=true/false` is accepted too. |
| `linger` | no | Headed only: how long the page stays visible after the fetch before closing (ms). Default `HEADED_LINGER_MS` (5000). `0` closes at once, `<0` keeps it open. |

| `format` | Returns |
|---|---|
| `source` | `text/html` page source. Final URL in `X-Final-Url` header. |
| `plain` | `text/plain` rendered text. |
| `pdf` | `application/pdf` download (A4, backgrounds included). |
| `tar` | `application/gzip` download: `index.html` + `images/` + `manifest.json` (original URL → file map). Max 50 images, 8MB each. |
| `full` | JSON `{url, finalUrl, title, text, imageCount, truncated, images:[{src, alt, width, height, mime, bytes, data(base64)}]}`. Max 30 images. |

```bash
# rendered text
curl -s -G http://localhost:3000/api/browse --data-urlencode "url=https://example.com"
# page source
curl -s -G http://localhost:3000/api/browse --data-urlencode "url=https://example.com" --data-urlencode "format=source"
# PDF download
curl -s -X POST http://localhost:3000/api/browse \
  -H 'Content-Type: application/json' \
  -d '{"url":"https://example.com","format":"pdf"}' -o page.pdf
# archive with images
curl -s -X POST http://localhost:3000/api/browse \
  -H 'Content-Type: application/json' \
  -d '{"url":"https://example.com","format":"tar"}' -o page.tar.gz
# POST with fields + upload, JSON result
curl -s -X POST http://localhost:3000/api/browse \
  -F "url=https://httpbin.org/post" -F "method=post" -F "format=full" \
  -F 'data={"q":"test"}' -F "files=@report.pdf"
```

### /launch:browser — start the browser headed

Starts the persistent Chromium visibly — watch it on VNC at `localhost:5900`. Replaces a running headless browser (in-flight `ask`/`browse` calls may fail). Optionally opens a URL and leaves the tab open, e.g. to log in by hand. Same bearer auth as `/api/*` applies.

```bash
curl -s -X POST http://localhost:3000/launch:browser \
  -H 'Content-Type: application/json' \
  -d '{"url":"https://chatgpt.com/"}'
# {"ok":true,"running":true,"headless":false,"already":false,"opened":"https://chatgpt.com/","display":":99","profile":"default","profileDir":"/data/profiles/default"}
```

| Param | Required | Description |
|---|---|---|
| `url` | no | Page to open after start (aliases `u`, `link`). Only `http`/`https`. |
| `profile` | no | Named profile to start (created if missing). Default: `default`. |

### /profile:unlock — unlock a transferred profile

A Chromium profile copied from another computer contains stale lock files (`SingletonSocket`, `SingletonCookie`, `SingletonLock`), which Chromium refuses as "profile in use". This endpoint (or `npm run unlock:profile` on desktop) removes them. Only run while **no** browser uses the profile — the endpoint refuses with 409 while the API browser runs; stop the container (or close the API browser) first.

```bash
curl -s -X POST http://localhost:3000/profile:unlock
# {"ok":true,"dir":"/data/profile","removed":["SingletonSocket","SingletonCookie","SingletonLock"],"count":3}
npm run unlock:profile   # same, for ./data/profiles/default on desktop
```

### /api/failures — browse and delete failure screenshots

Every error/timeout screenshot (see Login section) is listed here and can be viewed on `/` or downloaded/deleted. The newest **10** are kept (`MAX_FAILURES`); older ones are deleted automatically. File names are restricted to `*.png` inside the failures dir (no path traversal).

```bash
curl -s http://localhost:3000/api/failures
# {"ok":true,"count":1,"failures":[{"file":"gemini-NO_ANSWER-....png","bytes":105176,"mtime":"..."}]}
curl -s http://localhost:3000/api/failures/gemini-NO_ANSWER-....png -o shot.png
curl -s -X DELETE http://localhost:3000/api/failures/gemini-NO_ANSWER-....png
curl -s -X DELETE http://localhost:3000/api/failures   # delete all
```

### /launch:chat-login — log in to a chatbot over VNC

Starts the headed browser on the chatbot's page and leaves the tab open, so you can log in by hand over VNC at `localhost:5900`. The session persists in the profile and later `ask` calls reuse it. Same bearer auth as `/api/*` applies.

```bash
curl -s -X POST http://localhost:3000/launch:chat-login \
  -H 'Content-Type: application/json' \
  -d '{"chatbot":"chatgpt"}'
# {"ok":true,"chatbot":"chatgpt","name":"ChatGPT (OpenAI)","url":"https://chatgpt.com/",...}
```

| Param | Required | Description |
|---|---|---|
| `chatbot` | yes | Bot id from `command=list` (aliases `bot`, `id`). |
| `profile` | no | Named profile to log in with (created if missing). Default: `default`. |

### Errors

```json
{"ok": false, "error": "Missing or unknown parameter: 'command'", "valid": ["list", "ask"]} // 400
{"ok": false, "error": "Invalid or unsupported URL (only http/https allowed)", "code": "INVALID_URL"} // 400
{"ok": false, "error": "Invalid method 'put' (use get or post)", "code": "INVALID_METHOD"} // 400
{"ok": false, "error": "Invalid profile name '../x' (letters, digits, dot, dash, underscore; max 64 chars)", "code": "INVALID_PROFILE"} // 400
{"ok": false, "error": "Missing parameter: 'prompt'"}                                   // 400
{"ok": false, "error": "Unknown chatbot 'x'", "valid": ["chatgpt", ...]}                // 404
{"ok": false, "error": "Prompt box not found ... login is required ...", "code": "PROMPT_BOX_NOT_FOUND"} // 502
{"ok": false, "error": "No answer captured ... within 120000ms ...", "code": "NO_ANSWER"} // 504
{"ok": false, "error": "Unauthorized: missing or invalid bearer token"}                 // 401
```

## Authentication

If `BEARER_TOKEN` is set, **all** `/api/*` routes require the token — except `/api/readme`, which is always public (so developer agents can read the docs):

```bash
curl -s "http://localhost:3000/api/chatbot?command=list" -H "Authorization: Bearer $BEARER_TOKEN"
```

If unset, the API is open. The `/` status page is always public.

## Login / profile volume

- The container stores Chromium state in `/data/profiles` (see `VOLUME` + `docker-compose.yml` mount `./data/profiles:/data/profiles`).
- `node scripts/login.mjs [--all | <bot-id> | --list]` launches desktop Chromium with `./data/profiles/default` so you can log in once per site. The API then reuses those sessions. For a NAMED profile: `PROFILE_DIR=./data/profiles/work node scripts/login.mjs --all`.
- Named profiles (`profile=work`, …) live next to the default: `data/profiles/work`. Each has its own logins, history, and running browser. Pass `profile` to `/api/chatbot`, `/api/browse` (also `/launch:browser`, `/launch:chat-login`, `/profile:unlock`). Missing profiles are created on demand; see `/api/status` → `profiles` for the list.
- `npm run launch:browser` opens a local headed browser with `./data/profiles/default` only to build up the profile (log in to sites); the API reuses it. No pages are opened for you.
- If a bot answers with a login wall, re-run the login script for that bot and restart the container.
- On errors or timeouts the API saves a screenshot of the browser window under `data/failures` (container: `/data/failures`, see `FAILURES_DIR`); the file path is included in the error response and the count in `/api/status`.

## VNC remote desktop

The image runs Xvfb + TigerVNC's `x0vncserver` + openbox via `start.sh`, so you can watch and use the container browser with any VNC viewer at `localhost:5900` (see `VNC_PORT`). (TigerVNC ≥1.14 names it `x0tigervncserver`; both are supported.)

- No password by default. Set `VNC_PASSWORD` in `.env` to require one. (Passwordless mode uses `-SecurityTypes None -localhost no`, which TigerVNC only allows with the explicit `--I-KNOW-THIS-IS-INSECURE` acknowledgement — the entrypoint adds it automatically.)
- Resolution via `VNC_GEOMETRY` (default `1366x900`, matches the automation viewport).
- The browser runs **headed by default** so VNC shows everything. Set `HEADLESS=true` (or `headless=true` per call) to run invisibly. Some bots (e.g. ChatGPT) force headed internally because Cloudflare blocks headless.
- Warning: VNC without a password on an untrusted network lets anyone control the browser. Set `VNC_PASSWORD` or don't publish port 5900.

## Chrome extensions

Unpacked Chrome extensions can be loaded (e.g. cookie-banner removers like *I Still Don't Care About Cookies*). Put each extension in its own subdirectory of `data/extensions/` (container `/data/extensions`), with a `manifest.json` at the top:

```
data/extensions/
  i-still-dont-care-about-cookies/
    manifest.json
    ...
```

Load with `npm run ext:install` (accepts a local `.zip`/`.crx` or an http(s) URL, strips the CRX header, flattens a single wrapper folder):

```bash
# from a release zip
mkdir -p data/extensions
npm run ext:install -- ./i-still-dont-care-about-cookies.zip i-still-dont-care
# or direct URL
npm run ext:install -- https://github.com/OhMyGuus/I-Still-Dont-Care-About-Cookies/releases/download/vX.Y.Z/Chrome.zip i-still-dont-care

docker compose up -d --force-recreate   # restart to load
curl -s localhost:3000/api/status | grep -A3 extensions
```

Notes:
- Extensions require a headed browser (the default here) or Chromium's *new* headless. They are loaded for every call/bot using that profile; `--disable-extensions` (Playwright's default) is lifted automatically when any extension is present.
- A profile that never had the extension may show a "developer mode extensions" warning on first launch — dismiss it over VNC once.

## Configuration (env vars)

| Var | Default | Description |
|---|---|---|
| `PORT` | `3000` | HTTP port. If busy, server auto-falls back to `PORT+1`, … Set `PORT=3001` (compose maps host:container with the same value). |
| `BEARER_TOKEN` | _(empty)_ | If set, bearer auth on `/api/*`. |
| `PROFILE_DIR` | `/data/profiles/default` | Default profile dir (used when no `profile` param is given). Desktop/local default: `./data/profiles/default`. |
| `PROFILES_DIR` | `/data/profiles` | Parent dir for named profiles (`profile=work` → `/data/profiles/work`). |
| `FAILURES_DIR` | `/data/failures` | Browser-window screenshots on errors/timeouts. Local default: `./data/failures`. |
| `UNLOCK_PROFILE` | `false` | Remove stale profile lock files on every browser launch (transferred profiles). See `/profile:unlock`. |
| `HEADED_LINGER_MS` | `5000` | How long a headed page stays visible after the answer before closing (`linger` param overrides). |
| `MAX_FAILURES` | `10` | Failure screenshots kept; the oldest are auto-deleted beyond this. |
| `EXTENSIONS_DIR` | `/data/extensions` | Unpacked Chrome extensions to load (one subdir each). Local default `./data/extensions`. |
| `DISABLED_CHATBOTS` | _(empty)_ | Deactivate chatbots: comma-separated ids (e.g. `chatgpt,claude`) or `all`. Disabled bots are hidden from `command=list` and rejected on `ask`. |
| `ANSWER_MARKER` | `PWAPI-END-9F3A2B` | Marker appended to the prompt; the bot is asked to end its answer with it. Its presence means the answer is complete (stripped from the reply). Use letters/digits/dashes only; set empty to disable. |
| `HEADLESS` | `false` | Default browser mode. `false` = headed/visible (recommended: bots behind Cloudflare need it, and you can watch on VNC). `true` = headless default; override per call with `headless`. |
| `DEFAULT_TIMEOUT_MS` | `120000` | Default `ask` timeout. |
| `MAX_TIMEOUT_MS` | `600000` | Upper cap for `timeout`. |
| `NAV_TIMEOUT_MS` | `60000` | Navigation timeout per bot page. |

## Local dev (without Docker)

```bash
npm install
npx playwright install chromium
HEADLESS=false PROFILE_DIR=./data/profiles/default node server.js
```

## Extending (adding functions later)

- `server.js` — add new chatbot functions as entries in the `COMMANDS` map (served by `/api/chatbot` via the `command` param; `auth` auto-applies to `/api/*`).
- `chatbots.js` — registry; add `{ id, name, url, input[], send[], response[] }`.
- `pw.js` — `ask(bot, prompt, timeoutMs)` + persistent context + FIFO mutex. Export new helpers from here for new commands.

## Notes / limitations

- Requests are **serialized** (one browser mutex) to keep the single profile stable. Parallel `ask` commands queue.
- Prompts are **pasted, not typed** (clipboard → `execCommand` → typing fallback, preserves newlines/paragraphs); the method used is logged per request.
- `tempProfile=true` runs on a throwaway profile: no logins (most chatbots will show login walls), nothing persists, the dir is deleted after the call. Requests still serialize through the single browser mutex.
- If the browser process dies (crash, OOM-kill), the next call detects the dead context and relaunches it automatically (`[browser] previous context is dead, relaunching…` in the log).
- Session restore ("Restore pages?" bubble) is always suppressed: `--disable-session-crashed-bubble` plus crash-state scrubbing of the profile before every launch.
- Chatbot UIs change often; selectors in `chatbots.js` are fallback lists + generic heuristics (`textarea`, `[contenteditable]`, `role=textbox`). Update them when a site breaks.
- Answer detection waits for response text to **stabilize** (~3s unchanged) or until `timeout`. A fresh chat is started first when the bot supports it (`newChat`); a repeated identical answer still counts when the message count grew.
- Graceful shutdown: handles `SIGTERM` (`docker stop`) and `SIGINT` — drops idle keep-alive connections, closes the browser (releases the profile lock), then exits; second signal or 10s hang forces exit. Compose adds `init: true` (reaps Chromium zombies) and `stop_grace_period: 30s`.
