Files
prometeu-runtime/docs/specs/runtime/11a-headless-automation-protocol.md
T

168 lines
9.8 KiB
Markdown

# Headless Automation Protocol v1
**Domain:** runtime host tooling. **Function:** normative.
This chapter implements Studio DSC-0068 / DEC-0060 baseline v1, runtime phase
of PLN-0139. The host owns this wire contract. It does not change guest ABI,
firmware, VM, frame/input semantics or the desktop DevTools protocol.
## Process and transport
`prometeu headless --stdio` starts the distributed `prometeu-headless` tool from
the same installation. One process owns one HeadlessHost. No display, native
audio, network service or realtime pacing is required. A client must use its
configured installation; missing binaries/capabilities are explicit failures.
Transport is UTF-8 JSON objects separated by LF (CRLF is accepted). stdout is
protocol-only; diagnostics go to stderr. Fragmented reads must be accumulated;
allocation is bounded by the command limit. An oversized line is rejected and
drained through LF before reading the next request. EOF with an incomplete line
reports `invalid_request`, then closes the session. EOF always requests shutdown.
All sizes exclude the LF delimiter and include the complete JSON envelope and
base64 payload. Responses exceeding their bound become `response_too_large`,
never truncated data. Clients must continuously consume stdout, including events.
Backpressure may block output; the supervising client owns wall-clock deadlines
and may terminate the process tree. There is no transport replay or durable queue.
## Handshake and compatibility
The server first emits a `hello` object with `sessionId`, `protocolVersion`
(`major: 1, minor: 0`), real `runtimeVersion`, `capabilities` and `limits`.
Session identity is opaque and process-local, excluded from deterministic oracles.
Before work, the client sends `initialize` with `protocolVersion` and an array
`requiredCapabilities`. An incompatible major returns `incompatible_version`;
missing capabilities return `unsupported_capability`. The session remains
uninitialized and cannot execute work. Compatible minor additions are permitted;
the initialize result returns the lesser supported minor. Initialize is accepted
once; repeated initialization returns `already_initialized`. Shutdown is permitted
even before initialization. All other work requires successful initialization.
## Envelopes
```json
{"requestId":"a1","command":"advance","params":{"frames":60}}
```
`requestId` is a nonempty string of at most 128 UTF-8 bytes, selected by the
client; concurrent requests must have distinct identities. `command` and `params`
are required. Unknown fields and invalid parameter types are rejected. The
request schema is distributed in `devtools/headless-protocol/request.schema.json`;
`response.schema.json` defines hello, progress and every response/result shape.
Valid and invalid request fixtures are shipped beside the schemas. Process tests
validate actual server output against the response schema (including image results).
```json
{"type":"response","sessionId":"opaque","requestId":"a1","result":{"requested":60,"completed":60,"stop":"completed"}}
{"type":"response","sessionId":"opaque","requestId":"a1","error":{"code":"busy","message":"...","details":{}}}
```
A response contains exactly one of result/error. Errors have stable `code`,
human-readable `message` and structured `details`. Unparseable/unusable request
identity is represented by null; valid identity is preserved on parameter errors.
Malformed JSON, invalid schema and unknown commands must never disappear silently.
Wire requestId is correlation, not deduplication: the client must not retry an
advance blindly after a lost response. Studio task-level clientRequestId and
operationId are a separate boundary, not part of this wire protocol.
## Commands
| Command | Parameters | Result/meaning |
| --- | --- | --- |
| initialize | protocolVersion, requiredCapabilities | negotiated version and capabilities |
| boot | path (nonempty directory-cartridge path) | current state; existing boot preconditions apply |
| reset | empty object | reset state, clears input/fault/frame correlation |
| set_input | complete snapshot fields listed below; omitted fields reset to defaults | input replaced, not patched |
| clear_input | empty object | input restored to defaults |
| advance | frames: unsigned integer, including zero | requested, completed, stop, optional fault/error details |
| capture | empty object | PNG/base64 plus canonical frame metadata |
| get_state | empty object | pc, stackTop, logicalFrameIndex, tickIndex, appId, status |
| get_fault | empty object | fault object or null |
| cancel | targetRequestId | acknowledgement that cancellation was requested for that active advance |
| shutdown | empty object | acknowledgement after the active operation stops and host is dropped |
Input snapshot fields are `up`, `down`, `left`, `right`, `a`, `b`, `x`, `y`, `l`,
`r`, `start`, `select`, `touch` (booleans), and `touchX`, `touchY` (signed i32).
Omitted booleans are false and omitted coordinates are zero. The ordinary runtime
begin-frame sampling derives press/release/hold edges. No new input semantics exist.
State statuses are `running`, `paused`, `terminated`, `faulted`; `running` does
not mean background execution. Stack values preserve their type through tagged
`kind`/`value` objects; i64 values are decimal strings and float values carry an
exact round-trippable string (including non-finite values). Faults expose kind,
pc, summary and structural trap code/opcode/message/source span or init-error code.
No client must parse a summary to distinguish trap, panic or initialization failure.
## Ordering, cancellation and lifecycle
Only one host operation is admitted at a time. Conflicting work, including state
inspection while the host is executing, returns `busy`; it is not implicitly
queued. The command reader remains available for cancel/shutdown while an advance
executes. Cancellation targets an active advance's requestId; no active matching
advance returns `not_cancelable`. An acknowledgement is not a completed cancellation.
Advancement is repeated `advance_frame()`, checking cancellation between frames.
The current frame keeps the existing deterministic host-tick watchdog. Zero frames
is a no-op. Results preserve requested/completed counts and `stop` values:
`completed`, `faulted`, `terminated`, `canceled`, `host_error`.
Guest faults are outcomes, not malformed-request errors. Host errors include a
stable code and known completed progress; they do not manufacture guest faults.
Each completed frame emits `type: progress`, requestId, sessionId, requested and
completed counts before the terminal response. A client can retain known progress
if the process dies. The final response is authoritative when delivered.
Shutdown/EOF requests cancellation, waits for the active work to reach its boundary,
drops the host and exits; explicit shutdown receives its response after cleanup.
Disconnect never starts/resumes execution. A failed process requires a new explicit
session, not replay. Host session loss does not implicitly release Studio authority.
## Capture
Capture returns `mimeType: image/png`, `encoding: base64`, `data`, `width`, `height`,
`stridePixels`, `pixelFormat: RGBA8888`, `logicalFrameIndex` and `frameId`.
The envelope carries sessionId; the Studio consumer adds build correlation.
Frame identities/counters on this wire are unsigned JSON integers and must be
decoded losslessly. logicalFrameIndex and frameId have no numeric equality rule.
PNG stores visible RGBA channels in row order, losslessly, without stride padding.
stridePixels describes the original canonical buffer. Before a completed frame,
including after reset, capture returns `no_frame_available`; it cannot reuse an
old run. No desktop screenshot, hash-only substitute, temporary-image-file transport
or continuous video is permitted.
## Configurable limits and supervision
| CLI option / handshake field | Default |
| --- | --- |
| --max-frames / maxFrames | 600 |
| --max-command-bytes / maxCommandBytes | 65536 |
| --max-response-bytes / maxResponseBytes | 33554432 |
| --handshake-timeout-ms / handshakeTimeoutMs | 5000 |
| --call-timeout-ms / callTimeoutMs | 60000 |
| --shutdown-timeout-ms / shutdownTimeoutMs | 5000 |
Limits must be positive; message bounds must be at least 4096 bytes to admit the
handshake and bounded errors. Limits apply to serialized bytes, not characters.
Clients must enforce the advertised handshake/call deadlines and 5-second default
cancel/shutdown grace, then terminate only the process tree they own. Deadlines are
host supervision, not simulated guest time. Runtime enforces frame/message bounds
without clamping. Requests over limits fail explicitly. Clients configure startup
timeouts before seeing the handshake, then verify the announced values.
## Conformance
The runtime gate includes fragmented/invalid/oversized lines, negotiation failures,
all commands, busy/cancel/shutdown races, EOF, real CLI distribution invocation,
PNG pixel equality, independent logical/render identity, repeat/reset determinism,
structured faults, progress on partial failure and retained desktop run/debug.
Neither Studio UI nor an AI model is required. See `tests/automation_process.rs`
in prometeu-cli and the in-process deterministic-control tests in the headless crate.
## Program Registry v1 integration
When exposing initialization failures, retain the [structured load error](02c-program-registry-and-pbx-v1.md#errors-and-publication) code, typed reason and available context. Human-readable messages are not a parsing contract; a load error has no fabricated runtime PC. Failed loads must not publish executable sessions. Existing protocol request names and transport behavior are unchanged.
Heap reference inspection values use `{"kind":"heap_ref","value":{"index":u32,"generation":u32}}`. Both components are required to distinguish a live incarnation from a reused slot; the wire representation must not truncate handles to indices. Inspection does not grant cross-session transfer authority.