The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(contracts): Pydantic wire-contract registry, runtime validation and TS/OpenRPC generator (#110522, part 1)
teknium1d4840f92366d
diff --git a/scripts/gen_gateway_contracts.py b/scripts/gen_gateway_contracts.pynew file mode 100644index 00000000000..d67091b5def--- /dev/null+++ b/scripts/gen_gateway_contracts.py@@ -0,0 +1,314 @@+"""Render ``tui_gateway/contracts`` into TypeScript and OpenRPC.++Python-only (the Python CI lane has no Node): Pydantic's ``model_json_schema()`` output is walked+by a deliberately small JSON-Schema-subset renderer — object/properties/required, primitives,+enum, const, anyOf-with-null, array/items, ``$ref``, oneOf + discriminator, additionalProperties.+Anything else raises at generation time so an unsupported model is fixed at the model, never+worked around in the output. Prettier runs on the TS when a node_modules binary is present+(the committed file is the prettier-formatted one either way — CI regenerates and diffs).+"""++from __future__ import annotations++import json+import re+import subprocess+from collections import OrderedDict+from pathlib import Path+from typing import Any++from pydantic import TypeAdapter+from pydantic.json_schema import GenerateJsonSchema++from tui_gateway import contracts # noqa: F401 (imports every topic module → fills the tables)+from tui_gateway.contracts.registry import EVENTS, METHODS, SERVER_REQUESTS++ROOT = Path(__file__).resolve().parent.parent+TS_OUT = ROOT / "apps" / "shared" / "src" / "gateway-contract.generated.ts"+OPENRPC_OUT = ROOT / "apps" / "shared" / "src" / "gateway-contract.openrpc.json"++HEADER = (+ "// GENERATED by scripts/gen_gateway_contracts.py from tui_gateway/contracts — DO NOT EDIT.\n"+ "// Regenerate: .venv/bin/python scripts/gen_gateway_contracts.py\n"+ "// tests/contracts/test_generated.py fails when this file is stale.\n"+)+++class _Schema(GenerateJsonSchema):+ """Stable ``$defs`` naming: the model's class name (no module qualifiers)."""++ def normalize_name(self, name: str) -> str:+ return re.sub(r"[^A-Za-z0-9_]", "_", name)+++def _schema_for(models: list[type]) -> tuple[dict[str, dict], list[dict]]:+ """One shared ``$defs`` for every model, plus each model's own schema (a ``$ref`` in practice)."""+ from pydantic.json_schema import models_json_schema++ defs, top = models_json_schema(+ [(m, "serialization") for m in models], schema_generator=_Schema, ref_template="#/$defs/{model}"+ )+ return top.get("$defs", {}), [defs[(m, "serialization")] for m in models]+++# ── TypeScript rendering ─────────────────────────────────────────────────────────────────────────+++class Renderer:+ def __init__(self, defs: dict[str, dict]):+ self.defs = defs+ self.emitted: OrderedDict[str, str] = OrderedDict()++ def ref_name(self, ref: str) -> str:+ assert ref.startswith("#/$defs/"), ref+ return ref[len("#/$defs/"):]++ def type_of(self, schema: dict, *, inline_depth: int = 0) -> str:+ if "$ref" in schema:+ name = self.ref_name(schema["$ref"])+ self.ensure(name)+ return name+ if "const" in schema:+ return json.dumps(schema["const"])+ if "enum" in schema:+ return " | ".join(json.dumps(v) for v in schema["enum"])+ if "anyOf" in schema or "oneOf" in schema:+ variants = schema.get("anyOf") or schema.get("oneOf")+ return " | ".join(self.type_of(v, inline_depth=inline_depth) for v in variants)+ t = schema.get("type")+ if isinstance(t, list):+ return " | ".join(self.type_of({**schema, "type": x}, inline_depth=inline_depth) for x in t)+ if t == "string":+ return "string"+ if t in ("integer", "number"):+ return "number"+ if t == "boolean":+ return "boolean"+ if t == "null":+ return "null"+ if t == "array":+ items = schema.get("items")+ if items is None:+ return "unknown[]"+ if "prefixItems" in schema:+ return "[" + ", ".join(self.type_of(x) for x in schema["prefixItems"]) + "]"+ inner = self.type_of(items, inline_depth=inline_depth)+ return f"({inner})[]" if " | " in inner else f"{inner}[]"+ if t == "object" or "properties" in schema or "additionalProperties" in schema:+ return self.object_literal(schema, inline_depth)+ if not schema or set(schema) <= {"title", "description", "default"}:+ return "unknown"+ raise ValueError(f"unsupported JSON-Schema construct: {json.dumps(schema)[:200]}")++ def object_literal(self, schema: dict, depth: int) -> str:+ props = schema.get("properties")+ extra = schema.get("additionalProperties")+ if not props:+ if extra is False:+ return "Record<string, never>"+ if extra in (None, True):+ return "Record<string, unknown>"+ return f"Record<string, {self.type_of(extra, inline_depth=depth + 1)}>"+ required = set(schema.get("required", ()))+ lines = ["{"]+ for key, sub in props.items():+ opt = "" if key in required else "?"+ lines.append(f" {_prop(key)}{opt}: {self.type_of(sub, inline_depth=depth + 1)}")+ if extra not in (None, False):+ lines.append(f" [key: string]: {'unknown' if extra is True else self.type_of(extra)}")+ lines.append("}")+ return "\n".join(lines)++ def ensure(self, name: str) -> None:+ if name in self.emitted:+ return+ self.emitted[name] = "" # cycle guard+ schema = self.defs[name]+ doc = _doc(schema.get("description"))+ if "enum" in schema:+ body = f"export type {name} = {self.type_of({'enum': schema['enum']})}\n"+ elif "properties" in schema or schema.get("type") == "object":+ body = f"export interface {name} {self.object_literal(schema, 0)}\n"+ else:+ body = f"export type {name} = {self.type_of(schema)}\n"+ self.emitted[name] = doc + body+++_IDENT = re.compile(r"^[A-Za-z_$][A-Za-z0-9_$]*$")+++def _prop(key: str) -> str:+ return key if _IDENT.match(key) else json.dumps(key)+++def _doc(text: str | None) -> str:+ if not text:+ return ""+ clean = " ".join(text.split())+ return f"/** {clean} */\n"+++def _pascal(name: str) -> str:+ return "".join(p[:1].upper() + p[1:] for p in re.split(r"[._]", name))+++def render_ts() -> str:+ models: list[type] = []+ for m in METHODS.values():+ models += [m.params, m.result]+ for r in SERVER_REQUESTS.values():+ models += [r.params, r.result]+ for e in EVENTS.values():+ if e.payload is not None:+ models.append(e.payload)+ # de-dup preserving order+ seen: dict[type, None] = OrderedDict()+ for m in models:+ seen.setdefault(m)+ models = list(seen)+ defs, tops = _schema_for(models)+ r = Renderer(defs)+ name_of = {m: r.ref_name(t["$ref"]) for m, t in zip(models, tops)}+ for m in models:+ r.ensure(name_of[m])++ out = [HEADER, "/* eslint-disable */\n", "// ── Types ──\n"]+ out.extend(r.emitted.values())++ out.append("\n// ── Client→server methods ──\n")+ out.append("export interface RpcMethods {\n")+ for m in sorted(METHODS.values(), key=lambda x: x.name):+ out.append(_doc(m.doc))+ out.append(f" {json.dumps(m.name)}: {{ params: {name_of[m.params]}; result: {name_of[m.result]} }}\n")+ out.append("}\n")+ out.append("export type RpcMethod = keyof RpcMethods\n")+ out.append("export const RPC_METHODS = [\n")+ out.extend(f" {json.dumps(n)},\n" for n in sorted(METHODS))+ out.append("] as const satisfies readonly RpcMethod[]\n")++ out.append("\n// ── Server→client requests ──\n")+ out.append("export interface ServerRequestMap {\n")+ for s in sorted(SERVER_REQUESTS.values(), key=lambda x: x.name):+ out.append(_doc(s.doc))+ out.append(f" {json.dumps(s.name)}: {{ params: {name_of[s.params]}; result: {name_of[s.result]} }}\n")+ out.append("}\n")+ out.append("export type ServerRequestMethod = keyof ServerRequestMap\n")+ out.append("export const SERVER_REQUEST_METHODS = [\n")+ out.extend(f" {json.dumps(n)},\n" for n in sorted(SERVER_REQUESTS))+ out.append("] as const satisfies readonly ServerRequestMethod[]\n")++ out.append("\n// ── Notifications (`event` frames) ──\n")+ out.append("export interface GatewayEventMap {\n")+ for e in sorted(EVENTS.values(), key=lambda x: x.name):+ out.append(_doc(e.doc))+ payload = name_of[e.payload] if e.payload is not None else "Record<string, never>"+ out.append(f" {json.dumps(e.name)}: {payload}\n")+ out.append("}\n")+ out.append("export type GatewayEventType = keyof GatewayEventMap\n")+ out.append("export const GATEWAY_EVENT_TYPES = [\n")+ out.extend(f" {json.dumps(n)},\n" for n in sorted(EVENTS))+ out.append("] as const satisfies readonly GatewayEventType[]\n")+ return "".join(out)+++def prettier(text: str) -> str:+ bin_ = ROOT / "node_modules" / ".bin" / "prettier"+ if not bin_.exists():+ return text+ proc = subprocess.run(+ [str(bin_), "--stdin-filepath", str(TS_OUT)], input=text, capture_output=True, text=True,+ encoding="utf-8", cwd=str(ROOT), check=False,+ )+ if proc.returncode != 0:+ raise RuntimeError(f"prettier failed: {proc.stderr}")+ return proc.stdout+++# ── OpenRPC rendering ────────────────────────────────────────────────────────────────────────────+++def _openrpc_schema(model: type) -> dict:+ schema = TypeAdapter(model).json_schema(schema_generator=_Schema, ref_template="#/components/schemas/{model}")+ schema.pop("$defs", None)+ return schema+++def render_openrpc() -> str:+ components: dict[str, dict] = {}+ all_models: list[type] = []+ for m in METHODS.values():+ all_models += [m.params, m.result]+ for r in SERVER_REQUESTS.values():+ all_models += [r.params, r.result]+ for e in EVENTS.values():+ if e.payload is not None:+ all_models.append(e.payload)+ from pydantic.json_schema import models_json_schema++ seen: dict[type, None] = OrderedDict()+ for m in all_models:+ seen.setdefault(m)+ _, top = models_json_schema(+ [(m, "serialization") for m in seen], schema_generator=_Schema,+ ref_template="#/components/schemas/{model}",+ )+ components = top.get("$defs", {})++ def ref(model: type) -> dict:+ return {"$ref": f"#/components/schemas/{model.__name__}"}++ doc = {+ "openrpc": "1.3.2",+ "info": {"title": "Hermes TUI/Desktop gateway", "version": "1",+ "description": "Generated from tui_gateway/contracts by scripts/gen_gateway_contracts.py."},+ "methods": [+ {"name": m.name, "summary": " ".join(m.doc.split()),+ "params": [{"name": "params", "schema": ref(m.params)}],+ "result": {"name": "result", "schema": ref(m.result)}}+ for m in sorted(METHODS.values(), key=lambda x: x.name)+ ],+ "components": {"schemas": components},+ "x-server-requests": [+ {"name": s.name, "summary": " ".join(s.doc.split()),+ "params": [{"name": "params", "schema": ref(s.params)}],+ "result": {"name": "result", "schema": ref(s.result)}}+ for s in sorted(SERVER_REQUESTS.values(), key=lambda x: x.name)+ ],+ "x-notifications": [+ {"name": e.name, "summary": " ".join(e.doc.split()),+ "params": [{"name": "payload", "schema": ref(e.payload) if e.payload is not None+ else {"type": "object", "additionalProperties": False}}]}+ for e in sorted(EVENTS.values(), key=lambda x: x.name)+ ],+ }+ return json.dumps(doc, indent=2, sort_keys=False) + "\n"+++def render_all() -> dict[Path, str]:+ return {TS_OUT: prettier(render_ts()), OPENRPC_OUT: render_openrpc()}+++def main(argv: list[str] | None = None) -> int:+ import sys++ args = argv if argv is not None else sys.argv[1:]+ check = "--check" in args+ stale = []+ for path, text in render_all().items():+ current = path.read_text(encoding="utf-8") if path.exists() else None+ if current == text:+ continue+ if check:+ stale.append(path)+ else:+ path.write_text(text, encoding="utf-8")+ print(f"wrote {path.relative_to(ROOT)}")+ if stale:+ for p in stale:+ print(f"stale: {p.relative_to(ROOT)} — run scripts/gen_gateway_contracts.py", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tui_gateway/contracts/__init__.py b/tui_gateway/contracts/__init__.pynew file mode 100644index 00000000000..0660f5bd518--- /dev/null+++ b/tui_gateway/contracts/__init__.py@@ -0,0 +1,8 @@+"""Wire contracts (see ``base.py``). Importing this package fills the registry tables; every topic+module is listed here so the generator and the runtime see the same catalog."""++from . import common, liveness, server_requests # noqa: F401+from .base import JsonValue, Params, Payload, Result, WireEnum+from .registry import EVENTS, METHODS, SERVER_REQUESTS++__all__ = ["EVENTS", "METHODS", "SERVER_REQUESTS", "JsonValue", "Params", "Payload", "Result", "WireEnum"]diff --git a/tui_gateway/contracts/base.py b/tui_gateway/contracts/base.pynew file mode 100644index 00000000000..4c4eedf76bf--- /dev/null+++ b/tui_gateway/contracts/base.py@@ -0,0 +1,55 @@+"""Wire contract primitives for the TUI/desktop gateway.++Python is the single source of truth for the JSON-RPC wire: every client→server method+(params + result), every server→client request (params + result) and every notification+payload is a Pydantic model declared in this package. ``scripts/gen_gateway_contracts.py``+renders them into ``apps/shared/src/gateway-contract.generated.ts`` and+``apps/shared/src/gateway-contract.openrpc.json``; ``tests/contracts/test_generated.py``+regenerates in memory and diffs the committed files, so a model edited without regenerating+fails CI on the Python side, and TS that reads a phantom field fails ``tsc``.++Modelling rules (they keep the generated TS clean and the wire stable):++- ``snake_case`` field names, exactly as they travel.+- Closed sets are ``StrEnum`` (rendered as literal unions); discriminators are ``Literal``.+- ``X | None = None`` renders ``x?: X | null``; a plain default renders ``x?: X``.+- Params models are ``extra="forbid"``: an unknown key is a client bug and answers ``4000``+ instead of being silently ignored. Result and payload models are ``extra="allow"`` only+ while a field is genuinely open (``dict[str, Any]`` is banned in a contract — declare the+ shape or use ``JsonValue``).+"""++from __future__ import annotations++from enum import StrEnum+from typing import Any++from pydantic import BaseModel, ConfigDict++JsonValue = Any # a JSON scalar/array/object the contract deliberately leaves open (renders ``unknown``)+++class Params(BaseModel):+ """Client→server method params / server→client request params. Unknown keys are rejected."""++ model_config = ConfigDict(extra="forbid", populate_by_name=True)+++class Result(BaseModel):+ """Method / server-request result. Serialised with ``exclude_none=False`` so an explicit+ ``null`` stays a ``null`` on the wire (clients distinguish absent from null)."""++ model_config = ConfigDict(extra="forbid")+++class Payload(BaseModel):+ """Notification payload (``event`` frame ``params.payload``)."""++ model_config = ConfigDict(extra="forbid")+++class WireEnum(StrEnum):+ """A closed string set on the wire; renders as a TS literal union."""+++__all__ = ["JsonValue", "Params", "Payload", "Result", "WireEnum"]diff --git a/tui_gateway/contracts/common.py b/tui_gateway/contracts/common.pynew file mode 100644index 00000000000..c83cf1d4719--- /dev/null+++ b/tui_gateway/contracts/common.py@@ -0,0 +1,194 @@+"""Value shapes shared by several methods and events (declared once, imported everywhere)."""++from __future__ import annotations++from pydantic import Field++from .base import JsonValue, Params, Payload, Result, WireEnum+++class OpenModel(Result):+ """A result/payload row whose known fields are typed but which the producer may extend+ (the closed set is owned elsewhere: hermes_state rows, provider inventories)."""++ model_config = Result.model_config | {"extra": "allow"}+++class Usage(OpenModel):+ """``tui_gateway/server.py::_get_usage`` + ``agent/context_breakdown.py::context_usage_fields``."""++ model: str = ""+ input: int = 0+ output: int = 0+ reasoning: int = 0+ prompt: int = 0+ completion: int = 0+ total: int = 0+ calls: int = 0+ compressions: int | None = None+ context_used: int | None = None+ context_max: int | None = None+ context_percent: int | None = None+ context_source: str | None = None+ context_estimated: bool | None = None+ cache_hit_pct: int | None = None+ cache_read: int | None = None+ cache_write: int | None = None+ avg_latency_s: float | None = None+ avg_tps: float | None = None+ active_subagents: int | None = None+ dev_credits_spent_micros: int | None = None+ cost_usd: float | None = None+ cost_status: str | None = None+++class ProjectRef(Result):+ """``tui_gateway/server.py::_project_info_for_cwd``."""++ id: str+ slug: str+ name: str+ primary_path: str | None = None+++class McpServerStatus(OpenModel):+ name: str = ""+ status: str | None = None+ tool_count: int | None = None+ error: str | None = None+++class SessionLiveInfo(OpenModel):+ """``tui_gateway/server.py::_session_info`` — the ``session.info`` event and the ``info`` field of+ ``session.create`` / ``session.resume`` / ``session.activate`` results."""++ model: str = ""+ provider: str = ""+ reasoning_effort: str = ""+ service_tier: str = ""+ fast: bool = False+ yolo: bool = False+ approval_mode: str = "manual"+ tools: dict[str, list[str]] = Field(default_factory=dict)+ skills: dict[str, JsonValue] = Field(default_factory=dict)+ cwd: str = ""+ branch: str | None = None+ project: ProjectRef | None = None+ terminal_backend: str = ""+ personality: str = ""+ running: bool = False+ turn_started_at: float | None = None+ title: str = ""+ stored_session_id: str = ""+ desktop_contract: int | str | None = None+ version: str = ""+ release_date: str = ""+ update_behind: JsonValue | None = None+ update_command: str = ""+ usage: Usage | None = None+ profile_name: str | None = None+ mcp_servers: list[McpServerStatus] = Field(default_factory=list)+ system_prompt: str | None = None+ credential_warning: str | None = None+ lazy: bool | None = None+++class StoredSessionRow(OpenModel):+ """One ``sessions`` row as ``hermes_state`` lists it (``session.list`` / ``session.info`` rows /+ ``sessions.changed``)."""++ id: str+ title: str | None = None+ preview: str | None = None+ source: str | None = None+ model: str | None = None+ started_at: float | None = None+ ended_at: float | None = None+ last_active: float | None = None+ message_count: int = 0+ tool_call_count: int = 0+ input_tokens: int = 0+ output_tokens: int = 0+ is_active: bool = False+ cwd: str | None = None+ git_branch: str | None = None+ git_repo_root: str | None = None+ parent_session_id: str | None = None+ pinned: bool | None = None+ unread: bool | None = None+ archived: bool | None = None+ actual_cost_usd: float | None = None+ estimated_cost_usd: float | None = None+ handoff_platform: str | None = None+ handoff_state: str | None = None+ lineage_root_id: str | None = Field(default=None, alias="_lineage_root_id")+ lineage_ids: list[str] | None = Field(default=None, alias="_lineage_ids")+++class TranscriptMessage(OpenModel):+ """One stored transcript row as ``session.history`` / resume ``messages`` deliver it."""++ role: str+ content: JsonValue = None+ timestamp: float | None = None+ tool_calls: list[dict[str, JsonValue]] | None = None+ tool_call_id: str | None = None+ name: str | None = None+ display_kind: str | None = None+ row_id: int | None = None+ reasoning: str | None = None+++class SubagentStatus(WireEnum):+ """Lifecycle of one delegated child (``tools/delegate_tool_child_run.py``); ``failed`` /+ ``error`` / ``timeout`` / ``interrupted`` / ``completed`` are terminal."""++ queued = "queued"+ running = "running"+ completed = "completed"+ failed = "failed"+ error = "error"+ timeout = "timeout"+ interrupted = "interrupted"+++TERMINAL_SUBAGENT_STATUSES = frozenset({+ SubagentStatus.completed, SubagentStatus.failed, SubagentStatus.error,+ SubagentStatus.timeout, SubagentStatus.interrupted,+})+++class SessionParams(Params):+ """Any method addressed at one live session."""++ session_id: str+ profile: str | None = None+++class ProfileParams(Params):+ """Any method the desktop may route to a named profile (``requestGatewayForProfile`` adds ``profile``)."""++ profile: str | None = None+++class OkResult(Result):+ ok: bool = True+++class StatusResult(OpenModel):+ status: str+++class EmptyResult(Result):+ pass+++class EmptyPayload(Payload):+ pass+++__all__ = [+ "TERMINAL_SUBAGENT_STATUSES", "EmptyPayload", "EmptyResult", "McpServerStatus", "OkResult", "OpenModel",+ "ProfileParams", "ProjectRef", "SessionLiveInfo", "SessionParams", "StatusResult", "StoredSessionRow",+ "SubagentStatus", "TranscriptMessage", "Usage",+]diff --git a/tui_gateway/contracts/liveness.py b/tui_gateway/contracts/liveness.pynew file mode 100644index 00000000000..f9e3c7cbe7b--- /dev/null+++ b/tui_gateway/contracts/liveness.py@@ -0,0 +1,26 @@+"""Transport liveness + build capability probes (``methods_voice.py`` hosts them)."""++from __future__ import annotations++from .base import Params, Result+from .registry import method+++class PingParams(Params):+ pass+++class PingResult(Result):+ pong: bool+++method("ping", params=PingParams, result=PingResult,+ doc="Cheapest liveness probe; answered on the WS reader thread even while every agent is mid-turn.")+++class GatewayCapabilitiesResult(Result):+ per_session_exclusive_submit: bool+++method("gateway.capabilities", params=PingParams, result=GatewayCapabilitiesResult,+ doc="What THIS build enforces (a client withholds a feature unless advertised).")diff --git a/tui_gateway/contracts/registry.py b/tui_gateway/contracts/registry.pynew file mode 100644index 00000000000..aba91e68d85--- /dev/null+++ b/tui_gateway/contracts/registry.py@@ -0,0 +1,163 @@+"""The contract catalog: every method, server→client request and event the gateway speaks.++Three tables, filled by the ``contracts.*`` topic modules at import time and read by+``tui_gateway/server.py`` (runtime validation) and ``scripts/gen_gateway_contracts.py``+(TypeScript + OpenRPC rendering). A handler registered with ``@method`` for a name that has+no contract here fails at import: the wire has no undeclared surface.+"""++from __future__ import annotations++import logging+import os+from dataclasses import dataclass++from pydantic import ValidationError++from .base import Params, Payload, Result++logger = logging.getLogger(__name__)+++@dataclass(frozen=True)+class MethodContract:+ name: str+ params: type[Params]+ result: type[Result]+ doc: str = ""+++@dataclass(frozen=True)+class ServerRequestContract:+ """A question the backend asks the client (``server_requests.send``)."""++ name: str+ params: type[Params]+ result: type[Result]+ doc: str = ""+++@dataclass(frozen=True)+class EventContract:+ name: str+ payload: type[Payload] | None # None: the frame carries no payload+ doc: str = ""+++METHODS: dict[str, MethodContract] = {}+SERVER_REQUESTS: dict[str, ServerRequestContract] = {}+EVENTS: dict[str, EventContract] = {}+++def _declare(table: dict, entry) -> None:+ if entry.name in table:+ raise RuntimeError(f"contract declared twice: {entry.name}")+ table[entry.name] = entry+++def method(name: str, *, params: type[Params], result: type[Result], doc: str = "") -> MethodContract:+ entry = MethodContract(name, params, result, doc)+ _declare(METHODS, entry)+ return entry+++def server_request(name: str, *, params: type[Params], result: type[Result], doc: str = "") -> ServerRequestContract:+ entry = ServerRequestContract(name, params, result, doc)+ _declare(SERVER_REQUESTS, entry)+ return entry+++def event(name: str, payload: type[Payload] | None = None, *, doc: str = "") -> EventContract:+ entry = EventContract(name, payload, doc)+ _declare(EVENTS, entry)+ return entry+++# ── runtime checks ────────────────────────────────────────────────────────────────────────────+#+# Params are validated on every call: an unknown or mistyped key is the CLIENT's bug and answers+# JSON-RPC ``4000`` with the field path, never a silent ignore. Results and payloads are OUR bug when+# they drift, so they never break a user's turn: outside the test suite a mismatch is logged once per+# name; under ``HERMES_TEST_ISOLATION`` (set by ``scripts/run_tests.sh`` / ``tests/conftest.py``) it+# raises, which is what makes the suite the gate.++STRICT = bool(os.environ.get("HERMES_TEST_ISOLATION"))+_reported: set[str] = set()+++class ContractViolation(AssertionError):+ """A result/payload the gateway produced does not match its declared contract."""+++def _report(kind: str, name: str, exc: ValidationError) -> None:+ if STRICT:+ raise ContractViolation(f"{kind} {name!r} violates its contract: {exc}") from exc+ if name not in _reported:+ _reported.add(name)+ logger.warning("%s %r violates its wire contract: %s", kind, name, exc)+++def validate_params(contract: MethodContract | ServerRequestContract, params: dict) -> tuple[dict | None, str | None]:+ """``(params, None)`` when valid — the ORIGINAL dict, so handlers keep reading what the client+ sent; ``(None, message)`` for the ``4000`` error."""+ try:+ contract.params.model_validate(params)+ except ValidationError as exc:+ first = exc.errors()[0]+ loc = ".".join(str(p) for p in first.get("loc", ())) or "params"+ return None, f"invalid params for {contract.name}: {loc}: {first.get('msg')}"+ return params, None+++def check_result(contract: MethodContract | ServerRequestContract, result: dict) -> None:+ try:+ contract.result.model_validate(result)+ except ValidationError as exc:+ _report("result of", contract.name, exc)+++def check_payload(name: str, payload: dict | None) -> None:+ contract = EVENTS.get(name)+ if contract is None:+ # Completeness (every emitted name has a contract) is the generator's / the contract+ # test's job; at emit time only a DECLARED contract can be violated.+ return+ if contract.payload is None:+ if payload:+ _report("payload of", name, _no_payload_error(payload))+ return+ try:+ contract.payload.model_validate(payload or {})+ except ValidationError as exc:+ _report("payload of", name, exc)+++def assert_complete(methods: dict[str, object], emitted_events: set[str], server_requests: set[str]) -> None:+ """Every registered method / emitted event name / sent server request has a contract, and no+ contract is orphaned. Raises with the full lists."""+ problems = []+ if missing := sorted(set(methods) - set(METHODS)):+ problems.append(f"methods without a contract: {missing}")+ if orphan := sorted(set(METHODS) - set(methods)):+ problems.append(f"method contracts with no handler: {orphan}")+ if missing := sorted(emitted_events - set(EVENTS)):+ problems.append(f"events without a contract: {missing}")+ if orphan := sorted(set(EVENTS) - emitted_events):+ problems.append(f"event contracts nothing emits: {orphan}")+ if missing := sorted(server_requests - set(SERVER_REQUESTS)):+ problems.append(f"server requests without a contract: {missing}")+ if orphan := sorted(set(SERVER_REQUESTS) - server_requests):+ problems.append(f"server request contracts nothing sends: {orphan}")+ if problems:+ raise ContractViolation("tui_gateway/contracts is incomplete:\n " + "\n ".join(problems))+++def _no_payload_error(payload: dict) -> ValidationError:+ class _Empty(Payload):+ pass++ try:+ _Empty.model_validate(payload)+ except ValidationError as exc:+ return exc+ raise AssertionError("unreachable")diff --git a/tui_gateway/contracts/server_requests.py b/tui_gateway/contracts/server_requests.pynew file mode 100644index 00000000000..8488cf20ea5--- /dev/null+++ b/tui_gateway/contracts/server_requests.py@@ -0,0 +1,234 @@+"""Server→client requests: the backend asks the renderer a question (``server_requests.send``).++Every entry is one request method: the ``params`` the frame carries (``session_id`` is added by+the transport and declared on the shared base) and the ``result`` the client answers with. The+``request.cancel`` event that withdraws an open request lives here too.+"""++from __future__ import annotations++from pydantic import Field++from .base import JsonValue, Params, Payload, Result, WireEnum+from .registry import event, server_request+++class ServerRequestParams(Params):+ """Every request frame's params start with the session the question belongs to."""++ session_id: str+++class ValueResult(Result):+ """The answer to any one-string prompt (sudo, secret, vault prompts, desktop bridges,+ mcp.setup): ``''`` means skipped / declined."""++ value: str+++# ── clarify ───────────────────────────────────────────────────────────────────────────────────+++class ClarifyQuestion(Params):+ qid: str+ question: str+ choices: list[str] | None = None+ multi_select: bool = False+++class ClarifyRequestParams(ServerRequestParams):+ """Single question: ``question`` / ``choices`` (/ ``multi_select``); batch: ``questions``.+ ``answers`` rides only on a reconnect replay (locks the server already accepted)."""++ question: str | None = None+ choices: list[str] | None = None+ multi_select: bool | None = None+ questions: list[ClarifyQuestion] | None = None+ answers: dict[str, str] | None = None+++class ClarifyResult(Result):+ """Single: ``{answer}`` ('' = skip). Batch: ``{answers}`` for the whole set (early locks go through+ the ``clarify.lock`` RPC); a response with neither is cancel-all."""++ answer: str | None = None+ answers: dict[str, str] | None = None+++server_request("clarify", params=ClarifyRequestParams, result=ClarifyResult,+ doc="The clarify tool: ask the user one question or a batch.")+++# ── approval ──────────────────────────────────────────────────────────────────────────────────+++class ApprovalChoice(WireEnum):+ once = "once"+ session = "session"+ always = "always"+ deny = "deny"+++class ApprovalRequestParams(ServerRequestParams):+ """``tui_gateway/server.py::_approval_request_payload`` — the command is redacted server-side."""++ request_id: str+ command: str = ""+ description: str = ""+ choices: list[ApprovalChoice] = Field(default_factory=list)+ allow_permanent: bool | None = None+ allow_session: bool | None = None+ smart_denied: bool | None = None+ tool_name: str | None = None+ session_id_hint: str | None = Field(default=None, alias="gateway_session_id")+ # The approval queue entry carries tool-specific context the card may render; the closed set+ # of keys is owned by tools/approval.py, so it stays open here.+ model_config = Params.model_config | {"extra": "allow"}+++class ApprovalResult(Result):+ choice: ApprovalChoice+ all: bool | None = None+++server_request("approval", params=ApprovalRequestParams, result=ApprovalResult,+ doc="A dangerous command awaits the user's decision.")+++# ── one-string prompts ────────────────────────────────────────────────────────────────────────+++class EmptyRequestParams(ServerRequestParams):+ pass+++server_request("sudo", params=EmptyRequestParams, result=ValueResult,+ doc="Masked sudo password for the terminal tool.")+++class SecretRequestParams(ServerRequestParams):+ env_var: str+ prompt: str+ metadata: dict[str, JsonValue] | None = None+++server_request("secret", params=SecretRequestParams, result=ValueResult,+ doc="Masked value for a named env var (skills / setup flows).")+++class VaultUnlockRequestParams(ServerRequestParams):+ backend: str+ display_name: str+++server_request("vault.unlock_prompt", params=VaultUnlockRequestParams, result=ValueResult,+ doc="Master password to unlock an external password manager for this session.")+++class VaultSaveLoginRequestParams(ServerRequestParams):+ origin: str+ site: str+++server_request("vault.save_login", params=VaultSaveLoginRequestParams, result=ValueResult,+ doc="Save a login for a site the agent is about to fill; the answer is JSON {identifier, password}.")+++class VaultCodeRequestParams(ServerRequestParams):+ site: str | None = None+ hint: str | None = None+++server_request("vault.code", params=VaultCodeRequestParams, result=ValueResult,+ doc="A one-time / 2FA code the user reads from their device.")+++class McpSetupRequestParams(ServerRequestParams):+ server: str | None = None+ action: str | None = None+ reason: str | None = None+++server_request("mcp.setup", params=McpSetupRequestParams, result=ValueResult,+ doc="Consent card for installing / enabling / authorising an MCP server.")+++# ── desktop GUI bridges ───────────────────────────────────────────────────────────────────────+++class ReadRangeRequestParams(ServerRequestParams):+ start: int | None = None+ count: int | None = None+++server_request("terminal.read", params=ReadRangeRequestParams, result=ValueResult,+ doc="Read the visible in-app terminal buffer (JSON text answer).")+server_request("preview.read", params=ReadRangeRequestParams, result=ValueResult,+ doc="Read the in-app browser preview's text (JSON text answer).")+server_request("window.read", params=EmptyRequestParams, result=ValueResult,+ doc="Enumerate the native window below the app (JSON text answer).")+++class PreviewActRequestParams(ServerRequestParams):+ """``tools/drive_preview_tool.py`` and ``tools/annotate_preview_tool.py`` field sets."""++ action: str+ ref: str | None = None+ selector: str | None = None+ text: str | None = None+ key: str | None = None+ submit: bool | None = None+ full: bool | None = None+ to: str | None = None+ amount: int | None = None+ max: int | None = None+++server_request("preview.act", params=PreviewActRequestParams, result=ValueResult,+ doc="Click / type / scroll / annotate inside the in-app browser preview.")+++class TourStep(Params):+ selector: str | None = None+ title: str | None = None+ text: str | None = None+ side: str | None = None+ model_config = Params.model_config | {"extra": "allow"}+++class TourRequestParams(ServerRequestParams):+ """``tools/tour_tool.py`` field set."""++ action: str+ surface: str | None = None+ selector: str | None = None+ title: str | None = None+ text: str | None = None+ side: str | None = None+ steps: list[TourStep] | None = None+ step_index: int | None = None+++server_request("tour", params=TourRequestParams, result=ValueResult,+ doc="Drive a guided tour highlight in the desktop renderer.")+++# ── withdrawal ────────────────────────────────────────────────────────────────────────────────+++class RequestCancelReason(WireEnum):+ timeout = "timeout"+ interrupted = "interrupted"+ shutdown = "shutdown"+ resolved = "resolved"+ session_closed = "session_closed"+++class RequestCancelPayload(Payload):+ id: str+ method: str+ reason: str # a RequestCancelReason value; callers in tools/approval may pass their own wording+++event("request.cancel", RequestCancelPayload,+ doc="The backend withdrew an open server→client request; clear the matching card only.")diff --git a/tui_gateway/method_ctx.py b/tui_gateway/method_ctx.pyindex 445f02c2744..6bb7049b74c 100644--- a/tui_gateway/method_ctx.py+++ b/tui_gateway/method_ctx.py@@ -66,7 +66,7 @@ class HandlerRegistry:real = rebind(fn, g)if getattr(fn, "_hermes_profile_scoped", False):real = server._profile_scoped(real)- server._methods[name] = real+ server.register_method(name, real)_PLUMBING = {"HandlerRegistry", "method", "_profile_scoped", "register", "rebind", "logger"}diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 623203b28c0..36ea6d9f863 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -36,6 +36,7 @@ from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX # noqa:from tui_gateway import git_probefrom tui_gateway._env import env_float, env_intfrom tui_gateway.turn_marker import clear_turn_marker, read_turn_marker, record_turn_start # noqa: F401+from tui_gateway.contracts import registry as _contractsfrom tui_gateway.transport import (FanoutTransport, StdioTransport, Transport, bind_transport,current_transport, reset_transport)@@ -614,6 +615,7 @@ def write_json(obj: dict) -> bool:def _event_frame(event: str, sid: str, payload: dict | None = None) -> dict:+ _contracts.check_payload(event, payload)params: dict = {"type": event, "session_id": sid, **({"payload": payload} if payload is not None else {})}return {"jsonrpc": "2.0", "method": "event", "params": params}@@ -765,9 +767,16 @@ def _err(rid, code: int, msg: str, data=None) -> dict:return {"jsonrpc": "2.0", "id": rid, "error": error}+def register_method(name: str, fn) -> None:+ """The ONE registration seam (``@method`` here and ``HandlerRegistry.install`` for the split+ modules). ``tests/contracts/test_generated.py::test_every_method_has_a_contract`` and the+ generator's ``assert_complete`` fail when a registered name has no contract."""+ _methods[name] = fn++def method(name: str):def dec(fn):- _methods[name] = fn+ register_method(name, fn)return fnreturn dec@@ -792,13 +801,23 @@ def handle_request(req: dict) -> dict | None:rid, method, params = normalizedif not (fn := _methods.get(method)):return _err(rid, -32601, f"unknown method: {method}")+ # Test doubles register straight into ``_methods`` without a contract; every production+ # handler comes through ``register_method`` and therefore has one.+ contract = _contracts.METHODS.get(method)+ if contract is not None:+ params, problem = _contracts.validate_params(contract, params)+ if problem is not None:+ return _err(rid, 4000, problem)token = _current_rpc_method.set(method)try:- return fn(rid, params)+ response = fn(rid, params)except ProfileUnavailableError as exc:return _err(rid, 4064, str(exc))finally:_current_rpc_method.reset(token)+ if contract is not None and isinstance(response, dict) and isinstance(response.get("result"), dict):+ _contracts.check_result(contract, response["result"])+ return responsedef _current_session_steer_authority(session_id: str) -> tuple[Transport | None, dict | None]:diff --git a/tui_gateway/server_requests.py b/tui_gateway/server_requests.pyindex 4e47daa89f1..ddfce56e747 100644--- a/tui_gateway/server_requests.py+++ b/tui_gateway/server_requests.py@@ -85,6 +85,14 @@ def _emit_cancel(req: ServerRequest, reason: str) -> None:def _register(req: ServerRequest) -> None:+ from tui_gateway.contracts import registry as contracts++ contract = contracts.SERVER_REQUESTS.get(req.method)+ if contract is None:+ raise RuntimeError(f"server request {req.method!r} has no contract in tui_gateway/contracts")+ _, problem = contracts.validate_params(contract, {"session_id": req.sid, **req.params})+ if problem is not None:+ raise ValueError(problem)with _lock:_open[req.id] = req_write(req.frame())