# SPEC — `scorpiox-scorpioplayer-agent-control-server` (`spctl_`)

Version: `1.0.0` · ABI: `1` · Prefix: `spctl_` · Header: `include/spctl.h`

## 1. Purpose & Design Thesis

`scorpiox-scorpioplayer-agent-control-server` is a pure-C99, in-process embeddable HTTP/1.1 REST and optional MCP (Model Context Protocol, Streamable HTTP JSON-RPC 2.0) server DLL for **SCORPIO PLAYER 2027**.

It implements the same HTTP + MCP Streamable HTTP wire dialect as `scorpiox-server` (`/codebases/clang/scorpiox/scorpiox-server.c`) while dispatching **100% in-process via C callbacks** — zero `fork`, zero `exec`, zero `popen`, zero child processes — so every SCORPIO PLAYER 2027 platform shell (iOS, tvOS, macOS App Sandbox, Xbox UWP AppContainer, Windows WinUI3, Android Kotlin/Compose, Linux GTK4) embeds one identical control and AI-agent visual-debugging server.

### Core Invariants
- **D01 — Zero engine coupling:** `spctl_` does not link any other `scorpiox-scorpioplayer-*` engine. Shells compose `spctl_` with `sppe_`, `sppb_`, `sptpl_`, `sphrm_`, `spsf_`, and `spmh_` through the `spctl_backend` callback vtable.
- **D02 — Vendored `yyjson` only:** All JSON parsing and generation uses vendored `vendor/yyjson/yyjson.{c,h}`. No hand-rolled JSON escaping or serialization.
- **D03 — Sandbox & cross-platform C99:** Compiles cleanly with `-std=c99 -Wall -Wextra -Werror` on GCC, Clang, MinGW-w64, Android NDK r27c, and Apple Darwin Clang. Zero glibc-only extensions (`open_memstream` forbidden), zero `fork`/`exec`/`popen`. On Windows, OS CSPRNG (`BCryptGenRandom` / `RtlGenRandom`) is resolved at runtime via `KERNEL32` `LoadLibraryA`/`GetProcAddress`, keeping static PE imports strictly `KERNEL32.dll`, `WS2_32.dll`, and CRT only.
- **D04 — Exact symbol surface:** Every exported symbol uses the `spctl_` prefix, declared in `include/spctl.h`, restricted via `-fvisibility=hidden` + `spctl.map`, and verified 1:1 against `exports.json` (`nm -D --defined-only`).

---

## 2. Lifecycle, Configuration & Public Exports (26 symbols)

### Error Codes (`spctl_err_t`)
| Code | Name | Meaning |
|---:|---|---|
| `0` | `SPCTL_OK` | Success |
| `-1` | `SPCTL_ERR_INVALID` | NULL pointer, bad argument, or struct/ABI mismatch |
| `-2` | `SPCTL_ERR_NOMEM` | Memory allocation failed |
| `-3` | `SPCTL_ERR_BIND` | Socket creation, bind, or listen failed |
| `-4` | `SPCTL_ERR_STATE` | Invalid lifecycle transition (already running / not running) |
| `-5` | `SPCTL_ERR_AUTH` | Authentication required, invalid token/code, or unsafe unauth LAN bind |
| `-6` | `SPCTL_ERR_RATE_LIMIT` | Pairing verification rate limit exceeded (5 failures / 60 s) |
| `-7` | `SPCTL_ERR_READ_ONLY` | Mutating action denied in read-only mode |
| `-8` | `SPCTL_ERR_NOT_IMPL` | Backend callback is NULL / not implemented |
| `-9` | `SPCTL_ERR_BACKEND` | Backend callback returned a failure |
| `-10` | `SPCTL_ERR_INTERNAL` | Unexpected internal error |
| `-11` | `SPCTL_ERR_NOT_FOUND` | Unknown route or disabled feature |
| `-12` | `SPCTL_ERR_BAD_REQUEST` | Malformed HTTP or invalid JSON parameters |

### Configuration (`spctl_config`, ABI 1)
Initialized via `spctl_config_init(&cfg)` or set via `spctl_set_config_json(s, json)`:
- `struct_size`: must equal `sizeof(spctl_config)`
- `bind_host`: default `"127.0.0.1"` (NULL or empty → `"127.0.0.1"`)
- `port`: `0` = OS-assigned ephemeral port (queryable via `spctl_bound_port(s)`), or `1..65535` (recommended default in shells: `19363` / `19365`)
- `enable_mcp`: `0` (default, `POST /mcp` returns HTTP 404) or `1` (serves MCP Streamable HTTP JSON-RPC 2.0 at `POST /mcp`)
- `read_only`: `0` (full control) or `1` (read-only)
- `require_auth`: `-1` (auto: `0` on loopback, `1` on non-loopback), `0` (disabled — allowed on loopback only unless `allow_unauth_lan = 1`), `1` (always required)
- `allow_unauth_lan`: `0` (default safety guard; binding non-loopback with `require_auth = 0` fails with `SPCTL_ERR_AUTH` unless explicitly `1`)
- `server_name`: default `"scorpio-player-2027"`
- `product_version`: default `"1.0.0"`
- `static_bearer_token`: optional pre-shared Bearer token (e.g. restored from shell settings)
- `max_body_bytes`: default `1048576` (1 MiB), hard cap `16777216` (16 MiB)
- `io_timeout_ms`: default `10000` (10 s)
- `reserved[8]`: zeroed for forward compatibility

### Export Table
1. `spctl_version`
2. `spctl_abi_version`
3. `spctl_config_init`
4. `spctl_create`
5. `spctl_destroy`
6. `spctl_set_config`
7. `spctl_set_config_json`
8. `spctl_set_backend`
9. `spctl_install_fake_backend`
10. `spctl_start`
11. `spctl_stop`
12. `spctl_is_running`
13. `spctl_bound_port`
14. `spctl_status_json`
15. `spctl_pair_begin`
16. `spctl_pair_verify`
17. `spctl_add_token`
18. `spctl_revoke_tokens`
19. `spctl_active_token_count`
20. `spctl_set_clock`
21. `spctl_dispatch_http`
22. `spctl_free`
23. `spctl_last_error`
24. `spctl_last_error_code`
25. `spctl_strerror`
26. `spctl_selftest`

---

## 3. `spctl_backend` Vtable (ABI 1)

Every callback is **optional** (`NULL` → HTTP `501 Not Implemented` on REST, `isError: true` on MCP, never crashes).

### Buffer Ownership Contract
- For JSON callbacks (`char **out_json, size_t *out_len`): the backend allocates `*out_json` (UTF-8 JSON). If `*out_len == 0` and `*out_json != NULL`, the server uses `strlen(*out_json)`. The server releases `*out_json` using `backend.free_buf(backend.ctx, ptr)` (or standard `free(ptr)` if `free_buf == NULL`).
- For binary PNG callbacks (`uint8_t **out_buf, size_t *out_len`): the backend allocates `*out_buf` and sets `*out_len > 0`. Released via `free_buf` (or `free`).
- Callbacks return `0` (`SPCTL_OK`) on success, or a negative `spctl_err_t` on error (optionally setting `*out_json` to an error message string, which the server frees).
- Callbacks may be invoked from worker threads; backends must synchronize shared state internally (and dispatch UI-thread work onto the shell's main dispatcher if required).

### Vtable Fields
- Header: `uint32_t struct_size`, `uint32_t abi_version` (`SPCTL_ABI_VERSION == 1`), `void *ctx`, `void (*free_buf)(void *ctx, void *ptr)`
- **State & Playback (10):**
  - `get_state_json(ctx, &out_json, &out_len)`
  - `open_media(ctx, url_or_path, options_json, &out_json, &out_len)`
  - `set_playing(ctx, mode, &out_json, &out_len)` — `mode`: `0`=pause, `1`=play, `2`=toggle
  - `seek(ctx, seconds, accurate, &out_json, &out_len)`
  - `set_rate(ctx, rate, &out_json, &out_len)`
  - `set_volume(ctx, volume_0_100, muted, &out_json, &out_len)` — `-1` means unchanged
  - `get_tracks_json(ctx, &out_json, &out_len)`
  - `select_track(ctx, kind, index, &out_json, &out_len)` — `kind`: `"audio"|"subtitle"|"video"`
  - `get_chapters_json(ctx, &out_json, &out_len)`
  - `jump_chapter(ctx, index, &out_json, &out_len)`
- **Subtitles (3):**
  - `sub_search(ctx, query_json, &out_json, &out_len)`
  - `sub_load(ctx, path_or_url, &out_json, &out_len)`
  - `sub_set_delay(ctx, delay_ms, &out_json, &out_len)`
- **Library, Sources & Server-Driven Templates (6):**
  - `get_home_json(ctx, &out_json, &out_len)`
  - `get_sources_json(ctx, &out_json, &out_len)`
  - `browse(ctx, source, path, &out_json, &out_len)`
  - `tpl_render(ctx, template_name, page, &out_json, &out_len)`
  - `tpl_click(ctx, path, value_json, &out_json, &out_len)`
  - `menu_invoke(ctx, handler_or_path, args_json, &out_json, &out_len)`
- **Agent Visual & Diagnostic Debugging (4):**
  - `capture_frame_png(ctx, &out_buf, &out_len)`
  - `capture_ui_png(ctx, &out_buf, &out_len)`
  - `get_logs_json(ctx, limit, &out_json, &out_len)`
  - `custom_action(ctx, name, args_json, &out_json, &out_len)`
- Footer: `void *reserved[8]` (must be zeroed)

---

## 4. Security, Pairing & Read-Only Model

- **D05 — Loopback default:** Default `bind_host` is `"127.0.0.1"`. Loopback hosts (`127.0.0.1`, `localhost`, `::1`) default to `auth_required = 0` when `require_auth == -1`.
- **D06 — LAN auth enforcement:** Any non-loopback `bind_host` (e.g. `0.0.0.0`, LAN IP) automatically enables `auth_required = 1` when `require_auth == -1`, and refuses `require_auth == 0` with `SPCTL_ERR_AUTH` unless `allow_unauth_lan == 1`.
- **D07 — 6-digit pairing & Bearer tokens:**
  - `spctl_pair_begin(s, code_buf, cap, ttl_sec)` generates a CSPRNG 6-digit numeric code (`000000`–`999999`), default TTL 300 s.
  - `POST /api/v1/pair/start` invokes `spctl_pair_begin` only if the caller is loopback or already authenticated (otherwise HTTP `403`).
  - `POST /api/v1/pair/verify` (`{"code":"123456","client":"..."}`) or `spctl_pair_verify()`:
    - Sliding-window rate limiter: **5 failures per 60,000 ms** → HTTP `429 Too Many Requests` / `SPCTL_ERR_RATE_LIMIT`.
    - Constant-time string comparison (`spctl_ct_equal`).
    - Single-use code consumption on success.
    - Mints a 256-bit (64 lowercase hex chars) CSPRNG Bearer token stored in the server's active token table (up to 32 tokens; oldest evicted if full).
  - `Authorization: Bearer <token>` verified via constant-time comparison across all active tokens + `static_bearer_token`. Missing/invalid token → HTTP `401 Unauthorized` with `WWW-Authenticate: Bearer realm="scorpio-player-2027"`.
  - `spctl_revoke_tokens(s)` clears all issued tokens and any active pairing code immediately.
- **D08 — Read-only mode:**
  - Enforced when server `read_only == 1` OR the authenticated token has `read_only == 1`.
  - Read-only allowed: all `GET /api/v1/*` routes, `POST /api/v1/subtitles/search`, and read-only MCP tools (`player_get_state`, `player_get_tracks`, `player_get_chapters`, `player_search_subtitles`, `player_get_home`, `player_get_sources`, `player_browse`, `player_template_render`, `player_capture_frame`, `player_capture_ui`, `player_get_logs`).
  - Mutating REST routes → HTTP `403 Forbidden` (`{"ok":false,"error":"read-only mode","code":"read_only"}`).
  - Mutating MCP tools → JSON-RPC error `-32003` (`"Read-only mode: tool is not permitted"`).

---

## 5. HTTP/1.1 & REST API (`/api/v1/*`)

### HTTP Parser Safety (D09)
- Request line max 4,096 bytes; headers max 64 entries / 16,384 bytes (`431`).
- Body max `max_body_bytes` (default 1 MiB, max 16 MiB) (`413`).
- Supports `Content-Length` and `Transfer-Encoding: chunked`. Rejects conflicting `Content-Length` + `Transfer-Encoding` or duplicate differing `Content-Length` (`400`).
- Path normalization: percent-decodes `%XX` (rejects `%00` and malformed `%`), collapses duplicate `/`, rejects `..` traversal segments (`400`).
- Query parsing splits raw query on `&` and `=` **before** percent-decoding each key and value once.
- Always emits CORS headers (`Access-Control-Allow-Origin: *`, `Access-Control-Allow-Methods: GET, POST, OPTIONS`, `Access-Control-Allow-Headers: Content-Type, Authorization, Mcp-Session-Id`), `Content-Length`, `X-Content-Type-Options: nosniff`, and `Connection: close`.
- `OPTIONS *` returns `204 No Content`.

### REST Route Table
| Method | Path | Auth | RO | Backend / Behavior |
|---|---|---|---|---|
| `GET` | `/api/v1/health` | No | Yes | Minimal status JSON (`ok`, `product`, `server_name`, `version`, `abi_version`, `mcp_enabled`, `read_only`, `auth_required`) |
| `POST` | `/api/v1/pair/start` | Loopback or Auth | Yes | Begin 6-digit pairing (`{"ok":true,"code":"...","expires_in":300}`) |
| `POST` | `/api/v1/pair/verify` | No | Yes | Verify 6-digit code → `{"ok":true,"token":"...","token_type":"Bearer"}` |
| `GET` | `/api/v1/state` | Yes | Yes | `get_state_json` |
| `GET` | `/api/v1/tracks` | Yes | Yes | `get_tracks_json` |
| `GET` | `/api/v1/chapters` | Yes | Yes | `get_chapters_json` |
| `GET` | `/api/v1/home` | Yes | Yes | `get_home_json` |
| `GET` | `/api/v1/sources` | Yes | Yes | `get_sources_json` |
| `GET` | `/api/v1/browse?source=&path=` | Yes | Yes | `browse(source, path)` |
| `GET` | `/api/v1/templates?name=&page=` | Yes | Yes | `tpl_render(name, page)` |
| `GET` | `/api/v1/logs?limit=` | Yes | Yes | `get_logs_json(limit)` (default 100, clamped 1..2000) |
| `GET` | `/api/v1/debug/frame.png` | Yes | Yes | `capture_frame_png` → `200 image/png` |
| `GET` | `/api/v1/debug/ui.png` | Yes | Yes | `capture_ui_png` → `200 image/png` |
| `POST` | `/api/v1/open` | Yes | No | `open_media(url|path, options)` |
| `POST` | `/api/v1/play` | Yes | No | `set_playing(1)` |
| `POST` | `/api/v1/pause` | Yes | No | `set_playing(0)` |
| `POST` | `/api/v1/toggle` | Yes | No | `set_playing(2)` |
| `POST` | `/api/v1/seek` | Yes | No | `seek(seconds, accurate)` |
| `POST` | `/api/v1/rate` | Yes | No | `set_rate(rate)` |
| `POST` | `/api/v1/volume` | Yes | No | `set_volume(volume, muted)` |
| `POST` | `/api/v1/track` | Yes | No | `select_track(kind, index)` |
| `POST` | `/api/v1/chapter` | Yes | No | `jump_chapter(index)` |
| `POST` | `/api/v1/subtitles/search` | Yes | Yes | `sub_search(body_json)` |
| `POST` | `/api/v1/subtitles/load` | Yes | No | `sub_load(path|url)` |
| `POST` | `/api/v1/subtitles/delay` | Yes | No | `sub_set_delay(delay_ms|ms)` |
| `POST` | `/api/v1/templates/click` | Yes | No | `tpl_click(path, value_json)` |
| `POST` | `/api/v1/menu/invoke` | Yes | No | `menu_invoke(handler|path, args_json)` |
| `POST` | `/api/v1/action` | Yes | No | `custom_action(name, args_json)` |

---

## 6. MCP Streamable HTTP Server (`POST /mcp`)

- When `enable_mcp == 0`: `/mcp` returns HTTP `404 Not Found`.
- When `enable_mcp == 1`:
  - Auth applies identically to REST endpoints.
  - `GET /mcp` returns HTTP `405 Method Not Allowed` with `Allow: POST, OPTIONS`.
  - `POST /mcp` parses JSON-RPC 2.0 request (supporting integer, string, or null `id`):
    - `initialize` → `protocolVersion: "2024-11-05"`, `capabilities: {"tools": {"listChanged": false}}`, `serverInfo: {"name": server_name, "version": product_version}`.
    - `notifications/initialized` (and any `notifications/*`) → HTTP `202 Accepted`.
    - `ping` → `{"jsonrpc":"2.0","id":<id>,"result":{}}`.
    - `tools/list` → dynamically lists supported tools based on non-NULL backend callbacks and `read_only` mode, each with JSON Schema `inputSchema` and `annotations: {"readOnlyHint": bool}`.
    - `tools/call` → dispatches to the same `spctl_backend` vtable:
      - Standard tools return `content: [{"type":"text","text":"<json>"}]`.
      - Visual debugging tools (`player_capture_frame`, `player_capture_ui`) return **MCP image content**: `content: [{"type":"image","mimeType":"image/png","data":"<base64>"}]`.
      - Read-only violation returns JSON-RPC error `-32003`.
      - Missing/unknown tool or bad params returns `-32602`.
      - Unimplemented callback or backend failure returns `result: {"content":[{"type":"text","text":"..."}],"isError":true}`.

### MCP Tool Inventory (23 tools)
`player_get_state`, `player_open`, `player_play_pause`, `player_seek`, `player_set_rate`, `player_set_volume`, `player_get_tracks`, `player_select_track`, `player_get_chapters`, `player_jump_chapter`, `player_search_subtitles`, `player_load_subtitle`, `player_set_subtitle_delay`, `player_get_home`, `player_get_sources`, `player_browse`, `player_template_render`, `player_template_click`, `player_menu_invoke`, `player_capture_frame`, `player_capture_ui`, `player_get_logs`, `player_custom_action`.

---

## 7. In-Process Fake Player Backend (`spctl_install_fake_backend`)

Provides a complete, thread-safe, deterministic player implementation covering all 23 vtable callbacks:
- Tracks media URL/title, play/pause state, position (`0..3600s`), playback rate (`0.25..4.0`), volume (`0..100`), mute flag, audio/subtitle/video tracks (with dynamic external subtitle addition), 3 chapters, subtitle delay, home rows, sources, browse directory tree, template pages (`settings`, `home`), menu actions, custom actions, and a bounded action log ring.
- Generates genuine, valid, CRC32-checked PNG binaries for both `capture_frame_png` (4×4 RGBA test frame) and `capture_ui_png` (4×4 RGBA UI frame with distinct pixels) so PNG magic, IHDR, and full image decoders pass offline.

---

## 8. Concurrency & Clean Shutdown

- Each `spctl_server` runs one accept thread plus a fixed bounded worker slot table (16 concurrent connections).
- `spctl_stop(s)` sets the stop flag, wakes the accept loop via a loopback wakeup pipe/socket (POSIX `pipe` / Windows socket close + short `select` poll), shuts down active client sockets, and joins the accept thread and every active worker thread before returning.
- Result: deterministic teardown, zero detached threads, zero leaked descriptors or allocations under AddressSanitizer/LeakSanitizer across repeated start/stop cycles.
