Files
hyprland-headless-stream-pl…/docs/CONTRACT-sessions.md
Hermenix 98374b8457 docs: the plan for workspaces and pointer input, and the frozen sessions contract
The plan is the researched design (one compositor, one output+workspace per
session, serialised output-bound pointer input under a lease). The contract is
the freeze point for a parallel build: file ownership per slice, the exact
Python seams, the wire format, and the names and paths nobody may invent.

Kept separate from docs/CONTRACT.md, which governs the frame socket and is
untouched by this work.
2026-10-01 23:58:09 +00:00

14 KiB

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-v1 (2026-10-01).


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)

class CompositorUnavailable(Exception):
    """No request socket, or the compositor refused. Callers degrade, never guess."""

@dataclass(frozen=True)
class Monitor:
    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.

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.

@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_plan(quarantine_workspace: str) -> ContainerPlan | None: ...
    # the backstop: every window matching no container goes to
    # special:quarantine. Returns the keyword argv, or None if disabled.

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.

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 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]: ...

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 (share/wayland-protocols/wlr-unstable/zwlr-virtual-pointer-unstable-v1.xml). Compile the protocol at build time or vendor the generated module under your directory — your choice, stated in your report. 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:
{"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": "<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.


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 <runtime dir>/hypr/<signature>/.socket.sock
Compositor event socket <runtime dir>/hypr/<signature>/.socket2.sock
Broker control socket /run/hhstream/control.sock
Broker↔driver socket /run/hhstream/pointer.sock
Broker state dir /var/lib/hermes/hhstream-sessions
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
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/<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.