The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: Anthropic Messages wire-conformance E2E suite (SDK-oracle fake, native route via TLS intercept)
teknium148f6284d7261
diff --git a/tests/e2e/core/providers/_anthropic_helpers.py b/tests/e2e/core/providers/_anthropic_helpers.pynew file mode 100644index 00000000000..a3f5f4ed94d--- /dev/null+++ b/tests/e2e/core/providers/_anthropic_helpers.py@@ -0,0 +1,230 @@+"""Hermetic rig for the Anthropic Messages wire-conformance E2E suite.++Hermes' native ``anthropic`` provider runs with NO base URL override, i.e. the+exact production route to ``https://api.anthropic.com`` (native thinking-signature+policy, native headers). The child reaches the scripted fake through an+``HTTPS_PROXY`` that terminates TLS for ``api.anthropic.com`` with a leaf signed+by a throwaway CA trusted via ``SSL_CERT_FILE``; only the vendor HTTP boundary+is faked. Every child runs with an allowlisted env, ``HOME``/``HERMES_HOME``+under ``tmp_path`` and a unique tag so cleanup signals only its own tree.+"""++from __future__ import annotations++import copy+import json+import os+import signal+import sqlite3+import subprocess+import sys+import time+import uuid+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Callable++import yaml++from tests.fakes.providers.anthropic_messages import MODEL_ID, AnthropicMessagesServer, Response, Responder+from tests.fakes.providers.oauth_token_server import TLSInterceptProxy, make_test_ca++REPO_ROOT = Path(__file__).resolve().parents[4]+TAG_VAR = "ANTHROPIC_E2E_TAG"+VENDOR_HOST = "api.anthropic.com"+TURN_TIMEOUT = 180.0++_SECRET_ENV_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET", "_ACCESS_KEY")+_PASSTHROUGH_ENV = frozenset({"PATH", "LANG", "LANGUAGE", "USER", "LOGNAME", "SHELL", "TMPDIR", "TZ"})+++@dataclass+class Rig:+ root: Path+ home: Path+ hermes_home: Path+ project: Path+ srv: AnthropicMessagesServer+ proxy: TLSInterceptProxy+ ca_pem: Path+ tag: str = field(default_factory=lambda: uuid.uuid4().hex)++ def env(self, extra: dict[str, str] | None = None) -> dict[str, str]:+ import pwd # POSIX-only; 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", (+ f"fixture HERMES_HOME {fixture} is the real install's 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)}+ loopback = "127.0.0.1,localhost"+ env.update({+ "HOME": str(self.home), "HERMES_HOME": str(self.hermes_home), "PYTHONPATH": str(REPO_ROOT),+ "PYTHONUNBUFFERED": "1", "NO_COLOR": "1", "TERM": "dumb", TAG_VAR: self.tag,+ "HTTPS_PROXY": self.proxy.url, "https_proxy": self.proxy.url,+ "NO_PROXY": loopback, "no_proxy": loopback, "SSL_CERT_FILE": str(self.ca_pem),+ # The child's ~/.hermes/state.db IS the tmp home's db (see parity/_helpers.py).+ "HERMES_STATE_DB_GUARD_BYPASS": "1",+ })+ env.update(extra or {})+ return env++ def config(self) -> dict[str, Any]:+ return yaml.safe_load((self.hermes_home / "config.yaml").read_text(encoding="utf-8"))++ def update_config(self, mutate: Callable[[dict[str, Any]], None]) -> None:+ cfg = self.config()+ mutate(cfg)+ (self.hermes_home / "config.yaml").write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")++ def run(self, *args: str, timeout: float = TURN_TIMEOUT, extra_env: dict[str, str] | None = None,+ ) -> subprocess.CompletedProcess:+ return subprocess.run(hermes_argv(*args), cwd=self.project, env=self.env(extra_env), capture_output=True,+ text=True, timeout=timeout, stdin=subprocess.DEVNULL)++ def stop(self) -> None:+ kill_tagged(self.tag)+ self.proxy.stop()+ self.srv.stop()++ def log_tail(self, chars: int = 3000, pattern: str = "") -> str:+ """The child's agent.log tail (CI prints only the assertion message, so failures carry it)."""+ log = self.hermes_home / "logs" / "agent.log"+ if not log.exists():+ return "<no agent.log>"+ lines = log.read_text(encoding="utf-8", errors="replace").splitlines()+ return "\n".join(ln for ln in lines if pattern.lower() in ln.lower())[-chars:]++ # persisted state ------------------------------------------------------------+ def _db(self) -> sqlite3.Connection:+ return sqlite3.connect(f"file:{self.hermes_home / 'state.db'}?mode=ro", uri=True)++ def session_ids(self) -> list[str]:+ with self._db() as db:+ return [r[0] for r in db.execute("select id from sessions order by started_at")]++ def messages(self, session_id: str) -> list[dict[str, Any]]:+ with self._db() as db:+ db.row_factory = sqlite3.Row+ return [dict(r) for r in db.execute(+ "select * from messages where session_id = ? order by id", (session_id,))]+++def hermes_argv(*args: str) -> list[str]:+ return [sys.executable, "-m", "hermes_cli.main", *args]+++def start_rig(root: Path, script: list[Response] | Responder, *, config: dict[str, Any] | None = None,+ aux: Responder | None = None) -> Rig:+ srv = AnthropicMessagesServer(script, aux=aux).start()+ ca = make_test_ca(root / "ca", [VENDOR_HOST])+ proxy = TLSInterceptProxy(srv, ca, [VENDOR_HOST]).start() # type: ignore[arg-type]+ home = root / "home"+ rig = Rig(root=root, home=home, hermes_home=home / ".hermes", project=root / "project", srv=srv,+ proxy=proxy, ca_pem=ca.ca_pem)+ rig.hermes_home.mkdir(parents=True)+ rig.project.mkdir()+ cfg: dict[str, Any] = {+ # No base_url: the production native route (the proxy intercepts api.anthropic.com).+ "model": {"provider": "anthropic", "default": MODEL_ID, "context_length": 200000},+ "agent": {"api_max_retries": 1, "reasoning_effort": "medium"},+ "auxiliary": {"title_generation": {"enabled": False}},+ "updates": {"check": False},+ "display": {"compact": True},+ }+ for key, value in (config or {}).items():+ cfg[key] = {**cfg.get(key, {}), **value} if isinstance(value, dict) else value+ (rig.hermes_home / "config.yaml").write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")+ (rig.hermes_home / ".env").write_text("ANTHROPIC_API_KEY=sk-ant-api03-e2e-fake-key\n", encoding="utf-8")+ return rig+++def kill_tagged(tag: str) -> None:+ """SIGKILL every live process carrying ``ANTHROPIC_E2E_TAG=<tag>`` (this test's tree only)."""+ needle = f"{TAG_VAR}={tag}".encode()+ me = os.getpid()+ for entry in os.listdir("/proc"):+ if not entry.isdigit() or int(entry) == me:+ continue+ try:+ with open(f"/proc/{entry}/environ", "rb") as fh:+ env = fh.read()+ except OSError:+ continue+ if needle in env.split(b"\0"):+ try:+ os.kill(int(entry), signal.SIGKILL)+ except OSError:+ pass+++def wait_until(pred: Callable[[], Any], timeout: float, what: str, interval: float = 0.05) -> Any:+ deadline = time.monotonic() + timeout+ while True:+ value = pred()+ if value:+ return value+ if time.monotonic() >= deadline:+ raise AssertionError(f"timed out after {timeout}s waiting for {what}")+ time.sleep(interval)+++# wire views -----------------------------------------------------------------------+++def blocks(message: dict[str, Any]) -> list[dict[str, Any]]:+ content = message.get("content")+ if isinstance(content, str):+ return [{"type": "text", "text": content}]+ return list(content or [])+++def thinking_of(message: dict[str, Any]) -> list[tuple[str, str]]:+ return [(b.get("thinking", ""), b.get("signature", "")) for b in blocks(message) if b.get("type") == "thinking"]+++def assistant_messages(body: dict[str, Any]) -> list[dict[str, Any]]:+ return [m for m in body.get("messages") or [] if m.get("role") == "assistant"]+++def without_cache_control(value: Any) -> Any:+ """History with the moving ``cache_control`` breakpoints removed (they legitimately shift per turn)."""+ value = copy.deepcopy(value)+ if isinstance(value, dict):+ value.pop("cache_control", None)+ return {k: without_cache_control(v) for k, v in value.items()}+ if isinstance(value, list):+ return [without_cache_control(v) for v in value]+ return value+++def normalised(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Messages with string content expanded to one text block and cache markers dropped."""+ return [{"role": m["role"], "content": without_cache_control(blocks(m))} for m in messages]+++def tool_pairing_problems(body: dict[str, Any]) -> list[str]:+ """Anthropic's pairing rule: every tool_use id is answered by a tool_result in the NEXT user+ message, and every tool_result answers a tool_use of the immediately preceding assistant message."""+ problems: list[str] = []+ msgs = body.get("messages") or []+ for i, m in enumerate(msgs):+ if m.get("role") == "assistant":+ uses = [b["id"] for b in blocks(m) if b.get("type") == "tool_use"]+ nxt = msgs[i + 1] if i + 1 < len(msgs) else None+ results = [b.get("tool_use_id") for b in blocks(nxt or {}) if b.get("type") == "tool_result"]+ if uses and sorted(uses) != sorted(results):+ problems.append(f"msg {i}: tool_use {uses} answered by {results}")+ else:+ prev = msgs[i - 1] if i else {}+ uses = {b.get("id") for b in blocks(prev) if b.get("type") == "tool_use"}+ orphans = [b.get("tool_use_id") for b in blocks(m)+ if b.get("type") == "tool_result" and b.get("tool_use_id") not in uses]+ if orphans:+ problems.append(f"msg {i}: orphan tool_result {orphans}")+ return problems+++def dump(body: dict[str, Any], limit: int = 3000) -> str:+ return json.dumps(without_cache_control(body.get("messages")), default=str)[-limit:]diff --git a/tests/e2e/core/providers/test_anthropic_compaction.py b/tests/e2e/core/providers/test_anthropic_compaction.pynew file mode 100644index 00000000000..a610b9b5e6c--- /dev/null+++ b/tests/e2e/core/providers/test_anthropic_compaction.py@@ -0,0 +1,121 @@+"""Anthropic Messages wire conformance: compaction in a session full of signed thinking.++Real ``hermes chat -q`` / ``--resume`` turns run interleaved [thinking, tool_use] rounds+whose tool results are large, with the compaction trigger pinned low (documented+``compression.threshold_tokens``) so older history is summarised repeatedly. For EVERY request+the fake saw: tool_use/tool_result pairing holds (no orphan tool_result after a+summary cut), the latest assistant message still leads with ITS signed thinking+byte-exact, and the body validates against the SDK schema.+"""++from __future__ import annotations++import json+import sys+import threading+from pathlib import Path++import pytest++from tests.e2e.core.providers._anthropic_helpers import (+ assistant_messages,+ blocks,+ dump,+ start_rig,+ thinking_of,+ tool_pairing_problems,+)+from tests.fakes.providers.anthropic_messages import Reply, Text, Thinking, ToolUse++pytestmark = [pytest.mark.skipif(not sys.platform.startswith("linux"), reason="process-tree cleanup uses /proc"),+ pytest.mark.live_system_guard_bypass]++TURNS = 6+SUMMARY_TOKEN = "E2E-ANTHROPIC-SUMMARY-7f3a"+++def _sig(i: int) -> str:+ return f"EqRound{i:02d}+/sigBytes{'x' * i}=="+++def _think(i: int) -> str:+ return f"Round {i}: read the next chunk."+++def _last_is_tool_result(body: dict) -> bool:+ last = (body.get("messages") or [{}])[-1]+ return last.get("role") == "user" and any(b.get("type") == "tool_result" for b in blocks(last))+++def rig(tmp_path: Path):+ lock = threading.Lock()+ state = {"calls": 0, "answers": 0}+ files: list[Path] = []++ def respond(record):+ body = record["body"]+ tokens = len(json.dumps(body)) // 4+ with lock:+ if _last_is_tool_result(body):+ state["answers"] += 1+ n = state["answers"]+ return Reply([Thinking(f"Answer {n}.", _sig(50 + n)), Text(f"TURN-{n}-DONE")], input_tokens=tokens)+ state["calls"] += 1+ i = state["calls"]+ return Reply([Thinking(_think(i), _sig(i)), ToolUse("read_file", {"path": str(files[i - 1])})],+ input_tokens=tokens)++ def aux(record):+ return Reply([Text(f"{SUMMARY_TOKEN}: the assistant read chunks and is still reading.")],+ input_tokens=len(json.dumps(record["body"])) // 4)++ r = start_rig(tmp_path / "r", respond, aux=aux, config={+ "model": {"context_length": 64000},+ "compression": {"threshold_tokens": 20000, "protect_last_n": 4},+ })+ for i in range(1, TURNS + 1):+ path = r.project / f"chunk{i}.txt"+ path.write_text("\n".join(f"chunk {i} line {n}: " + "lorem ipsum dolor sit amet " * 6+ for n in range(200)), encoding="utf-8")+ files.append(path)+ yield r+ r.stop()+++def _drive_turns(rig) -> None:+ first = rig.run("chat", "-q", "Read chunk 1.", "-Q")+ assert first.returncode == 0 and "TURN-1-DONE" in first.stdout, first.stderr[-2000:]+ (session_id,) = rig.session_ids()+ for n in range(2, TURNS + 1):+ proc = rig.run("chat", "--resume", session_id, "-q", f"Read chunk {n}.", "-Q")+ assert proc.returncode == 0 and f"TURN-{n}-DONE" in proc.stdout, (n, proc.stderr[-2000:])+++def test_compaction_keeps_pairing_and_signatures(rig) -> None:+ """Six resumed turns of [thinking, tool_use] -> [thinking, text] with ~9K-token tool results+ against a 20K trigger: history is summarised repeatedly. No request may carry an orphan+ tool_result, and every in-flight tool turn still leads with ITS signed thinking byte-exact."""+ _drive_turns(rig)+ mains = [r["body"] for r in rig.srv.main_requests()]+ assert len(mains) == 2 * TURNS, f"expected {2 * TURNS} main requests, saw {len(mains)}"+ summarised = [i for i, b in enumerate(mains) if SUMMARY_TOKEN in json.dumps(b.get("messages"))]+ assert summarised, (+ f"precondition: the trigger never fired, nothing was compacted (last request "+ f"{len(json.dumps(mains[-1])) // 4} est. tokens)\n{rig.log_tail(pattern='compress', chars=6000)}")+ assert not rig.srv.schema_errors(), rig.srv.schema_errors()++ checked = 0+ for n, body in enumerate(mains, start=1):+ assert not tool_pairing_problems(body), (f"request {n}", tool_pairing_problems(body), dump(body))+ if not _last_is_tool_result(body):+ continue+ latest = assistant_messages(body)[-1]+ uses = [b for b in blocks(latest) if b.get("type") == "tool_use"]+ assert uses, f"request {n}: the in-flight tool_use turn was dropped: {dump(body)}"+ i = int(Path(uses[0]["input"]["path"]).stem.removeprefix("chunk"))+ assert blocks(latest)[0].get("type") == "thinking", f"request {n}: signed thinking dropped {dump(body)}"+ assert thinking_of(latest)[0] == (_think(i), _sig(i)), (+ f"request {n}: round {i} thinking/signature altered across compaction: {thinking_of(latest)}")+ checked += n > summarised[0]+ assert checked, "no in-flight tool turn was sent after the first summary; the post-compaction check is vacuous"diff --git a/tests/e2e/core/providers/test_anthropic_discovery_and_aliases.py b/tests/e2e/core/providers/test_anthropic_discovery_and_aliases.pynew file mode 100644index 00000000000..e44aaab2d06--- /dev/null+++ b/tests/e2e/core/providers/test_anthropic_discovery_and_aliases.py@@ -0,0 +1,157 @@+"""Anthropic route plumbing: model discovery endpoint and OAuth wire tool-name aliases.++* Discovery: with a custom Anthropic-protocol endpoint configured (``ANTHROPIC_BASE_URL``+ or ``model.base_url``), the picker catalog (``provider_model_ids``, behind ``hermes model``,+ ``/model``, the dashboard and Desktop pickers) must come from THAT endpoint's+ ``/v1/models`` — asserted by the fake seeing the GET and its relay-only id in the result.+* OAuth wire aliases: on the Claude subscription route Hermes renames tools on the wire+ (``mcp__`` prefix, ``memory`` -> ``context_notes``, ``session_search`` ->+ ``chat_history_lookup``). A real ``hermes -z`` turn must map every wire name the model+ may use back to the real tool, including names passed as tool-search arguments.+"""++from __future__ import annotations++import json+import subprocess+import sys+from pathlib import Path++import pytest++from tests.e2e.core.providers._anthropic_helpers import Rig, blocks, start_rig+from tests.fakes.providers.anthropic_messages import AnthropicMessagesServer, Reply, Text, ToolUse++pytestmark = [pytest.mark.skipif(not sys.platform.startswith("linux"), reason="process-tree cleanup uses /proc"),+ pytest.mark.live_system_guard_bypass]++KNOWN: dict[str, str] = {+ "discovery_env": "#120844 Anthropic model discovery ignores ANTHROPIC_BASE_URL",+ "alias_describe": "#120858 wire alias chat_history_lookup not reverse-mapped in tool_describe args",+}+RELAY_ONLY_MODEL = "claude-e2e-relay-only-7"+OAUTH_TOKEN = "sk-ant-oat01-e2e-fake-oauth-token"+++def known(key: str):+ return pytest.mark.xfail(strict=True, reason=KNOWN[key])+++def rig(tmp_path: Path):+ made: list[Rig] = []++ def make(script, **kw) -> Rig:+ r = start_rig(tmp_path / f"r{len(made)}", script, **kw)+ made.append(r)+ return r++ yield make+ for r in made:+ r.stop()+++# The CLI's own startup sequence (load ~/.hermes/.env), then the picker entry point.+_DISCOVERY_PROBE = (+ "import json; from hermes_cli.env_loader import load_hermes_dotenv; load_hermes_dotenv(); "+ "from hermes_cli.models import provider_model_ids; "+ "print('IDS=' + json.dumps(list(provider_model_ids('anthropic', force_refresh=True))))"+)+++def _discover(r: Rig, relay: AnthropicMessagesServer | None, *, via: str) -> list[str]:+ if relay is None:+ extra: dict[str, str] = {}+ elif via == "config":+ r.update_config(lambda c: c["model"].__setitem__("base_url", relay.base_url))+ extra = {}+ else:+ extra = {"ANTHROPIC_BASE_URL": relay.base_url.removesuffix("/anthropic")}+ proc = subprocess.run([sys.executable, "-c", _DISCOVERY_PROBE], cwd=r.project, env=r.env(extra),+ capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)+ assert proc.returncode == 0, proc.stderr[-2000:]+ line = next(ln for ln in proc.stdout.splitlines() if ln.startswith("IDS="))+ return json.loads(line[4:])+++def test_model_discovery_serves_the_live_native_catalog(rig) -> None:+ """Control for the override cases: with no custom endpoint the picker probes the native+ host's /v1/models (the intercepted fake) and serves its live ids, not the static table."""+ r = rig([])+ r.srv.models = [RELAY_ONLY_MODEL, "claude-e2e-native-other"]+ ids = _discover(r, None, via="native")+ assert [g for g in r.srv.gets if "/v1/models" in g["path"]], "discovery never probed the native endpoint"+ assert RELAY_ONLY_MODEL in ids, f"live catalog not served: {ids[:15]}"++[email protected]("via", [+ pytest.param("env", marks=known("discovery_env")),+ "config",+])+def test_model_discovery_probes_the_configured_anthropic_endpoint(rig, via: str) -> None:+ relay = AnthropicMessagesServer([], models=[RELAY_ONLY_MODEL, "claude-e2e-relay-other"]).start()+ try:+ r = rig([])+ ids = _discover(r, relay, via=via)+ probed = [g["path"] for g in relay.gets if "/v1/models" in g["path"]]+ assert probed, f"discovery never probed the configured endpoint (native host saw {len(r.srv.gets)} GETs)"+ assert RELAY_ONLY_MODEL in ids, f"relay catalog not served: {ids[:15]}"+ finally:+ relay.stop()+++def _oauth_rig(rig, script) -> Rig:+ r = rig(script)+ (r.hermes_home / ".env").write_text(f"ANTHROPIC_TOKEN={OAUTH_TOKEN}\n", encoding="utf-8")+ return r+++def _tool_results(body: dict) -> list[str]:+ return [json.dumps(b.get("content")) for m in body["messages"] if m["role"] == "user"+ for b in blocks(m) if b.get("type") == "tool_result"]+++def test_oauth_wire_names_map_back_to_real_tools(rig) -> None:+ """The model answers with wire names (``mcp__read_file`` and the ``context_notes`` alias of+ ``memory``) in one parallel turn; both must execute as the real tools: the file content comes+ back in the tool_result and the note lands in the real MEMORY.md."""+ note = "E2E-OAUTH-ALIAS-NOTE-5d1c"+ r = _oauth_rig(rig, [])+ target = r.project / "wire.txt"+ target.write_text("WIRE-FILE-CONTENT-93", encoding="utf-8")+ r.srv.push(+ Reply([ToolUse("mcp__read_file", {"path": str(target)}),+ ToolUse("mcp__context_notes", {"action": "add", "target": "memory", "content": note})]),+ Reply([Text("ALIASES-DONE")]),+ )+ proc = r.run("-z", "Read wire.txt and remember the note.")+ assert proc.returncode == 0 and "ALIASES-DONE" in proc.stdout, proc.stderr[-2000:]+ mains = r.srv.main_requests()+ assert len(mains) == 2+ first = mains[0]+ assert first["headers"].get("authorization") == f"Bearer {OAUTH_TOKEN}", "OAuth route must send the bearer"+ wire_names = {t["name"] for t in first["body"]["tools"]}+ assert {"mcp__read_file", "mcp__context_notes"} <= wire_names, sorted(wire_names)+ assert not {"memory", "session_search", "read_file"} & wire_names, "real names leaked onto the OAuth wire"+ results = _tool_results(mains[1]["body"])+ assert any("WIRE-FILE-CONTENT-93" in res for res in results), results+ memory_md = r.hermes_home / "memories" / "MEMORY.md"+ assert memory_md.exists() and note in memory_md.read_text(encoding="utf-8"), (+ f"aliased context_notes call did not reach the memory tool: {results}")+ assert not r.srv.schema_errors(), r.srv.schema_errors()+++@known("alias_describe")+def test_oauth_deferred_alias_resolves_through_tool_describe(rig) -> None:+ """The deferred catalog advertises ``chat_history_lookup`` (the OAuth alias of+ ``session_search``); asking ``tool_describe`` for that exact name must return its schema."""+ r = _oauth_rig(rig, [Reply([ToolUse("mcp__tool_describe", {"names": ["chat_history_lookup"]})]),+ Reply([Text("DESCRIBED")])])+ proc = r.run("-z", "Look up how to recall past chats.")+ assert proc.returncode == 0 and "DESCRIBED" in proc.stdout, proc.stderr[-2000:]+ mains = r.srv.main_requests()+ catalog = next(t for t in mains[0]["body"]["tools"] if t["name"] == "mcp__tool_search")+ assert "chat_history_lookup" in catalog["description"], "precondition: alias advertised in the catalog"+ (result,) = _tool_results(mains[1]["body"])+ assert "not_found" not in result or "chat_history_lookup" not in result.split("not_found", 1)[1][:80], result+ assert "chat_history_lookup" in result and ("parameters" in result or "input_schema" in result), resultdiff --git a/tests/e2e/core/providers/test_anthropic_errors.py b/tests/e2e/core/providers/test_anthropic_errors.pynew file mode 100644index 00000000000..e3442ed1878--- /dev/null+++ b/tests/e2e/core/providers/test_anthropic_errors.py@@ -0,0 +1,140 @@+"""Anthropic Messages wire conformance: documented error envelopes and stream faults.++A real ``hermes -z`` process on the native route meets the vendor's documented+failures (built from the SDK's error models): ``429 rate_limit_error`` with+``retry-after``, ``529 overloaded_error``, ``400 invalid_request_error`` and a+socket dropped in the middle of a thinking block. Each test asserts the retry+cadence/count the fake observed and what the user and state.db end up with.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++import pytest++from tests.e2e.core.providers._anthropic_helpers import Rig, dump, normalised, start_rig, thinking_of+from tests.fakes.providers.anthropic_messages import ApiError, DropStream, Reply, Text, Thinking++pytestmark = [pytest.mark.skipif(not sys.platform.startswith("linux"), reason="process-tree cleanup uses /proc"),+ pytest.mark.live_system_guard_bypass]+++# Red on current main for a tracked, open bug. Strict: the test FAILS the moment the bug is+# fixed, so the entry is removed with the fix instead of masking a later regression.+KNOWN: dict[str, str] = {+ "stream_drop_retry": "#121320 stream closed before message_stop is accepted as a complete answer",+}+++def known(key: str) -> pytest.MarkDecorator:+ return pytest.mark.xfail(strict=True, reason=KNOWN[key])+++def rig_factory(tmp_path: Path):+ rigs: list[Rig] = []++ def make(script, **kw) -> Rig:+ rig = start_rig(tmp_path / f"r{len(rigs)}", script, **kw)+ rigs.append(rig)+ return rig++ yield make+ for rig in rigs:+ rig.stop()+++def _gaps(rig: Rig) -> list[float]:+ t = [r["t"] for r in rig.srv.main_requests()]+ return [round(b - a, 2) for a, b in zip(t, t[1:])]+++def test_429_waits_the_retry_after_then_succeeds(rig_factory) -> None:+ retry_after = 3.0+ rig = rig_factory([ApiError(429, "rate_limit_error", "Number of requests exceeded", retry_after=retry_after),+ Reply([Text("AFTER-RATE-LIMIT")])], config={"agent": {"api_max_retries": 2}})+ proc = rig.run("-z", "hello")+ assert proc.returncode == 0 and "AFTER-RATE-LIMIT" in proc.stdout, proc.stderr[-2000:]+ assert len(rig.srv.main_requests()) == 2, [r.get("response") for r in rig.srv.requests]+ (gap,) = _gaps(rig)+ assert gap >= retry_after - 0.05, f"retried after {gap}s, before the server's retry-after {retry_after}s"+ assert gap < retry_after + 15, f"retry-after {retry_after}s stretched to {gap}s"+++def test_529_overloaded_is_retried_then_surfaced(rig_factory) -> None:+ retries = 2+ # auto_recovery_cycles: 0 disables the documented post-exhaustion wait ladder (15/30/60 s+ # cycles) so the attempt budget alone decides when the error reaches the user.+ rig = rig_factory(lambda _r: ApiError(529, "overloaded_error", "Overloaded"),+ config={"agent": {"api_max_retries": retries, "auto_recovery_cycles": 0}})+ proc = rig.run("-z", "hello")+ mains = rig.srv.main_requests()+ assert len(mains) == retries, (+ f"529 must use exactly the api_max_retries={retries} attempt budget; saw {len(mains)} requests, "+ f"gaps {_gaps(rig)}")+ assert all(g >= 0.5 for g in _gaps(rig)), f"529 retries must back off, gaps {_gaps(rig)}"+ surfaced = (proc.stdout + proc.stderr).lower()+ assert proc.returncode != 0 or "overload" in surfaced or "529" in surfaced, (+ f"exhausted 529s must reach the user: rc={proc.returncode} out={proc.stdout[-500:]!r}")+ assert "overload" in surfaced or "529" in surfaced, f"error not named: {surfaced[-800:]}"+++def test_400_invalid_request_is_surfaced_without_a_retry_storm(rig_factory) -> None:+ rig = rig_factory(lambda _r: ApiError(400, "invalid_request_error", "tools.0.custom.name: scripted rejection"),+ config={"agent": {"api_max_retries": 3}})+ proc = rig.run("-z", "hello")+ mains = rig.srv.main_requests()+ assert len(mains) == 1, f"a non-retryable 400 was re-sent {len(mains) - 1} times: gaps {_gaps(rig)}"+ surfaced = proc.stdout + proc.stderr+ assert "scripted rejection" in surfaced or "invalid_request" in surfaced or "400" in surfaced, surfaced[-800:]+++@known("stream_drop_retry")+def test_stream_drop_mid_thinking_retries_without_duplicate_persisted_content(rig_factory) -> None:+ """The socket dies after two thinking deltas (no signature, no message_stop). The retry must+ resend the same history (no half-streamed assistant turn leaks into it), the user sees the+ answer once, and state.db holds exactly one assistant row carrying only the completed turn."""+ partial = "PARTIAL-THOUGHT " * 6+ rig = rig_factory([+ DropStream(Reply([Thinking(partial, "sig-never-sent"), Text("LOST-ANSWER")], chunk_chars=16), after_deltas=2),+ Reply([Thinking("Clean retry reasoning.", "EqRetrySig+/=="), Text("RECOVERED-ANSWER")]),+ ], config={"agent": {"api_max_retries": 2}})+ proc = rig.run("chat", "-q", "hello", "-Q")+ assert proc.returncode == 0, proc.stderr[-2000:]+ assert proc.stdout.count("RECOVERED-ANSWER") == 1 and "LOST-ANSWER" not in proc.stdout, proc.stdout[-800:]+ mains = [r["body"] for r in rig.srv.main_requests()]+ assert len(mains) == 2, [r.get("response") for r in rig.srv.requests]+ assert normalised(mains[1]["messages"]) == normalised(mains[0]["messages"]), (+ f"retry history differs from the dropped request's: {dump(mains[1])}")++ (session_id,) = rig.session_ids()+ rows = rig.messages(session_id)+ assistants = [r for r in rows if r["role"] == "assistant"]+ assert len(assistants) == 1, [(r["role"], (r["content"] or "")[:60]) for r in rows]+ persisted = json.dumps(assistants[0], default=str)+ assert "RECOVERED-ANSWER" in persisted and "PARTIAL-THOUGHT" not in persisted and "LOST-ANSWER" not in persisted+ assert persisted.count("Clean retry reasoning.") >= 1+++@known("stream_drop_retry")+def test_stream_drop_then_next_turn_replays_only_the_completed_signature(rig_factory) -> None:+ """After a mid-thinking drop + successful retry, the NEXT user turn replays the retry's signed+ thinking byte-exact — never the dropped stream's unsigned fragment."""+ rig = rig_factory([+ DropStream(Reply([Thinking("FRAGMENT " * 8, "sig-never-sent"), Text("x")], chunk_chars=12), after_deltas=2),+ Reply([Thinking("Completed reasoning.", "EqCompleted+/Sig=="), Text("TURN-ONE")]),+ Reply([Text("TURN-TWO")]),+ ], config={"agent": {"api_max_retries": 2}})+ first = rig.run("chat", "-q", "one", "-Q")+ assert first.returncode == 0 and "TURN-ONE" in first.stdout, first.stderr[-2000:]+ (session_id,) = rig.session_ids()+ second = rig.run("chat", "--resume", session_id, "-q", "two", "-Q")+ assert second.returncode == 0 and "TURN-TWO" in second.stdout, second.stderr[-2000:]+ last = rig.srv.main_requests()[-1]["body"]+ prior = [m for m in last["messages"] if m["role"] == "assistant"]+ assert len(prior) == 1 and thinking_of(prior[0]) == [("Completed reasoning.", "EqCompleted+/Sig==")], dump(last)+ assert "FRAGMENT" not in json.dumps(last["messages"])+ assert not rig.srv.schema_errors(), rig.srv.schema_errors()diff --git a/tests/e2e/core/providers/test_anthropic_thinking_replay.py b/tests/e2e/core/providers/test_anthropic_thinking_replay.pynew file mode 100644index 00000000000..15c8117b06c--- /dev/null+++ b/tests/e2e/core/providers/test_anthropic_thinking_replay.py@@ -0,0 +1,189 @@+"""Anthropic Messages wire conformance: thinking signatures + tool pairing.++Real ``hermes`` processes (``-z``, ``chat -q``, ``chat --resume``, the stdio+``tui_gateway``) talk to the SDK-oracle fake on the production native route.+Each test asserts the NEXT wire request Hermes sends: signed thinking blocks+come back byte-exact (text AND signature), parallel ``tool_use`` ids are each+answered in the very next user message, and every request body validates+against the SDK's ``MessageCreateParams``.+"""++from __future__ import annotations++import json+import subprocess+import sys+import threading+import queue+from pathlib import Path++import pytest++from tests.e2e.core.providers._anthropic_helpers import (+ TURN_TIMEOUT,+ Rig,+ assistant_messages,+ blocks,+ dump,+ normalised,+ start_rig,+ thinking_of,+ tool_pairing_problems,+)+from tests.fakes.providers.anthropic_messages import Reply, Text, Thinking, ToolUse++# The guard bypass is only for teardown: a daemonised helper the gateway spawns can be reparented+# to init, and kill_tagged() signals nothing but PIDs carrying this test's unique tag.+pytestmark = [pytest.mark.skipif(not sys.platform.startswith("linux"), reason="process-tree cleanup uses /proc"),+ pytest.mark.live_system_guard_bypass]++# Signatures are opaque base64 blobs on the real API; include every base64 symbol plus+# padding so any re-encoding, trimming or normalisation shows up as a byte mismatch.+SIG = {n: f"Eq{n}+/AbCdEfGhIjKlMnOpQrStUvWxYz0123456789+/{n * 3}==" for n in ("A", "B", "C", "D")}+THINK = {n: f"Reasoning step {n}: weigh the files.\n Keep spacing\tand unicode \u00e9\u2014{n}." for n in SIG}+++def rig_factory(tmp_path: Path):+ rigs: list[Rig] = []++ def make(script, **kw) -> Rig:+ rig = start_rig(tmp_path / f"r{len(rigs)}", script, **kw)+ rigs.append(rig)+ return rig++ yield make+ for rig in rigs:+ rig.stop()+++def _assert_conformant(rig: Rig) -> None:+ assert not rig.srv.schema_errors(), f"request bodies violate the SDK schema: {rig.srv.schema_errors()}"+++def test_interleaved_thinking_parallel_tools_three_turns(rig_factory) -> None:+ """3 model turns in one user turn: [thinking, 2 parallel tool_use] -> [thinking, tool_use] ->+ [thinking, text]. Every follow-up request replays the latest signed thinking byte-exact+ ahead of its tool_use blocks and answers every tool_use id in the next user message."""+ rig = rig_factory([])+ for name in ("a", "b", "c"):+ (rig.project / f"{name}.txt").write_text(f"content-{name}", encoding="utf-8")+ rig.srv.push(+ Reply([Thinking(THINK["A"], SIG["A"]),+ ToolUse("read_file", {"path": str(rig.project / "a.txt")}),+ ToolUse("read_file", {"path": str(rig.project / "b.txt")})]),+ Reply([Thinking(THINK["B"], SIG["B"]), ToolUse("read_file", {"path": str(rig.project / "c.txt")})]),+ Reply([Thinking(THINK["C"], SIG["C"]), Text("INTERLEAVED-DONE")]),+ )+ proc = rig.run("-z", "Read a.txt and b.txt together, then c.txt.")+ assert proc.returncode == 0, proc.stderr[-2000:]+ assert "INTERLEAVED-DONE" in proc.stdout+ mains = rig.srv.main_requests()+ assert len(mains) == 3, [r.get("response") for r in rig.srv.requests]+ _assert_conformant(rig)++ for turn, (req, expected) in enumerate(zip(mains[1:], ("A", "B")), start=2):+ body = req["body"]+ assert body.get("thinking", {}).get("type") in ("enabled", "adaptive"), body.get("thinking")+ latest = assistant_messages(body)[-1]+ kinds = [b["type"] for b in blocks(latest)]+ assert kinds[0] == "thinking", f"request {turn}: latest assistant must lead with thinking: {kinds}"+ assert thinking_of(latest)[0] == (THINK[expected], SIG[expected]), (+ f"request {turn}: signed thinking not replayed byte-exact: {thinking_of(latest)}")+ assert not tool_pairing_problems(body), (tool_pairing_problems(body), dump(body))+ parallel_uses = [b for b in blocks(assistant_messages(mains[1]["body"])[-1]) if b["type"] == "tool_use"]+ assert len(parallel_uses) == 2, "both parallel tool_use blocks must stay in ONE assistant message"+ results = [b for b in blocks(mains[1]["body"]["messages"][-1]) if b["type"] == "tool_result"]+ assert {json.dumps(r["content"]).count("content-a") + json.dumps(r["content"]).count("content-b")+ for r in results} == {1}, "each tool_result must carry its own file's content"+++def test_signature_replayed_byte_exact_after_resume(rig_factory) -> None:+ """Turn 1 in one process, turn 2 in a fresh ``chat --resume`` process: the resumed request's+ history is the first process's transcript (same blocks, same signature bytes) plus the+ new user message; nothing is re-encoded by the state.db round trip."""+ rig = rig_factory([+ Reply([Thinking(THINK["A"], SIG["A"]), ToolUse("terminal", {"command": "echo resume-probe"})]),+ Reply([Thinking(THINK["B"], SIG["B"]), Text("FIRST-ANSWER")]),+ Reply([Thinking(THINK["C"], SIG["C"]), Text("SECOND-ANSWER")]),+ ])+ first = rig.run("chat", "-q", "Run the probe command.", "-Q")+ assert first.returncode == 0 and "FIRST-ANSWER" in first.stdout, first.stderr[-2000:]+ (session_id,) = rig.session_ids()+ second = rig.run("chat", "--resume", session_id, "-q", "And now?", "-Q")+ assert second.returncode == 0 and "SECOND-ANSWER" in second.stdout, second.stderr[-2000:]+ _assert_conformant(rig)++ mains = [r["body"] for r in rig.srv.main_requests()]+ assert len(mains) == 3+ # Direct-Anthropic policy: only the LATEST assistant message keeps signed thinking (older+ # signatures are dropped by design), so compare everything else block for block.+ in_process = _unsigned(normalised(mains[1]["messages"]))+ resumed = normalised(mains[2]["messages"])+ assert _unsigned(resumed[:len(in_process)]) == in_process, (+ "resumed history diverges from the in-process transcript:\n"+ f"in-process: {json.dumps(in_process)[-1500:]}\nresumed: {json.dumps(resumed)[-1500:]}")+ final_assistant = resumed[len(in_process)]+ assert final_assistant["role"] == "assistant"+ assert thinking_of(final_assistant) == [(THINK["B"], SIG["B"])], (+ f"turn-1 final thinking lost or altered after resume: {final_assistant}")+ assert resumed[-1]["role"] == "user" and "And now?" in json.dumps(resumed[-1])+ assert not tool_pairing_problems(mains[2])+++def _unsigned(messages: list[dict]) -> list[dict]:+ return [{**m, "content": [b for b in m["content"] if b.get("type") != "thinking"]} for m in messages]+++def _tui_gateway_two_turns(rig: Rig, prompts: list[str]) -> list[str]:+ from tests.e2e.core.parity._drive_rpc import RpcClient, StreamCapture++ proc = subprocess.Popen([sys.executable, "-m", "tui_gateway.entry"], cwd=rig.project, env=rig.env(),+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ text=True, bufsize=1)+ cap = StreamCapture().start(proc)+ lock = threading.Lock()++ def send(line: str) -> None:+ with lock:+ assert proc.stdin is not None+ proc.stdin.write(line + "\n")+ proc.stdin.flush()++ answers: list[str] = []+ try:+ rpc = RpcClient(send, cap.stdout_lines)+ rpc.wait_event("gateway.ready", timeout=TURN_TIMEOUT)+ sid = rpc.call("session.create", {}, timeout=TURN_TIMEOUT)["session_id"]+ for n, prompt in enumerate(prompts, start=1):+ rpc.call("prompt.submit", {"session_id": sid, "text": prompt}, timeout=TURN_TIMEOUT)+ done = rpc.wait_event("message.complete", lambda e, n=n: e.get("session_id") == sid+ and sum(1 for x in rpc.events if x.get("type") == "message.complete") >= n)+ answers.append(str((done.get("payload") or {}).get("text")))+ except (AssertionError, queue.Empty) as exc:+ raise AssertionError(f"{exc}\ntui_gateway stderr: {cap.stderr[-2000:]}") from exc+ finally:+ if proc.stdin is not None and not proc.stdin.closed:+ proc.stdin.close()+ try:+ proc.wait(timeout=60)+ except subprocess.TimeoutExpired:+ proc.kill()+ return answers+++def test_tui_gateway_replays_signed_thinking_across_turns(rig_factory) -> None:+ """The Ink TUI / Desktop backend path: two prompts in one live session over stdio JSON-RPC.+ The second prompt's request replays turn 1's signed thinking byte-exact."""+ rig = rig_factory([+ Reply([Thinking(THINK["A"], SIG["A"]), Text("GW-ONE")]),+ Reply([Thinking(THINK["D"], SIG["D"]), Text("GW-TWO")]),+ ])+ answers = _tui_gateway_two_turns(rig, ["first question", "second question"])+ assert "GW-ONE" in answers[0] and "GW-TWO" in answers[1], answers+ _assert_conformant(rig)+ mains = [r["body"] for r in rig.srv.main_requests()]+ assert len(mains) == 2+ prior = assistant_messages(mains[1])+ assert prior and thinking_of(prior[-1]) == [(THINK["A"], SIG["A"])], dump(mains[1])+ assert "GW-ONE" in json.dumps(prior[-1])diff --git a/tests/fakes/providers/anthropic_messages.py b/tests/fakes/providers/anthropic_messages.pynew file mode 100644index 00000000000..0aefb02941d--- /dev/null+++ b/tests/fakes/providers/anthropic_messages.py@@ -0,0 +1,411 @@+"""Scripted, recording loopback server speaking the Anthropic Messages API.++The installed ``anthropic`` SDK is the ORACLE for both directions, so the fake+cannot invent wire shapes:++* every request body is validated against the SDK's request TypedDicts+ (``MessageCreateParams``; the beta variant when an ``anthropic-beta`` header is+ sent) with a pydantic ``TypeAdapter``; validation errors AND keys the schema+ does not know are recorded on the request (``record["schema_errors"]``);+* every response, SSE event and error envelope is built from ``anthropic.types``+ models and serialised with ``model_dump`` (the one exception is ``ping``, a+ documented stream event the SDK exposes no model for).++Scripted responses (``Reply`` of ``Thinking``/``Text``/``ToolUse`` blocks,+``ApiError``, ``DropStream``) are consumed by main-turn requests (those carrying+``tools``); tool-less requests (title generation, compression summaries) are+auxiliary and answered by ``aux`` so they never eat a scripted turn.++Record mode (documented, never run in CI or against a paid key by this suite):+``AnthropicMessagesServer(record_upstream="https://api.anthropic.com",+cassette="<name>")`` proxies each POST to the upstream base URL and appends a+sanitised exchange (no auth headers, no API keys) to+``tests/fakes/providers/cassettes/anthropic/<name>.jsonl``.+"""++from __future__ import annotations++import json+import threading+import time+import urllib.error+import urllib.request+import uuid+from dataclasses import dataclass, field+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import Any, Callable, Union++import anthropic.types as at+from anthropic.types import message_create_params as ga_params+from anthropic.types.beta import message_create_params as beta_params+from anthropic.types.raw_message_delta_event import Delta as MessageDelta+from pydantic import TypeAdapter, ValidationError++MODEL_ID = "claude-sonnet-4-5-e2e"+CASSETTE_DIR = Path(__file__).with_name("cassettes") / "anthropic"+_GA_ADAPTER = TypeAdapter(ga_params.MessageCreateParams)+_BETA_ADAPTER = TypeAdapter(beta_params.MessageCreateParams)+_SANITISED_HEADERS = frozenset({"authorization", "x-api-key", "cookie", "set-cookie"})+++# Scripted responses ---------------------------------------------------------+++@dataclass+class Thinking:+ thinking: str+ signature: str+++@dataclass+class Text:+ text: str+++@dataclass+class ToolUse:+ name: str+ input: dict[str, Any] = field(default_factory=dict)+ id: str | None = None+++Block = Union[Thinking, Text, ToolUse]+++@dataclass+class Reply:+ """One assistant message. ``stop_reason`` defaults to tool_use/end_turn by content."""++ blocks: list[Block]+ stop_reason: str | None = None+ input_tokens: int = 100+ output_tokens: int = 20+ chunk_chars: int = 7+++@dataclass+class ApiError:+ """A documented error envelope (400 invalid_request_error, 429 rate_limit_error, 529 overloaded_error ...)."""++ status: int+ type: str+ message: str = "scripted failure"+ retry_after: float | None = None+++@dataclass+class DropStream:+ """Stream ``reply`` and close the socket after ``after_deltas`` content deltas (no message_stop)."""++ reply: Reply+ after_deltas: int = 2+++Response = Union[Reply, ApiError, DropStream]+Responder = Callable[[dict[str, Any]], Response]++_ERROR_MODELS: dict[str, type] = {+ "invalid_request_error": at.InvalidRequestError,+ "authentication_error": at.AuthenticationError,+ "permission_error": at.PermissionError,+ "not_found_error": at.NotFoundError,+ "rate_limit_error": at.RateLimitError,+ "api_error": at.APIErrorObject,+ "overloaded_error": at.OverloadedError,+}+++# SDK-oracle request validation ------------------------------------------------+++def _materialise(value: Any) -> Any:+ """Drain pydantic's lazy ``Iterable`` validators so nested blocks are validated too."""+ if isinstance(value, dict):+ return {k: _materialise(v) for k, v in value.items()}+ if isinstance(value, (list, tuple)):+ return [_materialise(v) for v in value]+ if type(value).__name__ == "ValidatorIterator":+ return [_materialise(v) for v in value]+ return value+++def _unknown_keys(sent: Any, known: Any, path: str = "$") -> list[str]:+ if isinstance(sent, dict) and isinstance(known, dict):+ out = [f"{path}.{k}" for k in sent if k not in known]+ for k in sent:+ if k in known:+ out += _unknown_keys(sent[k], known[k], f"{path}.{k}")+ return out+ if isinstance(sent, list) and isinstance(known, list):+ return [p for i, (s, k) in enumerate(zip(sent, known)) for p in _unknown_keys(s, k, f"{path}[{i}]")]+ return []+++def validate_request(body: dict[str, Any], *, beta: bool) -> list[str]:+ """Schema problems of one request body per the SDK's request TypedDicts ([] = conformant)."""+ adapter = _BETA_ADAPTER if beta else _GA_ADAPTER+ try:+ known = _materialise(adapter.validate_python(body))+ except ValidationError as exc:+ return [f"{'.'.join(map(str, e['loc']))}: {e['msg']}" for e in exc.errors()]+ return [f"unknown key {p}" for p in _unknown_keys(body, known)]+++# SDK-built responses --------------------------------------------------------------+++def _sdk_block(block: Block, tool_id: str) -> Any:+ if isinstance(block, Thinking):+ return at.ThinkingBlock(type="thinking", thinking=block.thinking, signature=block.signature)+ if isinstance(block, Text):+ return at.TextBlock(type="text", text=block.text)+ return at.ToolUseBlock(type="tool_use", id=block.id or tool_id, name=block.name, input=block.input)+++def _stop_reason(reply: Reply) -> str:+ if reply.stop_reason:+ return reply.stop_reason+ return "tool_use" if any(isinstance(b, ToolUse) for b in reply.blocks) else "end_turn"+++def build_message(reply: Reply, tool_ids: list[str], content: bool = True) -> at.Message:+ return at.Message(+ id=f"msg_{uuid.uuid4().hex[:20]}", type="message", role="assistant", model=MODEL_ID,+ content=[_sdk_block(b, tid) for b, tid in zip(reply.blocks, tool_ids)] if content else [],+ stop_reason=_stop_reason(reply) if content else None, stop_sequence=None,+ usage=at.Usage(input_tokens=reply.input_tokens, output_tokens=reply.output_tokens if content else 1),+ )+++def _pieces(text: str, size: int) -> list[str]:+ return [text[i:i + size] for i in range(0, len(text), max(1, size))] or [""]+++def _block_events(index: int, block: Block, tool_id: str, chunk: int) -> list[Any]:+ """content_block_start / *_delta... / content_block_stop for one block (SDK event models)."""+ if isinstance(block, Thinking):+ start = at.ThinkingBlock(type="thinking", thinking="", signature="")+ deltas: list[Any] = [at.ThinkingDelta(type="thinking_delta", thinking=p) for p in _pieces(block.thinking, chunk)]+ deltas.append(at.SignatureDelta(type="signature_delta", signature=block.signature))+ elif isinstance(block, Text):+ start = at.TextBlock(type="text", text="")+ deltas = [at.TextDelta(type="text_delta", text=p) for p in _pieces(block.text, chunk)]+ else:+ start = at.ToolUseBlock(type="tool_use", id=block.id or tool_id, name=block.name, input={})+ deltas = [at.InputJSONDelta(type="input_json_delta", partial_json=p)+ for p in _pieces(json.dumps(block.input), chunk)]+ return [+ at.RawContentBlockStartEvent(type="content_block_start", index=index, content_block=start),+ *[at.RawContentBlockDeltaEvent(type="content_block_delta", index=index, delta=d) for d in deltas],+ at.RawContentBlockStopEvent(type="content_block_stop", index=index),+ ]+++def stream_events(reply: Reply, tool_ids: list[str]) -> list[Any]:+ """The full documented event sequence for ``reply`` (``"ping"`` marks the ping event)."""+ events: list[Any] = [at.RawMessageStartEvent(type="message_start", message=build_message(reply, tool_ids, False)),+ "ping"]+ for i, (block, tid) in enumerate(zip(reply.blocks, tool_ids)):+ events += _block_events(i, block, tid, reply.chunk_chars)+ events.append(at.RawMessageDeltaEvent(+ type="message_delta", delta=MessageDelta(stop_reason=_stop_reason(reply), stop_sequence=None),+ usage=at.MessageDeltaUsage(output_tokens=reply.output_tokens)))+ events.append(at.RawMessageStopEvent(type="message_stop"))+ return events+++def _event_bytes(event: Any) -> bytes:+ payload = {"type": "ping"} if event == "ping" else event.model_dump(mode="json")+ return f"event: {payload['type']}\ndata: {json.dumps(payload)}\n\n".encode()+++def error_envelope(err: ApiError) -> dict[str, Any]:+ model = _ERROR_MODELS[err.type]+ return at.ErrorResponse(type="error", error=model(type=err.type, message=err.message),+ request_id=f"req_{uuid.uuid4().hex[:16]}").model_dump(mode="json")+++# Server ---------------------------------------------------------------------------+++class AnthropicMessagesServer:+ """Threaded loopback Messages endpoint. ``base_url`` ends in ``/anthropic`` so Hermes'+ native ``anthropic`` provider accepts it as an Anthropic-protocol override."""++ def __init__(self, script: list[Response] | Responder | None = None, *, default_text: str = "ok",+ aux: Responder | None = None, models: list[str] | None = None,+ record_upstream: str | None = None, cassette: str = "session") -> None:+ self._script: list[Response] = list(script) if isinstance(script, list) else []+ self._responder: Responder | None = script if callable(script) else None+ self.default_text = default_text+ self._aux = aux or (lambda _r: Reply([Text("Fake summary of the earlier conversation.")]))+ self.models = models or [MODEL_ID]+ self.record_upstream = record_upstream+ self.cassette = CASSETTE_DIR / f"{cassette}.jsonl"+ self.requests: list[dict[str, Any]] = []+ self.gets: list[dict[str, Any]] = []+ self._lock = threading.Lock()+ self._stop = threading.Event()+ self._httpd: ThreadingHTTPServer | None = None+ self._tool_seq = 0++ def __enter__(self) -> "AnthropicMessagesServer":+ return self.start()++ def __exit__(self, *_exc: object) -> None:+ self.stop()++ def start(self) -> "AnthropicMessagesServer":+ self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), _handler_for(self))+ self._httpd.daemon_threads = True+ threading.Thread(target=self._httpd.serve_forever, kwargs={"poll_interval": 0.05},+ name="fake-anthropic", daemon=True).start()+ return self++ def stop(self) -> None:+ self._stop.set()+ if self._httpd is not None:+ self._httpd.shutdown()+ self._httpd.server_close()+ self._httpd = None++ @property+ def base_url(self) -> str:+ assert self._httpd is not None, "server not started"+ return f"http://127.0.0.1:{self._httpd.server_address[1]}/anthropic"++ def handler_class(self) -> type[BaseHTTPRequestHandler]:+ """Request handler, for serving TLS-intercepted connections (``TLSInterceptProxy``)."""+ return _handler_for(self)++ def push(self, *responses: Response) -> None:+ with self._lock:+ self._script.extend(responses)++ def main_requests(self) -> list[dict[str, Any]]:+ with self._lock:+ return [r for r in self.requests if r["kind"] == "main"]++ def schema_errors(self) -> list[tuple[int, list[str]]]:+ with self._lock:+ return [(i, r["schema_errors"]) for i, r in enumerate(self.requests) if r["schema_errors"]]++ def _next(self, record: dict[str, Any]) -> Response:+ if record["kind"] == "aux":+ return self._aux(record)+ if self._responder is not None:+ return self._responder(record)+ with self._lock:+ if self._script:+ return self._script.pop(0)+ return Reply([Text(self.default_text)])++ def _tool_ids(self, reply: Reply) -> list[str]:+ with self._lock:+ ids = []+ for _ in reply.blocks:+ self._tool_seq += 1+ ids.append(f"toolu_e2e_{self._tool_seq:04d}")+ return ids++ def _record_exchange(self, record: dict[str, Any], status: int, body: bytes) -> None:+ self.cassette.parent.mkdir(parents=True, exist_ok=True)+ headers = {k: v for k, v in record["headers"].items() if k not in _SANITISED_HEADERS}+ with self.cassette.open("a", encoding="utf-8") as fh:+ fh.write(json.dumps({"request": {"path": record["path"], "headers": headers, "body": record["body"]},+ "response": {"status": status, "body": body.decode("utf-8", "replace")}}) + "\n")+++def _handler_for(server: AnthropicMessagesServer) -> 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:+ data = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.send_header("request-id", f"req_{uuid.uuid4().hex[:16]}")+ for k, v in (headers or {}).items():+ self.send_header(k, v)+ self.end_headers()+ self.wfile.write(data)++ def do_GET(self) -> None: # noqa: N802 - model discovery (/v1/models)+ with server._lock:+ server.gets.append({"path": self.path, "headers": {k.lower(): v for k, v in self.headers.items()}})+ if self.path.split("?", 1)[0].rstrip("/").endswith("/v1/models"):+ page = at.ModelInfo # the SDK's /v1/models item model+ data = [page(id=m, type="model", display_name=m, created_at="2026-01-01T00:00:00Z")+ .model_dump(mode="json") for m in server.models]+ self._json(200, {"data": data, "has_more": False,+ "first_id": server.models[0], "last_id": server.models[-1]})+ return+ self._json(404, error_envelope(ApiError(404, "not_found_error", f"no route {self.path}")))++ def do_POST(self) -> None: # noqa: N802+ raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))+ if not self.path.split("?", 1)[0].endswith("/v1/messages"):+ self._json(404, error_envelope(ApiError(404, "not_found_error", f"no route {self.path}")))+ return+ body = json.loads(raw or b"{}")+ headers = {k.lower(): v for k, v in self.headers.items()}+ record = {+ "path": self.path, "headers": headers, "body": body, "t": time.monotonic(),+ "kind": "main" if body.get("tools") else "aux",+ "schema_errors": validate_request(body, beta=bool(headers.get("anthropic-beta"))),+ }+ with server._lock:+ server.requests.append(record)+ if server.record_upstream:+ self._proxy(record, raw)+ return+ resp = server._next(record)+ record["response"] = type(resp).__name__+ self._respond(resp, bool(body.get("stream")))++ def _proxy(self, record: dict[str, Any], raw: bytes) -> None:+ fwd = {k: v for k, v in self.headers.items() if k.lower() not in ("host", "content-length")}+ req = urllib.request.Request(str(server.record_upstream).rstrip("/") + "/v1/messages", data=raw,+ headers=fwd, method="POST")+ try:+ with urllib.request.urlopen(req, timeout=300) as up: # noqa: S310 - opt-in record mode+ status, data, ctype = up.status, up.read(), up.headers.get("Content-Type", "")+ except urllib.error.HTTPError as exc:+ status, data, ctype = exc.code, exc.read(), exc.headers.get("Content-Type", "")+ server._record_exchange(record, status, data)+ self.send_response(status)+ self.send_header("Content-Type", ctype or "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def _respond(self, resp: Response, stream: bool) -> None:+ if isinstance(resp, ApiError):+ headers = {"retry-after": str(resp.retry_after)} if resp.retry_after is not None else {}+ self._json(resp.status, error_envelope(resp), headers)+ return+ reply = resp.reply if isinstance(resp, DropStream) else resp+ tool_ids = server._tool_ids(reply)+ if not stream and not isinstance(resp, DropStream):+ self._json(200, build_message(reply, tool_ids).model_dump(mode="json"))+ return+ 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()+ deltas = 0+ for event in stream_events(reply, tool_ids):+ if isinstance(resp, DropStream) and deltas >= resp.after_deltas:+ break # socket closes with no content_block_stop / message_stop+ self.wfile.write(_event_bytes(event))+ self.wfile.flush()+ deltas += isinstance(event, at.RawContentBlockDeltaEvent)+ self.close_connection = True++ return Handler