# CONTRACT — sessions build (sessions-v1) This file is the interface for the **session** work: the broker, containers, compositor IPC and pointer 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-v2 (2026-10-02). v1 was the freeze the four slices built against; v2 records the decisions their reports asked for. Every v2 change is either a clarification or an addition — **no v1 signature changed meaning** — so v1 code stays valid except where noted. 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 `":"` (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 # /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 `":"`, 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- 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 ["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 ["hyprctl","output","remove",name] def app_id_for(session_id: str) -> str: ... # the bare "hh-" the launcher sets on the app; "^hh-$" # 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]: ... **`expire()` carries no bookmark and no lifted buttons** — it returns the lease that was released, nothing more. The broker therefore has two duties on expiry: read `pressed()` *before* calling `expire()` if it wants the lease's view of what was down, and lift those buttons on the driver (`release_all`), because the lease cannot lift them itself. The bookmark is not `expire()`'s to keep: the broker already stores it with the session (§1), which is where it belongs. 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: `hhstream-pointer --socket /run/hhstream/pointer.sock --compositor-runtime-dir /run/hypr-stream` - 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": "frame"} -> {"ok": true} {"op": "pressed"} -> {"ok": true, "buttons": ["left"]} {"op": "release_all"} -> {"ok": true, "lifted": ["left"]} ``` `{"ok": false, "error": ""}` 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. --- ## 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` | | `pointer.state` | — | `holder`, `since`, `lease_id` | ### 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)** | Activity accounting is unchanged and load-bearing: **`touch` is the only mark of activity**; `list`, `status`, `logs`, `gc`, and every `pointer.*` verb do **not** reset the idle clock. --- ## 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 | `/hypr//.socket.sock` | | Compositor event socket | `/hypr//.socket2.sock` | | Frame socket (published) | `/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 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/` | | Container output name | `hh-` | | 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` | | Binaries | `hhstream`, `hhstreamd`, `hhstream-server`, `hhstream-client`, `hhstream-pointer` | | 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/ -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.