Files
HermenixandClaude Opus 5 0f2810afaa docs(sessions)!: sessions-v4, the per-session live stream
`docs/CONTRACT-sessions.md` goes to sessions-v4 with a change table at the top,
for the reason mcp-v2 got one: everything in it is an addition, and a reader who
learned v3 should be told what moved rather than diff it.

The new §3.5 is the interface that needed freezing most, because it is the only
one in this build that two *processes* have to agree on: `/run/hhstream/live.sock`,
`LiveStreams.attach/detach/list/viewers`, the four JSON ops on the wire, and the
`Attachment` the broker gets back. Its shape is §3.4's deliberately -- the broker
holds the decision (which session streams, under which phrase), the daemon holds
the capture -- so a reader who knows the pointer driver already knows this.

Four rules in §3.5 are written out because each one is a thing a reasonable
implementation would get wrong:

* the daemon holds no session state and no idle clock; `viewers` is a reading,
  and what the broker does with it is the broker's;
* `fps` is optional and omitting it is normal -- the default is the daemon's,
  from its own unit's argv, for the same reason the port is. A broker that sent
  its own default on every attach would turn `sessions.stream.fps` into a
  setting that changed nothing, which is the failure `--xkb-layout` exists to
  avoid;
* `attach` is idempotent on the phrase, so a re-`enable` after a broker restart
  does not double the `grim` rate on one output;
* the phrase is never logged by either side. It is the stream's only credential.

§4 gains four verbs, the three `start` arguments, and the one genuinely new rule
in this version: **a connected viewer is activity**. That is the first exception
to "`touch` is the only mark of activity" since that rule was written, and it is
there for one failure -- an operator watching a long job on his phone, saying
nothing to the broker, and losing the session at three hours *because* watching
was all he was doing. It cannot hold a session open by itself: an enabled stream
with no viewer runs no `grim` and stamps nothing.

No new exit numbers. The three error names map onto codes the frozen table
already has (`stream_unavailable` -> 10, `stream_busy` -> 8, `stream_budget` ->
6), because no new *kind* of failure appeared: no container output is a
compositor-side failure, a phrase collision is a busy, a viewer cap is a budget.

§6 records schema 3 -> 4 (the record gains `stream`, older records migrate to
`null`), and §5 names the socket, the unit and port 9988 beside the other frozen
paths.

What v4 deliberately withholds from the broker is the port, the bind address and
the capture command. The broker learns the URL prefix *from* the daemon, in the
`attach` reply -- a URL it assembled itself from a port it was told about once
is a URL that lies the first time an operator moves the listener.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011ZeH65zd6pFTgBSu52W9PE
2026-10-11 22:46:54 +00:00

620 lines
37 KiB
Markdown

# CONTRACT — sessions build (sessions-v4)
This file is the interface for the **session** work: the broker, containers,
compositor IPC and pointer **and keyboard** input. It is the sibling of `docs/CONTRACT.md`, which
freezes the *frame-socket* wire format; that one is untouched by this build.
**Immutable without a version bump.** Every slice codes against this and nothing
else. If something here is wrong or missing, **stop and report it in your final
message** — the parent edits this file, not you. Do not widen your slice to work
around a gap.
Version: sessions-v4 (2026-10-11). v1 was the freeze the four slices built
against; v2 recorded the decisions their reports asked for; v3 adds the
keyboard; v4 adds the **per-session live stream**. Every change in all of them
has been an addition or a clarification — **no v1, v2 or v3 signature changed
meaning** — so earlier code stays valid except where noted.
v4 changes, all of them the stream
(`docs/plans/2026-10-04-session-stream-webapp.md`, Stage 2):
| § | Change | Why |
| --- | --- | --- |
| §3.5 | New: `hhstreamd/live.py`, the broker's end of `/run/hhstream/live.sock`, and that socket's wire format. | The stream is captured by `hhstream-live`, a third executor beside the pointer driver. `grim` blocks tens to hundreds of milliseconds, so it must not run in the broker, and a LAN-facing HTTP parser must not run in the frame server whose one-socket contract cannot grow one. The broker therefore *tells* a process what to publish, exactly as it tells the driver where to warp. |
| §4 | Verbs `stream.enable`, `stream.disable`, `stream.list`, `stream.status`. `enable` and `disable` are in the mutation set; `list` and `status` are not. | `enable` mints or rotates a phrase and opens a capture — a retried `enable` that minted a second phrase would invalidate the URL somebody is already holding. |
| §4 | `start` gains `stream?`, `stream_phrase?` and `stream_fps?`. | A stream needs the session's container output, which `start` creates; sequencing "start, then enable" in a *caller* means every caller repeats the ordering and the failure handling. One request, one answer, and the phrase comes back with the session. |
| §4 | **A connected viewer is activity.** The broker asks the daemon for viewer counts about once a minute and stamps `touch` when any is non-zero. | The one new way the idle clock moves, and the only exception to "`touch` is the only mark of activity" since that rule was written. A session an operator is watching on his phone must not be reaped at three hours *because* watching is all he is doing. An enabled stream with **no** viewer runs no `grim` and keeps nothing alive, so this cannot hold a session open by itself. |
| §4 | Error names `stream_unavailable` (exit 10), `stream_busy` (exit 8), `stream_budget` (exit 6). **No new exit numbers.** | The failures are the ones the table already has: no container is a compositor-side failure, a phrase collision is a busy, a viewer cap is a policy budget. |
| §5 | `/run/hhstream/live.sock`, the unit `hhstream-live`, and the stream port 9988. | Named here with the other frozen paths, because two processes have to agree on them. |
| §6 | Registry **schema 3 → 4**: the record gains `stream`. | A phrase has to survive a broker restart and a re-enable, so it lives in the record. Older records migrate to `stream: null` and are adopted, not refused. |
v4 deliberately does **not** give the broker the port, the bind address or the
capture command. Those are the daemon's, from its own unit's argv, for the
reason the keyboard layout is the driver's: the broker's TOML is read by
`hhstreamd`, and a setting an operator could change in it while the listener
stayed where it was would be worse than no setting at all. The broker learns
the URL prefix *from* the daemon, in the `attach` reply.
v3 changes, all of them keyboard (`docs/plans/2026-10-03-keyboard-input.md` as
amended by `docs/plans/2026-10-04-keyboard-verification.md`):
| § | Change | Why |
| --- | --- | --- |
| §3.3 | `PointerLease` gains `press_key` / `unpress_key` / `keys_pressed`; `LeaseOutcome` gains `keys_lifted`. **`expire()` still returns `LeaseInfo` and nothing else.** | One `wl_seat` means one keyboard focus, so the keyboard shares the pointer's lease. §6.7's "the lease gains a `keyboard` flag" is the wrong shape: a boolean cannot say to lift `Control_L` and not `a`, and order matters for the same reason it does for buttons. |
| §3.4 | Driver ops `key` and `type`; `pressed` gains `keys[]`; `release_all` gains `lifted_keys[]`; the frozen command line gains four `--xkb-*` flags. A rejected request may carry a `kind`. | There is no keyboard `frame` and no `release_all_keys`: the protocol has no frame, and expiry has one call site. The flags are the **only** path a layout has to the uploaded keymap — the broker's TOML is read by `hhstreamd`, and the driver is a different unit that never opens it. |
| §4 | Verbs `keyboard.key` and `keyboard.type`, both in the mutation set; `pointer.state` gains `keys[]`; `pointer.release` gains `keys_lifted[]`. | A retried `type` must not type twice, for the reason a retried click must not click twice. |
| §4 | **`pointer.acquire` takes keyboard focus as well as the cursor**, and is two `warp`s on the driver socket rather than one. | Measured (`tests/README-keyboard-probe.md`): one warp onto an idle cursor delivers `wl_pointer.enter` and no `wl_keyboard.enter`, so a one-warp acquire aims the cursor at the session and leaves the keys with whatever was focused before. |
v2 changes:
| § | Change | Why |
| --- | --- | --- |
| §3.1 | `Monitor` gains `id: int` | `clients -j` reports a client's monitor as a numeric **index**, `Workspace.monitor` as a **name**, so without an id there is no way to join a client to its output. Slice D's aiming is output-local. |
| §3.1 | `Client.stable_id` defined as `"<initial_class>:<pid>"` (fallback `address`); absent `pid` becomes `-1`; `Event.data` is a per-event field table plus always-present `raw`/`args`; `request_timeout_s` is an overridable class attribute (2 s); `version()` returns the compositor's banner verbatim | What slice B had to decide, now written down instead of re-derived. |
| §3.2 | `quarantine_argv()` replaces `quarantine_plan()`, returning `list[list[str]] \| None` | A quarantine rule is not a container: no output, no numbered workspace, no mode, and `container_plan` refuses a zero size. **Integration updates `containers.py` and its tests to this shape.** |
| §3.3 | `mark()` added; `expire()` precedence documented | §3.3 gave no way to record a position, so `LeaseOutcome.bookmark` could only ever be `None` and `pointer.acquire … restore?` had nothing to restore. |
| §3.4 | Vendored protocol is permitted, and the XML path is corrected | The v1 path was wrong (`share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml`). |
| §5 | The broker state dir is stated as an *option default* with this machine's override; the frame socket is named | §5's value was the deployed one, not the default, and the frame socket was missing while `docs/CONTRACT.md` still documents the old one. |
---
## 1. What is being built, in one paragraph
A headless Hyprland desktop is driven by an agent. A broker (`hhstreamd`) starts
allowlisted applications as **sessions** and tracks them. This build gives each
session its **own output and workspace** (a spatial container), teaches the
broker to **talk to the compositor** (IPC), and adds **serialised pointer input**
aimed at one session, under a **lease** whose bookmark is stored with the
session.
Read `docs/PLAN-workspaces-and-pointer.md` only if your brief tells you to. It
describes the whole system; you are building one part.
---
## 2. File ownership — the rule that makes four sessions possible
| Slice | Owns (only these) |
| --- | --- |
| **A — stage0-rename** | `nix/module.nix`, `src/hhstream/cli.py` (the two socket-path defaults only), `examples/agent-eyes` |
| **B — ipc-client** | `src/hhstreamd/ipc.py`, `tests/ipc/**` |
| **C — containers** | `src/hhstreamd/containers.py`, `tests/containers/**` |
| **D — pointer** | `src/hhstreamd/pointer.py`, `src/hhstream_pointer/**`, `tests/pointer/**`, `pyproject.toml`, `nix/package.nix` |
| **parent (integration)** | `src/hhstreamd/{protocol,registry,manager,launcher,compositor,procmon}.py`, `checks/**`, `docs/**`, `src/hhstream/cli.py` (everything but the path defaults), `nix/module.nix` (after A merges) |
Two slices never edit the same file. A shared-file change you believe you need is
a **report**, not an edit.
**Never touch:** `/etc/nixos` (outside this repo), anything under
`/var/lib/hermes/nixos`, any systemd unit, any running service. Never run
`nixos-rebuild`, `nixosTest`, `nix build .#checks.*`, or launch a GUI
application. The parent serialises all of that on a 2-core machine.
---
## 3. Python seams (exact signatures — code to these)
### 3.1 `hhstreamd/ipc.py` (B)
```python
class CompositorUnavailable(Exception):
"""No request socket, or the compositor refused. Callers degrade, never guess."""
@dataclass(frozen=True)
class Monitor:
id: int; name: str; x: int; y: int; width: int; height: int; scale: float
active_workspace_id: int | None
@dataclass(frozen=True)
class Workspace:
id: int; name: str; monitor: str | None; windows: int; is_special: bool
@dataclass(frozen=True)
class Client:
address: str; pid: int; workspace_id: int | None; monitor: str | None
class_: str; initial_class: str; title: str; stable_id: str; visible: bool
@dataclass(frozen=True)
class CursorPos:
x: int; y: int
@dataclass(frozen=True)
class Event:
name: str # "openwindow", "workspace", "monitorremoved", ...
data: dict # parsed payload; keys are whatever the event carried
class HyprlandIPC:
@classmethod
def discover(cls, runtime_dir: Path, signature: str | None = None) -> "HyprlandIPC": ...
# raises CompositorUnavailable. Signature from the argument, else
# $HYPRLAND_INSTANCE_SIGNATURE, else the single directory under
# <runtime_dir>/hypr/. More than one and no signature = CompositorUnavailable.
def __init__(self, request_socket: Path, event_socket: Path | None = None) -> None: ...
def version(self) -> str: ...
def monitors(self) -> list[Monitor]: ...
def workspaces(self) -> list[Workspace]: ...
def clients(self) -> list[Client]: ...
def cursorpos(self) -> CursorPos: ...
def query(self, command: str) -> str: ... # raw request socket, for anything not wrapped
def events(self) -> Iterator[Event]: ... # blocking; raises CompositorUnavailable on EOF
def close(self) -> None: ...
def parse_event(line: str) -> Event: ... # "name>>a,b,c" -> Event
```
Rules: every method raises `CompositorUnavailable` rather than returning a
guess. `clients()` parses `clients -j`; `monitors()` parses `monitors -j`;
`workspaces()` parses `workspaces -j`. Stdlib only.
Decisions, so they are not re-derived per caller:
- **A client's monitor is an index, an output's name is a name.** `Client.monitor`
is the numeric index rendered as text (or `None` when the reply said nothing);
join it to a `Monitor` through `Monitor.id`. `Workspace.monitor` is a name.
- **`Client.stable_id`** is `"<initial_class>:<pid>"`, falling back to
`address`. Hyprland publishes no such key; this is the identity that survives a
remap, and the launcher sets the class per session.
- **An absent `pid` becomes `-1`**, not `0` — no process has pid `-1`.
- **Events are positional on the wire** (`name>>a,b,c`). `Event.data` is built
from a per-event field table, with the last named field absorbing the remaining
commas (titles contain them); `raw` and `args` are always present so an unknown
event is still usable. An event that carries fewer fields than the table names
only what arrived — never invented empties.
- **`request_timeout_s`** is a class attribute (2 s) on `HyprlandIPC` because
`__init__` is frozen.
- **`version()` returns the compositor's banner verbatim**, not a parsed number.
### 3.2 `hhstreamd/containers.py` (C)
**Pure logic. No I/O, no subprocess, no socket, no import of `ipc.py`.** It
computes command lines and parses nothing. Seams are primitives so this module
stands alone.
```python
@dataclass(frozen=True)
class ContainerPlan:
output: str # hh-<session-id>
workspace: int
mode: tuple[int, int] # width, height
create: list[list[str]] # full argv lists, in order, each ["hyprctl", ...]
teardown: list[list[str]]
def output_name(session_id: str) -> str: ...
# "hh-" + session_id. Ids are already [a-z0-9-]; assert and raise ValueError otherwise.
def contains_output(name: str) -> bool: ...
# True for names this broker creates (prefix "hh-"), so a start-up scan can
# find orphans.
def container_plan(session_id: str, workspace: int, width: int, height: int,
app_id: str) -> ContainerPlan: ...
# create: output create headless <name> ["hyprctl","output","create","headless",name]
# workspace rule ["hyprctl","keyword","workspace",
# f"{workspace}, monitor:{name}, default:true, persistent:true"]
# window rule ["hyprctl","keyword","windowrule",
# f"match:initial_class ^{app_id}$, workspace {workspace}, monitor {name}"]
# output mode ["hyprctl","keyword","monitor", f"{name},{width}x{height},auto,1"]
# teardown: output remove <name> ["hyprctl","output","remove",name]
def app_id_for(session_id: str) -> str: ...
# the bare "hh-<session-id>" the launcher sets on the app; "^hh-<session-id>$"
# is built in container_plan.
def quarantine_argv(quarantine_workspace: str) -> list[list[str]] | None: ...
# the backstop: every window matching no container goes to
# special:quarantine. Returns the keyword argv, or None when the target is
# blank/whitespace (which is how "disabled" is spelled).
#
# Deliberately NOT a ContainerPlan: a quarantine rule has no output, no
# numbered workspace and no mode. The argv shape mirrors the per-session
# rule, with a catch-all class:
# ["hyprctl","keyword","windowrule",
# f"match:initial_class .*, workspace {target}"]
# It must be installed BEFORE any per-session rule, or the catch-all wins.
# That ordering is the caller's, and this module cannot enforce it.
class WorkspaceAllocator:
def __init__(self, base: int, count: int) -> None: ...
def allocate(self) -> int: ... # lowest free slot in [base, base+count); raises NoSlots
def release(self, workspace: int) -> None: ... # unknown id -> KeyError (a bug, not a no-op)
def in_use(self) -> list[int]: ...
class NoSlots(Exception): ...
```
### 3.3 `hhstreamd/pointer.py` (D)
Lease state machine + coordinate maths. **No Wayland, no socket, no I/O.** The
clock is injected so expiry is testable without sleeping.
```python
class LeaseBusy(Exception): # another session holds it
def __init__(self, holder: str) -> None: ...
class LeaseInvalid(Exception): # not held, or held by someone else / stale lease_id
@dataclass(frozen=True)
class Bookmark:
x: float; y: float # 0..1, output-local, normalised
output: str
at: str # ISO-8601 UTC
@dataclass(frozen=True)
class LeaseInfo:
session_id: str; lease_id: str; acquired_at: float; expires_at: float
hard_deadline: float
@dataclass(frozen=True)
class LeaseOutcome:
bookmark: Bookmark | None; reason: str; buttons_lifted: list[str]
class PointerLease:
def __init__(self, ttl_s: float = 30.0, max_s: float = 300.0,
clock: Callable[[], float] = time.monotonic) -> None: ...
def acquire(self, session_id: str) -> str: ... # -> lease_id; raises LeaseBusy
def refresh(self, session_id: str, lease_id: str) -> None: ... # raises LeaseInvalid
def release(self, session_id: str, lease_id: str, reason: str) -> LeaseOutcome: ...
def mark(self, session_id: str, lease_id: str, bookmark: Bookmark) -> None: ...
# records where the cursor was left, called on every move and before
# release. Added in v2: without it LeaseOutcome.bookmark could only ever
# be None, so `pointer.acquire --restore` had nothing to restore.
# raises LeaseInvalid for a non-holder.
def state(self) -> dict: ... # {"holder": str|None, "since": float|None,
# "lease_id": str|None, "expires_at": float|None}
def expire(self) -> LeaseInfo | None: ...
# force-release if past ttl or hard cap; returns what was released.
# The caller (broker) lifts buttons on the driver side.
def press(self, session_id: str, button: str) -> None: ...
def unpress(self, session_id: str, button: str) -> list[str]: ...
def pressed(self) -> list[str]: ...
# v3: the same three for keysym names. A `keys` dict beside `buttons` on
# the held record, not a `keyboard` boolean: `release_all` has to know
# *which* keys went down and in what order.
def press_key(self, session_id: str, key: str) -> None: ...
def unpress_key(self, session_id: str, key: str) -> list[str]: ...
def keys_pressed(self) -> list[str]: ...
**`expire()` carries no bookmark, no lifted buttons and no lifted keys** — it
returns the lease that was released, nothing more. The broker therefore has two
duties on expiry: read `pressed()` **and `keys_pressed()`** *before* calling
`expire()` if it wants the lease's view of what was down, and lift them on the
driver (one `release_all`), because the lease cannot lift anything itself. The
bookmark is not `expire()`'s to keep: the broker already stores it with the
session (§1), which is where it belongs.
v3 deliberately did **not** widen this return. The ordering it forces — read,
then expire — is the only thing stopping a key from being forgotten before the
driver has been told to lift it, and on this compositor a forgotten key is
worse than a forgotten button: `InputManager::onKeyboardKey` drops the *next*
press of a code it still believes is down, so the key is dead rather than
merely stuck.
def window_to_absolute(point: tuple[int, int], window: tuple[int, int, int, int],
monitor: tuple[int, int, int, int]) -> tuple[float, float]:
# point is window-local pixels; window is (x, y, w, h) global; monitor is
# (x, y, w, h) global. Returns normalised 0..1 in the MONITOR's frame,
# clamped to [0, 1]. Raises ValueError if the point is outside the window.
```
### 3.4 `src/hhstream_pointer/**` (D) — the driver process
A separate process, because a Wayland client needs its own connection and a
blocked driver must not stall the broker.
- Entry point `hhstream-pointer` (add to `pyproject.toml`:
`hhstream-pointer = "hhstream_pointer.__main__:main"`).
- Command line the module will pass, exactly (**amended in v3**: the four
`--xkb-*` flags, whose defaults are the values below):
```
hhstream-pointer --socket /run/hhstream/pointer.sock \
--compositor-runtime-dir /run/hypr-stream \
--xkb-layout us --xkb-model pc105 \
--xkb-variant '' --xkb-options ''
```
These flags are the **only** path a layout has to the uploaded keymap. There
is deliberately no `[keyboard]` table in the broker's TOML: that file is read
by `hhstreamd`, and this is a different unit that never opens it, so such a
table would be a setting an operator could change while every injected key
stayed on `us`.
A layout `xkb_keymap_new_from_names` rejects — and a comma-separated one,
and an empty one — is exit **2**, raised *before* the compositor is
contacted. A keymap the compositor refuses is exit **10**, and the socket is
never listened on: `key` before `keymap` is the protocol error `no_keymap`,
which kills the connection rather than returning anything reportable.
- Uses **pywayland** (packaged as `python3Packages.pywayland`) and the **wlr
virtual pointer XML** from `pkgs.wlr-protocols`, which lives at
`share/wlr-protocols/unstable/wlr-virtual-pointer-unstable-v1.xml` (the v1
contract had this path wrong: different middle directory, and no `z` prefix on
the filename). **Vendoring the generated module is explicitly permitted** (v2):
generating at build time puts a code generator between a checkout and a runnable
driver, and the dev shell has neither the XML nor a scanner. State which you
did. `pyproject.toml` and `nix/package.nix` are yours precisely so this is
possible.
- Binds `zwlr_virtual_pointer_manager_v1` **version 2** and uses
`create_virtual_pointer_with_output(seat, output, id)` so coordinates are
output-local. If only version 1 is offered, **report it — never silently fall
back** to a global pointer, which would break aiming.
- Private socket protocol with the broker, newline-delimited JSON:
```json
{"op": "warp", "output": "hh-x", "x": 0.42, "y": 0.61} -> {"ok": true}
{"op": "button", "button": "left", "state": "down"} -> {"ok": true}
{"op": "axis", "axis": "vertical", "value": 3.0} -> {"ok": true}
{"op": "frame"} -> {"ok": true}
{"op": "pressed"} -> {"ok": true, "buttons": ["left"], "keys": ["Control_L"]}
{"op": "release_all"} -> {"ok": true, "lifted": ["left"], "lifted_keys": ["Control_L"]}
{"op": "key", "key": "Return", "state": "down"} -> {"ok": true, "keys": ["Return"], "lifted": []}
{"op": "type", "text": "Hello"} -> {"ok": true, "keys": []}
```
**Amended in v3 — `key` and `type`, for the keyboard.** Names on this socket,
evdev codes only on the Wayland request: the driver owns the keymap, so it is
the only thing that can say which keycode `z` is on the uploaded layout. Four
rules that are not interchangeable:
- **No output and no frame.** A virtual keyboard is seat-global, so `key` and
`type` take no output and must not require a prior `warp`. And
`zwp_virtual_keyboard_v1` has no `frame` request — a key queued until one
would never arrive — so each request is flushed the way `button` already is.
- **`pressed` and `release_all` grow key fields** rather than gaining a
parallel `release_all_keys`. Expiry has one call site, and a second op would
be a second thing to forget in the path that runs when nobody is watching.
`release_all` lifts buttons, then keys in press order, then sends
`modifiers(0, 0, 0, 0)` if a mask was ever set — a virtual key-up clears no
modifier state, so without that a lease that ended under Shift hands the
next holder a keyboard where every letter is a capital.
- **`type` is one request for the whole string.** The driver resolves every
character before emitting anything, so an unmappable one types no prefix.
Capped at 4096 Unicode **scalars** (not bytes) in the driver and in the
broker.
- **A rejection may carry `kind`.** `{"ok": false, "error": "…", "kind":
"invalid_argument"}` is the caller's mistake — a keysym the layout does not
have, an unmappable character, a bad `state`, a string over the cap — and the
broker maps it to exit 2. Any other value, and an older driver's absent
field, stay `driver_refused` (exit 10), which is what the button and axis
paths already do.
**Amended after the freeze — `axis`, for scrolling.** Added to the op set above
and to the broker's verbs as `pointer.scroll`. Positive vertical is *down* and
positive horizontal is *right*: the protocol's direction, not a choice of ours,
and the reason there is no `up`/`down` vocabulary layered over it. The output is
whatever the last `warp` aimed at, exactly like `button`, so scrolling somewhere
else is a warp first — which is what keeps the whole gesture atomic under the
lease. The magnitude is bounded at 100 wheel clicks per request, in both the
driver and the broker, because a decimal-point slip should be a refusal rather
than a session scrolled somewhere unrecoverable. Unit tests cover validation and
the lease; a real-compositor case is still missing — see
`docs/TODO/scroll-has-no-compositor-proof.md`.
`{"ok": false, "error": "<text>"}` for anything rejected. The driver holds **no
lease state** — the broker owns the lease; the driver is an executor that must
never be trusted to serialise anything.
### 3.5 `hhstreamd/live.py` (v4) — the broker's end of the stream daemon
A third executor beside the pointer driver, and the same shape as §3.4: the
broker holds the *decision* (which session streams, under which phrase) and the
daemon holds the *capture*. `hhstream-live` owns the port, the bind address and
the capture command, from its own unit's argv; the broker never passes them and
never reads them from its own TOML.
```python
class LiveUnavailable(Exception):
"""The stream daemon could not be reached, or did not answer intelligibly."""
class LiveRejected(Exception):
"""The daemon refused. `kind` maps to an exit code, as the driver's does."""
def __init__(self, message: str, *, kind: str | None = None) -> None: ...
@dataclass(frozen=True)
class Attachment:
phrase: str; output: str; fps: int; session: str | None
url: str # the daemon's own prefix, e.g. http://127.0.0.1:9988/<phrase>/
viewers: int
class LiveStreams:
def __init__(self, socket_path: Path | str, *, timeout_s: float = 2.0) -> None: ...
def attach(self, *, phrase: str, output: str, fps: int,
session: str | None = None, label: str = "") -> Attachment: ...
def detach(self, phrase: str) -> bool: ... # False if it was not attached
def list(self) -> list[Attachment]: ...
def viewers(self) -> dict[str, int]: ... # phrase -> connected viewers
def close(self) -> None: ...
```
Private socket protocol, newline-delimited JSON, the driver's conventions
exactly — `{"ok": true, …}` or `{"ok": false, "error": "…", "kind": "…"}`:
```json
{"op": "attach", "phrase": "amber-otter-lantern-harbor-7k2qp", "output": "hh-x",
"session": "x", "label": "chromium", "fps": 5} // fps is OPTIONAL
-> {"ok": true, "stream": {"phrase": "…", "output": "hh-x",
"fps": 5, "session": "x", "url": "http://…/", "viewers": 0}}
{"op": "detach", "phrase": "…"} -> {"ok": true, "detached": true}
{"op": "list"} -> {"ok": true, "streams": [ {…}, … ]}
{"op": "viewers"} -> {"ok": true, "viewers": {"<phrase>": 2}}
```
Four rules that are not interchangeable:
- **The daemon holds no session state and no idea of an idle clock.** It
publishes what it was told to publish. `viewers` is a *reading*, and what the
broker does with it (§4) is the broker's.
- **`fps` is optional, and omitting it is the normal case.** The default rate is
the daemon's, from its own unit's argv (`sessions.stream.fps`), for the same
reason the port is. The broker sends one only when a caller named one, or
when re-attaching a stream that already had one. A broker that sent its own
default on every attach would make the operator's option a setting that
changed nothing — the same failure `--xkb-layout` (§3.4) exists to avoid.
- **`attach` is idempotent on the phrase.** Re-attaching the same phrase to the
same output returns the existing stream rather than starting a second
capture, because a re-`enable` after a broker restart must not double the
`grim` rate on one output. The same phrase aimed at a *different* output is
`{"kind": "invalid_argument"}`.
- **The phrase is never logged by either side.** It is the stream's only
credential. The daemon logs the output and the viewer count; the broker's
audit log records the session and the output (§4), and neither records the
phrase.
`url` comes back from the daemon rather than being built by the broker, for the
reason the port is the daemon's: a URL the broker assembled from a port it was
told about once is a URL that silently lies the first time an operator moves
the listener.
---
---
## 4. Wire format (broker control socket) — B, C and D do not implement this
Newline-delimited JSON over `/run/hhstream/control.sock`. Existing verbs are
unchanged. New verbs (integration implements; listed so slices know what their
code will be called with):
| Verb | Request (beyond `verb`, `request_id`) | Response |
| --- | --- | --- |
| `container.list` | — | `containers[]`, `orphans[]` |
| `container.reconcile` | `id?` | `container`, `diff` |
| `pointer.acquire` | `id`, `ttl_s?`, `restore?` | `lease_id`, `bookmark` |
| `pointer.move` | `id`, `lease_id`, `x`, `y` \| `dx`, `dy` | `bookmark` |
| `pointer.button` | `id`, `lease_id`, `button`, `state` | `buttons[]` |
| `pointer.click` | `id`, `lease_id`, `button?`, `count?` | `bookmark` |
| `pointer.release` | `id`, `lease_id` | `bookmark`, `released_by`, `buttons_lifted[]`, `keys_lifted[]` |
| `pointer.state` | — | `holder`, `since`, `lease_id`, `buttons[]`, `keys[]` |
| `keyboard.key` (v3) | `id`, `lease_id`, `key`, `state` | `keys[]` |
| `keyboard.type` (v3) | `id`, `lease_id`, `text` | `chars`, `keys[]` |
| `stream.enable` (v4) | `id`, `phrase?`, `fps?` | `stream` |
| `stream.disable` (v4) | `id` | `stream`, `detached` |
| `stream.list` (v4) | — | `streams[]`, `available` |
| `stream.status` (v4) | `id?` | `stream` \| `streams[]` |
**v4, the stream.** `stream.enable` and `stream.disable` are in the
`request_id` mutation set; `stream.list` and `stream.status` are not.
`start` additionally accepts `stream?` (bool), `stream_phrase?` and
`stream_fps?`, and when `stream` is true its reply's session carries the same
`stream` object `stream.enable` would have returned.
The `stream` object is the record's, with the daemon's `url` and `viewers`
merged in when it could be asked:
```json
{"enabled": true, "phrase": "amber-otter-lantern-harbor-7k2qp",
"output": "hh-x", "fps": 5, "port": 9988,
"url": "http://127.0.0.1:9988/amber-otter-lantern-harbor-7k2qp/",
"viewers": 0, "enabled_at": "2026-10-11T…Z", "attached": true}
```
`attached` is its own field and is **not** folded into `enabled`: a record may
say a session is enabled while the daemon is down, and "the operator asked for
this stream" and "a capture is running right now" are two different facts. A
caller that wants the second one reads `attached`; `url` and `viewers` are
absent when it is false, rather than stale.
**`stream.enable` requires the session's container output.** Without one it is
`stream_unavailable` (exit 10). A stream never falls back to the main output:
that output carries every other session, and putting it on a phone is the one
mistake this feature must not make. Re-enabling an enabled session returns the
same phrase; a `phrase` that differs from the stored one is `stream_busy`
(exit 8). `disable` then `enable` rotates it.
**Teardown order is load-bearing.** `kill` detaches the stream *before*
`hyprctl output remove`, because a capture aimed at a removed output fails every
time and the daemon's own failure budget would close the viewers with
"unknown output" instead of "the session ended".
**v3, the keyboard.** `keyboard.*` verbs take the **pointer** lease: there is
no `keyboard.acquire` and no second lease id. One `wl_seat` means one keyboard
focus, and the shipped `input:follow_mouse = 1` means another session's warp
retargets the keys, so two leases would let session B move the pointer while
session A believed it was typing into its own window. Both verbs are in the
`request_id` mutation set, for the reason `pointer.click` is: a retried `type`
that typed twice is the one failure an agent cannot undo.
**v3, acquire takes the keyboard too.** `pointer.acquire` sends **two** warps
to the driver — a neighbouring pixel, then the real target — because one warp
onto an idle cursor moves the cursor and not keyboard focus. Measured; see
`tests/README-keyboard-probe.md`. The reply gains `focus`, naming which
mechanism took it (`warp`, `focuswindow`, or `none`). This depends on
`input:follow_mouse_threshold` being 0, which `nix/hyprland-conf.nix` now sets
explicitly rather than inheriting.
### Error codes (extend `ExitCode`, do not renumber)
| 0 OK | 2 USAGE | 3 NO_SUCH_SESSION | 4 BAD_STATE | 5 DAEMON_UNREACHABLE |
| 6 POLICY | 7 TIMEOUT | 8 BUSY | **9 NO_LEASE (new)** | **10 COMPOSITOR (new)** |
**v4 adds error names and no numbers.** `stream_unavailable` → 10 (no
container, or the daemon is unreachable — the session itself is fine either
way), `stream_busy` → 8 (a `phrase` that is not this session's), `stream_budget`
→ 6 (the daemon's viewer or stream cap). A bad `fps` is `invalid_argument` → 2,
as every other bad argument is.
Activity accounting is load-bearing and has **one** exception as of v4:
**`touch` is the only mark of activity a caller can make**; `list`, `status`,
`logs`, `gc`, every `pointer.*` **and `keyboard.*`** verb, and every
`stream.*` verb do **not** reset the idle clock. A session being typed into is
still a session nobody has said they want kept.
The exception is **a connected viewer**. About once a minute the broker asks
the daemon for viewer counts and stamps `touch` on every session whose stream
has at least one; the audit entry names the session, the output and the count,
never the phrase. This is not a caller's verb and cannot be invoked — it is the
broker observing that a person is *looking*, which is the one form of "still
wanted" that does not come down the control socket. It cannot hold a session
open on its own: an enabled stream with no viewer runs no `grim` and stamps
nothing.
The *lease* clock is a different one, and v3 widens it: every `pointer.*` and
`keyboard.*` gesture verb refreshes the lease's idle deadline, because they all
go through the same gate. `pointer acquire`'s own stderr says so.
---
## 5. Names and paths (frozen)
| Thing | Value |
| --- | --- |
| Compositor runtime dir | `/run/hypr-stream` — **must be ≤ 25 chars** (socket paths must stay under `sun_path`'s 108-byte limit) |
| Compositor request socket | `<runtime dir>/hypr/<signature>/.socket.sock` |
| Compositor event socket | `<runtime dir>/hypr/<signature>/.socket2.sock` |
| Frame socket (published) | `<runtime dir>/stream.sock` — default `/run/hypr-stream/stream.sock`. Also frozen in `docs/CONTRACT.md`, which v1 of this file left disagreeing with it. |
| Broker control socket | `/run/hhstream/control.sock` |
| Broker↔driver socket | `/run/hhstream/pointer.sock` |
| Broker↔stream socket | `/run/hhstream/live.sock` (v4) |
| Stream port | **option default** `9988` (`sessions.stream.port`), fixed and single — no range, no fallback. The daemon owns it; the broker learns the URL from the daemon (§3.5). |
| Stream bind | **option default** `127.0.0.1` (`sessions.stream.bind`) |
| Broker state dir | **option default** `/var/lib/hhstream`; this machine sets `/var/lib/hermes/hhstream-sessions` (`sessions.stateDir`). v1 listed the deployed value, which read as a contradiction of the module. |
| Session runtime dir | `/run/hhstream/sessions/<session-id>` |
| Container output name | `hh-<session-id>` |
| Container workspace band | `1000 + slot`, allocated from the registry's free list |
| Container mode | `1280x720` |
| Units | `hyprland-headless`, `hyprland-headless-stream`, `hhstream-sessions`, `hhstream-pointer`, `hhstream-live` (v4) |
| Keyboard layout | **option default** `us` (`sessions.keyboard.layout`), reaching the driver as `--xkb-layout`. One group: a comma is refused. Hyprland's `input:kb_layout` is not read. |
| Binaries | `hhstream`, `hhstreamd`, `hhstream-server`, `hhstream-client`, `hhstream-pointer`, `hhstream-live` |
| Registry schema | **4** (v4; 3 → 4 adds `stream`, migrating to `null`) |
| Service account | `hermes`, supplementary group `hhstream` |
---
## 6. Rules of engagement
1. **Only your files** (§2). A shared-file change you need is a report.
2. **Unit tests only.** `nix develop -c python -m pytest tests/<yours> -q`.
Nothing that builds a VM, rebuilds the system, or touches a live service.
3. **Stdlib only**, except slice D which may add `pywayland`.
4. **Machine style:** module docstrings that say *why*, not what; comments carry
reasoning; no TODO placeholders; no speculative generality.
5. **Definition of done:** a commit on your branch; your tests pass; your final
message states (a) what you built, (b) the exact test command and its result,
(c) what you could **not** verify, (d) any contract gap you hit. A slice that
"finishes" without (b) is not done.
6. **Do not open by reading the whole repo.** Your brief plus this contract is
your context. Read the two or three files you actually touch.
7. If the contract is wrong, say so and stop. If your slice turns out to need
another slice's file, say so and stop. Both are successful outcomes.