The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: OpenAI Responses fake (SDK-oracle validated) + Responses replay/parallel-call/soft-failure E2E
teknium1823107a1d0c4
diff --git a/tests/e2e/core/providers/__init__.py b/tests/e2e/core/providers/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/e2e/core/providers/_openai_helpers.py b/tests/e2e/core/providers/_openai_helpers.pynew file mode 100644index 00000000000..3beed0cec08--- /dev/null+++ b/tests/e2e/core/providers/_openai_helpers.py@@ -0,0 +1,214 @@+"""Shared harness for the OpenAI-dialect provider wire-conformance suite.++Every test drives REAL Hermes processes (``hermes -z`` oneshot, ``--resume``, the+``tui_gateway`` stdio server) against a loopback fake of the vendor HTTP API+(``tests/fakes/providers``) and asserts on the next wire request Hermes sends, the+user-visible answer, and persisted ``state.db`` rows. Homes are hermetic: a fake HOME+whose ``.hermes`` is the HERMES_HOME, an allowlisted env with no credentials.+"""++from __future__ import annotations++import json+import os+import sqlite3+import subprocess+import sys+import time+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable++import yaml++REPO_ROOT = Path(__file__).resolve().parents[4]+TURN_TIMEOUT = 150.0+_SECRET_ENV_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET", "_ACCESS_KEY")+_PASSTHROUGH_ENV = frozenset({"PATH", "LANG", "LANGUAGE", "USER", "LOGNAME", "SHELL", "TMPDIR", "TZ"})++# One tool Hermes always offers on the CLI toolset and that has an observable,+# side-effect-free result: the model reads a file the fixture wrote.+READ_TOOL = "read_file"+++@dataclass+class Home:+ root: Path++ @property+ def home(self) -> Path:+ return self.root / "home"++ @property+ def hermes_home(self) -> Path:+ return self.home / ".hermes"++ @property+ def project(self) -> Path:+ return self.root / "project"++ @property+ def db_path(self) -> Path:+ return self.hermes_home / "state.db"++ def env(self, extra: dict[str, str] | None = None) -> dict[str, str]:+ """Allowlisted env: the runner may itself be a Hermes process whose HERMES_* or+ credential env would silently reroute the child."""+ import pwd # the suite is Linux-gated++ real_root = Path(pwd.getpwuid(os.getuid()).pw_dir, ".hermes").resolve()+ fixture = self.hermes_home.resolve()+ assert fixture != real_root and fixture.parent != real_root / "profiles", "fixture is a live home"+ env = {k: v for k, v in os.environ.items()+ if (k in _PASSTHROUGH_ENV or k.startswith("LC_")) and not k.endswith(_SECRET_ENV_SUFFIXES)}+ env.update({+ "HOME": str(self.home), "HERMES_HOME": str(self.hermes_home), "PYTHONPATH": str(REPO_ROOT),+ "PYTHONUNBUFFERED": "1", "NO_COLOR": "1", "TERM": "dumb",+ # The child's state.db lives under tmp_path; the live-DB guard's documented child escape hatch.+ "HERMES_STATE_DB_GUARD_BYPASS": "1",+ })+ env.update(extra or {})+ return env++ def write(self, config: dict[str, Any], dotenv: dict[str, str] | None = None,+ auth: dict[str, Any] | None = None) -> "Home":+ self.hermes_home.mkdir(parents=True, exist_ok=True)+ self.project.mkdir(parents=True, exist_ok=True)+ base = {"updates": {"check": False}, "agent": {"api_max_retries": 2},+ "terminal": {"cwd": str(self.project)}, "memory": {"memory_enabled": False}}+ _deep_merge(base, config)+ (self.hermes_home / "config.yaml").write_text(yaml.safe_dump(base, sort_keys=False), encoding="utf-8")+ (self.hermes_home / ".env").write_text(+ "".join(f"{k}={v}\n" for k, v in (dotenv or {}).items()), encoding="utf-8")+ if auth is not None:+ (self.hermes_home / "auth.json").write_text(json.dumps(auth), encoding="utf-8")+ return self++ def update_config(self, mutate: Callable[[dict], None]) -> None:+ path = self.hermes_home / "config.yaml"+ cfg = yaml.safe_load(path.read_text(encoding="utf-8"))+ mutate(cfg)+ path.write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")+++def _deep_merge(dst: dict, src: dict) -> None:+ for k, v in src.items():+ if isinstance(v, dict) and isinstance(dst.get(k), dict):+ _deep_merge(dst[k], v)+ else:+ dst[k] = v+++# Provider configs ----------------------------------------------------------------+++def responses_provider_config(base_url: str, *, name: str = "resp-relay", model: str = "fake-responses-model") -> dict:+ """A config-defined provider that opts into the Responses transport (a Responses relay)."""+ return {+ "model": {"provider": name, "default": model, "context_length": 128000},+ "providers": {name: {"name": name, "base_url": base_url, "api_key": "sk-fake-relay",+ "transport": "codex_responses", "default_model": model}},+ }+++def custom_chat_config(base_url: str, *, model: str = "fake-model") -> dict:+ """Plain ``provider: custom`` chat-completions endpoint (Ollama / vLLM / LiteLLM shape)."""+ return {"model": {"provider": "custom", "base_url": base_url, "default": model, "context_length": 128000}}+++# Processes -------------------------------------------------------------------------+++@dataclass+class Run:+ proc: subprocess.CompletedProcess+ usage: dict[str, Any]++ @property+ def stdout(self) -> str:+ return self.proc.stdout++ @property+ def session_id(self) -> str | None:+ return self.usage.get("session_id")++ def describe(self) -> str:+ return (f"exit={self.proc.returncode}\nusage={json.dumps(self.usage)[:1500]}\n"+ f"stdout={self.proc.stdout[-1500:]!r}\nstderr={self.proc.stderr[-4000:]}")+++def hermes_argv(*args: str) -> list[str]:+ return [sys.executable, "-m", "hermes_cli.main", *args]+++def oneshot(h: Home, prompt: str, *args: str, resume: str | None = None, timeout: float = TURN_TIMEOUT,+ env: dict[str, str] | None = None) -> Run:+ """One real ``hermes -z`` turn; the usage file names the session for ``--resume``."""+ usage_file = h.root / f"usage-{time.monotonic_ns()}.json"+ argv = ["-z", prompt, "--usage-file", str(usage_file), *args]+ if resume:+ argv += ["--resume", resume]+ proc = subprocess.run(hermes_argv(*argv), cwd=h.project, env=h.env(env), capture_output=True, text=True,+ timeout=timeout, stdin=subprocess.DEVNULL)+ usage = json.loads(usage_file.read_text(encoding="utf-8")) if usage_file.exists() else {}+ return Run(proc, usage)+++def wait_until(pred: Callable[[], Any], timeout: float, what: str, interval: float = 0.05) -> Any:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ value = pred()+ if value:+ return value+ time.sleep(interval)+ raise AssertionError(f"timed out after {timeout}s waiting for {what}")+++# Persisted state ---------------------------------------------------------------------+++def db_messages(h: Home, session_id: str | None = None) -> list[dict[str, Any]]:+ """Active message rows (oldest first), read-only; every session when ``session_id`` is None."""+ if not h.db_path.exists():+ return []+ con = sqlite3.connect(f"file:{h.db_path}?mode=ro", uri=True, timeout=10)+ con.row_factory = sqlite3.Row+ try:+ sql = "SELECT * FROM messages WHERE active = 1"+ params: tuple = ()+ if session_id:+ sql += " AND session_id = ?"+ params = (session_id,)+ return [dict(r) for r in con.execute(sql + " ORDER BY id", params)]+ finally:+ con.close()+++def db_tool_calls(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Every persisted assistant tool call (parsed), in order."""+ out: list[dict[str, Any]] = []+ for r in rows:+ if r["role"] == "assistant" and r.get("tool_calls"):+ out.extend(json.loads(r["tool_calls"]))+ return out+++def tool_call_args(tc: dict[str, Any]) -> Any:+ fn = tc.get("function") or {}+ raw = fn.get("arguments", tc.get("arguments"))+ try:+ return json.loads(raw) if isinstance(raw, str) else raw+ except json.JSONDecodeError:+ return raw+++# Wire inspection ---------------------------------------------------------------------+++def responses_input_items(body: dict[str, Any], item_type: str) -> list[dict[str, Any]]:+ return [i for i in body.get("input") or [] if isinstance(i, dict) and i.get("type") == item_type]+++def chat_messages(body: dict[str, Any], role: str | None = None) -> list[dict[str, Any]]:+ msgs = [m for m in body.get("messages") or [] if isinstance(m, dict)]+ return [m for m in msgs if role is None or m.get("role") == role]diff --git a/tests/e2e/core/providers/_openai_tui.py b/tests/e2e/core/providers/_openai_tui.pynew file mode 100644index 00000000000..e827d83ae50--- /dev/null+++ b/tests/e2e/core/providers/_openai_tui.py@@ -0,0 +1,110 @@+"""Minimal stdio JSON-RPC driver for a REAL ``python -m tui_gateway.entry`` process —+the backend the Ink TUI and Desktop talk to (one long-lived agent across turns)."""++from __future__ import annotations++import itertools+import json+import subprocess+import sys+import threading+import time+from pathlib import Path+from typing import Any, Callable++from tests.e2e.core.providers._openai_helpers import Home+++class TuiGateway:+ def __init__(self, h: Home) -> None:+ env = h.env({"TERMINAL_ENV": "local", "TERMINAL_CWD": str(h.project), "HERMES_YOLO_MODE": "1"})+ self.stderr_path = h.root / f"tui-gateway-{time.monotonic_ns()}.log"+ self._stderr = open(self.stderr_path, "wb") # noqa: SIM115 - closed in close()+ self.proc = subprocess.Popen([sys.executable, "-m", "tui_gateway.entry"], cwd=h.project, env=env,+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self._stderr, bufsize=0)+ self._ids = itertools.count(1)+ self._cv = threading.Condition()+ self._responses: dict[int, dict[str, Any]] = {}+ self.events: list[dict[str, Any]] = []+ threading.Thread(target=self._read, name="tui-rpc", daemon=True).start()++ def _read(self) -> None:+ assert self.proc.stdout is not None+ for raw in iter(self.proc.stdout.readline, b""):+ try:+ frame = json.loads(raw)+ except json.JSONDecodeError:+ continue+ with self._cv:+ if frame.get("method") == "event":+ self.events.append(dict(frame.get("params") or {}))+ elif "id" in frame:+ self._responses[frame["id"]] = frame+ self._cv.notify_all()+ with self._cv:+ self._cv.notify_all()++ def call(self, method: str, params: dict[str, Any] | None = None, timeout: float = 90.0) -> dict[str, Any]:+ rid = next(self._ids)+ assert self.proc.stdin is not None+ self.proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": rid, "method": method,+ "params": params or {}}).encode() + b"\n")+ self.proc.stdin.flush()+ deadline = time.monotonic() + timeout+ with self._cv:+ while rid not in self._responses:+ left = deadline - time.monotonic()+ if left <= 0 or self.proc.poll() is not None:+ raise AssertionError(f"no reply to {method} (rc={self.proc.poll()}){self.tail()}")+ self._cv.wait(min(left, 0.5))+ frame = self._responses.pop(rid)+ if "error" in frame:+ raise AssertionError(f"{method} -> {frame['error']}{self.tail()}")+ return frame["result"]++ def wait_event(self, pred: Callable[[dict[str, Any]], bool], timeout: float, start: int = 0) -> dict[str, Any]:+ deadline = time.monotonic() + timeout+ seen = start+ with self._cv:+ while True:+ while seen < len(self.events):+ ev = self.events[seen]+ seen += 1+ if pred(ev):+ return {**ev, "_i": seen - 1}+ left = deadline - time.monotonic()+ if left <= 0 or self.proc.poll() is not None:+ raise AssertionError(f"event never arrived within {timeout}s{self.tail()}")+ self._cv.wait(min(left, 0.5))++ def turn(self, sid: str, text: str, timeout: float = 120.0) -> str:+ """Submit one prompt and return the completed assistant text once the session settles."""+ start = len(self.events)+ reply = self.call("prompt.submit", {"session_id": sid, "text": text})+ assert reply.get("status") == "streaming", reply+ done = self.wait_event(lambda e: e.get("type") == "message.complete" and e.get("session_id") == sid,+ timeout, start)+ self.wait_event(lambda e: e.get("type") == "session.info" and e.get("session_id") == sid+ and (e.get("payload") or {}).get("running") is False, 60.0, done["_i"] + 1)+ payload = done.get("payload") or {}+ text_out = payload.get("text")+ return text_out if isinstance(text_out, str) else json.dumps(text_out)++ def close(self, timeout: float = 30.0) -> int | None:+ try:+ assert self.proc.stdin is not None+ self.proc.stdin.close()+ return self.proc.wait(timeout=timeout)+ except (OSError, subprocess.TimeoutExpired):+ self.proc.kill()+ self.proc.wait(timeout=10)+ return None+ finally:+ self._stderr.close()++ def tail(self, n: int = 3000) -> str:+ try:+ self._stderr.flush()+ return "\n--- tui_gateway stderr ---\n" + Path(self.stderr_path).read_bytes()[-n:].decode(errors="replace")+ except (OSError, ValueError):+ return ""diff --git a/tests/e2e/core/providers/test_openai_responses.py b/tests/e2e/core/providers/test_openai_responses.pynew file mode 100644index 00000000000..e6d369efd98--- /dev/null+++ b/tests/e2e/core/providers/test_openai_responses.py@@ -0,0 +1,178 @@+"""OpenAI Responses (Codex) wire conformance through REAL Hermes processes.++The fake (``tests/fakes/providers/openai_responses.py``) speaks the streamed Responses+dialect built from the installed ``openai`` SDK's own models and validates every+request Hermes sends against the SDK's request schema. The provider is a config-defined+Responses relay (``providers.<name>.transport: codex_responses``) — the same transport+the ChatGPT Codex and api.openai.com routes use.++Proven here:++* encrypted reasoning items are replayed verbatim, in output order, on the next API call+ of the same turn, on the next user turn after a process restart (``--resume`` from+ state.db), and across turns of one long-lived ``tui_gateway`` session;+* parallel ``function_call`` items round-trip: every call gets exactly one+ ``function_call_output`` with its own ``call_id`` and its own result, persisted once;+* a stale encrypted blob rejected with HTTP 400 ``invalid_encrypted_content`` is+ stripped and the SAME primary is retried (no fallback, no give-up) — and the HTTP-200+ soft-failure twin of that rejection must behave the same (#120399).+"""++from __future__ import annotations++import json+import sys++import pytest++from tests.e2e.core.providers._openai_helpers import (+ READ_TOOL,+ Home,+ db_messages,+ oneshot,+ responses_input_items,+ responses_provider_config,+)+from tests.e2e.core.providers._openai_tui import TuiGateway+from tests.fakes.fake_llm_provider import FakeLLMServer+from tests.fakes.providers.openai_responses import (+ FakeResponsesServer,+ FunctionCall,+ HttpError,+ Message,+ Reasoning,+ SoftFail,+ Turn,+)++pytestmark = pytest.mark.skipif(not sys.platform.startswith("linux"), reason="subprocess harness is Linux-gated")++# Scenario -> "#issue one-line symptom" for scenarios red on origin/main. Strict: the test+# FAILS the moment the bug is fixed, forcing the entry out.+KNOWN: dict[str, str] = {+ "soft_failure_recovers_on_primary": "#120399 HTTP-200 invalid_encrypted_content skips replay-strip recovery",+}+++def known(name: str) -> list:+ """Marks for a scenario: a strict xfail while it is in KNOWN, nothing once fixed."""+ return [pytest.mark.xfail(strict=True, raises=AssertionError, reason=KNOWN[name])] if name in KNOWN else []+++def _encs(body: dict) -> list:+ return [i.get("encrypted_content") for i in responses_input_items(body, "reasoning")]+++def _answer(run) -> str:+ return run.stdout.strip()+++def test_encrypted_reasoning_replayed_in_turn_and_after_resume(tmp_path) -> None:+ h = Home(tmp_path)+ script = [+ Turn([Reasoning("ENC-A", "plan: read the file"), FunctionCall(READ_TOOL, {"path": "notes.txt"})]),+ Turn([Reasoning("ENC-B"), Message("ANSWER-ONE")]),+ Turn([Reasoning("ENC-C"), Message("ANSWER-TWO")]),+ ]+ with FakeResponsesServer(script) as srv:+ h.write(responses_provider_config(srv.base_url))+ (h.project / "notes.txt").write_text("CANARY-RESP-1\n", encoding="utf-8")+ first = oneshot(h, "read notes.txt and report")+ assert first.proc.returncode == 0 and _answer(first) == "ANSWER-ONE", first.describe()+ second = oneshot(h, "and again", resume=first.session_id)+ assert second.proc.returncode == 0 and _answer(second) == "ANSWER-TWO", second.describe()+ mains = srv.main_requests()+ invalid = srv.invalid_requests()++ assert len(mains) == 3, [b.get("input") for b in mains]+ assert invalid == [], invalid+ for body in mains:+ assert body.get("store") is False and "reasoning.encrypted_content" in (body.get("include") or []), body+ assert _encs(mains[0]) == []+ # Same turn, next call: the blob precedes the function_call it produced, and the tool+ # output answering that call follows it.+ kinds = [i.get("type") or i.get("role") for i in mains[1]["input"]]+ assert _encs(mains[1]) == ["ENC-A"], mains[1]["input"]+ assert kinds.index("reasoning") < kinds.index("function_call") < kinds.index("function_call_output"), kinds+ # After a process restart the replay comes from state.db, in the original order.+ assert _encs(mains[2]) == ["ENC-A", "ENC-B"], mains[2]["input"]+ persisted = [r for r in db_messages(h, first.session_id) if r["role"] == "assistant"]+ assert all(r["codex_reasoning_items"] for r in persisted), persisted+++def test_parallel_function_calls_round_trip_once(tmp_path) -> None:+ h = Home(tmp_path)+ script = [+ Turn([Reasoning("ENC-P"), FunctionCall(READ_TOOL, {"path": "a.txt"}), FunctionCall(READ_TOOL, {"path": "b.txt"})]),+ Turn([Message("BOTH-READ")]),+ ]+ with FakeResponsesServer(script) as srv:+ h.write(responses_provider_config(srv.base_url))+ (h.project / "a.txt").write_text("CANARY-ALPHA\n", encoding="utf-8")+ (h.project / "b.txt").write_text("CANARY-BRAVO\n", encoding="utf-8")+ run = oneshot(h, "read a.txt and b.txt")+ mains = srv.main_requests()+ invalid = srv.invalid_requests()++ assert run.proc.returncode == 0 and _answer(run) == "BOTH-READ", run.describe()+ assert invalid == [], invalid+ calls = responses_input_items(mains[1], "function_call")+ outputs = {o["call_id"]: o["output"] for o in responses_input_items(mains[1], "function_call_output")}+ assert len(calls) == 2 and len(outputs) == 2, mains[1]["input"]+ by_path = {json.loads(c["arguments"])["path"]: c["call_id"] for c in calls}+ assert "CANARY-ALPHA" in outputs[by_path["a.txt"]] and "CANARY-BRAVO" in outputs[by_path["b.txt"]], outputs+ rows = db_messages(h, run.session_id)+ tool_rows = [r for r in rows if r["role"] == "tool"]+ assert sorted(r["tool_call_id"] for r in tool_rows) == sorted(outputs), tool_rows+++def _stale_blob_session(h: Home, srv: FakeResponsesServer, fallback: FakeLLMServer) -> str:+ """Turn 1 mints a reasoning blob; returns the session id whose resume replays it."""+ cfg = responses_provider_config(srv.base_url)+ cfg["fallback_providers"] = [{"provider": "custom", "model": "fallback-model", "base_url": fallback.base_url}]+ h.write(cfg)+ first = oneshot(h, "first question")+ assert first.proc.returncode == 0 and _answer(first) == "FIRST", first.describe()+ return first.session_id++[email protected]("rejection", [+ pytest.param(HttpError(400, "Encrypted content could not be decrypted or parsed.", code="invalid_encrypted_content",+ type="invalid_request_error"), id="http_400"),+ pytest.param(SoftFail(), id="http_200_soft_failure",+ marks=known("soft_failure_recovers_on_primary")),+])+def test_rejected_encrypted_replay_is_stripped_and_primary_retried(tmp_path, rejection) -> None:+ h = Home(tmp_path)+ script = [Turn([Reasoning("ENC-STALE"), Message("FIRST")]), rejection, Turn([Message("RECOVERED-ON-PRIMARY")])]+ with FakeResponsesServer(script) as srv, FakeLLMServer(default_text="FROM-FALLBACK") as fallback:+ sid = _stale_blob_session(h, srv, fallback)+ run = oneshot(h, "second question", resume=sid)+ mains = srv.main_requests()+ fallback_mains = fallback.main_requests()++ assert _encs(mains[1]) == ["ENC-STALE"], "precondition: the resumed turn replays the stale blob"+ assert fallback_mains == [], f"fallback engaged instead of replay recovery: {run.describe()}"+ assert len(mains) == 3, [m.get("input") for m in mains]+ assert _encs(mains[2]) == [], "the retry must drop the rejected blob"+ assert run.proc.returncode == 0 and _answer(run) == "RECOVERED-ON-PRIMARY", run.describe()+++def test_tui_gateway_session_replays_reasoning_across_turns(tmp_path) -> None:+ """One long-lived backend (the Desktop/TUI shape): turn 2's request carries turn 1's+ blob without any restart, and the fallback chat endpoint is never touched."""+ h = Home(tmp_path)+ script = [Turn([Reasoning("ENC-T1"), Message("TUI-ONE")]), Turn([Reasoning("ENC-T2"), Message("TUI-TWO")])]+ with FakeResponsesServer(script) as srv:+ h.write(responses_provider_config(srv.base_url))+ gw = TuiGateway(h)+ try:+ sid = gw.call("session.create", {"cols": 120})["session_id"]+ assert "TUI-ONE" in gw.turn(sid, "hello")+ assert "TUI-TWO" in gw.turn(sid, "again")+ finally:+ gw.close()+ mains = srv.main_requests()+ invalid = srv.invalid_requests()+ assert invalid == [], invalid+ assert len(mains) == 2 and _encs(mains[1]) == ["ENC-T1"], [m.get("input") for m in mains]diff --git a/tests/fakes/providers/__init__.py b/tests/fakes/providers/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/fakes/providers/openai_responses.py b/tests/fakes/providers/openai_responses.pynew file mode 100644index 00000000000..9f160225cad--- /dev/null+++ b/tests/fakes/providers/openai_responses.py@@ -0,0 +1,520 @@+"""Scripted, recording loopback server for the OpenAI **Responses** wire dialect.++The external boundary Hermes' ``codex_responses`` transport talks to (ChatGPT Codex,+api.openai.com ``/v1/responses``, Responses-speaking relays). One real HTTP server on+127.0.0.1 that:++* answers ``POST .../responses`` with a streamed SSE event sequence+ (``response.created`` → ``response.output_item.added``/``.done`` per item, text and+ function-call argument deltas → ``response.completed`` with ``usage``) or a scripted+ fault: an HTTP error with ``Retry-After``, the HTTP-200 soft failure+ (``response.failed`` carrying ``invalid_encrypted_content``), or a socket drop after+ N events;+* records every request body and validates it against the installed ``openai`` SDK's+ own request schema (``ResponseCreateParamsStreaming`` through a pydantic+ ``TypeAdapter``) — the SDK is the oracle for what a well-formed request is, so a test+ can assert ``srv.invalid_requests() == []`` instead of hand-pinning field names;+* builds every emitted event from ``openai.types.responses`` models, so the stream is+ exactly what the SDK itself would parse from the real vendor.++Main-turn requests (those carrying ``tools``) consume the script in order; tool-less+requests (title generation and other auxiliary calls, on ``/responses`` or+``/chat/completions``) get a canned answer and never eat a scripted turn.++Record mode (manual, never run by the suite — no paid call is ever made by tests)::++ python -m tests.fakes.providers.openai_responses record \\+ --upstream https://api.openai.com/v1 --out tests/fakes/providers/cassettes/openai/<name>.json++starts a pass-through proxy on 127.0.0.1; point a Hermes home's ``base_url`` at it,+run one turn, and the proxy writes a *sanitized* cassette (auth headers dropped,+``encrypted_content`` and ids replaced with stable placeholders, bodies kept). A+cassette's recorded event list can be replayed with ``Cassette(path)`` in a script.+"""++from __future__ import annotations++import json+import re+import threading+import time+import uuid+from dataclasses import dataclass, field+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import Any, Callable, Union++from openai.types.responses import (+ Response,+ ResponseCompletedEvent,+ ResponseCreatedEvent,+ ResponseError,+ ResponseFailedEvent,+ ResponseFunctionCallArgumentsDeltaEvent,+ ResponseFunctionCallArgumentsDoneEvent,+ ResponseFunctionToolCall,+ ResponseOutputItemAddedEvent,+ ResponseOutputItemDoneEvent,+ ResponseOutputMessage,+ ResponseOutputText,+ ResponseReasoningItem,+ ResponseTextDeltaEvent,+ ResponseUsage,+)+from openai.types.responses.response_create_params import ResponseCreateParamsStreaming+from openai.types.responses.response_reasoning_item import Summary+from openai.types.responses.response_usage import InputTokensDetails, OutputTokensDetails+from pydantic import TypeAdapter++MODEL_ID = "fake-responses-model"++# Script items ------------------------------------------------------------------+++@dataclass+class Reasoning:+ """A reasoning output item carrying an opaque ``encrypted_content`` blob."""++ encrypted: str+ summary: str = ""+++@dataclass+class Message:+ """An assistant ``message`` output item (streamed as ``output_text`` deltas)."""++ text: str+++@dataclass+class FunctionCall:+ """A ``function_call`` output item. ``args`` as ``str`` is sent verbatim."""++ name: str+ args: dict[str, Any] | str = field(default_factory=dict)+++Item = Union[Reasoning, Message, FunctionCall]+++@dataclass+class Turn:+ """One successful streamed response made of ``items`` (in output order)."""++ items: list[Item]+ input_tokens: int = 100+ output_tokens: int = 20+ cached_tokens: int = 0+ drop_after_events: int | None = None # close the socket after N events (no terminal event)+++@dataclass+class SoftFail:+ """HTTP 200 whose stream ends in ``response.failed`` (the error lives in the body)."""++ code: str = "invalid_encrypted_content"+ message: str = "Encrypted content could not be decrypted or parsed."+++@dataclass+class HttpError:+ """A non-2xx JSON error (``{"error": {...}}``), optionally with ``Retry-After``."""++ status: int = 500+ message: str = "scripted failure"+ code: str | None = None+ type: str = "server_error"+ retry_after: float | None = None+++@dataclass+class Cassette:+ """Replay the event list of a sanitized cassette written by record mode."""++ path: Path+++Step = Union[Turn, SoftFail, HttpError, Cassette]+Responder = Callable[[dict[str, Any]], Step]++_REQUEST_ADAPTER = TypeAdapter(ResponseCreateParamsStreaming)+++# Replayed output items the vendor accepts WITHOUT ``id`` under ``store: false``. The SDK+# TypedDicts mark ``id`` required, but with nothing persisted server-side a replayed id has+# nothing to resolve against (a foreign/unpersisted id 404s), so Hermes replays these items+# by content alone (``encrypted_content`` for reasoning, the text for assistant messages).+# This is the ONLY relaxation of the oracle; every other field is still validated.+_ID_OPTIONAL_REPLAY_TYPES = frozenset({"reasoning", "message"})+++def _apply_vendor_deviations(body: dict[str, Any]) -> dict[str, Any]:+ items = body.get("input")+ if not isinstance(items, list) or body.get("store") is not False:+ return body+ return {**body, "input": [+ {**i, "id": "replayed_without_id"}+ if isinstance(i, dict) and i.get("type") in _ID_OPTIONAL_REPLAY_TYPES and "id" not in i+ and i.get("role", "assistant") == "assistant" else i+ for i in items]}+++def _item_members() -> dict[str, list[Any]]:+ """``type`` literal -> the SDK input-item TypedDicts declaring it (for readable errors)."""+ from typing import get_args, get_type_hints++ from openai.types.responses.response_input_item_param import ResponseInputItemParam++ out: dict[str, list[Any]] = {}+ for member in get_args(ResponseInputItemParam):+ for lit in get_args(get_type_hints(member).get("type")):+ out.setdefault(lit, []).append(member)+ return out+++def _explain_items(items: list[Any]) -> str:+ """Per-item errors against the members sharing the item's ``type`` (the union error+ pydantic reports for the whole request is thousands of lines of non-matching members)."""+ members, lines = _item_members(), []+ for idx, item in enumerate(items):+ if not isinstance(item, dict) or "type" not in item:+ continue+ errors = []+ for member in members.get(item["type"], []):+ ta = TypeAdapter(member)+ try:+ ta.dump_json(ta.validate_python(item), warnings=False)+ errors = []+ break+ except Exception as exc: # noqa: BLE001+ errors.append(f"{member.__name__}: {exc}")+ if errors:+ lines.append(f"input[{idx}] type={item['type']}: " + " | ".join(errors))+ return "\n".join(lines)+++def validate_request(body: dict[str, Any]) -> str | None:+ """SDK-oracle validation of one ``/responses`` request body; ``None`` when well-formed.++ ``dump_json`` forces pydantic's lazy ``Iterable[...]`` validators (``input``,+ ``tools``) to walk every element, so a malformed nested item is reported too."""+ body = _apply_vendor_deviations(body)+ try:+ _REQUEST_ADAPTER.dump_json(_REQUEST_ADAPTER.validate_python(body), warnings=False)+ except Exception as exc: # noqa: BLE001 - reported to the test verbatim+ detail = _explain_items(body["input"]) if isinstance(body.get("input"), list) else ""+ return (detail or str(exc))[:4000]+ return None+++# Event rendering ---------------------------------------------------------------+++class _Seq:+ def __init__(self) -> None:+ self.n = 0++ def __call__(self) -> int:+ self.n += 1+ return self.n+++def _response(resp_id: str, status: str, output: list[Any], usage: ResponseUsage | None = None) -> Response:+ return Response(+ id=resp_id, created_at=time.time(), model=MODEL_ID, object="response", output=output,+ parallel_tool_calls=True, tool_choice="auto", tools=[], status=status, usage=usage,+ )+++def _built_item(item: Item, idx: int) -> Any:+ if isinstance(item, Reasoning):+ summary = [Summary(text=item.summary, type="summary_text")] if item.summary else []+ return ResponseReasoningItem(id=f"rs_{idx}_{uuid.uuid4().hex[:8]}", summary=summary, type="reasoning",+ encrypted_content=item.encrypted)+ if isinstance(item, Message):+ return ResponseOutputMessage(+ id=f"msg_{idx}_{uuid.uuid4().hex[:8]}", role="assistant", status="completed", type="message",+ content=[ResponseOutputText(annotations=[], text=item.text, type="output_text")])+ args = item.args if isinstance(item.args, str) else json.dumps(item.args)+ return ResponseFunctionToolCall(id=f"fc_{idx}_{uuid.uuid4().hex[:8]}", call_id=f"call_{uuid.uuid4().hex[:10]}",+ name=item.name, arguments=args, type="function_call", status="completed")+++def _item_events(built: Any, idx: int, seq: _Seq) -> list[Any]:+ events: list[Any] = []+ if isinstance(built, ResponseOutputMessage):+ opening = built.model_copy(update={"content": [], "status": "in_progress"})+ elif isinstance(built, ResponseFunctionToolCall):+ opening = built.model_copy(update={"arguments": "", "status": "in_progress"})+ else:+ opening = built+ events.append(ResponseOutputItemAddedEvent(item=opening, output_index=idx, sequence_number=seq(),+ type="response.output_item.added"))+ if isinstance(built, ResponseOutputMessage):+ text = built.content[0].text+ for i in range(0, len(text), 16):+ events.append(ResponseTextDeltaEvent(content_index=0, delta=text[i:i + 16], item_id=built.id, logprobs=[],+ output_index=idx, sequence_number=seq(),+ type="response.output_text.delta"))+ if isinstance(built, ResponseFunctionToolCall):+ events.append(ResponseFunctionCallArgumentsDeltaEvent(+ delta=built.arguments, item_id=built.id or "", output_index=idx, sequence_number=seq(),+ type="response.function_call_arguments.delta"))+ events.append(ResponseFunctionCallArgumentsDoneEvent(+ arguments=built.arguments, item_id=built.id or "", name=built.name, output_index=idx,+ sequence_number=seq(), type="response.function_call_arguments.done"))+ events.append(ResponseOutputItemDoneEvent(item=built, output_index=idx, sequence_number=seq(),+ type="response.output_item.done"))+ return events+++def turn_events(turn: Turn) -> list[dict[str, Any]]:+ """The full SSE event sequence for ``turn``, each event a JSON-mode dict."""+ seq, resp_id = _Seq(), f"resp_{uuid.uuid4().hex[:12]}"+ events: list[Any] = [ResponseCreatedEvent(response=_response(resp_id, "in_progress", []),+ sequence_number=seq(), type="response.created")]+ built = [_built_item(item, i) for i, item in enumerate(turn.items)]+ for i, b in enumerate(built):+ events.extend(_item_events(b, i, seq))+ usage = ResponseUsage(+ input_tokens=turn.input_tokens, output_tokens=turn.output_tokens,+ total_tokens=turn.input_tokens + turn.output_tokens,+ input_tokens_details=InputTokensDetails(cached_tokens=turn.cached_tokens),+ output_tokens_details=OutputTokensDetails(reasoning_tokens=0))+ events.append(ResponseCompletedEvent(response=_response(resp_id, "completed", built, usage),+ sequence_number=seq(), type="response.completed"))+ return [e.model_dump(mode="json", exclude_none=True) for e in events]+++def soft_fail_events(fail: SoftFail) -> list[dict[str, Any]]:+ """``response.created`` then ``response.failed``. ``model_construct`` for the error: the+ SDK's ``ResponseError.code`` literal lags the codes the vendor actually sends in this slot+ (``invalid_encrypted_content`` is observed in production and absent from the literal)."""+ seq, resp_id = _Seq(), f"resp_{uuid.uuid4().hex[:12]}"+ created = ResponseCreatedEvent(response=_response(resp_id, "in_progress", []), sequence_number=seq(),+ type="response.created")+ failed_resp = _response(resp_id, "failed", []).model_copy(+ update={"error": ResponseError.model_construct(code=fail.code, message=fail.message)})+ failed = ResponseFailedEvent.model_construct(response=failed_resp, sequence_number=seq(), type="response.failed")+ out = [created.model_dump(mode="json", exclude_none=True)]+ dumped = failed.model_dump(mode="json", exclude_none=True, warnings=False)+ dumped["response"]["error"] = {"code": fail.code, "message": fail.message}+ return out + [dumped]+++# Server ------------------------------------------------------------------------+++class FakeResponsesServer:+ """Threaded loopback Responses provider. Use as a context manager."""++ def __init__(self, script: list[Step] | Responder | None = None, *, default_text: str = "ok",+ api_key: str | None = None) -> None:+ self._script: list[Step] = list(script) if isinstance(script, list) else []+ self._responder: Responder | None = script if callable(script) else None+ self.default_text = default_text+ self.api_key = api_key+ self.requests: list[dict[str, Any]] = []+ self._lock = threading.Lock()+ self._server: ThreadingHTTPServer | None = None++ def __enter__(self) -> "FakeResponsesServer":+ server = ThreadingHTTPServer(("127.0.0.1", 0), _handler_for(self))+ server.daemon_threads = True+ self._server = server+ threading.Thread(target=server.serve_forever, name="fake-responses", daemon=True).start()+ return self++ def __exit__(self, *_exc: object) -> None:+ if self._server is not None:+ self._server.shutdown()+ self._server.server_close()++ @property+ def base_url(self) -> str:+ assert self._server is not None, "server not started"+ return f"http://127.0.0.1:{self._server.server_address[1]}/v1"++ def push(self, *steps: Step) -> None:+ with self._lock:+ self._script.extend(steps)++ def next_step(self, record: dict[str, Any]) -> Step:+ if self._responder is not None:+ return self._responder(record)+ with self._lock:+ if self._script:+ return self._script.pop(0)+ return Turn([Message(self.default_text)])++ def main_requests(self) -> list[dict[str, Any]]:+ return [r["body"] for r in self.requests if r["kind"] == "main"]++ def invalid_requests(self) -> list[tuple[int, str]]:+ """``(index, error)`` for every main request the SDK schema rejects."""+ mains = [r for r in self.requests if r["kind"] == "main"]+ return [(i, r["invalid"]) for i, r in enumerate(mains) if r.get("invalid")]+++def _handler_for(server: FakeResponsesServer) -> type[BaseHTTPRequestHandler]:+ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *_a: object) -> None:+ pass++ def _json(self, status: int, payload: dict[str, Any], headers: dict[str, str] | None = None) -> None:+ body = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ for k, v in (headers or {}).items():+ self.send_header(k, v)+ self.end_headers()+ self.wfile.write(body)++ def do_GET(self) -> None: # noqa: N802+ if self.path.rstrip("/").endswith("/models"):+ self._json(200, {"object": "list", "data": [+ {"id": MODEL_ID, "object": "model", "context_length": 128000}]})+ return+ self._json(404, {"error": {"message": "not found"}})++ def do_POST(self) -> None: # noqa: N802+ raw = self.rfile.read(int(self.headers.get("Content-Length", 0) or 0))+ try:+ body = json.loads(raw or b"{}")+ except json.JSONDecodeError:+ self._json(400, {"error": {"message": "invalid json"}})+ return+ path = self.path.rstrip("/")+ is_responses = path.endswith("/responses")+ kind = "main" if is_responses and body.get("tools") else "aux"+ record = {"path": self.path, "kind": kind, "body": body, "t": time.time(),+ "headers": {k.lower(): v for k, v in self.headers.items()}}+ if is_responses:+ record["invalid"] = validate_request(body)+ with server._lock:+ server.requests.append(record)+ if server.api_key and self.headers.get("Authorization", "") != f"Bearer {server.api_key}":+ self._json(401, {"error": {"message": "invalid api key", "type": "authentication_error"}})+ return+ if path.endswith("/chat/completions"):+ self._aux_chat(bool(body.get("stream")))+ return+ if not is_responses:+ self._json(404, {"error": {"message": f"unsupported path {self.path}"}})+ return+ step = server.next_step(record) if kind == "main" else Turn([Message("Fake title")])+ record["response"] = type(step).__name__+ self._render(step)++ def _render(self, step: Step) -> None:+ if isinstance(step, HttpError):+ headers = {"Retry-After": str(step.retry_after)} if step.retry_after is not None else {}+ self._json(step.status, {"error": {"message": step.message, "type": step.type, "code": step.code}},+ headers)+ return+ if isinstance(step, SoftFail):+ events, limit = soft_fail_events(step), None+ elif isinstance(step, Cassette):+ events, limit = json.loads(Path(step.path).read_text(encoding="utf-8"))["events"], None+ else:+ events, limit = turn_events(step), step.drop_after_events+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Cache-Control", "no-cache")+ self.send_header("Connection", "close")+ self.end_headers()+ for i, event in enumerate(events):+ if limit is not None and i >= limit:+ break+ self.wfile.write(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode())+ self.wfile.flush()+ self.close_connection = True++ def _aux_chat(self, stream: bool) -> None:+ msg = {"role": "assistant", "content": "Fake title"}+ usage = {"prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12}+ if not stream:+ self._json(200, {"id": "chatcmpl-aux", "object": "chat.completion", "created": int(time.time()),+ "model": MODEL_ID, "usage": usage,+ "choices": [{"index": 0, "message": msg, "finish_reason": "stop"}]})+ return+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Connection", "close")+ self.end_headers()+ for delta, fin in ((msg, None), ({}, "stop")):+ chunk = {"id": "chatcmpl-aux", "object": "chat.completion.chunk", "created": int(time.time()),+ "model": MODEL_ID, "choices": [{"index": 0, "delta": delta, "finish_reason": fin}]}+ self.wfile.write(f"data: {json.dumps(chunk)}\n\n".encode())+ self.wfile.write(b"data: [DONE]\n\n")+ self.wfile.flush()+ self.close_connection = True++ return Handler+++# Record mode (manual) ------------------------------------------------------------++_SECRETISH = re.compile(r"(sk-[A-Za-z0-9_-]{8,}|eyJ[A-Za-z0-9_.-]{20,})")+++def sanitize_event(event: dict[str, Any], counter: list[int]) -> dict[str, Any]:+ """Replace opaque/secret-bearing values with stable placeholders (recursive)."""+ def walk(v: Any, key: str = "") -> Any:+ if isinstance(v, dict):+ return {k: walk(x, k) for k, x in v.items()}+ if isinstance(v, list):+ return [walk(x) for x in v]+ if isinstance(v, str):+ if key == "encrypted_content":+ counter[0] += 1+ return f"ENC-PLACEHOLDER-{counter[0]}"+ return _SECRETISH.sub("REDACTED", v)+ return v+ return walk(event)+++def record_proxy(upstream: str, out: Path, port: int = 0) -> None: # pragma: no cover - manual tool+ """Pass-through proxy that writes one sanitized cassette per ``/responses`` call."""+ import httpx++ def handler_cls() -> type[BaseHTTPRequestHandler]:+ class H(BaseHTTPRequestHandler):+ def do_POST(self) -> None: # noqa: N802+ raw = self.rfile.read(int(self.headers.get("Content-Length", 0) or 0))+ headers = {k: v for k, v in self.headers.items() if k.lower() in {"authorization", "content-type"}}+ url = upstream.rstrip("/") + self.path.removeprefix("/v1")+ events: list[dict[str, Any]] = []+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.end_headers()+ with httpx.stream("POST", url, content=raw, headers=headers, timeout=300) as resp:+ for line in resp.iter_lines():+ if line.startswith("data: ") and line != "data: [DONE]":+ events.append(json.loads(line[6:]))+ self.wfile.write((line + "\n").encode())+ self.wfile.flush()+ counter = [0]+ out.write_text(json.dumps({+ "request": sanitize_event(json.loads(raw or b"{}"), counter),+ "events": [sanitize_event(e, counter) for e in events]}, indent=1), encoding="utf-8")+ return H++ srv = ThreadingHTTPServer(("127.0.0.1", port), handler_cls())+ print(f"recording proxy on http://127.0.0.1:{srv.server_address[1]}/v1 -> {upstream}", flush=True)+ srv.serve_forever()+++if __name__ == "__main__": # pragma: no cover - manual entry point+ import argparse++ ap = argparse.ArgumentParser()+ ap.add_argument("mode", choices=["record"])+ ap.add_argument("--upstream", required=True)+ ap.add_argument("--out", required=True, type=Path)+ ap.add_argument("--port", type=int, default=0)+ ns = ap.parse_args()+ record_proxy(ns.upstream, ns.out, ns.port)