Skip to content

Hermes Agent context engine: the main model writes the compaction handoff on its cached prompt prefix

Add warm compaction for Responses and Anthropic Messages

Elevatormusic1ff85c982491
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f556b52..a2ddd28 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,8 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
### Added
+- Warm request adapters for Responses and Anthropic Messages. Keep native input prefixes, cache controls, and verified encrypted or signed reasoning. Unsupported request shapes and authentication routes use the fallback. See [Provider support](docs/provider-support.md) for limits.
+- Native reply completion checks, token counters, and a synthetic real-Hermes provider integration check. Native replay blocks count in tail estimates and cannot be cut apart.
- A WARNING for each saved compaction that Hermes confirms without the warm path, with its reason (Hermes copies it to `errors.log`).
- After 3 confirmed compactions in a row without the warm path, one notice with a hint for each distinct reason, in the logs and at the next automatic compaction when engine status is enabled. The notice has no routine progress text. Later confirmed failures update the pending notice and its fixed-summary count until Hermes shows it.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ab6ff6d..6c92683 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -73,6 +73,14 @@ For changes to Hermes interaction, also run the integration check. It runs real
The integration check covers install, request, compaction, and history behavior on that Hermes version. It does not call a real model or prove live cache reuse or a performance gain. Keep evidence small and metadata only.
+For changes to Responses or Anthropic Messages routes, also run the native provider check. It uses real Hermes transports and synthetic loopback replies. The isolated interpreter needs the Hermes dependencies for both API formats. Use `--dependency-path <dependency-folder>` if those dependencies are in a separate local folder.
+
+```bash
+<hermes-venv-python> -B scripts/check_provider_apis.py --hermes-source <clean-hermes-checkout> --report .work/provider-api-report.json
+```
+
+See [provider support](docs/provider-support.md) for the supported request and authentication limits. A passing local check does not qualify a live provider.
+
For document or form changes, check local Markdown links and run `git diff --check`. For issue forms, parse the YAML and check its fields against the [GitHub form schema](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/syntax-for-githubs-form-schema). No live model check is needed for these changes.
CI runs the unit tests on Python 3.10 to 3.13 (Linux) and on Python 3.12 (Windows and macOS), and the lint. A pull request must pass both.
diff --git a/README.md b/README.md
index cab4f3d..144b8ee 100644
--- a/README.md
+++ b/README.md
@@ -90,7 +90,7 @@ From the server documentation and issue trackers; tested here only on DGX and LM
## Requirements
- Hermes Agent `45871e10` (2026-10-02) or a later version that keeps the plugin APIs that the plugin uses. At load time, the plugin checks for each API. If an API is missing, the plugin registers nothing, writes a warning to the log, and Hermes keeps its built-in compressor.
-- For the warm path: the OpenAI chat completions API mode (`chat_completions`). Other API modes always use the fallback summary.
+- For the warm path: `chat_completions`, `codex_responses`, or `anthropic_messages`, with a supported request and authentication route. See [Provider support](docs/provider-support.md) for the tested scope. Other formats use the fallback summary.
- Python 3.10 or later. No third-party package.
## Install
@@ -176,7 +176,7 @@ plugins:
threshold: 0.5
```
-The warm request sends the whole earlier request again, plus the new rows and the reply reserve. The reply limit of the warm request is the `max_tokens` or `max_completion_tokens` value of the earlier request, kept between 2,048 and 8,192 tokens. If the earlier request had no limit, the warm request gets 8,192 tokens in the field that Hermes uses for the route (`max_completion_tokens` for OpenAI, Azure OpenAI, GitHub Copilot, and the newer OpenAI models; else `max_tokens`). The warm request sends the default headers of the Hermes client for the route: the provider headers, `model.default_headers`, and `providers.<name>.extra_headers`. It also keeps a captured `x-opencode-session` request header. Hermes can add this header automatically for OpenCode routes. The captured value stays in memory and overrides a default header with the same name, without regard to case. It goes through both middleware checks and is sent as an HTTP header, never as a JSON field. It uses the `ssl_ca_cert` of a custom provider route. A route with `ssl_verify: false` uses the fallback summary (refusal code `tls_unverified`): the plugin does not send without certificate checks. Thus it must fit in the context window. At the default threshold, about half of the window stays free for it. If the request does not fit, the plugin uses the fallback summary (refusal code `capacity`). The plugin uses the prompt token count that the server reported for the earlier request, and estimates only the new rows.
+On Chat Completions routes, the warm request sends the whole earlier request again, plus the new rows and the reply reserve. The reply limit of the warm request is the `max_tokens` or `max_completion_tokens` value of the earlier request, kept between 2,048 and 8,192 tokens. If the earlier request had no limit, the warm request gets 8,192 tokens in the field that Hermes uses for the route (`max_completion_tokens` for OpenAI, Azure OpenAI, GitHub Copilot, and the newer OpenAI models; else `max_tokens`). The warm request sends the default headers of the Hermes client for the route: the provider headers, `model.default_headers`, and `providers.<name>.extra_headers`. It also keeps a captured `x-opencode-session` request header. Hermes can add this header automatically for OpenCode routes. The captured value stays in memory and overrides a default header with the same name, without regard to case. It goes through both middleware checks and is sent as an HTTP header, never as a JSON field. It uses the `ssl_ca_cert` of a custom provider route. A route with `ssl_verify: false` uses the fallback summary (refusal code `tls_unverified`): the plugin does not send without certificate checks. Thus it must fit in the context window. At the default threshold, about half of the window stays free for it. If the request does not fit, the plugin uses the fallback summary (refusal code `capacity`). The plugin uses the prompt token count that the server reported for the earlier request, and estimates only the new rows.
## Fallback model and keys
@@ -201,8 +201,8 @@ Hermes writes compaction metadata to `logs/agent.log` in the Hermes home folder:
warm_compaction: path=warm reason=accepted elapsed_s=10.656 prompt_tokens=108021 cached_tokens=107968
```
-- `path` is `warm`, `fallback`, or `fixed`.
-- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `api_mode_unsupported`, `route_changed`, `settings_unsupported`, `request_not_mapping`, `request_options_unsupported`, `request_not_json`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_repeated`, `middleware_after_capture`, `middleware_order_unknown`, `headers_unknown`, `tls_unknown`, `tls_unverified`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_request` and `llm_execution` middleware, as a main request does.
+- `path` is `warm`, `fallback`, or `fixed`. `unchanged` means that an indivisible native replay block left no room for a valid new history; no compaction was committed.
+- `reason` is `accepted` or the refusal code of the warm request: `disabled`, `no_capture`, `api_mode_unsupported`, `auth_unsupported`, `route_changed`, `settings_unsupported`, `request_not_mapping`, `request_options_unsupported`, `request_not_json`, `source_transform_unsupported`, `history_changed`, `capacity`, `cancelled`, `middleware_unavailable`, `middleware_refused`, `middleware_rewrite`, `middleware_repeated`, `middleware_after_capture`, `middleware_order_unknown`, `headers_unknown`, `tls_unknown`, `tls_unverified`, `middleware_changed_reply`, `provider_error`, `timeout`, `incomplete_response`, or `gate:<reason>`. The warm request goes through the Hermes `llm_request` and `llm_execution` middleware, as a main request does.
- `cached_tokens` is `None` when the server does not report it. Then the cache reuse is unknown.
Capture refusal codes identify the failed check: `request_not_mapping` means that the request is not a mapping; `request_options_unsupported` means that extra headers, query options, or `extra_body` cannot be kept; `request_not_json` means that a body value cannot be sent as JSON (including NaN and infinity). `settings_unsupported` still applies to unsupported model settings. These codes contain no request values.
@@ -279,11 +279,12 @@ The plugin was faster than both other engines in 10 of 10 cases. hermes-lcm and
- A model or session switch, or a host timeout, during the attempt stops it, also while the warm request is on the network: the history stays unchanged (`route_changed` or `cancelled`).
- A provider or API key switch forgets the capture of the session: the next compaction uses the fallback summary (`no_capture`) until a main request on the new configuration completes. A key that Hermes gives as a function can change without a switch (a token that refreshes or rotates): the capture keeps a PBKDF2-HMAC-SHA-256 digest of the key that sent it, never the key, and the warm request is not sent with another key (reason `credential_changed`). The digest uses a random salt made when the plugin module loads. The salt and the captures stay in memory. A key change while a request is open keeps no capture.
- A captured row with a field that Hermes does not send for the stored row (other than the prompt caching marker `cache_control`) refuses the warm path (`source_transform_unsupported`).
-- The source check accepts exact text or removal of trailing whitespace from a complete text string, including a stored `api_content` string. Leading or inner whitespace changes, added whitespace, and changes to text inside a content list still refuse the warm path (`source_transform_unsupported`). The captured request prefix stays unchanged.
+- On Chat Completions routes, the source check accepts exact text or removal of trailing whitespace from a complete text string, including a stored `api_content` string. Leading or inner whitespace changes, added whitespace, and changes to text inside a content list still refuse the warm path (`source_transform_unsupported`). The captured request prefix stays unchanged.
+- Responses and Anthropic Messages use their own source checks. Native signed and encrypted replay records stay whole and count in tail estimates. A record that leaves no room for a valid new history returns the original history with `path=unchanged reason=capacity`. See [Provider support](docs/provider-support.md).
- The handoff must start with `## Goal`: text before the first heading is refused (`gate:heading_preamble`).
- The verbatim tail keeps the newest rows that fit in `tail_tokens`, and in the free room after the system rows and tool schemas of a usable capture, the reply reserve, and a summary: a large system prompt can make a short history compact. It stops at the first older row that does not fit, and that row goes into the summary. When the newest unit alone is larger than the tail or the free room, its largest sent payloads keep only their start and end: message text, tool call arguments (kept as a JSON object), and reasoning text. A large image or other media part is replaced by its attachment mark: a web URL or a file name stays (at most 200 characters), a data URL does not. If the cuts are not enough, the payloads are dropped, largest first; only the row structure stays. Signed `reasoning_details` stay as they are. The fallback summary gets the cut middles, and the fixed summary quotes them (at most 8,000 characters), also the cut middle of a long latest user message that goes in front of the tail. A fallback summary above its 4,096-token reserve (a dense CJK summary, for example) is not used: the fixed summary quotes the parts that the final tail cuts. Each quote makes the fixed summary larger and the tail smaller; after 10 rounds, the tail is cut at the size that the summary quotes, also when that is a little above the free room. The sizes come from the fields that Hermes sends: row metadata does not count; reasoning counts only on a route that needs it back (DeepSeek, Kimi, MiMo thinking; a capture of the route shows it, else a stored row with `reasoning_content`); `reasoning_details` counts only on a route that replays it, without the private native-assistant entries; the native-assistant entry type that the provider profile declares (`native_reasoning_details_type`) counts on every route of the provider, as Hermes replays it; a tool call counts only its id, type, name, and arguments, and a usable thought signature counts only for a Gemini or Gemma model. The fixed summary keeps bounded quotes of the earlier summary, the focus topic, the memory context, and the cut middles; together with the tool inventory (the most used names, and one count for the others) they stay in one budget (4,096 tokens, and at most the free room). When the fallback summary is used and the latest user request in front of the tail must be cut, the cut middle goes after the summary as a bounded quote, in what the summary budget has left: the fallback transcript had only the start and end of a long row. When no quote fits there, the fixed summary is used: it quotes the cut middle. A fallback summary that does not fit in the free room is not used: the fixed summary takes its place. A model, session, window, or threshold change at any time during the compaction discards its result (reason `route_changed`). On a Gemini or Gemma route, a tool call with a thought signature stays whole: Gemini needs it back as it was. A change of the provider or the key forgets the capture, also from an empty provider and key. A warm summary that does not fit in the free room (a dense reply under a low threshold, for example) is not used: the fallback summary runs (reason `summary_too_large`). A retry middleware cannot send the warm request a second time, also after a failed send. A warm reply body above 1 MiB is not read (reason `response_too_large`). The fallback request does not start after a model, provider, or session switch. The plugin API has no request on a fixed route (an override needs a trust setting), so a switch in the short time after that check, before the host resolves the auxiliary route, can still send the transcript to the new route. Reasoning is cut only when a usable capture of the route shows that the route sends it: other reasoning (of an earlier route after a model switch, for example) does not go to the fallback model or into the fixed summary. The latest user request in front of the tail gets the room that stays after the tail is cut. Hermes notifications, task lists, and recovery nudges are not user requests only when the whole text matches the Hermes template. The copied user messages get the room that stays after the tail is cut. Without a usable capture (after a restart, after a model change, or when a middleware changed the captured rows), the request overhead is unknown: the summary has no copied user messages, the summary, the prepended row, and the tail take at most half of the free room, the check before a request compacts when the history estimate reaches half of the window less the reply reserve, and the reply reserve is a quarter of the window (at most 65,536 and at least 4,096 tokens). The same reserve applies when the captured request had no positive `max_tokens` or `max_completion_tokens`: the provider default is not known. The host token count is not used for the overhead: it does not use the plugin tokenizer.
-- The warm request is not streamed and not retried. Its time limit is 120 seconds. The fallback request also has a 120-second limit.
-- Per-request `extra_headers` supports only one `x-opencode-session` header, with a non-empty plain ASCII string value, no control characters, and no leading or trailing space. Other headers, duplicate names with different case, non-empty `extra_query`, or an invalid `extra_body` use the fallback (`request_options_unsupported`). A JSON `extra_body.extra_headers` field cannot be combined with the session header. A request with `n` above 1, a forced `tool_choice`, `response_format`, or audio settings uses the fallback (`settings_unsupported`).
+- Responses warm requests are streamed; Chat Completions and Messages warm requests are not streamed. No warm request is retried. Its time limit is 120 seconds. The fallback request also has a 120-second limit. Native formats have additional limits in [Provider support](docs/provider-support.md).
+- On Chat Completions routes, per-request `extra_headers` supports only one `x-opencode-session` header, with a non-empty plain ASCII string value, no control characters, and no leading or trailing space. Other headers, duplicate names with different case, non-empty `extra_query`, or an invalid `extra_body` use the fallback (`request_options_unsupported`). A JSON `extra_body.extra_headers` field cannot be combined with the session header. A request with `n` above 1, a forced `tool_choice`, `response_format`, or audio settings uses the fallback (`settings_unsupported`).
- After `/compress`, Hermes builds the system prompt again from its configuration. A system message that a host gave in code is not kept. This is Hermes behavior, and it is the same for the built-in compressor.
- Each new agent writes this Hermes warning to the log: `Context engine 'warm_compaction' loaded but no engine instance found`. Hermes first tries its context engine loader, which cannot make this engine. Then Hermes uses the engine of the enabled plugin. The warning has no effect.
diff --git a/docs/provider-support.md b/docs/provider-support.md
new file mode 100644
index 0000000..e668251
--- /dev/null
+++ b/docs/provider-support.md
@@ -0,0 +1,43 @@
+# Provider support
+
+The warm path supports three API formats. A model name alone does not identify its API format. Check the selected Hermes route and the `warm_compaction:` log line.
+
+| API format | Warm path scope |
+| --- | --- |
+| `chat_completions` | Existing OpenAI-compatible chat endpoints. |
+| `codex_responses` | Stateless Responses requests with text and function tools, including the consumer Codex endpoint. Verified encrypted reasoning and native assistant message phases are replayed. |
+| `anthropic_messages` | API-key Messages routes with text and function tools. Native Claude signed and redacted thinking blocks retain their exact order and bytes. |
+
+Requests that cannot pass the source, route, credential, middleware, or capacity checks use the normal auxiliary summary. A failed auxiliary summary uses the fixed summary. A live cache or speed benefit needs a separate provider test.
+
+## Responses
+
+The request keeps the captured `input` prefix, `instructions`, tools, reasoning settings, and cache controls. New rows and the host handoff instruction follow the prefix. The warm request uses `/responses` and streaming. Only a terminal, completed response can pass the handoff gate. Partial text, a failed or incomplete response, tool calls, and refusals cannot become a warm summary.
+
+Supported session headers stay in memory and are sent as HTTP headers. The official consumer Codex route keeps the Hermes identity and account headers. A key change after capture still refuses the attempt.
+
+Standard Responses routes use a bounded `max_output_tokens`. The consumer Codex route does not get an added output limit that its endpoint rejects. It keeps a conservative reserve of a quarter of the context window, from 4,096 to 65,536 tokens, when its output limit is unknown.
+
+Native server compaction checkpoints, stateful `previous_response_id` or conversation requests, media, forced tools, built-in server tools, structured output, and ambiguous tool IDs use the fallback. Opaque reasoning from a different model or issuer refuses. Fields that Hermes removes after the capture also refuse when the plugin cannot prove the final request shape.
+
+## Anthropic Messages
+
+The request keeps the captured native `messages` prefix, system blocks, tools, cache markers, tool choice, and thinking settings. The warm request uses `/v1/messages`. Native replies use their stop reason and content blocks; the reader also accepts complete native SSE replies.
+
+The adapter uses `x-api-key`, `anthropic-version`, the checked Hermes beta defaults, and custom provider headers. Claude Code OAuth or subscription authentication, bearer routes (MiniMax, Kimi, CommandCode, Palantir, and Nous), Azure/Entra authentication, and Bedrock remain on the fallback. Custom `Authorization` headers also refuse. Their authentication and final-client transformations need separate integration work.
+
+Forced or server tools, media, structured output, unknown request controls, and unproved replay blocks use the fallback. Signed thinking is replayed only on the native Anthropic host. A manual thinking budget stays unchanged; the output limit leaves at least 2,048 tokens after that budget. A request that then exceeds the window uses the fallback.
+
+## Retained history and checks
+
+Native replay fields count in retained-tail estimates. A signed or encrypted assistant record stays whole, including the canonical text and tool data that its replay blocks describe. If an indivisible retained record exceeds the context budget, the attempt returns the original history with `path=unchanged reason=capacity`.
+
+The adapters are checked against Hermes `bc2e4d3773518f2129023383a29dc51133dc6048` with synthetic data and a loopback server. These checks prove local request and history behavior on that source. The native test driver calls real hooks and middleware explicitly; the full native conversation loop has not been tested. The checks do not prove every deployed provider, summary quality, cached-token reuse, or a speed gain. The plugin has no documented final-wire capture or raw provider-dispatch API; future host transforms still need review.
+
+Run the provider integration check with an isolated Hermes dependency interpreter:
+
+```bash
+<hermes-venv-python> -B scripts/check_provider_apis.py --hermes-source <clean-hermes-checkout> --report .work/provider-api-report.json
+```
+
+The [contribution guide](../CONTRIBUTING.md#run-the-checks) gives the full regression checks.
diff --git a/evidence/provider-api-integration.json b/evidence/provider-api-integration.json
new file mode 100644
index 0000000..df85975
--- /dev/null
+++ b/evidence/provider-api-integration.json
@@ -0,0 +1,464 @@
+{
+ "check": "native provider transport and warm loopback check",
+ "python": "3.11.14",
+ "hermes": {
+ "commit": "bc2e4d3773518f2129023383a29dc51133dc6048",
+ "clean": true
+ },
+ "synthetic": true,
+ "live_provider": false,
+ "cache_reuse_proved": false,
+ "cases": [
+ {
+ "case": "responses_text",
+ "checks": {
+ "plugin_discovered": true,
+ "plugin_origin_is_temporary_install": true,
+ "transport_origin_is_pinned_source": true,
+ "main_capture_exact_wire_body": true,
+ "capture_has_no_refusal": true,
+ "main_native_endpoint": true,
+ "main_protocol_auth": true,
+ "main_request_headers_sent": true,
+ "main_instructions_exact": true,
+ "warm_or_fallback_outcome": true,
+ "history_compacted": true,
+ "summary_has_synthetic_handoff": true,
+ "synthetic_token_counters": true,
+ "warm_sent_once": true,
+ "warm_native_endpoint": true,
+ "warm_prefix_exact": true,
+ "warm_prompt_and_tools_exact": true,
+ "warm_request_headers_kept": true,
+ "warm_protocol_auth": true,
+ "request_headers_not_json": true,
+ "failure_reason_expected": true,
+ "fallback_only_on_failure": true,
+ "plugin_made_no_blocked_call": true,
+ "no_external_network_attempt": true
+ },
+ "error": null,
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_denied": {},
+ "fence_callers": [],
+ "fence_programs": [],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "passed": true,
+ "exit_ok": true
+ },
+ {
+ "case": "responses_tool",
+ "checks": {
+ "plugin_discovered": true,
+ "plugin_origin_is_temporary_install": true,
+ "transport_origin_is_pinned_source": true,
+ "main_capture_exact_wire_body": true,
+ "capture_has_no_refusal": true,
+ "main_native_endpoint": true,
+ "main_protocol_auth": true,
+ "main_request_headers_sent": true,
+ "main_instructions_exact": true,
+ "warm_or_fallback_outcome": true,
+ "history_compacted": true,
+ "summary_has_synthetic_handoff": true,
+ "synthetic_token_counters": true,
+ "warm_sent_once": true,
+ "warm_native_endpoint": true,
+ "warm_prefix_exact": true,
+ "warm_prompt_and_tools_exact": true,
+ "warm_request_headers_kept": true,
+ "warm_protocol_auth": true,
+ "request_headers_not_json": true,
+ "old_and_new_tool_pairs": true,
+ "new_tool_payloads_exact": true,
+ "failure_reason_expected": true,
+ "fallback_only_on_failure": true,
+ "plugin_made_no_blocked_call": true,
+ "no_external_network_attempt": true
+ },
+ "error": null,
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_denied": {},
+ "fence_callers": [],
+ "fence_programs": [],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "passed": true,
+ "exit_ok": true
+ },
+ {
+ "case": "responses_incomplete",
+ "checks": {
+ "plugin_discovered": true,
+ "plugin_origin_is_temporary_install": true,
+ "transport_origin_is_pinned_source": true,
+ "main_capture_exact_wire_body": true,
+ "capture_has_no_refusal": true,
+ "main_native_endpoint": true,
+ "main_protocol_auth": true,
+ "main_request_headers_sent": true,
+ "main_instructions_exact": true,
+ "warm_or_fallback_outcome": true,
+ "history_compacted": true,
+ "summary_has_synthetic_handoff": true,
+ "warm_sent_once": true,
+ "warm_native_endpoint": true,
+ "warm_prefix_exact": true,
+ "warm_prompt_and_tools_exact": true,
+ "warm_request_headers_kept": true,
+ "warm_protocol_auth": true,
+ "request_headers_not_json": true,
+ "failure_reason_expected": true,
+ "fallback_only_on_failure": true,
+ "plugin_made_no_blocked_call": true,
+ "no_external_network_attempt": true
+ },
+ "error": null,
+ "outcome": {
+ "path": "fallback",
+ "reason": "incomplete_response",
+ "prompt_tokens": null,
+ "cached_tokens": null
+ },
+ "fence_denied": {},
+ "fence_callers": [],
+ "fence_programs": [],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 1
+ },
+ "passed": true,
+ "exit_ok": true
+ },
+ {
+ "case": "responses_codex",
+ "checks": {
+ "plugin_discovered": true,
+ "plugin_origin_is_temporary_install": true,
+ "transport_origin_is_pinned_source": true,
+ "main_capture_exact_wire_body": true,
+ "capture_has_no_refusal": true,
+ "main_native_endpoint": true,
+ "main_protocol_auth": true,
+ "main_request_headers_sent": true,
+ "main_instructions_exact": true,
+ "warm_or_fallback_outcome": true,
+ "history_compacted": true,
+ "summary_has_synthetic_handoff": true,
+ "synthetic_token_counters": true,
+ "warm_sent_once": true,
+ "warm_native_endpoint": true,
+ "warm_prefix_exact": true,
+ "warm_prompt_and_tools_exact": true,
+ "warm_request_headers_kept": true,
+ "warm_protocol_auth": true,
+ "request_headers_not_json": true,
+ "consumer_codex_typed_parts": true,
+ "consumer_codex_stream_required": true,
+ "consumer_codex_session_header": true,
+ "failure_reason_expected": true,
+ "fallback_only_on_failure": true,
+ "plugin_made_no_blocked_call": true,
+ "no_external_network_attempt": true,
+ "official_logical_route_redirected_once": true
+ },
+ "error": null,
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_denied": {},
+ "fence_callers": [],
+ "fence_programs": [],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "passed": true,
+ "exit_ok": true
+ },
+ {
+ "case": "responses_codex_reasoning",
+ "checks": {
+ "plugin_discovered": true,
+ "plugin_origin_is_temporary_install": true,
+ "transport_origin_is_pinned_source": true,
+ "main_capture_exact_wire_body": true,
+ "capture_has_no_refusal": true,
+ "main_native_endpoint": true,
+ "main_protocol_auth": true,
+ "main_request_headers_sent": true,
+ "main_instructions_exact": true,
+ "warm_or_fallback_outcome": true,
+ "history_compacted": true,
+ "summary_has_synthetic_handoff": true,
+ "synthetic_token_counters": true,
+ "latest_native_carrier_retained_exact": true,
+ "warm_sent_once": true,
+ "warm_native_endpoint": true,
+ "warm_prefix_exact": true,
+ "warm_prompt_and_tools_exact": true,
+ "warm_request_headers_kept": true,
+ "warm_protocol_auth": true,
+ "request_headers_not_json": true,
+ "consumer_codex_typed_parts": true,
+ "consumer_codex_stream_required": true,
+ "consumer_codex_session_header": true,
+ "old_and_new_encrypted_reasoning_exact": true,
+ "reasoning_local_metadata_not_sent": true,
+ "failure_reason_expected": true,
+ "fallback_only_on_failure": true,
+ "plugin_made_no_blocked_call": true,
+ "no_external_network_attempt": true,
+ "official_logical_route_redirected_once": true
+ },
+ "error": null,
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_denied": {},
+ "fence_callers": [],
+ "fence_programs": [],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "passed": true,
+ "exit_ok": true
+ },
+ {
+ "case": "anthropic_text",
+ "checks": {
+ "plugin_discovered": true,
+ "plugin_origin_is_temporary_install": true,
+ "transport_origin_is_pinned_source": true,
+ "main_capture_exact_wire_body": true,
+ "capture_has_no_refusal": true,
+ "main_native_endpoint": true,
+ "main_protocol_auth": true,
+ "main_request_headers_sent": true,
+ "main_system_exact": true,
+ "warm_or_fallback_outcome": true,
+ "history_compacted": true,
+ "summary_has_synthetic_handoff": true,
+ "synthetic_token_counters": true,
+ "warm_sent_once": true,
+ "warm_native_endpoint": true,
+ "warm_prefix_exact": true,
+ "warm_prompt_and_tools_exact": true,
+ "warm_request_headers_kept": true,
+ "warm_protocol_auth": true,
+ "request_headers_not_json": true,
+ "failure_reason_expected": true,
+ "fallback_only_on_failure": true,
+ "plugin_made_no_blocked_call": true,
+ "no_external_network_attempt": true
+ },
+ "error": null,
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_denied": {},
+ "fence_callers": [],
+ "fence_programs": [],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "passed": true,
+ "exit_ok": true
+ },
+ {
+ "case": "anthropic_tool",
+ "checks": {
+ "plugin_discovered": true,
+ "plugin_origin_is_temporary_install": true,
+ "transport_origin_is_pinned_source": true,
+ "main_capture_exact_wire_body": true,
+ "capture_has_no_refusal": true,
+ "main_native_endpoint": true,
+ "main_protocol_auth": true,
+ "main_request_headers_sent": true,
+ "main_system_exact": true,
+ "warm_or_fallback_outcome": true,
+ "history_compacted": true,
+ "summary_has_synthetic_handoff": true,
+ "synthetic_token_counters": true,
+ "warm_sent_once": true,
+ "warm_native_endpoint": true,
+ "warm_prefix_exact": true,
+ "warm_prompt_and_tools_exact": true,
+ "warm_request_headers_kept": true,
+ "warm_protocol_auth": true,
+ "request_headers_not_json": true,
+ "old_and_new_tool_pairs": true,
+ "new_tool_payloads_exact": true,
+ "failure_reason_expected": true,
+ "fallback_only_on_failure": true,
+ "plugin_made_no_blocked_call": true,
+ "no_external_network_attempt": true
+ },
+ "error": null,
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_denied": {},
+ "fence_callers": [],
+ "fence_programs": [],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "passed": true,
+ "exit_ok": true
+ },
+ {
+ "case": "anthropic_refusal",
+ "checks": {
+ "plugin_discovered": true,
+ "plugin_origin_is_temporary_install": true,
+ "transport_origin_is_pinned_source": true,
+ "main_capture_exact_wire_body": true,
+ "capture_has_no_refusal": true,
+ "main_native_endpoint": true,
+ "main_protocol_auth": true,
+ "main_request_headers_sent": true,
+ "main_system_exact": true,
+ "warm_or_fallback_outcome": true,
+ "history_compacted": true,
+ "summary_has_synthetic_handoff": true,
+ "warm_sent_once": true,
+ "warm_native_endpoint": true,
+ "warm_prefix_exact": true,
+ "warm_prompt_and_tools_exact": true,
+ "warm_request_headers_kept": true,
+ "warm_protocol_auth": true,
+ "request_headers_not_json": true,
+ "failure_reason_expected": true,
+ "fallback_only_on_failure": true,
+ "plugin_made_no_blocked_call": true,
+ "no_external_network_attempt": true
+ },
+ "error": null,
+ "outcome": {
+ "path": "fallback",
+ "reason": "gate:finish_not_stop",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_denied": {},
+ "fence_callers": [],
+ "fence_programs": [],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 1
+ },
+ "passed": true,
+ "exit_ok": true
+ },
+ {
+ "case": "anthropic_signed",
+ "checks": {
+ "plugin_discovered": true,
+ "plugin_origin_is_temporary_install": true,
+ "transport_origin_is_pinned_source": true,
+ "main_capture_exact_wire_body": true,
+ "capture_has_no_refusal": true,
+ "main_native_endpoint": true,
+ "main_protocol_auth": true,
+ "main_request_headers_sent": true,
+ "main_system_exact": true,
+ "warm_or_fallback_outcome": true,
+ "history_compacted": true,
+ "summary_has_synthetic_handoff": true,
+ "synthetic_token_counters": true,
+ "latest_native_carrier_retained_exact": true,
+ "warm_sent_once": true,
+ "warm_native_endpoint": true,
+ "warm_prefix_exact": true,
+ "warm_prompt_and_tools_exact": true,
+ "warm_request_headers_kept": true,
+ "warm_protocol_auth": true,
+ "request_headers_not_json": true,
+ "old_and_new_thinking_signatures_exact": true,
+ "failure_reason_expected": true,
+ "fallback_only_on_failure": true,
+ "plugin_made_no_blocked_call": true,
+ "no_external_network_attempt": true,
+ "official_logical_route_redirected_once": true
+ },
+ "error": null,
+ "outcome": {
+ "path": "warm",
+ "reason": "accepted",
+ "prompt_tokens": 200,
+ "cached_tokens": 120
+ },
+ "fence_denied": {},
+ "fence_callers": [],
+ "fence_programs": [],
+ "request_counts": {
+ "main": 1,
+ "warm": 1,
+ "fallback": 0
+ },
+ "passed": true,
+ "exit_ok": true
+ }
+ ],
+ "error": null,
+ "script_sha256": "e3c74c4e14de19bb2d799f279b100d247cc9fbc962bbb6f87ba3fe9ef9af1c67",
+ "plugin_sha256": {
+ "warm_compaction/__init__.py": "760484ace80b9da77d7397828f69178905c9ac95df7b8114956bde727bd98aef",
+ "warm_compaction/anthropic.py": "7bd4cb0e075c4f279f62d3b6f0c3dcf7405308c7360f9136369476a59dca4fd3",
+ "warm_compaction/capture.py": "d2ce12d20fca5649d94b17d376a7bd9e21ba7f6a828b94cb62d030ca55adf791",
+ "warm_compaction/engine.py": "97a5ca7b779d4cfbaf4f4b2c9cd9d8e4616985d19578551d9c76679011204a12",
+ "warm_compaction/fallback.py": "9b2d0529767ff157bbe0d1cbf096ca6ac35217118f81eee769adf41d50189a9a",
+ "warm_compaction/handoff.py": "fcab51def8fbcc2b1928957930c9a5c58a4ad202c949fd9f870a77f3b30276ae",
+ "warm_compaction/layout.py": "3722ca05a4b84c9ed9f5cef5c7f7a175201efaba4208f3819dabcc556a2cfd57",
+ "warm_compaction/native.py": "2bac322bf7779e7d4ec78137a1ba1fdff25d3e58910ace51200147aebf15f494",
+ "warm_compaction/plugin.yaml": "baa7820b3ce9a40d2a53f70a4d0525131860ea2ec670143d0a7742b59c4d937b",
+ "warm_compaction/protocol.py": "f319d7a38ebb60d68d09b3575fe4f88f324b03be6017efbc5fd9932f05299853",
+ "warm_compaction/responses.py": "1b9b85cd3821455d462dc4fb6f0d63b9a7f2ca65d450fcd5e9cdb320d3367104",
+ "warm_compaction/rows.py": "2f5d9bd1e1d72c620354c4ec317526b4bca56033e9f080dde9967feff4bdb50c",
+ "warm_compaction/warm.py": "6b5cacd003acfa5027b871a73d3ca34ec1612ac70b7497e24cd8ecb74e9025d2"
+ },
+ "hermes_source_unchanged": true,
+ "plugin_source_unchanged": true,
+ "script_unchanged": true,
+ "passed": true
+}
diff --git a/scripts/check_provider_apis.py b/scripts/check_provider_apis.py
new file mode 100644
index 0000000..830e62a
--- /dev/null
+++ b/scripts/check_provider_apis.py
@@ -0,0 +1,479 @@
+"""Check native provider requests with real Hermes transports and a loopback fake server.
+
+Run with a Hermes dependency interpreter and a clean Hermes source checkout. Each case has a fresh
+process and home. The plugin loads from a copied plugin folder through normal Hermes discovery.
+Only invented history, fake keys, and fake token counters are used. The report contains metadata only.
+This check does not prove a live provider, cache reuse, summary quality, or a speed gain.
+"""
+
+from __future__ import annotations
+
+import argparse
+import copy
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import shutil
+import subprocess
+import sys
+import tempfile
+import threading
+import traceback
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+ROOT = Path(__file__).resolve().parents[1]
+CASES = ("responses_text", "responses_tool", "responses_incomplete",
+ "responses_codex", "responses_codex_reasoning", "anthropic_text", "anthropic_tool",
+ "anthropic_refusal", "anthropic_signed")
+MODEL = "synthetic-model"
+KEY = "synthetic-api-key"
+SYSTEM = "You are a synthetic test agent. Keep the code word BLUE-7."
+MAIN_TEXT = "Synthetic main answer."
+TOOL_NAME = "wc_note"
+TOOL_ID = "call_new"
+HANDOFF = (
+ "## Goal\nFinish the synthetic task.\n\n"
+ "## User instructions\n- Keep the code word BLUE-7.\n\n"
+ "## Current state\n- [OPEN] Report the code word.\n\n"
+ "## Key facts\n- The code word is BLUE-7.\n\n"
+ "## Next step\nReport the code word BLUE-7."
+)
+TOOLS = [{"type": "function", "function": {"name": TOOL_NAME, "description": "Return a synthetic note.",
+ "parameters": {"type": "object", "properties": {}, "required": []}}}]
+WARM_MARK = "Stop the current task now. This request comes from the host program"
+FALLBACK_MARK = "Write a handoff summary of the conversation transcript"
+
+
+def mode_for(case):
+ return "codex_responses" if case.startswith("responses_") else "anthropic_messages"
+
+
+def model_for(case):
+ return "claude-sonnet-4-6" if case == "anthropic_signed" else MODEL
+
+
+def logical_url(case, server):
+ """Official routes select the real renderer. Their test sends are redirected to loopback."""
+ if "codex" in case:
+ return "https://chatgpt.com/backend-api/codex"
+ return "https://api.anthropic.com" if case == "anthropic_signed" else server.base_url
+
+
+def plugin_hashes():
+ """Hash only the public plugin files that each worker receives."""
+ return {p.relative_to(ROOT).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest()
+ for p in sorted((ROOT / "warm_compaction").glob("*")) if p.is_file()}
+
+
+def history_for(case):
+ """Include a complete earlier tool pair in the tool cases."""
+ rows = []
+ for index in range(6):
+ rows += [{"role": "user", "content": f"Synthetic question {index}. " + ("Detail text. " * 40).rstrip()},
+ {"role": "assistant", "content": f"Synthetic answer {index}. " + ("Answer text. " * 40).rstrip()}]
+ if case.endswith("_tool"):
+ rows += [{"role": "assistant", "content": "", "tool_calls": [{"id": "call_old", "type": "function",
+ "function": {"name": TOOL_NAME, "arguments": "{}"}}]},
+ {"role": "tool", "tool_call_id": "call_old", "content": "Synthetic earlier result."},
+ {"role": "assistant", "content": "Synthetic tool round complete."}]
+ rows.append({"role": "user", "content": "Continue the synthetic task."})
+ if case == "responses_codex_reasoning":
+ rows[1]["codex_reasoning_items"] = [{
+ "type": "reasoning", "id": "rs_synthetic_old", "encrypted_content": "synthetic-sealed-bytes",
+ "summary": [{"type": "summary_text", "text": "Synthetic reasoning."}],
+ "_issuer_kind": "codex_backend", "_issuer_model": MODEL}]
+ rows[1]["codex_message_items"] = [{
+ "type": "message", "id": "msg_synthetic_old", "role": "assistant", "status": "completed",
+ "content": [{"type": "output_text", "text": rows[1]["content"]}], "phase": "final_answer"}]
+ elif case == "anthropic_signed":
+ rows[1]["reasoning_details"] = [{"type": "thinking", "thinking": "Synthetic earlier thought.",
+ "signature": "synthetic-old-signature"}]
+ return rows
+
+
+class FakeServer:
+ """Serve native protocols. Keep raw synthetic bodies in memory only."""
+
+ def __init__(self, case):
+ self.case, self.requests = case, []
+ owner = self
+
+ class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *_args):
+ pass
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
+ text = json.dumps(body)
+ kind = "warm" if WARM_MARK in text else "fallback" if FALLBACK_MARK in text else "main"
+ owner.requests.append({"kind": kind, "path": self.path, "body": body,
+ "headers": {k.lower(): v for k, v in self.headers.items()}})
+ payload = owner.payload(kind)
+ if self.path.endswith("/chat/completions"):
+ payload = {"id": "synthetic", "object": "chat.completion", "created": 0, "model": MODEL,
+ "choices": [{"index": 0, "finish_reason": "stop",
+ "message": {"role": "assistant",
+ "content": HANDOFF + "\n[END OF SUMMARY]"}}],
+ "usage": {"prompt_tokens": 50, "completion_tokens": 30, "total_tokens": 80}}
+ if body.get("stream") and mode_for(owner.case) == "codex_responses":
+ event = "response.incomplete" if payload["status"] == "incomplete" else "response.completed"
+ parts = []
+ if owner.case == "responses_codex" and kind == "warm":
+ # The consumer route can send completed items before an empty terminal envelope.
+ for index, item in enumerate(payload["output"]):
+ done = {"type": "response.output_item.done", "output_index": index, "item": item}
+ parts.append("event: response.output_item.done\ndata: " + json.dumps(done) + "\n\n")
+ payload = {**payload, "output": None}
+ parts.append(f"event: {event}\ndata: "
+ + json.dumps({"type": event, "response": payload}) + "\n\n")
+ data = "".join(parts).encode()
+ content_type = "text/event-stream"
+ elif body.get("stream") and mode_for(owner.case) == "anthropic_messages":
+ start = {**payload, "content": [], "stop_reason": None, "stop_sequence": None}
+ events = [("message_start", {"type": "message_start", "message": start})]
+ for index, block in enumerate(payload["content"]):
+ events.extend([
+ ("content_block_start", {"type": "content_block_start", "index": index,
+ "content_block": {"type": "text", "text": ""}}),
+ ("content_block_delta", {"type": "content_block_delta", "index": index,
+ "delta": {"type": "text_delta", "text": block["text"]}}),
+ ("content_block_stop", {"type": "content_block_stop", "index": index})])
+ events.extend([
+ ("message_delta", {"type": "message_delta", "delta": {
+ "stop_reason": payload["stop_reason"], "stop_sequence": None},
+ "usage": {"output_tokens": 40}}),
+ ("message_stop", {"type": "message_stop"})])
+ data = "".join(f"event: {event}\ndata: {json.dumps(value)}\n\n"
+ for event, value in events).encode()
+ content_type = "text/event-stream"
+ else:
+ data, content_type = json.dumps(payload).encode(), "application/json"
+ self.send_response(200)
+ self.send_header("Content-Type", content_type)
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True)
+
+ @property
+ def base_url(self):
+ root = f"http://127.0.0.1:{self.httpd.server_port}"
+ return root + "/v1" if mode_for(self.case) == "codex_responses" else root
+
+ def payload(self, kind):
+ is_tool = kind == "main" and self.case.endswith("_tool")
+ text = MAIN_TEXT if kind == "main" else HANDOFF
+ if kind == "fallback":
+ text += "\n[END OF SUMMARY]"
+ if mode_for(self.case) == "codex_responses":
+ output = [{"type": "message", "id": "msg_synthetic", "role": "assistant", "status": "completed",
+ "content": [{"type": "output_text", "text": text, "annotations": []}]}]
+ if is_tool:
+ output = [{"type": "function_call", "id": "fc_new", "call_id": TOOL_ID,
+ "status": "completed", "name": TOOL_NAME, "arguments": "{}"}]
+ if kind == "main" and self.case == "responses_codex_reasoning":
+ output.insert(0, {"type": "reasoning", "id": "rs_synthetic_new",
+ "encrypted_content": "synthetic-new-sealed-bytes",
+ "summary": [{"type": "summary_text", "text": "Synthetic new reasoning."}]})
+ incomplete = kind == "warm" and self.case.endswith("_incomplete")
+ return {"id": "resp_synthetic", "object": "response", "created_at": 0, "model": MODEL,
+ "status": "incomplete" if incomplete else "completed", "output": output,
+ "incomplete_details": {"reason": "max_output_tokens"} if incomplete else None,
+ "usage": {"input_tokens": 200, "output_tokens": 40, "total_tokens": 240,
+ "input_tokens_details": {"cached_tokens": 120}}}
+ refusal = kind == "warm" and self.case.endswith("_refusal")
+ content = ([{"type": "tool_use", "id": TOOL_ID, "name": TOOL_NAME, "input": {}}] if is_tool
+ else [{"type": "text", "text": text}])
+ if kind == "main" and self.case == "anthropic_signed":
+ content.insert(0, {"type": "thinking", "thinking": "Synthetic new thought.",
+ "signature": "synthetic-new-signature"})
+ return {"id": "msg_synthetic", "type": "message", "role": "assistant", "model": model_for(self.case),
+ "content": content, "stop_reason": "refusal" if refusal else "tool_use" if is_tool else "end_turn",
+ "stop_sequence": None, "usage": {"input_tokens": 80, "output_tokens": 40,
+ "cache_read_input_tokens": 120, "cache_creation_input_tokens": 0}}
+
+
+def worker(source, case, dependency_paths):
+ """Build and send a main request through real Hermes hooks and middleware."""
+ sys.path[:0] = [str(source), *map(str, dependency_paths), str(ROOT / "scripts")]
+ from check_plugin_hermes import Fence, merge_config
+ home = Path(os.environ["HERMES_HOME"])
+ installed = home / "plugins" / "warm_compaction"
+ server = FakeServer(case)
+ server.thread.start()
+ fence = Fence(home.parent, server.httpd.server_port, source, installed)
+
+ def early_network_fence(event, args):
+ # Block external network access during import and host capability discovery too.
+ if event in {"socket.getaddrinfo", "socket.connect", "socket.connect_ex"}:
+ fence(event, args)
+
+ sys.addaudithook(early_network_fence)
+ checks, result = {}, {"case": case, "checks": {}, "error": None}
+ try:
+ mode = mode_for(case)
+ model, route_url = model_for(case), logical_url(case, server)
+ # The native packet includes the exact replay carrier. Give that packet enough tail room.
+ tail_tokens = 512 if case in {"responses_codex_reasoning", "anthropic_signed"} else 128
+ merge_config(home / "config.yaml", {
+ "model": {"provider": "custom", "model": model, "base_url": server.base_url,
+ "api_key": KEY, "api_mode": mode},
+ "context": {"engine": "warm_compaction"},
+ "compression": {"progress_notices": False},
+ "auxiliary": {"warm_compaction": {"provider": "auto", "model": MODEL}},
+ "plugins": {"enabled": ["warm_compaction"], "hook_callback_timeout": 0,
+ "entries": {"warm_compaction": {"settings": {"tail_tokens": tail_tokens}}}},
+ })
+ platform.uname()
+ platform.platform()
+ platform.architecture()
+ from hermes_cli import plugins
+ from hermes_cli.middleware import apply_llm_request_middleware, run_llm_execution_middleware
+ from agent.transports.anthropic import AnthropicTransport
+ from agent.transports.codex import ResponsesApiTransport
+ manager = plugins.get_plugin_manager()
+ manager.discover_and_load()
+ engine = plugins.get_plugin_context_engine()
+ # Host capability discovery can call system tools. Finish it before the request fence.
+ checks["plugin_discovered"] = getattr(engine, "name", None) == "warm_compaction"
+ checks["plugin_origin_is_temporary_install"] = engine is not None and Path(
+ sys.modules[type(engine).__module__].__file__).resolve().is_relative_to(installed)
+ checks["transport_origin_is_pinned_source"] = all(
+ Path(sys.modules[transport.__module__].__file__).resolve().is_relative_to(source)
+ for transport in (AnthropicTransport, ResponsesApiTransport))
+ redirected = []
+ if route_url != server.base_url:
+ def loopback_post(url, data, headers, timeout_s, context=None):
+ from urllib.parse import urlsplit
+ from importlib import import_module
+ expected_path = "/backend-api/codex/responses" if "codex" in case else "/v1/messages"
+ if urlsplit(url).path != expected_path or not url.startswith(route_url):
+ raise ValueError("unexpected_logical_endpoint")
+ redirected.append(True)
+ warm = import_module(type(engine).__module__.rsplit(".", 1)[0] + ".warm")
+ path = "/responses" if mode == "codex_responses" else "/v1/messages"
+ return warm.urllib_post(server.base_url + path, data, headers, timeout_s)
+ engine = type(engine)(store=engine._store, llm=engine._llm,
+ settings={"tail_tokens": tail_tokens}, post=loopback_post)
+ engine.on_session_start("synthetic-session", platform="cli")
+ engine.update_model(model=model, context_length=200_000, base_url=route_url, api_key=KEY,
+ provider="custom", api_mode=mode)
+ transport = ResponsesApiTransport() if mode == "codex_responses" else AnthropicTransport()
+ history = history_for(case)
+ tools = copy.deepcopy(TOOLS) if case.endswith("_tool") else []
+ kwargs = transport.build_kwargs(
+ model=model, messages=[{"role": "system", "content": SYSTEM}, *history], tools=tools,
+ base_url=route_url, provider="custom", max_tokens=4096, is_codex_backend="codex" in case,
+ session_id="synthetic-session", context_length=200_000,
+ reasoning_config={"enabled": case.endswith(("_reasoning", "_signed")), "effort": "low"})
+ if mode == "codex_responses":
+ kwargs = transport.preflight_kwargs(kwargs, allow_stream=True, sanitize_harmony_tokens="codex" in case)
+ headers = {"x-opencode-session": "synthetic-session-header"}
+ if mode == "anthropic_messages":
+ headers.update({"anthropic-beta": "synthetic-beta", "anthropic-version": "2023-06-01"})
+ kwargs["extra_headers"] = {**kwargs.get("extra_headers", {}), **headers}
+ runtime = {"api_request_id": "synthetic-main-request", "session_id": "synthetic-session",
+ "model": model, "base_url": route_url, "api_mode": mode}
+ if mode == "codex_responses":
+ from openai import OpenAI
+ client = OpenAI(base_url=server.base_url, api_key=KEY, max_retries=0)
+ else:
+ from anthropic import Anthropic
+ client = Anthropic(base_url=server.base_url, api_key=KEY, max_retries=0)
+ _ = client.default_headers
+ sys.addaudithook(fence)
+ def terminal(body):
+ return client.responses.create(**body) if mode == "codex_responses" else client.messages.create(**body)
+ applied = apply_llm_request_middleware(kwargs, **runtime)
+ plugins.invoke_hook("pre_api_request", conversation_history=history, **runtime)
+ response = run_llm_execution_middleware(applied.payload, terminal,
+ original_request=applied.original_payload, **runtime)
+ normalized = transport.normalize_response(response)
+ plugins.invoke_hook("post_api_request", finish_reason=normalized.finish_reason,
+ assistant_message=normalized, usage={"prompt_tokens": 200}, **runtime)
+ capture = engine._store.latest("synthetic-session") or {}
+ main = next(row for row in server.requests if row["kind"] == "main")
+ checks["main_capture_exact_wire_body"] = capture.get("body") == main["body"]
+ checks["capture_has_no_refusal"] = capture.get("refusal") is None
+ endpoint = "/v1/responses" if mode == "codex_responses" else "/v1/messages"
+ checks["main_native_endpoint"] = main["path"] == endpoint
+ checks["main_protocol_auth"] = (main["headers"].get("authorization") == f"Bearer {KEY}"
+ if mode == "codex_responses" else main["headers"].get("x-api-key") == KEY)
+ checks["main_request_headers_sent"] = all(main["headers"].get(k) == v for k, v in headers.items())
+ if mode == "codex_responses":
+ checks["main_instructions_exact"] = main["body"].get("instructions") == SYSTEM
+ else:
+ checks["main_system_exact"] = main["body"].get("system") == SYSTEM
+ row = {"role": "assistant", "content": normalized.content or ""}
+ row.update(normalized.provider_data or {})
+ if normalized.tool_calls:
+ row["tool_calls"] = [{"id": tc.id, "type": "function", "function": {
+ "name": tc.name, "arguments": tc.arguments}} for tc in normalized.tool_calls]
+ history.append(row)
+ if normalized.tool_calls:
+ history.append({"role": "tool", "tool_call_id": TOOL_ID, "content": "Synthetic new result."})
+ else:
+ history.append({"role": "user", "content": "Keep the synthetic next step."})
+ compacted = engine.compress(history)
+ outcome = dict(engine.warm_last or {})
+ result["outcome"] = {k: outcome.get(k) for k in ("path", "reason", "prompt_tokens", "cached_tokens")}
+ failure = case.endswith(("_incomplete", "_refusal"))
+ checks["warm_or_fallback_outcome"] = outcome.get("path") == ("fallback" if failure else "warm")
+ checks["history_compacted"] = compacted is not history and len(compacted) < len(history)
+ checks["summary_has_synthetic_handoff"] = any(HANDOFF in str(r.get("content")) for r in compacted)
+ if not failure:
+ checks["synthetic_token_counters"] = (
+ outcome.get("prompt_tokens") == 200 and outcome.get("cached_tokens") == 120)
+ carrier = "codex_reasoning_items" if case == "responses_codex_reasoning" else "reasoning_details"
+ if case in {"responses_codex_reasoning", "anthropic_signed"}:
+ checks["latest_native_carrier_retained_exact"] = bool(row.get(carrier)) and any(
+ candidate.get(carrier) == row[carrier] for candidate in compacted)
+ warm_rows = [r for r in server.requests if r["kind"] == "warm"]
+ checks["warm_sent_once"] = len(warm_rows) == 1
+ if warm_rows:
+ sent = warm_rows[0]
+ body, earlier = sent["body"], main["body"]
+ field = "input" if mode == "codex_responses" else "messages"
+ checks["warm_native_endpoint"] = sent["path"] == main["path"]
+ checks["warm_prefix_exact"] = body[field][:len(earlier[field])] == earlier[field]
+ checks["warm_prompt_and_tools_exact"] = all(
+ body.get(k) == earlier.get(k) for k in ("instructions", "system", "tools", "prompt_cache_key"))
+ checks["warm_request_headers_kept"] = all(sent["headers"].get(k) == v for k, v in headers.items())
+ checks["warm_protocol_auth"] = (sent["headers"].get("authorization") == f"Bearer {KEY}"
+ if mode == "codex_responses" else sent["headers"].get("x-api-key") == KEY)
+ checks["request_headers_not_json"] = "extra_headers" not in body
+ if "codex" in case:
+ checks["consumer_codex_typed_parts"] = all(
+ isinstance(item["content"], list) for item in body["input"] if item.get("type") == "message")
+ checks["consumer_codex_stream_required"] = body.get("stream") is True
+ checks["consumer_codex_session_header"] = sent["headers"].get("session_id") == "synthetic-session"
+ if case == "responses_codex_reasoning":
+ items = [item for item in body["input"] if item.get("type") == "reasoning"]
+ checks["old_and_new_encrypted_reasoning_exact"] = [item.get("encrypted_content") for item in items] == [
+ "synthetic-sealed-bytes", "synthetic-new-sealed-bytes"]
+ checks["reasoning_local_metadata_not_sent"] = all(not any(
+ key.startswith("_") or key == "id" for key in item) for item in items)
+ if case == "anthropic_signed":
+ thinking = [block for msg in body["messages"] if isinstance(msg["content"], list)
+ for block in msg["content"] if block.get("type") == "thinking"]
+ checks["old_and_new_thinking_signatures_exact"] = [block.get("signature") for block in thinking] == [
+ "synthetic-old-signature", "synthetic-new-signature"]
+ if case.endswith("_tool"):
+ if mode == "codex_responses":
+ ids = [(x.get("type"), x.get("call_id")) for x in body[field]]
+ checks["old_and_new_tool_pairs"] = all(ids.count((kind, call_id)) == 1
+ for kind in ("function_call", "function_call_output") for call_id in ("call_old", TOOL_ID))
+ calls = [item for item in body[field] if item.get("type") == "function_call"
+ and item.get("call_id") == TOOL_ID]
+ outputs = [item for item in body[field] if item.get("type") == "function_call_output"
+ and item.get("call_id") == TOOL_ID]
+ checks["new_tool_payloads_exact"] = (
+ len(calls) == len(outputs) == 1 and calls[0].get("arguments") == "{}"
+ and outputs[0].get("output") == "Synthetic new result.")
+ else:
+ blocks = [block for msg in body[field] if isinstance(msg["content"], list)
+ for block in msg["content"]]
+ checks["old_and_new_tool_pairs"] = all(
+ sum(block.get("type") == kind and block.get(key) == call_id for block in blocks) == 1
+ for kind, key in (("tool_use", "id"), ("tool_result", "tool_use_id"))
+ for call_id in ("call_old", TOOL_ID))
+ calls = [block for block in blocks if block.get("type") == "tool_use"
+ and block.get("id") == TOOL_ID]
+ outputs = [block for block in blocks if block.get("type") == "tool_result"
+ and block.get("tool_use_id") == TOOL_ID]
+ checks["new_tool_payloads_exact"] = (
+ len(calls) == len(outputs) == 1 and calls[0].get("input") == {}
+ and outputs[0].get("content") == "Synthetic new result.")
+ checks["failure_reason_expected"] = outcome.get("reason") == (
+ "incomplete_response" if case.endswith("_incomplete")
+ else "gate:finish_not_stop" if failure else "accepted")
+ checks["fallback_only_on_failure"] = bool([r for r in server.requests if r["kind"] == "fallback"]) == failure
+ checks["plugin_made_no_blocked_call"] = fence.plugin_denied == 0
+ checks["no_external_network_attempt"] = not any(reason.startswith("network_") for reason in fence.denied)
+ result["fence_denied"] = fence.denied
+ result["fence_callers"] = sorted(fence.callers)
+ result["fence_programs"] = sorted(fence.programs)
+ if route_url != server.base_url:
+ checks["official_logical_route_redirected_once"] = len(redirected) == 1
+ result["request_counts"] = {kind: sum(r["kind"] == kind for r in server.requests)
+ for kind in ("main", "warm", "fallback")}
+ client.close()
+ finally:
+ server.httpd.shutdown()
+ server.httpd.server_close()
+ result["checks"] = checks
+ result["passed"] = bool(checks) and all(checks.values())
+ return result
+
+
+def run(source, cases, dependency_paths):
+ """Run cases in clean processes. Discard raw output and temporary synthetic data."""
+ from check_hermes_compatibility import source_state, worker_environment
+ report = {"check": "native provider transport and warm loopback check", "python": sys.version.split()[0],
+ "hermes": source_state(source), "synthetic": True, "live_provider": False,
+ "cache_reuse_proved": False, "cases": [], "error": None,
+ "script_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
+ "plugin_sha256": plugin_hashes()}
+ for case in cases:
+ with tempfile.TemporaryDirectory(prefix="wc-provider-") as folder:
+ scenario = Path(folder)
+ home = scenario / "home"
+ shutil.copytree(ROOT / "warm_compaction", home / "plugins" / "warm_compaction",
+ ignore=shutil.ignore_patterns("__pycache__"))
+ result_path = scenario / "result.json"
+ command = [sys.executable, "-I", "-B", str(Path(__file__).resolve()), "--hermes-source", str(source),
+ "--worker-case", case, "--report", str(result_path)]
+ for path in dependency_paths:
+ command += ["--dependency-path", str(path)]
+ completed = subprocess.run(command, cwd=scenario, env=worker_environment(home),
+ capture_output=True, timeout=180)
+ result = json.loads(result_path.read_text()) if result_path.exists() else {
+ "case": case, "passed": False, "error": "worker_no_report", "checks": {}}
+ result["exit_ok"] = completed.returncode == 0
+ report["cases"].append(result)
+ print(f"{case}: {'passed' if result['passed'] else 'failed'}", flush=True)
+ report["hermes_source_unchanged"] = source_state(source) == report["hermes"]
+ report["plugin_source_unchanged"] = plugin_hashes() == report["plugin_sha256"]
+ report["script_unchanged"] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() == report["script_sha256"]
+ report["passed"] = all(report[key] for key in (
+ "hermes_source_unchanged", "plugin_source_unchanged", "script_unchanged")) and all(
+ r["passed"] and r["exit_ok"] for r in report["cases"])
+ return report
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--hermes-source", type=Path, required=True)
+ parser.add_argument("--dependency-path", type=Path, action="append", default=[])
+ parser.add_argument("--case", choices=CASES, action="append")
+ parser.add_argument("--report", type=Path)
+ parser.add_argument("--worker-case", choices=CASES, help=argparse.SUPPRESS)
+ args = parser.parse_args()
+ source = args.hermes_source.resolve()
+ paths = [p.resolve() for p in args.dependency_path]
+ try:
+ report = worker(source, args.worker_case, paths) if args.worker_case else run(source, args.case or CASES, paths)
+ except Exception as error:
+ frames = traceback.extract_tb(error.__traceback__)[-3:]
+ report = {"passed": False, "error": "worker_runtime_failed" if args.worker_case else "setup_failed",
+ "error_type": type(error).__name__, "checks": {},
+ "error_locations": [{"file": Path(frame.filename).name, "function": frame.name,
+ "line": frame.lineno} for frame in frames]}
+ # A fixed exception class is safe. Do not put exception text or raw provider data in the report.
+ if args.worker_case:
+ report["case"] = args.worker_case
+ if args.report:
+ args.report.parent.mkdir(parents=True, exist_ok=True)
+ args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+ print(json.dumps({"passed": report["passed"], "error": report.get("error")}))
+ return 0 if report["passed"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_wc_anthropic.py b/tests/test_wc_anthropic.py
new file mode 100644
index 0000000..b37c9d0
--- /dev/null
+++ b/tests/test_wc_anthropic.py
@@ -0,0 +1,250 @@
+"""Synthetic checks for the bounded Anthropic Messages adapter."""
+
+import copy
+import unittest
+
+from warm_compaction import anthropic
+from warm_compaction.rows import row_digest
+from warm_compaction.warm import WarmRefusal
+from wc_fixtures import assistant, tool, user
+
+ROUTE = ("claude-sonnet-4-6", "https://api.anthropic.com", "anthropic_messages")
+INSTRUCTION = "Write the handoff."
+
+
+def capture(rows, reply):
+ """Make an invented capture. No provider or real credentials are used."""
+ return {"route": ROUTE, "digests": [row_digest(r) for r in rows],
+ "reply": {"content": reply["content"], "tool_calls": [
+ [c["id"], c["function"]["name"]] for c in reply.get("tool_calls", [])]},
+ "body": {"model": ROUTE[0], "system": [{"type": "text", "text": "Synthetic rule.",
+ "cache_control": {"type": "ephemeral"}}],
+ "messages": anthropic._rows(rows), "max_tokens": 4096,
+ "thinking": {"type": "disabled"}}}
+
+
+class BuildTest(unittest.TestCase):
+ def setUp(self):
+ self.rows = [user("first"), assistant("answer"), user("next")]
+ self.reply = assistant("result")
+ self.capture = capture(self.rows, self.reply)
+ self.messages = [*self.rows, self.reply, user("latest")]
+
+ def build(self, cap=None, messages=None, context=100000):
+ return anthropic.build_request(cap or self.capture, messages or self.messages, ROUTE, context, INSTRUCTION)
+
+ def refusal(self, code, callback):
+ with self.assertRaises(WarmRefusal) as caught:
+ callback()
+ self.assertEqual(caught.exception.code, code)
+
+ def test_keeps_the_native_prefix_and_settings_without_mutation(self):
+ self.capture["body"].update(tool_choice={"type": "auto"}, tools=[{
+ "name": "read", "description": "Synthetic tool", "input_schema": {"type": "object"}}],
+ stop_sequences=["cut"], output_config={"effort": "medium"})
+ self.capture["body"]["messages"][0]["content"][0]["cache_control"] = {"type": "ephemeral"}
+ before = copy.deepcopy((self.capture, self.messages))
+ body = self.build()
+ self.assertEqual(body["messages"][:3], before[0]["body"]["messages"])
+ for name in ("system", "tools", "tool_choice", "thinking", "output_config"):
+ self.assertEqual(body[name], before[0]["body"][name])
+ self.assertEqual(body["messages"][-1], {"role": "user", "content": [
+ {"type": "text", "text": "latest"}, {"type": "text", "text": INSTRUCTION}]})
+ self.assertFalse(body["stream"])
+ self.assertNotIn("stop_sequences", body)
+ self.assertEqual((self.capture, self.messages), before)
+
+ def test_complete_new_tool_pairs_keep_arguments_and_results(self):
+ reply = assistant("call", [("call1", "read", '{"path":"synthetic"}')])
+ cap = capture(self.rows, reply)
+ body = self.build(cap, [*self.rows, reply, tool("call1", "synthetic output"), user("latest")])
+ self.assertEqual(body["messages"][-2]["content"][-1], {
+ "type": "tool_use", "id": "call1", "name": "read", "input": {"path": "synthetic"}})
+ self.assertEqual(body["messages"][-1]["content"][0], {
+ "type": "tool_result", "tool_use_id": "call1", "content": "synthetic output"})
+
+ def test_source_tool_rows_are_matched_after_native_folding(self):
+ rows = [user("task"), assistant("call", [("c1", "read", "{}")]), tool("c1", "output"), user("next")]
+ cap = capture(rows, self.reply)
+ body = self.build(cap, [*rows, self.reply])
+ self.assertEqual(body["messages"][:len(cap["body"]["messages"])], cap["body"]["messages"])
+ cap["body"]["messages"][1]["content"][1]["input"] = {"changed": True}
+ self.refusal("source_transform_unsupported", lambda: self.build(cap, [*rows, self.reply]))
+
+ def test_captured_thinking_stays_intact(self):
+ self.rows[1]["reasoning_details"] = [{"type": "thinking", "thinking": "synthetic", "signature": "fake"}]
+ self.capture = capture(self.rows, self.reply)
+ block = {"type": "thinking", "thinking": "synthetic", "signature": "fake"}
+ body = self.build()
+ self.assertEqual(body["messages"][1]["content"][0], block)
+
+ def test_new_reasoning_and_media_are_refused(self):
+ for key in anthropic.OPAQUE_ROWS:
+ with self.subTest(key=key):
+ reply = dict(self.reply, **{key: "synthetic opaque field"})
+ self.refusal("source_transform_unsupported", lambda reply=reply: self.build(
+ messages=[*self.rows, reply]))
+ reply = dict(self.reply, api_content=[{"type": "image", "source": {"type": "base64", "data": "fake"}}])
+ # The plain content itself must be unsupported too: api_content is a string-only sidecar in Hermes.
+ reply["content"] = reply["api_content"]
+ cap = capture(self.rows, self.reply)
+ cap["reply"]["content"] = ""
+ self.refusal("source_transform_unsupported", lambda: self.build(cap, [*self.rows, reply]))
+
+ def test_changed_capture_text_and_native_media_are_refused(self):
+ self.capture["body"]["messages"][0]["content"][0]["text"] = "changed"
+ self.refusal("source_transform_unsupported", self.build)
+ self.capture["body"]["messages"][0]["content"] = [{"type": "image", "source": {}}]
+ self.refusal("source_transform_unsupported", self.build)
+
+ def test_forced_tools_server_tools_and_stateful_options_are_refused(self):
+ for change in ({"tool_choice": {"type": "any"}}, {"tool_choice": {"type": "tool", "name": "read"}},
+ {"tools": [{"type": "web_search_20250305", "name": "web_search"}]},
+ {"context_management": {"edits": []}}, {"container": "synthetic"},
+ {"output_config": {"format": {"type": "json_schema"}}}):
+ with self.subTest(change=change):
+ cap = copy.deepcopy(self.capture)
+ cap["body"].update(change)
+ self.refusal("settings_unsupported", lambda cap=cap: self.build(cap))
+
+ def test_missing_tool_result_and_changed_route_are_refused(self):
+ reply = assistant("call", [("c1", "read", "{}")])
+ cap = capture(self.rows, reply)
+ self.refusal("history_changed", lambda: self.build(cap, [*self.rows, reply]))
+ cap["route"] = ("changed", *ROUTE[1:])
+ self.refusal("route_changed", lambda: self.build(cap))
+
+ def test_signed_ordered_source_rows_are_refused(self):
+ self.rows[1]["anthropic_content_blocks"] = [{"type": "text", "text": "other"}]
+ self.capture["digests"] = [row_digest(r) for r in self.rows]
+ self.refusal("source_transform_unsupported", self.build)
+
+ def test_size_estimate_includes_system_and_keeps_manual_thinking_budget(self):
+ cap = copy.deepcopy(self.capture)
+ cap["body"]["system"] = "synthetic " * 10000
+ self.refusal("capacity", lambda: self.build(cap, context=9000))
+ cap["prompt_tokens"] = 10
+ self.build(cap, context=9000)
+ cap["body"]["thinking"] = {"type": "enabled", "budget_tokens": 8000}
+ body = self.build(cap)
+ self.assertEqual(body["thinking"], cap["body"]["thinking"])
+ self.assertEqual(body["max_tokens"], 8000 + anthropic.HANDOFF_MIN_TOKENS)
+ self.refusal("capacity", lambda: self.build(cap, context=9000))
+
+ def test_signed_and_redacted_reply_fields_follow_the_hermes_normalizer(self):
+ # Hermes bc2e4d37 agent/transports/anthropic.py:65-105 keeps these signed blocks in reasoning_details.
+ blocks = [{"type": "thinking", "thinking": "synthetic thought", "signature": "fake-signed-value"},
+ {"type": "redacted_thinking", "data": "fake-redacted-data"}]
+ reply = dict(self.reply, reasoning_content="synthetic thought", reasoning_details=blocks)
+ body = self.build(messages=[*self.rows, reply, user("latest")])
+ self.assertEqual(body["messages"][-2]["content"], [*blocks, {"type": "text", "text": "result"}])
+ self.assertEqual(reply["reasoning_details"], blocks)
+
+ def test_ordered_thinking_tool_carrier_keeps_exact_block_order(self):
+ # The normalizer adds anthropic_content_blocks for signed thinking interleaved with tool use.
+ first = {"type": "thinking", "thinking": "before", "signature": "fake-first"}
+ second = {"type": "thinking", "thinking": "after", "signature": "fake-second"}
+ call = {"type": "tool_use", "id": "c1", "name": "read", "input": {"path": "synthetic"}}
+ ordered = [first, {"type": "text", "text": "call"}, call, second]
+ reply = assistant("call", [("c1", "read", '{"path":"synthetic"}')])
+ reply.update(reasoning_details=[first, second], reasoning_content="before\n\nafter",
+ anthropic_content_blocks=ordered)
+ cap = capture(self.rows, reply)
+ messages = [*self.rows, reply, tool("c1", "output")]
+ body = self.build(cap, messages)
+ self.assertEqual(body["messages"][-2]["content"], ordered)
+ changed = copy.deepcopy(reply)
+ changed["anthropic_content_blocks"][2]["input"] = {"path": "changed"}
+ self.refusal("source_transform_unsupported", lambda: self.build(
+ cap, [*self.rows, changed, tool("c1", "output")]))
+
+ def test_changed_or_unknown_thinking_fields_are_refused(self):
+ blocks = [{"type": "thinking", "thinking": "synthetic", "signature": "fake"}]
+ self.rows[1].update(reasoning_details=blocks, reasoning_content="synthetic")
+ self.capture = capture(self.rows, self.reply)
+ self.capture["body"]["messages"][1]["content"][0]["signature"] = "changed"
+ self.refusal("source_transform_unsupported", self.build)
+ for details in ([{"type": "thinking", "thinking": "unsigned"}],
+ [{"type": "redacted_thinking", "data": ""}],
+ [{"type": "custom.native_assistant", "payload": "opaque"}],
+ [{**blocks[0], "output_only": True}]):
+ reply = dict(self.reply, reasoning_details=details)
+ with self.subTest(details=details):
+ self.refusal("source_transform_unsupported", lambda reply=reply: self.build(
+ messages=[*self.rows, reply]))
+
+
+class HeaderTest(unittest.TestCase):
+ def test_api_key_auth_keeps_custom_headers(self):
+ headers = anthropic.route_headers("sk-ant-api-synthetic", ROUTE[1], {
+ "X-Title": "Synthetic"})
+ self.assertNotIn("Authorization", headers)
+ self.assertEqual(headers["x-api-key"], "sk-ant-api-synthetic")
+ self.assertEqual(headers["anthropic-beta"], anthropic.COMMON_BETAS)
+ self.assertEqual(headers["anthropic-version"], "2023-06-01")
+ self.assertEqual(headers["X-Title"], "Synthetic")
+
+ def test_known_headers_keep_their_case_and_value(self):
+ defaults = {"Anthropic-Beta": "synthetic-beta", "Anthropic-Version": "synthetic-version"}
+ headers = anthropic.route_headers("fake", "http://127.0.0.1:9", defaults)
+ self.assertEqual(headers, {**defaults, "x-api-key": "fake"})
+ self.assertEqual(defaults, {"Anthropic-Beta": "synthetic-beta", "Anthropic-Version": "synthetic-version"})
+
+ def test_oauth_bearer_and_signed_cloud_routes_are_refused(self):
+ for key, base, provider in (("sk-ant-oat-fake", ROUTE[1], ""), ("eyJfake", ROUTE[1], ""),
+ ("fake", "https://api.minimax.io/anthropic", ""),
+ ("fake", "https://synthetic.azure.com/anthropic", ""),
+ ("fake", "https://api.commandcode.ai", ""),
+ ("fake", "https://synthetic.palantirfoundry.com", ""),
+ ("fake", "https://inference-api.nousresearch.com", ""),
+ ("fake", "https://synthetic.example", "nous"),
+ ("fake", ROUTE[1], "bedrock")):
+ with self.subTest(base=base), self.assertRaises(WarmRefusal) as caught:
+ anthropic.route_headers(key, base, {}, provider)
+ self.assertEqual(caught.exception.code, "auth_unsupported")
+
+ def test_a_route_header_with_another_credential_is_refused(self):
+ for headers in ({"Authorization": "Bearer other"}, {"Authorization": "Bearer fake"},
+ {"X-Api-Key": "other"}):
+ with self.subTest(headers=headers), self.assertRaises(WarmRefusal) as caught:
+ anthropic.route_headers("fake", ROUTE[1], headers)
+ self.assertEqual(caught.exception.code, "auth_unsupported")
+
+
+class ParseTest(unittest.TestCase):
+ def reply(self, **changes):
+ return {"type": "message", "role": "assistant", "content": [{"type": "text", "text": "Synthetic handoff"}],
+ "stop_reason": "end_turn", "usage": {"input_tokens": 10, "cache_read_input_tokens": 90,
+ "cache_creation_input_tokens": 5, "output_tokens": 8}, **changes}
+
+ def test_native_usage_counts_all_input_components(self):
+ reply = anthropic.parse_reply(self.reply())
+ self.assertEqual((reply["prompt_tokens"], reply["cached_tokens"], reply["completion_tokens"]), (105, 90, 8))
+ self.assertEqual((reply["content"], reply["finish_reason"], reply["tool_calls"], reply["refusal"]),
+ ("Synthetic handoff", "stop", False, False))
+
+ def test_stops_tools_refusals_and_unknown_counters(self):
+ for reason, expected in (("end_turn", "stop"), ("stop_sequence", "stop"), ("max_tokens", "length"),
+ ("refusal", "content_filter"), ("tool_use", "tool_calls"), (None, None)):
+ with self.subTest(reason=reason):
+ reply = anthropic.parse_reply(self.reply(stop_reason=reason, usage={}))
+ self.assertEqual(reply["finish_reason"], expected)
+ self.assertEqual(reply["refusal"], reason == "refusal")
+ self.assertIsNone(reply["cached_tokens"])
+ self.assertIsNone(reply["prompt_tokens"])
+ reply = anthropic.parse_reply(self.reply(content=[{"type": "tool_use", "name": "read"}]))
+ self.assertTrue(reply["tool_calls"])
+
+ def test_thinking_is_not_summary_text_and_malformed_replies_are_refused(self):
+ reply = anthropic.parse_reply(self.reply(content=[{"type": "thinking", "thinking": "synthetic"},
+ {"type": "text", "text": "summary"}]))
+ self.assertEqual(reply["content"], "summary")
+ for payload in ({}, self.reply(content="wrong"), self.reply(content=[{"type": "text", "text": None}]),
+ self.reply(usage="wrong"), self.reply(usage=[]), self.reply(usage=False)):
+ with self.subTest(payload=payload), self.assertRaises(WarmRefusal) as caught:
+ anthropic.parse_reply(payload)
+ self.assertEqual(caught.exception.code, "incomplete_response")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_wc_capture.py b/tests/test_wc_capture.py
index 7b819d2..a9363f5 100644
--- a/tests/test_wc_capture.py
+++ b/tests/test_wc_capture.py
@@ -220,7 +220,7 @@ class CaptureStoreTest(unittest.TestCase):
self.assertEqual(self.store.latest("s1")["reply"]["tool_calls"], [["c1", "read"]])
def test_other_api_mode_keeps_no_body(self):
- self.run_request(api_mode="codex_responses")
+ self.run_request(api_mode="bedrock_converse")
self.assertIsNone(self.store.latest("s1")["body"])
def test_unusable_finish_reason_keeps_no_capture(self):
diff --git a/tests/test_wc_protocol.py b/tests/test_wc_protocol.py
new file mode 100644
index 0000000..9df17c6
--- /dev/null
+++ b/tests/test_wc_protocol.py
@@ -0,0 +1,281 @@
+"""Tests for native reply completion, request headers, and history stamps."""
+
+import copy
+import json
+import unittest
+
+from warm_compaction.capture import UnsupportedRequest, final_body, request_headers
+from warm_compaction.protocol import MAX_DONE_ITEMS, envelope
+from warm_compaction.rows import SendPolicy, row_digest, sent_tokens
+from warm_compaction.warm import WarmRefusal, fits, send
+
+
+def sse(events):
+ """Encode synthetic events."""
+ return "".join("data: " + json.dumps(event) + "\n\n" for event in events).encode()
+
+
+class EnvelopeTest(unittest.TestCase):
+ def test_responses_requires_one_completed_terminal(self):
+ response = {"status": "completed", "output": [{"type": "message", "role": "assistant",
+ "status": "completed", "content": [{"type": "output_text", "text": "synthetic"}]}]}
+ event = {"type": "response.completed", "response": response}
+ self.assertEqual(envelope(sse([event]), "codex_responses"), response)
+ for events in ([{"type": "response.output_text.delta", "delta": "partial"}], [event, event],
+ [event, {"type": "response.failed"}], [{"type": "response.incomplete"}]):
+ with self.subTest(events=events), self.assertRaises(WarmRefusal):
+ envelope(sse(events), "codex_responses")
+
+ def done_message(self, index=0, item_id="msg_synthetic", **changes):
+ return {"type": "response.output_item.done", "output_index": index, "item": {
+ "id": item_id, "type": "message", "role": "assistant", "status": "completed",
+ "content": [{"type": "output_text", "text": "synthetic summary", "annotations": []}], **changes}}
+
+ def completed(self, **changes):
+ return {"type": "response.completed", "response": {"status": "completed", "output": None, **changes}}
+
+ def test_completed_responses_fill_null_empty_and_absent_output_from_done_items(self):
+ from warm_compaction.responses import parse_reply
+ done = self.done_message()
+ for output in (None, [], "absent"):
+ terminal = self.completed(usage={"input_tokens": 12, "output_tokens": 3})
+ if output == "absent":
+ terminal["response"].pop("output")
+ else:
+ terminal["response"]["output"] = output
+ before = copy.deepcopy((done, terminal))
+ with self.subTest(output=output):
+ payload = envelope(sse([done, terminal]), "codex_responses")
+ self.assertEqual(payload["output"], [done["item"]])
+ self.assertEqual(parse_reply(payload)["content"], "synthetic summary")
+ self.assertEqual(payload["usage"], {"input_tokens": 12, "output_tokens": 3})
+ self.assertEqual((done, terminal), before)
+
+ def test_done_items_use_output_order_and_match_added_items(self):
+ reasoning = {"type": "response.output_item.done", "output_index": 0, "item": {
+ "id": "rs_synthetic", "type": "reasoning", "summary": [], "encrypted_content": "fake"}}
+ message = self.done_message(1)
+ added = {"type": "response.output_item.added", "output_index": 1, "item": {
+ "id": message["item"]["id"], "type": "message", "role": "assistant", "status": "in_progress",
+ "content": []}}
+ payload = envelope(sse([added, message, reasoning, self.completed()]), "codex_responses")
+ self.assertEqual(payload["output"], [reasoning["item"], message["item"]])
+
+ def test_missing_done_items_and_delta_only_text_are_refused(self):
+ delta = {"type": "response.output_text.delta", "output_index": 0, "item_id": "msg_synthetic",
+ "content_index": 0, "delta": "synthetic partial summary"}
+ for events in ([self.completed()], [delta, self.completed()], [self.done_message()],
+ [self.done_message(), {"type": "response.incomplete", "response": {"status": "incomplete"}}],
+ [self.done_message(), {"type": "response.failed"}],
+ [self.done_message(), {"type": "error"}, self.completed()],
+ [self.done_message(), {"type": "response.error"}, self.completed()]):
+ with self.subTest(events=events), self.assertRaises(WarmRefusal) as caught:
+ envelope(sse(events), "codex_responses")
+ self.assertEqual(caught.exception.code, "incomplete_response")
+
+ def test_malformed_incomplete_and_nontext_done_items_are_refused(self):
+ cases = [self.done_message(status="in_progress"), self.done_message(role="user"),
+ self.done_message(id=""), self.done_message(content=None), self.done_message(content=[]),
+ self.done_message(content=[{"type": "output_text", "text": None}]),
+ self.done_message(content=[{"type": "output_text", "text": " "}]),
+ self.done_message(content=[{"type": "image", "data": "fake"}]),
+ self.done_message(phase="commentary"),
+ {"type": "response.output_item.done", "output_index": 0, "item": []},
+ {"type": "response.output_item.done", "output_index": 0, "item": {
+ "id": "rs_synthetic", "type": "reasoning", "summary": []}},
+ {"type": "response.output_item.done", "output_index": 0, "item": {
+ "id": "rs_synthetic", "type": "reasoning", "summary": "wrong"}}]
+ for done in cases:
+ with self.subTest(done=done), self.assertRaises(WarmRefusal):
+ envelope(sse([done, self.completed()]), "codex_responses")
+
+ def test_done_indexes_ids_and_terminal_output_cannot_conflict(self):
+ done = self.done_message()
+ added = {"type": "response.output_item.added", "output_index": 0, "item": {
+ "id": "msg_synthetic", "type": "message"}}
+ wrong_added = copy.deepcopy(added)
+ wrong_added["item"]["id"] = "msg_other"
+ wrong_terminal = self.completed(output=[{**done["item"], "content": [{
+ "type": "output_text", "text": "changed"}]}])
+ cases = [[done, done, self.completed()], [done, self.done_message(item_id="other"), self.completed()],
+ [done, self.done_message(1), self.completed()], [wrong_added, done, self.completed()],
+ [added, added, done, self.completed()], [done, wrong_terminal]]
+ for index in (-1, 1, False, "0", MAX_DONE_ITEMS):
+ cases.append([self.done_message(index), self.completed()])
+ for events in cases:
+ with self.subTest(events=events), self.assertRaises(WarmRefusal):
+ envelope(sse(events), "codex_responses")
+
+ def test_completed_done_items_reject_invalid_terminal_and_trailing_events(self):
+ done = self.done_message()
+ terminals = [self.completed(status="incomplete"), self.completed(output="invalid"),
+ self.completed(error={"code": "synthetic_error"}),
+ self.completed(incomplete_details={"reason": "synthetic_limit"})]
+ for terminal in terminals:
+ with self.subTest(terminal=terminal), self.assertRaises(WarmRefusal):
+ envelope(sse([done, terminal]), "codex_responses")
+ for trailing in ({"type": "response.output_text.delta", "delta": "trailing"},
+ self.done_message(), self.completed(), {"type": "response.in_progress"}):
+ with self.subTest(trailing=trailing), self.assertRaises(WarmRefusal):
+ envelope(sse([done, self.completed(), trailing]), "codex_responses")
+
+ def test_progress_cannot_change_an_announced_id_or_reopen_a_done_item(self):
+ done = self.done_message()
+ added = {"type": "response.output_item.added", "output_index": 0, "item": {
+ "id": "msg_synthetic", "type": "message"}}
+ delta = {"type": "response.output_text.delta", "output_index": 0, "item_id": "msg_other", "delta": "text"}
+ for events in ([added, delta, done, self.completed()], [done, delta, self.completed()]):
+ with self.subTest(events=events), self.assertRaises(WarmRefusal):
+ envelope(sse(events), "codex_responses")
+ for index, item_id in ((1, "msg_missing"), (0, "msg_other"), (False, "msg_synthetic")):
+ delta = {"type": "response.output_text.delta", "output_index": index, "item_id": item_id, "delta": "text"}
+ with self.subTest(index=index, item_id=item_id), self.assertRaises(WarmRefusal):
+ envelope(sse([delta, done, self.completed()]), "codex_responses")
+
+ def anthropic_events(self):
+ return [{"type": "message_start", "message": {
+ "type": "message", "role": "assistant", "usage": {"input_tokens": 12}, "content": []}},
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "synthetic"}},
+ {"type": "content_block_stop", "index": 0},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 3}},
+ {"type": "message_stop"}]
+
+ def test_anthropic_requires_stop_and_closed_blocks(self):
+ events = self.anthropic_events()
+ payload = envelope(sse(events), "anthropic_messages")
+ self.assertEqual(payload["content"], [{"type": "text", "text": "synthetic"}])
+ self.assertEqual(payload["usage"], {"input_tokens": 12, "output_tokens": 3})
+ for bad in (events[:-1], [*events[:3], *events[4:]], [*events, {"type": "error"}]):
+ with self.subTest(events=bad), self.assertRaises(WarmRefusal):
+ envelope(sse(bad), "anthropic_messages")
+
+ def test_json_and_invalid_utf8(self):
+ self.assertEqual(envelope(b'{"status":"completed"}', "codex_responses"), {"status": "completed"})
+ for raw in (b'\xff', b'[]', b'data: {broken}\n\n'):
+ with self.subTest(raw=raw), self.assertRaises(WarmRefusal):
+ envelope(raw, "codex_responses")
+
+ def test_native_stream_refuses_wrong_delta_and_block_index(self):
+ for index in (-1, 2, False):
+ events = self.anthropic_events()
+ events[1]["index"] = index
+ with self.subTest(index=index), self.assertRaises(WarmRefusal):
+ envelope(sse(events), "anthropic_messages")
+ events = self.anthropic_events()
+ events[2]["delta"] = {"type": "thinking_delta", "thinking": "wrong block"}
+ with self.assertRaises(WarmRefusal):
+ envelope(sse(events), "anthropic_messages")
+
+
+class NativeCaptureTest(unittest.TestCase):
+ def test_headers_stay_out_of_json(self):
+ headers = {"session_id": "synthetic-session", "x-client-request-id": "synthetic-cache"}
+ request = {"model": "fake", "input": [], "extra_headers": headers}
+ self.assertEqual(request_headers(request, "codex_responses"), headers)
+ self.assertNotIn("extra_headers", final_body(request, "codex_responses"))
+ for bad in ({"Authorization": "fake"}, {"session_id": "ok", "Session_ID": "other"},
+ {"session_id": "bad\r\nheader"}):
+ with self.subTest(headers=bad), self.assertRaises(UnsupportedRequest):
+ request_headers({"extra_headers": bad}, "codex_responses")
+
+ def test_native_sidecar_changes_history_stamp(self):
+ row = {"role": "assistant", "content": "synthetic"}
+ for field in ("phase", "codex_message_items", "codex_reasoning_items", "reasoning_details",
+ "anthropic_content_blocks"):
+ changed = copy.deepcopy(row)
+ changed[field] = "synthetic-new-value"
+ with self.subTest(field=field):
+ self.assertNotEqual(row_digest(row), row_digest(changed))
+
+
+class NativeSendTest(unittest.TestCase):
+ def test_responses_dispatch_keeps_query_and_reads_terminal(self):
+ calls = []
+ payload = {"status": "completed", "output": [{"type": "message", "role": "assistant",
+ "status": "completed", "content": [{"type": "output_text", "text": "synthetic summary"}]}]}
+ def post(url, data, headers, timeout_s):
+ calls.append((url, json.loads(data), headers))
+ return 200, sse([{"type": "response.completed", "response": payload}])
+ result = send({"input": [], "stream": True}, "http://127.0.0.1:9/v1?api-version=fake", "fake",
+ post=post, api_mode="codex_responses")
+ self.assertEqual(calls[0][0], "http://127.0.0.1:9/v1/responses?api-version=fake")
+ self.assertEqual(calls[0][2]["Accept"], "text/event-stream")
+ self.assertEqual(result["content"], "synthetic summary")
+ self.assertIsNone(result["cached_tokens"])
+
+ def test_messages_dispatch_uses_native_auth_and_endpoint(self):
+ calls = []
+ payload = {"type": "message", "role": "assistant", "stop_reason": "end_turn",
+ "content": [{"type": "text", "text": "synthetic summary"}]}
+ def post(url, data, headers, timeout_s):
+ calls.append((url, headers))
+ return 200, json.dumps(payload).encode()
+ for path in ("/v1", ""):
+ result = send({"messages": []}, "http://127.0.0.1:9" + path, "fake", post=post,
+ api_mode="anthropic_messages")
+ self.assertEqual(calls[-1][0], "http://127.0.0.1:9/v1/messages")
+ self.assertEqual(calls[-1][1]["x-api-key"], "fake")
+ self.assertNotIn("Authorization", calls[-1][1])
+ self.assertEqual(result["finish_reason"], "stop")
+
+ def test_capacity_counts_native_instructions(self):
+ self.assertFalse(fits({"input": [], "instructions": "x" * 40000, "max_output_tokens": 2048},
+ 10000, api_mode="codex_responses"))
+ self.assertFalse(fits({"messages": [], "system": "x" * 40000, "max_tokens": 2048},
+ 10000, api_mode="anthropic_messages"))
+
+
+class NativeTailTest(unittest.TestCase):
+ def test_transformed_native_settings_cannot_supply_a_budget_capture(self):
+ from test_wc_engine import EngineTest
+ from warm_compaction.responses import wire_rows
+ fixture = EngineTest("test_threshold_comes_from_the_setting")
+ fixture.setUp()
+ self.addCleanup(fixture.doCleanups)
+ engine = fixture.engine
+ engine.update_model(model="fake", context_length=16384, base_url="http://127.0.0.1:9/v1",
+ api_key="fake", provider="custom", api_mode="codex_responses")
+ rows = [{"role": "user", "content": "synthetic"}]
+ capture = {"route": engine._wc_route, "digests": [row_digest(rows[0])], "body": {
+ "model": "fake", "instructions": "synthetic system", "store": False, "input": wire_rows(rows)},
+ "reply": {"content": "synthetic reply", "tool_calls": []}}
+ rows.append({"role": "assistant", "content": "synthetic reply"})
+ self.assertIs(engine._budget_capture(capture, rows), capture)
+ for field, value in (("instructions", ""), ("instructions", " synthetic system "), ("store", None)):
+ bad = copy.deepcopy(capture)
+ if field == "store":
+ bad["body"].pop(field)
+ else:
+ bad["body"][field] = value
+ with self.subTest(field=field, value=value):
+ self.assertIsNone(engine._budget_capture(bad, rows))
+
+ def test_native_replay_counts_and_cannot_be_cut(self):
+ from warm_compaction.layout import bound_tail
+ for mode, field in (("codex_responses", "codex_reasoning_items"),
+ ("anthropic_messages", "anthropic_content_blocks")):
+ row = {"role": "assistant", "content": "synthetic", field: [{"data": "x" * 50000}]}
+ policy = SendPolicy(echo=False, cut_reasoning=False, native_mode=mode)
+ with self.subTest(mode=mode):
+ self.assertGreater(sent_tokens(row, policy), 10000)
+ self.assertEqual(bound_tail([row], 100, policy=policy), [row])
+
+ def test_an_indivisible_native_tail_over_capacity_keeps_history(self):
+ from test_wc_engine import EngineTest, old_turns
+ fixture = EngineTest("test_threshold_comes_from_the_setting")
+ fixture.setUp()
+ self.addCleanup(fixture.doCleanups)
+ engine = fixture.engine
+ engine.update_model(model="fake", context_length=16384, base_url="http://127.0.0.1:9/v1",
+ api_key="fake", provider="custom", api_mode="codex_responses")
+ rows = [*old_turns(3), {"role": "user", "content": "synthetic last request"},
+ {"role": "assistant", "content": "synthetic", "codex_reasoning_items": [{"data": "x" * 100000}]}]
+ result = engine.compress(rows)
+ self.assertIs(result, rows)
+ self.assertEqual(engine.compression_count, 0)
+ self.assertEqual(engine.warm_last["reason"], "capacity")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_wc_responses.py b/tests/test_wc_responses.py
new file mode 100644
index 0000000..760db70
--- /dev/null
+++ b/tests/test_wc_responses.py
@@ -0,0 +1,301 @@
+"""Synthetic Responses request and reply checks. No provider request runs here."""
+
+import copy
+import unittest
+
+from warm_compaction import responses
+from warm_compaction.rows import row_digest
+from warm_compaction.warm import WarmRefusal
+from wc_fixtures import assistant, tool, user
+
+ROUTE = ("fake-model", "http://127.0.0.1:9/v1", "codex_responses")
+CODEX = ("fake-model", "https://chatgpt.com/backend-api/codex", "codex_responses")
+INSTRUCTION = "Write a handoff. Use no tools."
+
+
+def capture(rows, reply, route=ROUTE, **controls):
+ """Return a synthetic capture with the supported wire form."""
+ return {"route": route, "digests": [row_digest(row) for row in rows],
+ "body": {"model": route[0], "instructions": "Synthetic system text.", "store": False,
+ "input": responses.wire_rows(rows, route[1], model=route[0]), **controls},
+ "reply": {"content": reply.get("content") or "", "tool_calls": [
+ [call["id"], call["function"]["name"]] for call in reply.get("tool_calls", [])]}}
+
+
+def response(status="completed", **extra):
+ """Return a synthetic terminal provider payload."""
+ return {"status": status, "output": [{"type": "message", "role": "assistant", "status": "completed",
+ "content": [{"type": "output_text", "text": "Synthetic summary."}]}],
+ **extra}
+
+
+class ResponsesSourceTest(unittest.TestCase):
+ def test_plain_text_and_compact_tool_arguments_match(self):
+ rows = [user(" question "), assistant(None, [("call_a", "read", '{"z": 1, "a": "é"}')]),
+ tool("call_a", " result ")]
+ wire = responses.wire_rows(rows)
+ self.assertEqual(wire[0], {"type": "message", "role": "user", "content": "question"})
+ self.assertEqual(wire[1], {"type": "function_call", "call_id": "call_a", "name": "read",
+ "arguments": '{"a":"\\u00e9","z":1}'})
+ self.assertEqual(wire[2]["output"], " result ")
+ responses.check_source({"model": ROUTE[0], "instructions": "Synthetic system text.",
+ "store": False, "input": wire}, rows)
+
+ def test_codex_text_is_typed(self):
+ wire = responses.wire_rows([user("u"), assistant("a", phase="final_answer")], CODEX[1])
+ self.assertEqual(wire[0]["content"], [{"type": "input_text", "text": "u"}])
+ self.assertEqual(wire[1]["content"], [{"type": "output_text", "text": "a"}])
+ self.assertEqual(wire[1]["phase"], "final_answer")
+
+ def test_native_text_replay_keeps_phase_status_and_id(self):
+ row = assistant("a", codex_message_items=[{
+ "type": "message", "role": "assistant", "id": "msg_fake", "status": "completed",
+ "phase": "final_answer", "content": [{"type": "output_text", "text": "a", "annotations": []}]}])
+ wire = responses.wire_rows([row], CODEX[1])
+ self.assertEqual(wire[0]["id"], "msg_fake")
+ self.assertEqual(wire[0]["status"], "completed")
+ self.assertEqual(wire[0]["phase"], "final_answer")
+ self.assertEqual(wire[0]["content"], [{"type": "output_text", "text": "a"}])
+ foreign = copy.deepcopy(row)
+ foreign["codex_message_items"][0]["id"] = "foreign_id"
+ self.assertNotIn("id", responses.wire_rows([foreign], CODEX[1])[0])
+
+ def test_composite_tool_ids_use_call_id(self):
+ rows = [assistant(None, [("call_a|fc_a", "read", "{}")]), tool("call_a|fc_a", "done")]
+ wire = responses.wire_rows(rows)
+ self.assertEqual([item["call_id"] for item in wire], ["call_a", "call_a"])
+
+ def test_source_change_is_refused(self):
+ rows = [user("original")]
+ body = {"model": ROUTE[0], "instructions": "Synthetic system text.", "store": False,
+ "input": responses.wire_rows([user("changed")])}
+ with self.assertRaises(WarmRefusal) as caught:
+ responses.check_source(body, rows)
+ self.assertEqual(caught.exception.code, "source_transform_unsupported")
+
+ def test_source_check_refuses_settings_that_cannot_supply_budget_estimates(self):
+ rows, reply = [user("q")], assistant("a")
+ for field, value in (("instructions", ""), ("instructions", " Synthetic system text. "), ("store", None)):
+ body = capture(rows, reply)["body"]
+ if value is None:
+ body.pop(field)
+ else:
+ body[field] = value
+ with self.subTest(field=field, value=value), self.assertRaises(WarmRefusal):
+ responses.check_source(body, rows, ROUTE[1])
+
+ def test_main_preparation_whitespace_is_required_and_prefix_is_kept(self):
+ rows, reply = [user("question ")], assistant("answer")
+ saved = capture(rows, reply)
+ responses.check_source(saved["body"], rows)
+ built = responses.build_request(saved, [*rows, reply], ROUTE, 100_000, INSTRUCTION)
+ self.assertEqual(built["input"][0], saved["body"]["input"][0])
+ saved["body"]["input"][0]["content"] = "question "
+ with self.assertRaises(WarmRefusal):
+ responses.check_source(saved["body"], rows)
+
+ def test_unsafe_source_rows_are_refused(self):
+ replay = {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "old"}]}
+ cases = [
+ [user([{"type": "image_url", "image_url": {"url": "https://example.invalid/fake.png"}}])],
+ [assistant("a", codex_reasoning_items=[{"type": "compaction", "encrypted_content": "fake"}])],
+ [assistant("new", codex_message_items=[replay])],
+ [assistant(None, [("x" * 65, "read", "{}")]), tool("x" * 65, "done")],
+ [assistant(None, [("a", "read", "{}"), ("a", "read", "{}")]), tool("a", "done")],
+ [tool("unknown", "done")],
+ [assistant(None, [("a", "read", "{}")])],
+ ]
+ for rows in cases:
+ with self.subTest(rows=rows), self.assertRaises(WarmRefusal):
+ responses.wire_rows(rows)
+
+ def test_native_reasoning_and_message_replay_match_the_final_wire_shape(self):
+ row = assistant("final", codex_reasoning_items=[{
+ "type": "reasoning", "id": "rs_fake", "encrypted_content": "fake-sealed-bytes",
+ "summary": [{"type": "summary_text", "text": "Synthetic reasoning summary."}],
+ "_issuer_kind": "codex_backend", "_issuer_model": CODEX[0]}], codex_message_items=[{
+ "type": "message", "role": "assistant", "id": "msg_fake", "status": "completed",
+ "phase": "final_answer", "content": [{"type": "output_text", "text": "final"}]}])
+ wire = responses.wire_rows([row], CODEX[1], model=CODEX[0])
+ self.assertEqual(wire[0], {"type": "reasoning", "encrypted_content": "fake-sealed-bytes",
+ "summary": [{"type": "summary_text", "text": "Synthetic reasoning summary."}]})
+ self.assertNotIn("id", wire[1])
+ body = {"model": CODEX[0], "instructions": "Synthetic system text.", "store": False, "input": wire}
+ responses.check_source(body, [row], CODEX[1])
+ for changed_key, changed_value in (("encrypted_content", "changed-sealed-bytes"),
+ ("_issuer_kind", "xai_responses"), ("_issuer_model", "foreign-model")):
+ changed = copy.deepcopy(row)
+ changed["codex_reasoning_items"][0][changed_key] = changed_value
+ with self.subTest(changed_key=changed_key), self.assertRaises(WarmRefusal):
+ responses.check_source(body, [changed], CODEX[1])
+ changed = copy.deepcopy(row)
+ changed["codex_message_items"][0]["phase"] = "commentary"
+ with self.assertRaises(WarmRefusal):
+ responses.check_source(body, [changed], CODEX[1])
+
+ def test_reasoning_then_commentary_then_final_keeps_the_item_order(self):
+ row = assistant("final", codex_reasoning_items=[{"type": "reasoning", "encrypted_content": "fake"}],
+ codex_message_items=[{
+ "type": "message", "role": "assistant", "status": "completed", "phase": phase,
+ "content": [{"type": "output_text", "text": text}]}
+ for phase, text in (("commentary", "working"), ("final_answer", "final"))])
+ wire = responses.wire_rows([row], CODEX[1])
+ self.assertEqual([item["type"] for item in wire], ["reasoning", "message", "message"])
+ self.assertEqual([item["phase"] for item in wire[1:]], ["commentary", "final_answer"])
+
+ def test_reasoning_tool_pair_and_new_reply_keep_native_bytes(self):
+ rows = [user("q")]
+ reply = assistant(None, [("call_fake", "read", "{}")], codex_reasoning_items=[{
+ "type": "reasoning", "id": "rs_fake", "encrypted_content": "fake-sealed-bytes",
+ "_issuer_kind": "codex_backend", "_issuer_model": CODEX[0]}])
+ saved = capture(rows, reply, CODEX)
+ built = responses.build_request(saved, [*rows, reply, tool("call_fake", "done")],
+ CODEX, 100_000, INSTRUCTION)
+ self.assertEqual([item["type"] for item in built["input"]],
+ ["message", "reasoning", "function_call", "function_call_output", "message"])
+ self.assertEqual(built["input"][1]["encrypted_content"], "fake-sealed-bytes")
+
+ def test_new_codex_text_that_the_host_would_change_is_refused(self):
+ for text in ("<|start|>", "<\u200b|start|>"):
+ with self.subTest(text=text), self.assertRaises(WarmRefusal):
+ responses.wire_rows([user(text)], CODEX[1])
+
+ def test_reasoning_ids_cannot_repeat_across_the_capture_boundary(self):
+ native = {"type": "reasoning", "id": "rs_fake", "encrypted_content": "fake-sealed-bytes"}
+ rows = [user("q"), assistant("old", codex_reasoning_items=[native]), user("q2")]
+ reply = assistant("new", codex_reasoning_items=[copy.deepcopy(native)])
+ saved = capture(rows, reply, CODEX)
+ with self.assertRaises(WarmRefusal):
+ responses.build_request(saved, [*rows, reply], CODEX, 100_000, INSTRUCTION)
+
+
+class ResponsesBuildTest(unittest.TestCase):
+ def test_request_preserves_prefix_and_non_generation_controls(self):
+ rows, reply = [user("question")], assistant("answer")
+ controls = {"prompt_cache_key": "fake-cache", "prompt_cache_retention": "24h", "reasoning": {"effort": "low"},
+ "include": ["reasoning.encrypted_content"], "tool_choice": "auto", "parallel_tool_calls": True,
+ "tools": [{"type": "function", "name": "read", "description": "Read a fake file.",
+ "parameters": {"type": "object"}, "strict": False}],
+ "text": {"verbosity": "low"}, "max_output_tokens": 100}
+ saved = capture(rows, reply, **controls)
+ original = copy.deepcopy(saved)
+ built = responses.build_request(saved, [*rows, reply, user("follow up")], ROUTE, 100_000, INSTRUCTION)
+ self.assertEqual(saved, original)
+ self.assertEqual(built["input"][:len(saved["body"]["input"])], saved["body"]["input"])
+ for key, value in controls.items():
+ if key != "max_output_tokens":
+ self.assertEqual(built[key], value)
+ self.assertEqual(built["max_output_tokens"], 2048)
+ self.assertTrue(built["stream"])
+ self.assertEqual(built["input"][-1]["content"][0]["text"], INSTRUCTION)
+
+ def test_codex_has_no_added_output_limit(self):
+ rows, reply = [user("question")], assistant("answer")
+ built = responses.build_request(capture(rows, reply, CODEX), [*rows, reply], CODEX, 100_000, INSTRUCTION)
+ self.assertNotIn("max_output_tokens", built)
+ self.assertTrue(built["stream"])
+ self.assertEqual(responses.reply_reserve(built, 100_000), 25_000)
+
+ def test_new_tool_pair_is_added_without_changing_prefix(self):
+ rows = [user("question")]
+ reply = assistant(None, [("call_a|fc_a", "read", "{}")])
+ saved = capture(rows, reply)
+ built = responses.build_request(saved, [*rows, reply, tool("call_a|fc_a", "result")],
+ ROUTE, 100_000, INSTRUCTION)
+ self.assertEqual([item["type"] for item in built["input"]],
+ ["message", "function_call", "function_call_output", "message"])
+
+ def test_forced_output_and_stateful_controls_are_refused(self):
+ rows, reply = [user("q")], assistant("a")
+ cases = [{"tool_choice": "required"}, {"text": {"format": {"type": "json_schema"}}},
+ {"previous_response_id": "fake"}, {"conversation": "fake"},
+ {"context_management": [{"type": "compaction"}]}, {"store": True},
+ {"tools": [{"type": "web_search"}]}]
+ for options in cases:
+ with self.subTest(options=options), self.assertRaises(WarmRefusal):
+ responses.build_request(capture(rows, reply, **options), [*rows, reply], ROUTE, 100_000, INSTRUCTION)
+
+ def test_consumer_wire_transform_is_refused(self):
+ rows, reply = [user("q")], assistant("a")
+ with self.assertRaises(WarmRefusal) as caught:
+ responses.build_request(capture(rows, reply, CODEX, prompt_cache_retention="24h"),
+ [*rows, reply], CODEX, 100_000, INSTRUCTION)
+ self.assertEqual(caught.exception.code, "source_transform_unsupported")
+
+ def test_late_scalar_transforms_are_refused(self):
+ rows, reply = [user("q")], assistant("a")
+ cases = [{"instructions": " Synthetic system text. "}, {"model": " fake-model "},
+ {"prompt_cache_key": "x" * 65}, {"prompt_cache_key": " cache "},
+ {"reasoning": "low"}, {"include": "reasoning.encrypted_content"},
+ {"temperature": True}, {"service_tier": " auto "},
+ {"parallel_tool_calls": None}, {"prompt_cache_retention": None}, {"text": None},
+ {"tools": [{"type": "function", "name": " read ", "parameters": {},
+ "description": "synthetic", "strict": False}]}]
+ for options in cases:
+ with self.subTest(options=options), self.assertRaises(WarmRefusal):
+ responses.build_request(capture(rows, reply, **options), [*rows, reply], ROUTE, 100_000, INSTRUCTION)
+
+ def test_missing_store_false_cannot_enable_provider_default_storage(self):
+ rows, reply = [user("q")], assistant("a")
+ saved = capture(rows, reply)
+ saved["body"].pop("store")
+ with self.assertRaises(WarmRefusal):
+ responses.build_request(saved, [*rows, reply], ROUTE, 100_000, INSTRUCTION)
+
+ def test_new_opaque_reply_needs_issuer_and_model_stamps(self):
+ rows = [user("q")]
+ reply = assistant("a", codex_reasoning_items=[{"type": "reasoning", "encrypted_content": "fake"}])
+ saved = capture(rows, reply, CODEX)
+ with self.assertRaises(WarmRefusal):
+ responses.build_request(saved, [*rows, reply], CODEX, 100_000, INSTRUCTION)
+
+ def test_capacity_counts_the_consumer_unknown_output_reserve(self):
+ rows, reply = [user("q")], assistant("a")
+ saved = capture(rows, reply, CODEX)
+ saved["prompt_tokens"] = 98_000
+ with self.assertRaises(WarmRefusal) as caught:
+ responses.build_request(saved, [*rows, reply], CODEX, 100_000, INSTRUCTION)
+ self.assertEqual(caught.exception.code, "capacity")
+
+
+class ResponsesReplyTest(unittest.TestCase):
+ def test_completed_reply_reads_usage_and_cache_counter(self):
+ parsed = responses.parse_reply(response(usage={"input_tokens": 200, "output_tokens": 30,
+ "input_tokens_details": {"cached_tokens": 150}}))
+ self.assertEqual(parsed, {"content": "Synthetic summary.", "finish_reason": "stop", "tool_calls": False,
+ "refusal": False, "prompt_tokens": 200, "completion_tokens": 30,
+ "cached_tokens": 150})
+
+ def test_missing_counters_are_unknown(self):
+ parsed = responses.parse_reply(response(usage={"input_tokens": True, "output_tokens": -1}))
+ self.assertIsNone(parsed["prompt_tokens"])
+ self.assertIsNone(parsed["completion_tokens"])
+ self.assertIsNone(parsed["cached_tokens"])
+
+ def test_non_completed_status_fails_the_summary_gate(self):
+ for status in ("incomplete", "failed", "cancelled", None, "in_progress"):
+ with self.subTest(status=status):
+ self.assertEqual(responses.parse_reply(response(status))["finish_reason"], "length")
+
+ def test_tool_and_refusal_outputs_are_flagged(self):
+ for item, flag in (({"type": "function_call", "name": "read"}, "tool_calls"),
+ ({"type": "web_search_call"}, "tool_calls"),
+ ({"type": "message", "role": "assistant", "content": [
+ {"type": "refusal", "refusal": "fake"}]}, "refusal")):
+ with self.subTest(item=item):
+ self.assertTrue(responses.parse_reply(response(output=[item]))[flag])
+
+ def test_commentary_and_reasoning_are_not_final_summary_text(self):
+ payload = response()
+ payload["output"].insert(0, {"type": "reasoning", "summary": []})
+ payload["output"].insert(1, {"type": "message", "role": "assistant", "phase": "commentary",
+ "content": [{"type": "output_text", "text": "Working."}]})
+ self.assertEqual(responses.parse_reply(payload)["content"], "Synthetic summary.")
+
+ def test_bad_terminal_payload_is_refused(self):
+ cases = [{}, response(output=None), response(usage=[]), response(output=[{
+ "type": "message", "role": "assistant", "status": "incomplete", "content": []}]),
+ response(output=[{"type": "message", "role": "assistant", "content": [{"type": "audio"}]}])]
+ for payload in cases:
+ with self.subTest(payload=payload), self.assertRaises(WarmRefusal):
+ responses.parse_reply(payload)
diff --git a/tests/test_wc_warm.py b/tests/test_wc_warm.py
index 8c7ea5e..3006d28 100644
--- a/tests/test_wc_warm.py
+++ b/tests/test_wc_warm.py
@@ -271,7 +271,7 @@ class BuildRequestTest(unittest.TestCase):
def test_refusal_codes(self):
good = capture_for(self.rows, self.reply)
cases = [
- ("api_mode_unsupported", good, (ROUTE[0], ROUTE[1], "codex_responses")),
+ ("api_mode_unsupported", good, (ROUTE[0], ROUTE[1], "bedrock_converse")),
("route_changed", good, ("other-model", ROUTE[1], ROUTE[2])),
("settings_unsupported", dict(good, body=None), ROUTE),
("settings_unsupported", capture_for(self.rows, self.reply, body_extra={"n": 3}), ROUTE),
diff --git a/warm_compaction/anthropic.py b/warm_compaction/anthropic.py
new file mode 100644
index 0000000..8abf0ba
--- /dev/null
+++ b/warm_compaction/anthropic.py
@@ -0,0 +1,300 @@
+"""Build a bounded warm request for the Anthropic Messages API."""
+
+from __future__ import annotations
+
+import copy
+import json
+from typing import Any
+from urllib.parse import urlsplit
+
+from .rows import api_content, attr, tool_calls_of
+from .warm import HANDOFF_MAX_TOKENS, HANDOFF_MIN_TOKENS, WarmRefusal, fits, split_history
+
+COMMON_BETAS = "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"
+OPAQUE_ROWS = ("reasoning_details", "reasoning_content", "anthropic_content_blocks", "_anthropic_content_blocks")
+SETTINGS = {"model", "messages", "system", "tools", "tool_choice", "max_tokens", "stream", "stop_sequences",
+ "thinking", "output_config", "temperature", "top_p", "top_k", "metadata", "service_tier",
+ "cache_control"}
+
+
+def _refuse() -> None:
+ raise WarmRefusal("source_transform_unsupported")
+
+
+def _text(content: Any, *, empty: str = "") -> list[dict]:
+ if content is None:
+ content = ""
+ if isinstance(content, str):
+ return [{"type": "text", "text": content or empty}] if content or empty else []
+ if isinstance(content, list) and all(isinstance(p, dict) and p.get("type") == "text"
+ and isinstance(p.get("text"), str)
+ and set(p) <= {"type", "text", "cache_control"} for p in content):
+ return [{"type": "text", "text": p["text"]} for p in content]
+ _refuse()
+
+
+def _id(value: Any) -> str:
+ if not isinstance(value, str) or not value or any(not (c.isascii() and (c.isalnum() or c in "_-")) for c in value):
+ _refuse()
+ return value
+
+
+def _thinking(blocks: Any) -> list[dict]:
+ if blocks is None:
+ return []
+ if not isinstance(blocks, list):
+ _refuse()
+ result = []
+ for block in blocks:
+ if not isinstance(block, dict):
+ _refuse()
+ fields = {"thinking": {"type", "thinking", "signature"}, "redacted_thinking": {"type", "data"}}
+ kind = block.get("type")
+ if kind not in fields or set(block) != fields[kind] or any(type(v) is not str for v in block.values()):
+ _refuse()
+ if not block.get("signature" if kind == "thinking" else "data"):
+ _refuse()
+ result.append(copy.deepcopy(block))
+ return result
+
+
+def _assistant_blocks(row: Any, text: list[dict], calls: list[dict], base_url: Any) -> list[dict]:
+ if attr(row, "_anthropic_content_blocks"):
+ _refuse()
+ details = _thinking(attr(row, "reasoning_details"))
+ mirror = attr(row, "reasoning_content")
+ if mirror and (not details or mirror != "\n\n".join(b["thinking"] for b in details if b["type"] == "thinking")):
+ _refuse()
+ ordered = attr(row, "anthropic_content_blocks")
+ if ordered:
+ if not isinstance(ordered, list):
+ _refuse()
+ clean = []
+ for block in ordered:
+ if not isinstance(block, dict):
+ _refuse()
+ kind = block.get("type")
+ if kind in ("thinking", "redacted_thinking"):
+ clean.extend(_thinking([block]))
+ elif kind == "text":
+ clean.extend(_text([block]))
+ elif kind == "tool_use" and set(block) == {"type", "id", "name", "input"}:
+ clean.append(copy.deepcopy(block))
+ else:
+ _refuse()
+ if ([b for b in clean if b["type"] == "tool_use"] != calls
+ or "\n".join(b["text"] for b in clean if b["type"] == "text") != "\n".join(b["text"] for b in text)
+ or [b for b in clean if b["type"] in ("thinking", "redacted_thinking")] != details):
+ _refuse()
+ else:
+ clean = [*details, *text, *calls]
+ host = (urlsplit(str(base_url or "https://api.anthropic.com")).hostname or "").lower()
+ if details and host != "api.anthropic.com":
+ # Generic gateways can strip or reject native signatures. That renderer is not reproduced here.
+ _refuse()
+ return clean
+
+
+def _rows(rows: list, *, new: bool = False, base_url: Any = None) -> list[dict]:
+ result: list[dict] = []
+ pending: set[str] = set()
+ seen: set[str] = set()
+ for row in rows:
+ role = attr(row, "role")
+ if role in ("system", "developer"):
+ if new:
+ _refuse()
+ continue
+ if role != "assistant" and any(attr(row, key) for key in OPAQUE_ROWS):
+ _refuse()
+ if role == "tool":
+ call_id = _id(attr(row, "tool_call_id"))
+ if call_id not in pending or not isinstance(attr(row, "content"), str):
+ _refuse()
+ pending.remove(call_id)
+ content = [{"type": "tool_result", "tool_use_id": call_id,
+ "content": attr(row, "content") or "(no output)"}]
+ role = "user"
+ elif role in ("user", "assistant"):
+ if pending:
+ _refuse()
+ content = _text(api_content(row), empty="(empty message)" if role == "user" else "")
+ calls = []
+ for call_id, name, arguments in tool_calls_of(row):
+ if role != "assistant" or not isinstance(name, str) or not name:
+ _refuse()
+ call_id = _id(call_id)
+ if call_id in seen:
+ _refuse()
+ try:
+ args = json.loads(arguments) if isinstance(arguments, str) else arguments
+ except (TypeError, ValueError):
+ _refuse()
+ if not isinstance(args, dict):
+ _refuse()
+ calls.append({"type": "tool_use", "id": call_id, "name": name, "input": args})
+ pending.add(call_id)
+ seen.add(call_id)
+ if role == "assistant":
+ content = _assistant_blocks(row, content, calls, base_url)
+ content = content or [{"type": "text", "text": "(empty message)"}]
+ else:
+ _refuse()
+ if result and result[-1]["role"] == role:
+ if role == "assistant" and any(b["type"] in ("thinking", "redacted_thinking") for b in content):
+ _refuse()
+ result[-1]["content"].extend(content)
+ else:
+ result.append({"role": role, "content": content})
+ if pending:
+ _refuse()
+ return result
+
+
+def _native_rows(rows: Any) -> list[dict]:
+ if not isinstance(rows, list):
+ _refuse()
+ normalized = []
+ for row in rows:
+ if not isinstance(row, dict) or set(row) != {"role", "content"} or row["role"] not in ("user", "assistant"):
+ _refuse()
+ blocks = _text(row["content"]) if isinstance(row["content"], str) else row["content"]
+ if not isinstance(blocks, list):
+ _refuse()
+ clean = []
+ for block in blocks:
+ if not isinstance(block, dict):
+ _refuse()
+ part = {k: v for k, v in block.items() if k != "cache_control"}
+ kind = part.get("type")
+ if kind in ("thinking", "redacted_thinking") and row["role"] == "assistant":
+ clean.extend(_thinking([part]))
+ continue
+ fields = {"text": {"type", "text"}, "tool_use": {"type", "id", "name", "input"},
+ "tool_result": {"type", "tool_use_id", "content"}}
+ if kind not in fields or set(part) != fields[kind]:
+ _refuse()
+ clean.append(part)
+ normalized.append({"role": row["role"], "content": clean})
+ return normalized
+
+
+def check_source(body: dict[str, Any], history: list, base_url: Any = None, native_type: str | None = None) -> None:
+ """Check that the text and tool data in the captured prefix describe the stored history."""
+ del native_type
+ expected = _rows(history, base_url=base_url)
+ actual = _native_rows(body.get("messages"))
+ if actual != expected:
+ _refuse()
+
+
+def build_request(capture: dict[str, Any], messages: list, route: tuple, context_length: int,
+ instruction: str, native_type: str | None = None) -> dict[str, Any]:
+ """Keep the native prefix and append a text and tool handoff turn."""
+ del native_type
+ if route[2] != "anthropic_messages":
+ raise WarmRefusal("api_mode_unsupported")
+ if tuple(capture["route"]) != tuple(route):
+ raise WarmRefusal("route_changed")
+ body = capture.get("body")
+ if body is None:
+ raise WarmRefusal(capture.get("refusal") or "settings_unsupported")
+ if set(body) - SETTINGS or not isinstance(body.get("messages"), list):
+ raise WarmRefusal("settings_unsupported")
+ if isinstance(body.get("output_config"), dict) and set(body["output_config"]) - {"effort"}:
+ raise WarmRefusal("settings_unsupported")
+ choice = body.get("tool_choice")
+ if choice is not None and choice not in ({"type": "auto"}, {"type": "none"}):
+ raise WarmRefusal("settings_unsupported")
+ if any(not isinstance(t, dict) or "input_schema" not in t or t.get("type") for t in body.get("tools", [])):
+ raise WarmRefusal("settings_unsupported")
+ new_rows, trailing = split_history(capture, messages)
+ check_source(body, messages[:len(capture["digests"])], route[1])
+ added = _rows([*new_rows, *trailing], new=True, base_url=route[1])
+ block = {"type": "text", "text": instruction}
+ if added and added[-1]["role"] == "user":
+ added[-1]["content"].append(block)
+ else:
+ added.append({"role": "user", "content": [block]})
+ if body["messages"] and added and body["messages"][-1]["role"] == added[0]["role"]:
+ # Merging into the old turn would change its cache boundary or a thinking signature.
+ _refuse()
+ request = copy.deepcopy(body)
+ request["messages"].extend(added)
+ request["stream"] = False
+ request.pop("stop_sequences", None)
+ limit = body.get("max_tokens")
+ limit = limit if type(limit) is int and limit > 0 else HANDOFF_MAX_TOKENS
+ request["max_tokens"] = min(max(limit, HANDOFF_MIN_TOKENS), HANDOFF_MAX_TOKENS)
+ thinking = request.get("thinking")
+ if isinstance(thinking, dict) and thinking.get("type") == "enabled":
+ budget = thinking.get("budget_tokens")
+ if type(budget) is not int or budget <= 0:
+ raise WarmRefusal("settings_unsupported")
+ request["max_tokens"] = max(request["max_tokens"], budget + HANDOFF_MIN_TOKENS)
+ if not fits(request, context_length, capture.get("prompt_tokens"), len(body["messages"]),
+ api_mode="anthropic_messages"):
+ raise WarmRefusal("capacity")
+ return request
+
+
+def route_headers(key: str, base_url: Any, existing_headers: dict, provider: str = "") -> dict[str, str]:
+ """Use API-key auth for native Anthropic and ordinary Messages gateways. Refuse other auth routes."""
+ url = urlsplit(str(base_url or "https://api.anthropic.com"))
+ host = (url.hostname or "").lower()
+ oauth = key and not key.startswith("sk-ant-api") and key.startswith(("sk-ant-", "eyJ", "cc-"))
+ if oauth or provider in {"bedrock", "nous"}:
+ raise WarmRefusal("auth_unsupported")
+ if any(part in host for part in ("minimax", "moonshot", "kimi", "azure", "anthropic.aws")):
+ raise WarmRefusal("auth_unsupported")
+ if any(host == name or host.endswith("." + name) for name in (
+ "api.commandcode.ai", "palantirfoundry.com", "inference-api.nousresearch.com")):
+ raise WarmRefusal("auth_unsupported")
+ for name, value in existing_headers.items():
+ if name.lower() == "authorization":
+ raise WarmRefusal("auth_unsupported")
+ if name.lower() == "x-api-key" and value != key:
+ raise WarmRefusal("auth_unsupported")
+ headers = {k: v for k, v in existing_headers.items() if k.lower() not in ("authorization", "x-api-key")}
+ if not any(k.lower() == "anthropic-version" for k in headers):
+ headers["anthropic-version"] = "2023-06-01"
+ if not any(k.lower() == "anthropic-beta" for k in headers):
+ headers["anthropic-beta"] = COMMON_BETAS
+ if key:
+ headers["x-api-key"] = key
+ return headers
+
+
+def parse_reply(payload: dict) -> dict[str, Any]:
+ """Read the completed native message and its optional token counters."""
+ try:
+ if payload.get("type") != "message" or payload.get("role") != "assistant":
+ raise ValueError
+ blocks = payload["content"]
+ if not isinstance(blocks, list) or any(not isinstance(b, dict) for b in blocks):
+ raise ValueError
+ text = []
+ for block in blocks:
+ if block.get("type") == "text":
+ if not isinstance(block.get("text"), str):
+ raise ValueError
+ text.append(block["text"])
+ reason = payload.get("stop_reason")
+ finish = {"end_turn": "stop", "stop_sequence": "stop", "max_tokens": "length",
+ "model_context_window_exceeded": "length", "tool_use": "tool_calls",
+ "refusal": "content_filter"}.get(reason)
+ usage = payload.get("usage")
+ usage = {} if usage is None else usage
+ if not isinstance(usage, dict):
+ raise ValueError
+ counters = [usage.get(k) for k in ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens")]
+ def count(value):
+ return value if type(value) is int and value >= 0 else None
+ prompt = sum(counters) if all(count(v) is not None for v in counters) else None
+ return {"content": "\n".join(text), "finish_reason": finish,
+ "tool_calls": any(b.get("type") not in ("text", "thinking", "redacted_thinking") for b in blocks),
+ "refusal": reason == "refusal", "prompt_tokens": prompt,
+ "completion_tokens": count(usage.get("output_tokens")),
+ "cached_tokens": count(usage.get("cache_read_input_tokens"))}
+ except (TypeError, ValueError, KeyError, AttributeError) as error:
+ raise WarmRefusal("incomplete_response") from error
diff --git a/warm_compaction/capture.py b/warm_compaction/capture.py
index 3486b17..d54700b 100644
--- a/warm_compaction/capture.py
+++ b/warm_compaction/capture.py
@@ -35,8 +35,8 @@ class UnsupportedRequest(ValueError):
"""The request body cannot become a warm request. The message is the reason code."""
-def request_headers(request: Any) -> dict[str, str]:
- """Copy only the known session header. Refuse other headers and unsafe HTTP values.
+def request_headers(request: Any, api_mode: str = "chat_completions") -> dict[str, str]:
+ """Copy known session and API headers. Refuse other headers and unsafe HTTP values.
Hermes 1d6b2786 adds x-opencode-session for OpenCode routes. Keep the captured value: a new session id
need not select the same server. Header values stay in memory and never go to status or logs.
@@ -46,20 +46,27 @@ def request_headers(request: Any) -> dict[str, str]:
headers = request.get("extra_headers")
if headers is None:
return {}
- if not isinstance(headers, dict) or len(headers) > 1:
+ allowed = {"x-opencode-session"}
+ if api_mode == "codex_responses":
+ allowed.update(("session_id", "x-client-request-id", "x-grok-conv-id", "x-initiator"))
+ elif api_mode == "anthropic_messages":
+ allowed.update(("anthropic-beta", "anthropic-version", "x-initiator"))
+ if not isinstance(headers, dict) or len(headers) > len(allowed):
raise UnsupportedRequest("request_options_unsupported")
+ seen: set[str] = set()
for name, value in headers.items():
- if (type(name) is not str or name.lower() != "x-opencode-session" or type(value) is not str
+ if (type(name) is not str or name.lower() not in allowed or name.lower() in seen or type(value) is not str
or not value or value != value.strip() or any(ord(char) < 32 or ord(char) > 126 for char in value)):
raise UnsupportedRequest("request_options_unsupported")
+ seen.add(name.lower())
return dict(headers)
-def final_body(request: Any) -> dict[str, Any]:
- """Return the JSON body that the OpenAI client sends: a copy with extra_body merged in."""
+def final_body(request: Any, api_mode: str = "chat_completions") -> dict[str, Any]:
+ """Return a JSON body with extra_body merged in and SDK options removed."""
if not isinstance(request, dict):
raise UnsupportedRequest("request_not_mapping")
- headers = request_headers(request)
+ headers = request_headers(request, api_mode)
if request.get("extra_query"):
raise UnsupportedRequest("request_options_unsupported")
extra = request.get("extra_body") or {}
@@ -154,13 +161,13 @@ class CaptureStore:
def _keep_body(self, api_request_id: Any, request: Any) -> None:
with self._lock:
entry = self._open.get(str(api_request_id or ""))
- if entry is None or entry["route"][2] != "chat_completions":
+ if entry is None or entry["route"][2] not in ("chat_completions", "codex_responses", "anthropic_messages"):
return
refusal = None
headers: dict[str, str] = {}
try:
- body = final_body(request)
- headers = request_headers(request)
+ body = final_body(request, entry["route"][2])
+ headers = request_headers(request, entry["route"][2])
except UnsupportedRequest as error:
body = None
# Keep only fixed codes. Exception data must not reach the status or logs.
diff --git a/warm_compaction/engine.py b/warm_compaction/engine.py
index 8d53372..a398763 100644
--- a/warm_compaction/engine.py
+++ b/warm_compaction/engine.py
@@ -11,7 +11,7 @@ from collections.abc import Callable
from agent.context_engine import ContextEngine
-from . import fallback, handoff, layout, native, warm
+from . import fallback, handoff, layout, native, protocol, warm
from .capture import CaptureStore, key_stamp
from .rows import SendPolicy, api_content, attr, estimate_tokens, hermes_value, sent_rows, sent_tokens
@@ -42,7 +42,8 @@ FAILURE_HINTS = {
"no_capture": "no main-model request completed in this Hermes process before the compaction",
"provider_error": "the server refused the warm request (a provider error, or a gateway that needs a cookie)",
"timeout": "the warm request took longer than its time limit",
- "api_mode_unsupported": "this API mode has no warm path; only chat_completions has one",
+ "api_mode_unsupported": "this API format has no supported warm path",
+ "auth_unsupported": "the warm path cannot keep the authentication of this route",
"settings_unsupported": "the main request uses a setting that the warm request cannot keep",
"request_not_mapping": "the main request is not a mapping",
"request_options_unsupported": "the main request has unsupported extra headers, query options, or extra_body",
@@ -116,6 +117,15 @@ def request_overhead(capture: dict[str, Any] | None, messages: list | None = Non
count less the history estimate is not used: the two do not use the same tokenizer, and a compressible
history can have an estimate far above the server count, so the difference can be much too small."""
body = (capture or {}).get("body")
+ mode = ((capture or {}).get("route") or (None, None, "chat_completions"))[2]
+ if isinstance(body, dict) and mode != "chat_completions":
+ field = protocol.history_key(mode)
+ if not isinstance(body.get(field), list):
+ return None
+ # Native routes keep system text outside history. Count all other structured controls too.
+ controls = {key: value for key, value in body.items() if key != field
+ and isinstance(value, (str, dict, list))}
+ return estimate_tokens(controls)
if not isinstance(body, dict) or not isinstance(body.get("messages"), list):
return None
count = max(len(body["messages"]) - len(capture.get("digests") or ()), 0)
@@ -135,8 +145,10 @@ def request_reserve(capture: dict[str, Any] | None, context_length: int = 0) ->
captured limit, the reply limit of the next request is unknown (Hermes does not give it to a context engine):
a quarter of the window, at most UNKNOWN_RESERVE_MAX, and at least the default."""
body = (capture or {}).get("body")
- if isinstance(body, dict) and isinstance(body.get("messages"), list) and any(
- type(body.get(key)) is int and body[key] > 0 for key in warm.LIMIT_KEYS):
+ mode = ((capture or {}).get("route") or (None, None, "chat_completions"))[2]
+ if isinstance(body, dict) and isinstance(body.get(protocol.history_key(mode)), list) and any(
+ type(body.get(key)) is int and body[key] > 0
+ for key in (*warm.LIMIT_KEYS, "max_output_tokens")):
return warm.reply_reserve(body)
# Without a positive captured limit, the provider default applies to the next request: it is unknown too.
return max(warm.DEFAULT_RESERVE, min(context_length // 4, UNKNOWN_RESERVE_MAX))
@@ -426,12 +438,19 @@ class WarmCompactionEngine(ContextEngine):
end_marker=hermes_value("agent.context_compressor", "_SUMMARY_END_MARKER", HERMES_END_MARKER),
marker=hermes_value("agent.context_compressor", "_DB_PERSISTED_MARKER", HERMES_DB_MARKER),
copy_tokens=copy_tokens, tail_tokens=tail_tokens, policy=policy)
+ native_overflow = bool(policy.native_mode and int(self.context_length or 0) > 0 and (
+ estimate_tokens(sent_rows(new, policy)) + (overhead or 0) + reserve > int(self.context_length)))
# A stale worker must not change the counter or replace a newer candidate. No model call holds this lock.
with self._wc_result_lock:
if self._cancelled() or self._attempt() != attempt:
record.update(path="cancelled", reason="cancelled" if self._cancelled() else "route_changed")
self._finish(record, started, attempt[-1])
return messages
+ if native_overflow:
+ # An indivisible native replay block cannot be cut to make a valid signed request.
+ record.update(path="unchanged", reason="capacity")
+ self._finish(record, started, attempt[-1])
+ return messages
self.compression_count += 1
self._finish(record, started, attempt[-1])
# The host can still reject this candidate. Only its successful boundary updates the failure streak.
@@ -446,6 +465,9 @@ class WarmCompactionEngine(ContextEngine):
# Only a usable capture (_budget_capture: this route, and the stored rows) shows what the route sends.
capture = self._budget_capture(self._store.latest(self._wc_session_id), messages)
body = capture.get("body") if capture else None
+ mode = self._wc_route[2]
+ if mode in ("codex_responses", "anthropic_messages"):
+ return SendPolicy(details=True, signatures=False, echo=False, cut_reasoning=False, native_mode=mode)
sent = [row for row in (body.get("messages") or []) if isinstance(row, dict) and row.get("role") == "assistant"
] if isinstance(body, dict) else []
if sent:
@@ -496,7 +518,8 @@ class WarmCompactionEngine(ContextEngine):
warm.native_details_type(attempt[2]))
if self._cancelled():
raise warm.WarmRefusal("cancelled")
- reply = self._execute(body, instruction, len(capture["body"]["messages"]), attempt,
+ field = protocol.history_key(attempt[0][2])
+ reply = self._execute(body, instruction, len(capture["body"][field]), attempt,
capture.get("prompt_tokens"), key, capture.get("request_headers"))
record.update(prompt_tokens=reply["prompt_tokens"], cached_tokens=reply["cached_tokens"])
text, reason = handoff.gate(reply, prefixes)
@@ -527,7 +550,7 @@ class WarmCompactionEngine(ContextEngine):
route, api_key, provider, session_id = attempt[:4]
# The key that the capture check used (_warm_summary): a key function is not read again.
key = warm.api_key_text(api_key) if key is None else key
- headers = warm.route_headers(key, route[1], provider)
+ headers = warm.route_headers(key, route[1], provider, api_mode=route[2])
tls = warm.route_tls(route[1])
if request_headers:
# Per-request headers override client defaults without regard to case. Both middleware chains
@@ -536,6 +559,7 @@ class WarmCompactionEngine(ContextEngine):
headers = {name: value for name, value in headers.items() if name.lower() not in names}
headers.update(request_headers)
body = {**body, "extra_headers": dict(request_headers)}
+ headers = warm.native_headers(key, route[1], provider, route[2], headers)
context = {"purpose": NAME, "api_request_id": None, "session_id": session_id,
"model": route[0], "base_url": route[1], "api_mode": route[2]}
try:
@@ -544,19 +568,20 @@ class WarmCompactionEngine(ContextEngine):
changed = apply_llm_request_middleware(copy.deepcopy(body), **context).payload
except Exception as error:
raise warm.WarmRefusal("middleware_refused") from error
- if not isinstance(changed, dict) or not isinstance(changed.get("messages"), list):
+ field = protocol.history_key(route[2])
+ if not isinstance(changed, dict) or not isinstance(changed.get(field), list):
raise warm.WarmRefusal("middleware_refused")
# The captured part went through the request middleware already. A middleware that changes it again (for
# example, adds a system row) would apply twice and change the cached prefix. It can change the new rows.
- if ({k: v for k, v in changed.items() if k != "messages"} != {k: v for k, v in body.items() if k != "messages"}
- or changed["messages"][:captured] != body["messages"][:captured]
+ if ({k: v for k, v in changed.items() if k != field} != {k: v for k, v in body.items() if k != field}
+ or changed[field][:captured] != body[field][:captured]
# The host instruction must stay the last block of the last row: without it, the reply is not a
# handoff. The user text in front of it (a trailing user row) can change, as the other new rows.
- or not changed["messages"] or not warm.ends_with_instruction(changed["messages"][-1], instruction)):
+ or not changed[field] or not protocol.ends_with_instruction(changed[field][-1], instruction)):
raise warm.WarmRefusal("middleware_rewrite")
body = changed
# A request middleware can add text to the new rows. Check the size again before the request is sent.
- if not warm.fits(body, int(self.context_length or 0), measured, captured):
+ if not warm.fits(body, int(self.context_length or 0), measured, captured, api_mode=route[2]):
raise warm.WarmRefusal("capacity")
# A copy that no middleware can change in place.
base = copy.deepcopy(body)
@@ -585,7 +610,8 @@ class WarmCompactionEngine(ContextEngine):
# extra_headers is an SDK option, not part of the JSON body.
wire_body = ({name: value for name, value in base.items() if name != "extra_headers"}
if request_headers else base)
- result = warm.send(wire_body, route[1], key, post=self._post, extra_headers=headers, ssl_context=tls)
+ result = warm.send(wire_body, route[1], key, post=self._post, extra_headers=headers, ssl_context=tls,
+ api_mode=route[2], provider=provider)
# The send blocks on the network: a switch can occur before it returns.
if self._attempt() != attempt:
raise warm.WarmRefusal("route_changed")
@@ -667,12 +693,12 @@ class WarmCompactionEngine(ContextEngine):
if capture is None or tuple(capture.get("route") or ()) != tuple(self._wc_route):
return None
body = capture.get("body")
- if not isinstance(body, dict) or not isinstance(body.get("messages"), list):
+ if not isinstance(body, dict) or not isinstance(body.get(protocol.history_key(self._wc_route[2])), list):
return None
try:
warm.split_history(capture, messages)
- warm.check_source(body, messages[: len(capture["digests"])], self._wc_route[1],
- warm.native_details_type(self._wc_provider))
+ protocol.check_source(body, messages[: len(capture["digests"])], self._wc_route,
+ warm.native_details_type(self._wc_provider))
except Exception:
return None
return capture
diff --git a/warm_compaction/layout.py b/warm_compaction/layout.py
index 69e49ec..55f2a04 100644
--- a/warm_compaction/layout.py
+++ b/warm_compaction/layout.py
@@ -282,10 +282,12 @@ def _tail_row(row: Any, marker: str) -> Any:
def _tail_parts(row: Any, policy: SendPolicy = SendPolicy()) -> list[tuple[tuple, Any]]:
- """Return the sent payloads of a tail row that a cut can make smaller, as (key, value): the content (text, or
- each part of a list), the arguments of each tool call, and the reasoning text that the route sends for an
- assistant row (sent_reasoning_key). Reasoning that the route does not send is not a payload: a cut would give
- it to the fallback model and the fixed summary."""
+ """Return sent payloads that can be cut without breaking native replay."""
+ if policy.native_mode in ("codex_responses", "anthropic_messages") and any(
+ attr(row, key) for key in ("codex_message_items", "codex_reasoning_items", "reasoning_details",
+ "anthropic_content_blocks")):
+ # The canonical text and tool calls must still agree with their signed or encrypted replay blocks.
+ return []
if not isinstance(row, dict):
return []
role = row.get("role")
diff --git a/warm_compaction/protocol.py b/warm_compaction/protocol.py
new file mode 100644
index 0000000..becbabd
--- /dev/null
+++ b/warm_compaction/protocol.py
@@ -0,0 +1,227 @@
+"""Request field names and bounded native reply envelopes."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+SUPPORTED = ("chat_completions", "codex_responses", "anthropic_messages")
+MAX_DONE_ITEMS = 256
+
+
+def history_key(api_mode: str) -> str:
+ """Return the field with the conversation input."""
+ return "input" if api_mode == "codex_responses" else "messages"
+
+
+def ends_with_instruction(row: Any, instruction: str) -> bool:
+ """True when the last user input block is the host instruction."""
+ if not isinstance(row, dict) or row.get("role") != "user":
+ return False
+ content = row.get("content")
+ if isinstance(content, str):
+ return content == instruction or content.endswith("\n\n" + instruction)
+ return (isinstance(content, list) and bool(content) and isinstance(content[-1], dict)
+ and content[-1].get("type") in ("text", "input_text") and content[-1].get("text") == instruction)
+
+
+def check_source(body: dict, history: list, route: tuple, native_type: str | None = None) -> None:
+ """Check that the captured input represents the stored history."""
+ from . import anthropic, responses, warm
+ if route[2] == "codex_responses":
+ responses.check_source(body, history, route[1], native_type)
+ elif route[2] == "anthropic_messages":
+ anthropic.check_source(body, history, route[1], native_type)
+ else:
+ warm.check_source(body, history, route[1], native_type)
+
+
+def envelope(raw: bytes, api_mode: str) -> dict:
+ """Read JSON or a complete SSE reply. Never use partial text as a summary."""
+ from .warm import WarmRefusal
+ try:
+ text = raw.decode("utf-8")
+ if text.lstrip().startswith("{"):
+ payload = json.loads(text)
+ if not isinstance(payload, dict):
+ raise ValueError
+ return payload
+ events = []
+ for frame in text.replace("\r\n", "\n").split("\n\n"):
+ data = "\n".join(line[5:].lstrip(" ") for line in frame.splitlines() if line.startswith("data:"))
+ if data and data != "[DONE]":
+ event = json.loads(data)
+ if not isinstance(event, dict):
+ raise ValueError
+ events.append(event)
+ if api_mode == "codex_responses":
+ return _responses_stream(events)
+ if api_mode == "anthropic_messages":
+ return _anthropic_stream(events)
+ except (UnicodeError, ValueError, KeyError, TypeError, IndexError, AttributeError) as error:
+ raise WarmRefusal("incomplete_response") from error
+ raise WarmRefusal("incomplete_response")
+
+
+def _completed_item(item: Any) -> bool:
+ """Validate a complete done item. Return True for final assistant text."""
+ if not isinstance(item, dict) or not isinstance(item.get("id"), str) or not item["id"]:
+ raise ValueError
+ kind = item.get("type")
+ if not isinstance(kind, str) or not kind or item.get("status") not in (None, "completed"):
+ raise ValueError
+ if kind == "reasoning":
+ summary = item.get("summary")
+ if not isinstance(summary, list) or any(not isinstance(part, dict)
+ or part.get("type") != "summary_text"
+ or not isinstance(part.get("text"), str) for part in summary):
+ raise ValueError
+ if item.get("encrypted_content") is not None and not isinstance(item["encrypted_content"], str):
+ raise ValueError
+ if kind != "message":
+ # The reply parser keeps tools and refusals out of an accepted handoff.
+ return False
+ if (item.get("status") != "completed" or item.get("role") != "assistant"
+ or not isinstance(item.get("content"), list) or not item["content"]):
+ raise ValueError
+ text = False
+ for part in item["content"]:
+ if not isinstance(part, dict):
+ raise ValueError
+ if part.get("type") == "output_text" and isinstance(part.get("text"), str):
+ text = text or bool(part["text"].strip())
+ elif part.get("type") != "refusal" or not isinstance(part.get("refusal"), str):
+ raise ValueError
+ return text and item.get("phase") != "commentary"
+
+
+def _responses_stream(events: list[dict]) -> dict:
+ """Use completed done items when the completed terminal has no output list."""
+ payload = None
+ done: dict[int, dict] = {}
+ announced: dict[int, tuple[str, str]] = {}
+ referenced: dict[int, str | None] = {}
+ ids: set[str] = set()
+ text_done = False
+ progress_kinds = {"response.output_text.delta", "response.output_text.done", "response.content_part.added",
+ "response.content_part.done", "response.function_call_arguments.delta",
+ "response.function_call_arguments.done"}
+ for event in events:
+ kind = event.get("type")
+ if payload is not None or kind in ("response.incomplete", "response.failed", "error", "response.error"):
+ raise ValueError
+ if kind in ("response.output_item.added", "response.output_item.done"):
+ index, item = event.get("output_index"), event.get("item")
+ if type(index) is not int or not 0 <= index < MAX_DONE_ITEMS or not isinstance(item, dict):
+ raise ValueError
+ identity = (item.get("id"), item.get("type"))
+ if any(not isinstance(value, str) or not value for value in identity):
+ raise ValueError
+ if kind == "response.output_item.added":
+ if index in announced or index in done or any(other[0] == identity[0] for other in announced.values()):
+ raise ValueError
+ announced[index] = identity
+ else:
+ if index in done or identity[0] in ids or (index in announced and announced[index] != identity):
+ raise ValueError
+ if any(other_index != index and other[0] == identity[0] for other_index, other in announced.items()):
+ raise ValueError
+ text_done = _completed_item(item) or text_done
+ done[index] = item
+ ids.add(identity[0])
+ elif kind == "response.completed":
+ terminal = event.get("response")
+ if (not isinstance(terminal, dict) or terminal.get("status") != "completed"
+ or terminal.get("error") or terminal.get("incomplete_details")):
+ raise ValueError
+ payload = dict(terminal)
+ output = payload.get("output")
+ if output is not None and not isinstance(output, list):
+ raise ValueError
+ if output:
+ # A terminal output and a done item cannot disagree about one output position.
+ if any(index >= len(output) or output[index] != item for index, item in done.items()):
+ raise ValueError
+ if any(index >= len(output) or not isinstance(output[index], dict)
+ or (output[index].get("id"), output[index].get("type")) != identity
+ for index, identity in announced.items()):
+ raise ValueError
+ else:
+ if (not text_done or set(done) != set(range(len(done))) or set(announced) - set(done)):
+ raise ValueError
+ payload["output"] = [done[index] for index in range(len(done))]
+ if any(index >= len(payload["output"]) or not isinstance(payload["output"][index], dict)
+ or (item_id is not None and payload["output"][index].get("id") != item_id)
+ for index, item_id in referenced.items()):
+ raise ValueError
+ elif kind in progress_kinds:
+ # These events can report progress. Their text never supplies a missing done item.
+ index = event.get("output_index")
+ if type(index) is not int or not 0 <= index < MAX_DONE_ITEMS or index in done:
+ raise ValueError
+ item_id = event.get("item_id")
+ if item_id is not None and (not isinstance(item_id, str) or not item_id):
+ raise ValueError
+ if index in announced and item_id is not None and item_id != announced[index][0]:
+ raise ValueError
+ if index in referenced and item_id is not None and referenced[index] not in (None, item_id):
+ raise ValueError
+ referenced[index] = item_id or referenced.get(index)
+ if payload is None:
+ raise ValueError
+ return payload
+
+
+def _anthropic_stream(events: list[dict]) -> dict:
+ """Assemble only a complete native Messages stream."""
+ payload: dict = {}
+ blocks: dict[int, dict] = {}
+ closed: set[int] = set()
+ stopped = False
+ for event in events:
+ kind = event.get("type")
+ if stopped or kind == "error":
+ raise ValueError
+ if kind == "message_start":
+ if payload:
+ raise ValueError
+ payload = dict(event["message"])
+ if not isinstance(payload.get("usage", {}), dict):
+ raise ValueError
+ payload["usage"] = dict(payload.get("usage", {}))
+ elif kind == "content_block_start":
+ index = event["index"]
+ if not payload or type(index) is not int or index != len(blocks):
+ raise ValueError
+ blocks[index] = dict(event["content_block"])
+ elif kind == "content_block_delta":
+ index = event["index"]
+ block, delta = blocks[index], event["delta"]
+ if type(index) is not int or index in closed or not isinstance(delta, dict):
+ raise ValueError
+ compatible = {"text": {"text_delta"}, "thinking": {"thinking_delta", "signature_delta"},
+ "tool_use": {"input_json_delta"}}
+ if delta.get("type") not in compatible.get(block.get("type"), set()):
+ raise ValueError
+ if delta.get("type") == "text_delta":
+ if block.get("type") != "text":
+ raise ValueError
+ block["text"] = block.get("text", "") + delta["text"]
+ elif kind == "content_block_stop":
+ index = event["index"]
+ if type(index) is not int or index not in blocks or index in closed:
+ raise ValueError
+ closed.add(index)
+ elif kind == "message_delta":
+ if not payload or not isinstance(event.get("delta"), dict) or not isinstance(event.get("usage", {}), dict):
+ raise ValueError
+ payload.update(event["delta"])
+ payload["usage"].update(event.get("usage", {}))
+ elif kind == "message_stop":
+ if not payload or set(blocks) != closed or not payload.get("stop_reason"):
+ raise ValueError
+ stopped = True
+ if not stopped:
+ raise ValueError
+ payload["content"] = [blocks[index] for index in sorted(blocks)]
+ return payload
diff --git a/warm_compaction/responses.py b/warm_compaction/responses.py
new file mode 100644
index 0000000..ac45018
--- /dev/null
+++ b/warm_compaction/responses.py
@@ -0,0 +1,400 @@
+"""A bounded Responses adapter for plain text and function-tool history."""
+
+from __future__ import annotations
+
+import copy
+import json
+import re
+import unicodedata
+from typing import Any
+from urllib.parse import urlsplit
+
+from .rows import api_content
+from .warm import HANDOFF_MAX_TOKENS, HANDOFF_MIN_TOKENS, WarmRefusal, fits, split_history
+
+_PHASES = {"commentary", "final_answer"}
+_OPAQUE_FIELDS = ("reasoning_details",)
+_STATE_FIELDS = ("previous_response_id", "conversation", "context_management", "background", "truncation")
+_SETTINGS = {"model", "instructions", "input", "store", "tools", "tool_choice", "parallel_tool_calls",
+ "prompt_cache_key", "prompt_cache_retention", "reasoning", "include", "service_tier", "text",
+ "max_output_tokens", "temperature"}
+
+
+def _safe_text(text: str, base_url: Any) -> None:
+ if is_codex_backend(base_url):
+ visible = "".join(char for char in text if unicodedata.category(char) != "Cf")
+ if re.search(r"<\|(start|end|channel|message|constrain|return|call)\|>", visible):
+ raise WarmRefusal("source_transform_unsupported")
+
+
+def _safe_tree(value: Any, base_url: Any) -> None:
+ if isinstance(value, str):
+ _safe_text(value, base_url)
+ elif isinstance(value, dict):
+ for key, item in value.items():
+ _safe_tree(key, base_url)
+ _safe_tree(item, base_url)
+ elif isinstance(value, list):
+ for item in value:
+ _safe_tree(item, base_url)
+
+
+def is_codex_backend(base_url: Any) -> bool:
+ """Return True for the consumer Codex route used by Hermes."""
+ parsed = urlsplit(str(base_url or ""))
+ return parsed.hostname == "chatgpt.com" and parsed.path.startswith("/backend-api/codex")
+
+
+def _text(content: Any) -> str:
+ if content is None:
+ return ""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list) and all(
+ isinstance(part, dict) and part.get("type") in {"text", "input_text", "output_text"}
+ and isinstance(part.get("text"), str) and set(part) <= {"type", "text"} for part in content
+ ):
+ return "".join(part["text"] for part in content)
+ raise WarmRefusal("source_transform_unsupported")
+
+
+def _call_id(raw: Any) -> str:
+ """Read the stored call ID. Refuse IDs that need a generated replacement."""
+ if not isinstance(raw, str) or not raw.strip():
+ raise WarmRefusal("source_transform_unsupported")
+ value = raw.strip().split("|", 1)[0]
+ if value.startswith("fc_"):
+ value = "call_" + value[3:]
+ if not value or len(value) > 64:
+ raise WarmRefusal("source_transform_unsupported")
+ return value
+
+
+def _arguments(value: Any) -> str:
+ """Use the same compact JSON form for a valid function argument object."""
+ if isinstance(value, str):
+ try:
+ parsed = json.loads(value)
+ except (TypeError, ValueError) as error:
+ raise WarmRefusal("source_transform_unsupported") from error
+ else:
+ parsed = value
+ try:
+ return json.dumps(parsed, sort_keys=True, separators=(",", ":"), allow_nan=False)
+ except (TypeError, ValueError) as error:
+ raise WarmRefusal("source_transform_unsupported") from error
+
+
+def _message(row: dict, content: str, typed: bool) -> dict:
+ role = row["role"]
+ result = {"type": "message", "role": role, "content": content}
+ if typed:
+ result["content"] = [{"type": "output_text" if role == "assistant" else "input_text", "text": content}]
+ if role == "assistant" and row.get("phase") in _PHASES:
+ result["phase"] = row["phase"]
+ return result
+
+
+def _issuer(base_url: Any) -> str:
+ """Use the named Hermes issuer classes. Custom routes keep their URL stamp."""
+ parsed = urlsplit(str(base_url or ""))
+ host = parsed.hostname or ""
+ if host == "api.x.ai" or host.endswith(".x.ai"):
+ return "xai_responses"
+ if host == "githubcopilot.com" or host.endswith(".githubcopilot.com"):
+ return "github_responses"
+ if is_codex_backend(base_url):
+ return "codex_backend"
+ if parsed.query or parsed.fragment or parsed.username or parsed.port not in (None, 80, 443):
+ return "other:" + str(base_url or "").strip()
+ return "other:" + parsed._replace(scheme=parsed.scheme.lower(), netloc=host,
+ path=parsed.path.rstrip("/")).geturl()
+
+
+def _replay_reasoning(row: dict, base_url: Any, model: Any, seen: set, require_provenance: bool = False) -> list:
+ """Replay verified reasoning bytes. Native compaction checkpoints remain unsupported."""
+ raw_items = row.get("codex_reasoning_items") or []
+ if not isinstance(raw_items, list):
+ raise WarmRefusal("source_transform_unsupported")
+ items = []
+ for raw in raw_items:
+ if not isinstance(raw, dict) or raw.get("type") != "reasoning":
+ raise WarmRefusal("source_transform_unsupported")
+ encrypted = raw.get("encrypted_content")
+ if not isinstance(encrypted, str) or not encrypted:
+ raise WarmRefusal("source_transform_unsupported")
+ stamp = raw.get("_issuer_kind")
+ if require_provenance and (not isinstance(stamp, str) or not isinstance(raw.get("_issuer_model"), str)):
+ raise WarmRefusal("source_transform_unsupported")
+ if isinstance(stamp, str) and stamp.startswith("other:"):
+ stamp = _issuer(stamp[6:])
+ if stamp is not None and stamp != _issuer(base_url):
+ raise WarmRefusal("source_transform_unsupported")
+ if raw.get("_issuer_model") is not None and raw["_issuer_model"] != model:
+ raise WarmRefusal("source_transform_unsupported")
+ item_id = raw.get("id")
+ if item_id:
+ if not isinstance(item_id, str) or item_id in seen:
+ raise WarmRefusal("source_transform_unsupported")
+ seen.add(item_id)
+ summary = raw.get("summary") or []
+ if not isinstance(summary, list) or any(
+ not isinstance(part, dict) or part.get("type") != "summary_text"
+ or not isinstance(part.get("text"), str) or set(part) - {"type", "text"} for part in summary
+ ):
+ raise WarmRefusal("source_transform_unsupported")
+ for part in summary:
+ _safe_text(part["text"], base_url)
+ items.append({"type": "reasoning", "encrypted_content": encrypted, "summary": copy.deepcopy(summary)})
+ return items
+
+
+def _replay_messages(row: dict, content: str, base_url: Any) -> list:
+ replay = row.get("codex_message_items")
+ if not replay:
+ return []
+ if not isinstance(replay, list):
+ raise WarmRefusal("source_transform_unsupported")
+ items, final_text = [], []
+ linked = bool(row.get("codex_reasoning_items") or row.get("codex_reasoning_trimmed"))
+ copilot = (urlsplit(str(base_url or "")).hostname or "").endswith("githubcopilot.com")
+ for raw in replay:
+ if not isinstance(raw, dict) or raw.get("type") != "message" or raw.get("role") != "assistant":
+ raise WarmRefusal("source_transform_unsupported")
+ parts = raw.get("content")
+ if not isinstance(parts, list) or not parts or any(
+ not isinstance(part, dict) or part.get("type") != "output_text" or not isinstance(part.get("text"), str)
+ for part in parts
+ ):
+ raise WarmRefusal("source_transform_unsupported")
+ text = "".join(part["text"] for part in parts)
+ item = {"type": "message", "role": "assistant", "status": "completed",
+ "content": [{"type": "output_text", "text": part["text"]} for part in parts]}
+ if raw.get("status") not in (None, "completed") or raw.get("phase") not in (None, *_PHASES):
+ raise WarmRefusal("source_transform_unsupported")
+ if raw.get("phase"):
+ item["phase"] = raw["phase"]
+ if raw.get("phase") != "commentary":
+ final_text.append(text.strip())
+ item_id = raw.get("id")
+ if isinstance(item_id, str) and item_id.strip() and len(item_id.strip()) <= 64 and not copilot and not linked:
+ if not is_codex_backend(base_url) or item_id.strip().startswith("msg"):
+ item["id"] = item_id.strip()
+ items.append(item)
+ if "\n".join(final_text).strip() != content:
+ raise WarmRefusal("source_transform_unsupported")
+ return items
+
+
+def wire_rows(rows: list, base_url: Any = None, *, used_ids: set | None = None, model: Any = None,
+ used_reasoning_ids: set | None = None, require_provenance: bool = False) -> list:
+ """Render text, verified native replay, and matched function-tool rows."""
+ typed = is_codex_backend(base_url)
+ used = set(used_ids or ())
+ pending: set[str] = set()
+ seen_reasoning: set[str] = set(used_reasoning_ids or ())
+ output = []
+ for row in rows:
+ if not isinstance(row, dict) or any(row.get(key) for key in _OPAQUE_FIELDS):
+ raise WarmRefusal("source_transform_unsupported")
+ role = row.get("role")
+ if role not in {"user", "assistant", "tool"}:
+ raise WarmRefusal("source_transform_unsupported")
+ content = _text(api_content(row))
+ _safe_text(content, base_url)
+ # Hermes removes outer whitespace from scalar user and assistant content.
+ if role in {"user", "assistant"} and isinstance(api_content(row), str):
+ content = content.strip()
+ if role == "tool":
+ call_id = _call_id(row.get("tool_call_id"))
+ if call_id not in pending:
+ raise WarmRefusal("source_transform_unsupported")
+ pending.remove(call_id)
+ output.append({"type": "function_call_output", "call_id": call_id, "output": content})
+ continue
+ calls = row.get("tool_calls") or []
+ if role == "user" and (calls or row.get("codex_message_items")):
+ raise WarmRefusal("source_transform_unsupported")
+ reasoning = _replay_reasoning(row, base_url, model, seen_reasoning, require_provenance
+ ) if role == "assistant" else []
+ output.extend(reasoning)
+ replay = _replay_messages(row, content, base_url) if role == "assistant" else []
+ if replay:
+ output.extend(replay)
+ elif content or role == "user":
+ output.append(_message(row, content, typed or isinstance(api_content(row), list)))
+ elif reasoning and not calls:
+ output.append(_message(row, " ", typed))
+ if not isinstance(calls, list):
+ raise WarmRefusal("source_transform_unsupported")
+ for call in calls:
+ if not isinstance(call, dict) or call.get("type", "function") != "function":
+ raise WarmRefusal("source_transform_unsupported")
+ function = call.get("function")
+ if not isinstance(function, dict):
+ raise WarmRefusal("source_transform_unsupported")
+ name = function.get("name")
+ if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_-]+", name):
+ raise WarmRefusal("source_transform_unsupported")
+ call_id = _call_id(call.get("call_id") or call.get("id"))
+ if call_id in used:
+ raise WarmRefusal("source_transform_unsupported")
+ used.add(call_id)
+ pending.add(call_id)
+ arguments = _arguments(function.get("arguments", "{}"))
+ _safe_text(arguments, base_url)
+ output.append({"type": "function_call", "call_id": call_id, "name": name,
+ "arguments": arguments})
+ if pending:
+ raise WarmRefusal("source_transform_unsupported")
+ return output
+
+
+def check_source(body: dict[str, Any], history: list, base_url: Any = None, native_type: Any = None) -> None:
+ """Require that the captured input is the supported form of the stored history."""
+ check_settings(body, base_url)
+ if body.get("input") != wire_rows(history, base_url, model=body.get("model")):
+ raise WarmRefusal("source_transform_unsupported")
+
+
+def check_settings(body: dict[str, Any], base_url: Any = None) -> None:
+ """Refuse stateful and forced-output request settings."""
+ if (set(body) - _SETTINGS or not isinstance(body.get("input"), list)
+ or any(value is None for value in body.values())):
+ raise WarmRefusal("settings_unsupported")
+ # The main terminal runs preflight again after middleware. Accept only unchanged scalar forms.
+ for field in ("model", "instructions"):
+ value = body.get(field)
+ if not isinstance(value, str) or not value or value != value.strip():
+ raise WarmRefusal("source_transform_unsupported")
+ _safe_text(body["instructions"], base_url)
+ for field, kind in (("reasoning", dict), ("include", list)):
+ if field in body and not isinstance(body[field], kind):
+ raise WarmRefusal("source_transform_unsupported")
+ if "service_tier" in body and (not isinstance(body["service_tier"], str) or not body["service_tier"]
+ or body["service_tier"] != body["service_tier"].strip()):
+ raise WarmRefusal("source_transform_unsupported")
+ if "max_output_tokens" in body and (type(body["max_output_tokens"]) is not int or body["max_output_tokens"] <= 0):
+ raise WarmRefusal("source_transform_unsupported")
+ if "temperature" in body and type(body["temperature"]) is not float:
+ raise WarmRefusal("source_transform_unsupported")
+ if "prompt_cache_key" in body and (not isinstance(body["prompt_cache_key"], str) or not body["prompt_cache_key"]
+ or body["prompt_cache_key"] != body["prompt_cache_key"].strip()
+ or len(body["prompt_cache_key"]) > 64):
+ raise WarmRefusal("source_transform_unsupported")
+ if body.get("store") is not False or body.get("tool_choice") not in (None, "auto", "none"):
+ raise WarmRefusal("settings_unsupported")
+ if any(body.get(key) is not None for key in _STATE_FIELDS):
+ raise WarmRefusal("settings_unsupported")
+ text = body.get("text")
+ if text is not None and (not isinstance(text, dict) or not text or set(text) - {"verbosity"}):
+ raise WarmRefusal("settings_unsupported")
+ tools = body.get("tools", [])
+ if not isinstance(tools, list) or any(not isinstance(tool, dict) or tool.get("type") != "function"
+ for tool in tools):
+ raise WarmRefusal("settings_unsupported")
+ for tool in tools:
+ if (set(tool) != {"type", "name", "description", "strict", "parameters"}
+ or not isinstance(tool.get("name"), str) or not tool["name"]
+ or tool["name"] != tool["name"].strip() or not isinstance(tool.get("description"), str)
+ or type(tool.get("strict")) is not bool or not isinstance(tool.get("parameters"), dict)):
+ raise WarmRefusal("source_transform_unsupported")
+ _safe_tree(tools, base_url)
+ if is_codex_backend(base_url) and body.get("prompt_cache_retention") is not None:
+ # Hermes drops this value after execution middleware. It is not a wire capture.
+ raise WarmRefusal("source_transform_unsupported")
+
+
+def reply_reserve(body: dict, context_length: int = 0) -> int:
+ """Return the output reserve. An unknown consumer limit uses a conservative reserve."""
+ value = body.get("max_output_tokens")
+ if type(value) is int and value > 0:
+ return value
+ return max(4096, min(context_length // 4, 65_536))
+
+
+def build_request(capture: dict[str, Any], messages: list, route: tuple, context_length: int,
+ instruction: str, native_type: Any = None) -> dict:
+ """Keep the captured input prefix and add supported new rows and the handoff request."""
+ if route[2] != "codex_responses":
+ raise WarmRefusal("api_mode_unsupported")
+ if tuple(capture.get("route") or ()) != tuple(route):
+ raise WarmRefusal("route_changed")
+ body = capture.get("body")
+ if not isinstance(body, dict):
+ raise WarmRefusal(capture.get("refusal") or "no_capture")
+ check_settings(body, route[1])
+ count = len(capture["digests"])
+ check_source(body, messages[:count], route[1])
+ new_rows, trailing = split_history(capture, messages)
+ used_ids = {item["call_id"] for item in body["input"] if item.get("type") == "function_call"}
+ reasoning_ids = {item.get("id") for row in messages[:count] for item in (row.get("codex_reasoning_items") or [])
+ if item.get("id")}
+ added = wire_rows([*new_rows, *trailing], route[1], used_ids=used_ids, model=body.get("model"),
+ used_reasoning_ids=reasoning_ids, require_provenance=True)
+ added.append({"type": "message", "role": "user", "content": [{"type": "input_text", "text": instruction}]})
+ request = copy.deepcopy(body)
+ request["input"] = [*request["input"], *added]
+ request["stream"] = True
+ _safe_text(instruction, route[1])
+ if not is_codex_backend(route[1]):
+ limit = body.get("max_output_tokens")
+ request["max_output_tokens"] = (
+ min(max(limit, HANDOFF_MIN_TOKENS), HANDOFF_MAX_TOKENS)
+ if type(limit) is int and limit > 0 else HANDOFF_MAX_TOKENS
+ )
+ if not fits(request, context_length, capture.get("prompt_tokens"), len(body["input"]),
+ api_mode="codex_responses"):
+ raise WarmRefusal("capacity")
+ return request
+
+
+def _counter(value: Any) -> int | None:
+ return value if type(value) is int and value >= 0 else None
+
+
+def parse_reply(payload: dict) -> dict:
+ """Read a terminal Responses payload. The caller assembles streaming events first."""
+ if not isinstance(payload, dict) or not isinstance(payload.get("output"), list):
+ raise WarmRefusal("incomplete_response")
+ status = payload.get("status")
+ content = []
+ tool_calls = refusal = False
+ for item in payload["output"]:
+ if not isinstance(item, dict):
+ raise WarmRefusal("incomplete_response")
+ kind = item.get("type")
+ if kind in {"reasoning"}:
+ continue
+ if kind != "message":
+ tool_calls = True
+ continue
+ if item.get("role") != "assistant" or not isinstance(item.get("content"), list):
+ raise WarmRefusal("incomplete_response")
+ if item.get("status") not in (None, "completed") or item.get("phase") not in (None, *_PHASES):
+ raise WarmRefusal("incomplete_response")
+ for part in item["content"]:
+ if not isinstance(part, dict):
+ raise WarmRefusal("incomplete_response")
+ if part.get("type") == "refusal":
+ refusal = True
+ elif part.get("type") == "output_text" and isinstance(part.get("text"), str):
+ if item.get("phase") != "commentary":
+ content.append(part["text"])
+ else:
+ raise WarmRefusal("incomplete_response")
+ usage = payload.get("usage", {})
+ if usage is None:
+ usage = {}
+ if not isinstance(usage, dict):
+ raise WarmRefusal("incomplete_response")
+ details = usage.get("input_tokens_details", {})
+ if details is None:
+ details = {}
+ if not isinstance(details, dict):
+ raise WarmRefusal("incomplete_response")
+ return {"content": "".join(content), "finish_reason": "stop" if status == "completed" else "length",
+ "tool_calls": tool_calls, "refusal": refusal or bool(payload.get("error")),
+ "prompt_tokens": _counter(usage.get("input_tokens")),
+ "completion_tokens": _counter(usage.get("output_tokens")),
+ "cached_tokens": _counter(details.get("cached_tokens"))}
diff --git a/warm_compaction/rows.py b/warm_compaction/rows.py
index 829f645..8940085 100644
--- a/warm_compaction/rows.py
+++ b/warm_compaction/rows.py
@@ -118,6 +118,7 @@ class SendPolicy(NamedTuple):
echo: bool = True
cut_reasoning: bool = True
native_type: str | None = None
+ native_mode: str = ""
def reasoning_policy(source: dict, wire: dict, needs_pad: bool) -> None:
@@ -197,6 +198,11 @@ def sent_rows(messages: list, policy: SendPolicy = SendPolicy()) -> list:
details = replay_details(row.get("reasoning_details"), policy.native_type)
if details is not None:
sent["reasoning_details"] = details
+ if policy.native_mode in ("codex_responses", "anthropic_messages"):
+ # Count opaque replay too. Canonical text is also counted, which gives a safe upper estimate.
+ for field in ("codex_message_items", "codex_reasoning_items", "anthropic_content_blocks"):
+ if row.get(field):
+ sent[field] = row[field]
reasoning(row, sent, policy.echo)
out.append(sent)
else:
@@ -266,6 +272,11 @@ def row_digest(row: Any) -> str:
"tool_calls": [list(call) for call in tool_calls_of(row)],
# The text that the provider saw, when Hermes keeps it in the api_content sidecar.
"api_content": api_content(row) if api_content(row) is not attr(row, "content") else None,
+ # Native replay fields can change the provider input without changing the visible text.
+ "native": {name: attr(row, name) for name in (
+ "reasoning_content", "reasoning_details", "codex_message_items", "codex_reasoning_items",
+ "codex_checkpoint_items", "codex_reasoning_trimmed", "phase", "anthropic_content_blocks",
+ "_anthropic_content_blocks", "call_id", "response_item_id")},
}
text = json.dumps(canonical, sort_keys=True, separators=(",", ":"), default=str)
return hashlib.sha256(text.encode("ascii")).hexdigest()
diff --git a/warm_compaction/warm.py b/warm_compaction/warm.py
index ee9ed26..71fc66e 100644
--- a/warm_compaction/warm.py
+++ b/warm_compaction/warm.py
@@ -13,6 +13,7 @@ import urllib.request
from typing import Any
from collections.abc import Callable
+from . import protocol
from .rows import (
api_content, attr, compact_json, estimate_tokens, has_thought_signature, hermes_value, plain_text,
reasoning_policy as _reasoning_policy, replay_details, reply_text, row_digest, tool_calls_of,
@@ -362,13 +363,14 @@ def _join_user_rows(rows: list, instruction: str) -> list:
def reply_reserve(body: Any) -> int:
"""The reply reserve of a request: the larger positive max_tokens or max_completion_tokens (a server can
honor either), else DEFAULT_RESERVE."""
- values = [body.get(key) for key in ("max_tokens", "max_completion_tokens")] if isinstance(body, dict) else []
+ values = [body.get(key) for key in ("max_tokens", "max_completion_tokens", "max_output_tokens")
+ ] if isinstance(body, dict) else []
values = [value for value in values if type(value) is int and value > 0]
return max(values) if values else DEFAULT_RESERVE
def fits(body: dict[str, Any], context_length: int, measured_tokens: int | None = None,
- measured_rows: int = 0) -> bool:
+ measured_rows: int = 0, api_mode: str = "chat_completions") -> bool:
"""Return True when the request size plus the reply reserve fits in the context window.
When the server measured the prompt of the first measured_rows messages, use that count and estimate only
@@ -377,11 +379,16 @@ def fits(body: dict[str, Any], context_length: int, measured_tokens: int | None
if context_length <= 0:
return True
reserve = reply_reserve(body)
- messages = body.get("messages") or []
+ field = protocol.history_key(api_mode)
+ messages = body.get(field) or []
if type(measured_tokens) is int and measured_tokens > 0 and 0 < measured_rows <= len(messages):
- size = measured_tokens + estimate_tokens({"messages": messages[measured_rows:]}) * SAFETY
+ size = measured_tokens + estimate_tokens({field: messages[measured_rows:]}) * SAFETY
else:
- size = estimate_tokens({"messages": messages, "tools": body.get("tools")}) * SAFETY
+ size = estimate_tokens({key: value for key, value in body.items()
+ if key == field or isinstance(value, (str, list, dict))}) * SAFETY
+ if api_mode == "codex_responses" and not any(
+ type(body.get(key)) is int and body[key] > 0 for key in ("max_output_tokens", "max_tokens")):
+ reserve = max(DEFAULT_RESERVE, min(context_length // 4, 65_536))
return size + int(reserve) <= context_length
@@ -389,6 +396,12 @@ def build_request(capture: dict[str, Any], messages: list, route: tuple, context
instruction: str, native_type: str | None = None) -> dict[str, Any]:
"""Return the warm request body. Raise WarmRefusal when a condition is not true. native_type: the native
reasoning carrier type of the provider profile (native_details_type)."""
+ if route[2] == "codex_responses":
+ from .responses import build_request as build_native
+ return build_native(capture, messages, route, context_length, instruction, native_type)
+ if route[2] == "anthropic_messages":
+ from .anthropic import build_request as build_native
+ return build_native(capture, messages, route, context_length, instruction, native_type)
if route[2] != "chat_completions":
raise WarmRefusal("api_mode_unsupported")
if tuple(capture["route"]) != tuple(route):
@@ -482,7 +495,8 @@ def _normalize_finish_reason(raw: Any) -> Any:
return _FINISH_ALIASES.get(lowered, lowered)
-def route_headers(api_key: Any, base_url: Any, provider: Any) -> dict[str, str]:
+def route_headers(api_key: Any, base_url: Any, provider: Any,
+ api_mode: str = "chat_completions") -> dict[str, str]:
"""Return the default headers that the Hermes OpenAI client sends on this route, in the order of Hermes
45871e10 (agent.agent_init): the host headers or the provider profile headers, then model.default_headers,
then providers.<name>.extra_headers. Provider headers go with every request (attribution, a User-Agent for a
@@ -490,6 +504,13 @@ def route_headers(api_key: Any, base_url: Any, provider: Any) -> dict[str, str]:
without them can be refused or go to another cache. The engine adds supported per-request session headers
from the capture after this step. The values can be credentials: never log them."""
url = str(base_url or "")
+ if api_mode == "anthropic_messages":
+ try:
+ from hermes_cli.config_providers import get_custom_provider_extra_headers
+ headers = get_custom_provider_extra_headers(url) or {}
+ except Exception as error:
+ raise WarmRefusal("headers_unknown") from error
+ return native_headers(api_key_text(api_key), url, provider, api_mode, dict(headers))
try:
from agent.agent_init import _host_default_headers_factory
from agent.auxiliary_client import _apply_user_default_headers
@@ -539,25 +560,54 @@ def _optional_int(value: Any) -> int | None:
return value if isinstance(value, int) and not isinstance(value, bool) else None
+def native_headers(key: str, base_url: str, provider: str, api_mode: str, headers: dict) -> dict:
+ """Resolve native authentication before the middleware sees a warm request."""
+ if api_mode == "anthropic_messages":
+ from .anthropic import route_headers as messages_headers
+ return messages_headers(key, base_url, headers, provider)
+ if api_mode == "codex_responses" and urllib.parse.urlsplit(base_url).hostname == "chatgpt.com":
+ try:
+ from agent.codex_headers import codex_cloudflare_headers
+ required = codex_cloudflare_headers(key, base_url=base_url)
+ names = {name.lower() for name in required}
+ headers = {name: value for name, value in headers.items() if name.lower() not in names}
+ return {**headers, **required}
+ except Exception as error:
+ raise WarmRefusal("headers_unknown") from error
+ return headers
+
+
def send(body: dict[str, Any], base_url: str, api_key: Any, timeout_s: float = TIMEOUT_S,
post: Post | None = None, extra_headers: dict[str, str] | None = None,
- ssl_context: ssl.SSLContext | None = None) -> dict[str, Any]:
+ ssl_context: ssl.SSLContext | None = None, api_mode: str = "chat_completions",
+ provider: str = "") -> dict[str, Any]:
"""Send the warm request one time. Return the reply fields and the usage, or raise WarmRefusal.
extra_headers are the client default headers of the route (route_headers); they win, as in the SDK."""
if not base_url:
raise WarmRefusal("provider_error")
headers = {"Content-Type": "application/json", "Accept": "application/json"}
key = api_key_text(api_key)
- if key:
+ if key and api_mode != "anthropic_messages":
headers["Authorization"] = f"Bearer {key}"
headers.update(extra_headers or {})
+ headers = native_headers(key, base_url, provider, api_mode, headers)
+ if api_mode == "codex_responses" and body.get("stream"):
+ headers["Accept"] = "text/event-stream"
data = json.dumps(body).encode("utf-8")
started = time.monotonic()
try:
# The query of the route URL stays after the path: Hermes sends it as the client's default_query (the
# api-version of an Azure route, for example).
parts = urllib.parse.urlsplit(str(base_url))
- url = urllib.parse.urlunsplit(parts._replace(path=parts.path.rstrip("/") + "/chat/completions"))
+ path = parts.path.rstrip("/")
+ endpoint = "/chat/completions"
+ if api_mode == "codex_responses":
+ endpoint = "/responses"
+ elif api_mode == "anthropic_messages":
+ endpoint = "/messages" if path.endswith("/v1") else "/v1/messages"
+ elif api_mode != "chat_completions":
+ raise WarmRefusal("api_mode_unsupported")
+ url = urllib.parse.urlunsplit(parts._replace(path=path + endpoint))
if ssl_context is None:
status, raw = (post or urllib_post)(url, data, headers, timeout_s)
else:
@@ -572,6 +622,11 @@ def send(body: dict[str, Any], base_url: str, api_key: Any, timeout_s: float = T
if len(raw) > MAX_RESPONSE_BYTES:
raise WarmRefusal("response_too_large")
try:
+ if api_mode != "chat_completions":
+ from . import anthropic, responses
+ parser = responses.parse_reply if api_mode == "codex_responses" else anthropic.parse_reply
+ result = parser(protocol.envelope(raw, api_mode))
+ return {**result, "elapsed_s": round(elapsed, 3)}
payload = json.loads(raw.decode("utf-8"))
choice = payload["choices"][0]
message = choice["message"]