Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(examples): run Codex CLI against SIE through /v1/responses (#1018)
Krisztian Gajdar26e5af49af94
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 232b16fb3..1539aed04 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -118,6 +118,13 @@ jobs:mise exec -- uv run --frozen ruff format --check .mise exec -- uv run --frozen ruff check .mise exec -- uv run --frozen pytest -q+ - name: Codex example gate+ working-directory: examples/coding-agent-codex+ run: |+ mise exec -- uv lock --check+ mise exec -- uv run --frozen ruff format --check .+ mise exec -- uv run --frozen ruff check .+ mise exec -- uv run --frozen pytest -q- name: System One example checkerworking-directory: examples/systemone-localrun: |diff --git a/examples/coding-agent-codex/.gitignore b/examples/coding-agent-codex/.gitignorenew file mode 100644index 000000000..92bd2e73f--- /dev/null+++ b/examples/coding-agent-codex/.gitignore@@ -0,0 +1,5 @@+.venv/+run-output/+__pycache__/+.ruff_cache/+.pytest_cache/diff --git a/examples/coding-agent-codex/README.md b/examples/coding-agent-codex/README.mdnew file mode 100644index 000000000..fc7d69dbe--- /dev/null+++ b/examples/coding-agent-codex/README.md@@ -0,0 +1,446 @@+# Run Codex CLI on SIE through the OpenAI Responses API++## What this shows++Codex CLI talks to a custom model provider through the OpenAI Responses API+(`wire_api = "responses"`). The SIE gateway and `sie-server`, the single-node+server, both serve `POST /v1/responses`: each translates the request into a+`/v1/chat/completions` request, serves it on its own chat route with all of+that route's limits, and translates the answer back, streamed or buffered. So+Codex reaches a model served by SIE through a provider entry in its config.++Codex lets you configure other providers, but OpenAI does not endorse models+other than its own behind Codex. Nothing here is supported or endorsed by+OpenAI. This example records how Codex behaves against SIE's endpoint and+checks that the agent loop closes.++The pieces:++1. `recipes/cloud.sh`, `recipes/cluster.sh` and `recipes/laptop.sh`. Each+ writes the Codex config for SIE Cloud, for a self-hosted cluster's gateway+ or for `sie-server` on this machine, and defines `codex` as Codex CLI+ 0.167.0 run through `npx`.+2. The conformance check of the OpenCode example, run with `--api responses`.+ It drives `/v1/responses` the way Codex does and reports each case as+ pass, fail or recorded.+3. `run_gate.sh`, a seeded gate on the OpenCode example's fixture: a tiny+ package with two failing tests and the task "make the tests pass". Codex+ works a copy headless, then pytest judges the result.++## Run it++```sh+export SIE_BASE_URL=https://... # the gateway, without /v1+export SIE_API_KEY=...+source recipes/cloud.sh # or recipes/cluster.sh, see below+codex+```++The cluster recipe also reads the model, its window and its output cap, which+must match the `context_length` and `max_output_tokens` the gateway's+`GET /v1/models` declares for the model:++```sh+export SIE_MODEL=zai-org/GLM-5.3-Flash:relay+export SIE_CONTEXT_TOKENS=131072+export SIE_OUTPUT_TOKENS=32768+source recipes/cluster.sh+```++Codex's first request is about 35 KB of JSON, most of it Codex's developer+instructions and four tool schemas, and every later request repeats it.++The conformance check, from this directory, on the model the cloud recipe+configures:++```sh+uv run --project ../coding-agent-opencode python ../coding-agent-opencode/conformance.py \+ --api responses --base-url "$SIE_BASE_URL/v1" --model zai-org/GLM-5.3-Flash:relay+```++On your gateway, on the model the cluster recipe configures:++```sh+uv run --project ../coding-agent-opencode python ../coding-agent-opencode/conformance.py \+ --api responses --base-url "$SIE_BASE_URL/v1" --model "$SIE_MODEL"+```++The seeded gate, which needs `npx` and `uv` on `PATH`:++```sh+./run_gate.sh # SIE Cloud+./run_gate.sh cluster # your gateway, with SIE_MODEL, SIE_CONTEXT_TOKENS and SIE_OUTPUT_TOKENS set+./run_gate.sh laptop # sie-server on this machine, see below+```++The laptop recipe and the gate have run against `sie-server` serving a model+on a GPU, and the recipes against a recording stub and `sie-server` on the+weightless fake engine ([recorded below](#what-result-to-expect)). The cloud+and cluster recipes have not run against a live endpoint yet.++### On this machine++From a checkout of this repository, start `sie-server` with the generation+bundle:++```sh+mise run serve -- -b sglang # generation bundle; MLX on Apple Silicon+```++Then, from this directory:++```sh+source recipes/laptop.sh+codex+```++`recipes/laptop.sh` points Codex at `http://localhost:8080` and names+`Qwen/Qwen3.5-4B:long-context`, the 32K-window profile of a 4B model that+declares tool calling, with its 4,096-token output cap. `SIE_BASE_URL`,+`SIE_API_KEY`, `SIE_MODEL`, `SIE_CONTEXT_TOKENS` and `SIE_OUTPUT_TOKENS`+override those. A server with authentication off accepts+any key. With authentication on, `SIE_API_KEY` is the server's token.++The conformance check and the gate against it:++```sh+uv run --project ../coding-agent-opencode python ../coding-agent-opencode/conformance.py \+ --api responses --base-url "${SIE_BASE_URL:-http://localhost:8080}/v1" \+ --model "${SIE_MODEL:-Qwen/Qwen3.5-4B:long-context}"+./run_gate.sh laptop+```++## The recipe++`recipes/cloud.sh` in full:++```sh+export CODEX_HOME="${SIE_CODEX_HOME:-$HOME/.codex-sie}"+mkdir -p "$CODEX_HOME"+cat > "$CODEX_HOME/config.toml" <<TOML+model = "zai-org/GLM-5.3-Flash:relay"+model_provider = "sie"+model_context_window = 131072+model_auto_compact_token_limit = 81920+web_search = "disabled"++[features]+multi_agent = false+goals = false+plugins = false++[analytics]+enabled = false++[shell_environment_policy]+exclude = ["SIE_API_KEY"]++[model_providers.sie]+name = "SIE"+base_url = "$SIE_BASE_URL/v1"+env_key = "SIE_API_KEY"+wire_api = "responses"+stream_idle_timeout_ms = 1800000+TOML+codex() { npx -y @openai/[email protected] "$@"; }+```++- The config goes in its own `CODEX_HOME`, `~/.codex-sie` unless+ `SIE_CODEX_HOME` names another directory, so the config, login and sessions+ in `~/.codex` are left alone. Sourcing the recipe again rewrites+ `config.toml`.+- `codex` runs Codex CLI 0.167.0, the version the facts below were recorded+ with, whatever version is installed.+- `wire_api = "responses"` is the wire Codex speaks to a custom provider.+ `base_url` ends in `/v1`, and Codex appends `/responses`. Codex reads the+ key from `SIE_API_KEY` and sends it as `Authorization: Bearer ...`; the key+ is not in the file.+- The model id is sent byte for byte, slash and colon included.+- Codex has no metadata for a model outside its catalog. It prints `Model+ metadata for ... not found. Defaulting to fallback metadata` on every run,+ and the gate keeps that line as a warning. `model_context_window` sets the+ window Codex budgets against, so Codex compacts the conversation before the+ server refuses it. In a stub run with a 6,000-token window, Codex compacted+ after a turn that reported 5,810 tokens and not after one that reported+ 5,010. It compacted with an ordinary `POST /v1/responses` without tools,+ which SIE serves.+- With its defaults, Codex declares a hosted `web_search` tool and a+ `namespace` tool, `multi_agent_v1`. SIE serves function and custom tools+ only. It refuses both with a 400 that names `tools[i].type`, and Codex+ prints that error and exits non-zero on the first request.+ `web_search = "disabled"` and `multi_agent = false` leave them out. Web+ search is a hosted tool that the Responses server runs itself, and SIE runs+ none; the multi-agent tools come only as a `namespace`.+- `goals = false` leaves out three goal function tools that SIE would serve,+ so every request declares the four tools a coding session needs:+ `exec_command`, `write_stdin`, `request_user_input` and `view_image`.+- With its defaults, Codex also opened connections to `chatgpt.com`,+ `ab.chatgpt.com`, `github.com` and `api.github.com`, seen through a recording+ proxy. With `plugins = false` and `analytics.enabled = false` it opened none+ but SIE's.+- Codex passes its environment to the commands the model runs, and+ `SIE_API_KEY` went with it. `shell_environment_policy.exclude` keeps the key+ out of those commands; Codex itself still sends it.+- Codex ends a stream that sends no event for `stream_idle_timeout_ms`, 300+ seconds by default, and sends the request again. SIE keeps the model's+ reasoning private on `/v1/responses`, so a model that thinks for minutes+ streams nothing until it answers. SSE comment lines, such as the keep-alive+ `sie-server` sends every 15 seconds, did not reset Codex's timer in a stub+ run. The recipe allows 30 minutes, like the Claude Code example's+ `API_TIMEOUT_MS`.+- Codex sends no output cap, so the chat route's default for the model+ applies. On `sie-server` that is the profile's `max_output_tokens`, and the+ window must hold the input and that cap: the 32K profile of+ `Qwen/Qwen3.5-4B` refused 28,800 input tokens and answered 28,500. Codex+ compacts at about 90% of `model_context_window` by default (the stub run+ above), past that point, and in a live run it had not compacted at 28,590+ tokens when its next request was refused.+ `model_auto_compact_token_limit` is the total that triggers compaction. The+ recipes set it to three quarters of the window, or lower when the output cap+ is large, so that an eighth of the window is left between it and the input+ limit, the window less the cap: 81,920 for the cloud model's 131,072-token+ window and 32,768-token cap, 24,576 for the laptop profile. In a stub run+ with a limit of 2,000, Codex compacted after a turn that reported 3,010+ tokens.++## What Codex puts on the wire++Recorded on 2026-11-24 with Codex CLI 0.167.0, run headless (`codex exec`)+against a local stub that answered scripted Responses streams. No model was+called. The scrubbed requests are in+[`conformance/openai_responses/codex_requests.json`](../../conformance/openai_responses/codex_requests.json),+and the gateway's and `sie-server`'s tests translate every one of them.++- Every request goes to `POST /v1/responses` with `stream: true`,+ `store: false`, `include: ["reasoning.encrypted_content"]`,+ `reasoning: {"summary": "auto"}`, `tool_choice: "auto"`,+ `parallel_tool_calls: true`, a `prompt_cache_key` and `client_metadata`.+ SIE accepts all of them. `prompt_cache_key` goes on to the chat route; the+ rest have no effect. No `max_output_tokens` and no `temperature` are sent.+- Codex's instructions arrive as `developer` messages at the head of `input`,+ then a user message with the environment, then the task. SIE joins the+ leading `developer` messages into one system message.+- Each turn sends the whole conversation again: the `function_call` and+ `function_call_output` items, with Codex's ids, which SIE ignores. Codex+ sends no `previous_response_id`, which SIE refuses because it stores no+ responses.+- `view_image` returns the image as an `input_image` part with a base64+ `data:` URL inside the `function_call_output`. SIE moves it into a user+ message after the tool message. A model without image input refuses that+ with a 400, and Codex ends the turn on a 400.+- Codex retried a `503` while the fake engine's model loaded, with no event in+ its output. A dropped stream comes back as an `error` event+ `Reconnecting... n/m (...)` before the retry.+- Without `< /dev/null`, `codex exec` waits to read more of the prompt from+ standard input.+- With `--sandbox workspace-write`, the model's commands run without network+ and can write only in the working directory and the temporary directory.+ So `uv run pytest` there needs an environment synced beforehand and a uv+ cache inside the working directory, and the gate prepares both. The+ commands run in a login shell, so they use the `uv` your login shell finds.+ On macOS, Homebrew's uv 0.8.24 panicked inside the sandbox; uv 0.5.31 and+ 0.12.10 ran there.+- On Linux the sandbox is bubblewrap, which gives the commands a network+ namespace of their own. In a container whose kernel is gVisor that fails:+ every command exits 1 with `bwrap: loopback: Failed RTM_NEWADDR: No child+ process`. Adding `[sandbox_workspace_write]` with `network_access = true` to+ the config leaves the namespace out, so the commands run with network;+ writes outside the working directory were still refused.++To check another Codex version, change the version in the recipe, run+`codex exec --json --skip-git-repo-check --sandbox workspace-write "<task>" < /dev/null`+with `SIE_BASE_URL` pointing at a server that records each request body and+answers with a Responses stream, and compare the requests with+`codex_requests.json`: the tool types, the top-level fields and the input+items. Then run the conformance check and the gate.++## What the Responses conformance check checks++| Case | Passes when |+|---|---|+| `plain_answer` | a streamed one-word answer ends `completed` with `output_text` and usage carrying `input_tokens` and `output_tokens` |+| `function_call` | with Codex's fields and a developer message, a `function_call` item opens with a `call_id` and the name `get_weather`, its argument deltas join into a JSON object with `city`, its `output_item.done` carries the same `call_id`, name and arguments, the terminal response's `output` the same name and arguments, and the response ends `completed` |+| `tool_output_round_trip` | after the `function_call` and a `function_call_output` of 18 degrees, as Codex sends them, the answer carries 18, no further call, `completed` |+| `image_in_tool_output` | a `view_image` call whose output is an `input_image` `data:` URL, as Codex sends it, is answered with text, no further call, `completed`. A refusal saying the model `does not support image input` is recorded; any other refusal fails |+| `buffered_response` | a non-streamed request returns an `object: "response"` that is `completed`, with `output_text` and usage |+| `hosted_tool_refusal` | a `web_search` tool beside a function tool is refused with a 400 at `tools[1].type`, the refusal Codex prints with its default tools |+| `previous_response_id_refusal` | `previous_response_id` is refused with a 400 at that field |+| `event_order` | every stream starts with `response.created` and `response.in_progress`, numbers its events from 0 without a gap, carries each event's name as its `type`, opens one item at a time at the next `output_index`, sends each item's events with its id and `output_index` while it is open, and ends with one terminal event that closes every item, or with `response.failed` |++Busy refusals are retried as in the chat check: a `429` or `503` whose code+is `QUEUE_FULL`, `RESOURCE_EXHAUSTED` or `rate_limit_exceeded`, or a+`response.failed` with one of those codes before any output, with the+`Retry-After` wait, at most 4 times and 3 minutes. A model still loading is+waited for first, up to 15 minutes.++## What result to expect++### The gate against a recording stub, recorded++`run_gate.sh` with an installed Codex CLI 0.167.0 behind a stand-in for+`npx -y @openai/[email protected]`, and a stub on `SIE_BASE_URL` that plays a+model that reads the module,+prints `SIE_API_KEY`, rewrites the module and runs the tests, on macOS,+2026-11-24. The test command was sent as a non-login shell, so it used the+`uv` the gate ran with. Codex's JSON event lines are left out:++```+== before: the seeded tests+FAILED tests/test_amounts.py::test_credit_in_parentheses_is_negative - decima...+FAILED tests/test_amounts.py::test_total_nets_credits - decimal.InvalidOperat...+2 failed, 1 passed in 0.02s+== the worked copy's environment, for the tests Codex runs in its sandbox+== codex run, recipe cloud, up to 1800 s+Reading additional input from stdin...+== the run+{+ "commands": 4,+ "items": [+ "error",+ "command_execution",+ "command_execution",+ "command_execution",+ "command_execution",+ "agent_message"+ ],+ "usage": {+ "input_tokens": 500,+ "cached_input_tokens": 0,+ "output_tokens": 50+ },+ "reconnects": 0,+ "warnings": [+ "Model metadata for `zai-org/GLM-5.3-Flash:relay` not found. Defaulting to fallback metadata; this can degrade performance and cause issues."+ ],+ "unreadable_lines": 0,+ "problems": []+}+== after: the seeded tests must be untouched+== after: pytest in a fresh environment, pinned to the seeded config and tests+... [100%]+3 passed in 0.01s+GATE PASS (.../run-output/gate-20261124T141421Z-p8VUOB)+```++The `printenv SIE_API_KEY` command printed `SIE_API_KEY is not set`, every+request arrived with the key as a bearer token and declared only the four+function tools, and a recording proxy set as Codex's `HTTPS_PROXY` saw no+connection. The `uv run+pytest -q` the stub asked for ran in the sandbox and reported `3 passed`. This+checks the plumbing only: the recipe, the pinned Codex, the sandbox and the+verdict. It says nothing about a model.++### Codex against `sie-server` on the fake engine, recorded++`sie-server` from this repository with the fake bundle on the CPU (`mise run+serve -- -b fake --device cpu`), then `./run_gate.sh laptop` with+`SIE_BASE_URL=http://127.0.0.1:18900`, `SIE_MODEL=sie-fake:chat` and+`SIE_CONTEXT_TOKENS=131072`, the same day. The fake answers from a script: with+tools declared it calls the first one, `exec_command`, passing the last user+message, the task text, as the command. After the command's output it answers+`Tool result: ` and that output.++The first request was answered `503` while the model loaded, and Codex sent+it again. Every later request was answered `200`. The run finished cleanly in+one command, with 8,957 input tokens over two requests, and the gate then+failed on the seeded tests, 2 failed and 1 passed, because the fake changes+nothing. This is how Codex's real requests fare on SIE's translation and chat+route, not a model.++The conformance check against the same server:++```+ plain_answer pass status=completed after 'tok_b0437c31 tok_5aaf6099 tok_f3b6ad77 t'; usage {'input_tokens': 7, 'input_tokens_details': {'cached_tokens': 0}, 'output_tokens': 40, 'output_tokens_details': {'reasoning_tokens': 0}, 'total_tokens': 47}+ function_call pass 1 function_call: get_weather({"city": "What is the weather in Paris right now? Use the get_weather tool."}); 13 arguments deltas; status=completed+ tool_output_round_trip pass final answer used the tool output: 'Tool result: {"city": "Paris", "temperature_c": 18, "conditions": "overcast"}'+ image_in_tool_output recorded the model takes no image input: 400 unsupported_field: Model 'sie-fake:chat' does not support image input+ buffered_response pass status=completed, usage {'input_tokens': 7, 'input_tokens_details': {'cached_tokens': 0}, 'output_tokens': 40, 'output_tokens_details': {'reasoning_tokens': 0}, 'total_tokens': 47}+ hosted_tool_refusal pass 400 unsupported_field: tools[1].type: 'web_search' tools are not supported; send function or custom tools+ previous_response_id_refusal pass 400 unsupported_field: previous_response_id: SIE does not store responses; send the full conversation in input+ event_order pass 3 streams: created, in_progress, one item at a time, sequence numbers from 0, one terminal event last++7 pass, 0 fail, 1 recorded+```++The fake takes no image input, so the image is refused by the chat route and+recorded.++### Codex against `sie-server` on a GPU, recorded++`sie-server` from this branch with the `sglang` bundle (SGLang 0.5.10.post1),+serving `Qwen/Qwen3.5-4B:long-context` on one A100 80GB in a Linux container+whose kernel is gVisor, 2026-11-24. The bundle's `flashinfer-jit-cache` pin was+left out, which moves FlashInfer's kernel compile into the model load and+changes nothing on the wire. Then `./run_gate.sh laptop` and the conformance+check, from the same container.++- **The gate as written failed on the sandbox.** Every command Codex ran+ exited with the bubblewrap error above. The model tried again for 223+ requests while its input grew to 28,590 tokens, the next request was+ refused because the input and the 4,096-token output cap no longer fit the+ 32K window, and the turn failed with the tests untouched.+- **With `network_access = true` the gate passed 3 times out of 3.** Each run+ was one turn of 6 or 7 requests and 15 to 16 seconds, with 4 or 5 commands,+ 43,010 to 50,834 input tokens and no reconnects. Each made the same+ three-line fix to the module, and the seeded tests passed in a fresh+ environment.+- **The model also called `apply_patch`**, a tool these requests did not+ declare. SIE passes a call through as the model makes it, Codex answered it+ as an unsupported call, and the model wrote the file with a shell command+ instead.+- **The conformance check passed every case.** This model reads images, so+ `image_in_tool_output` was answered rather than recorded:++```+8 pass, 0 fail, 0 recorded+```++### Checked in this repository++- The gateway's and `sie-server`'s tests replay the shared vectors in+ `conformance/openai_responses/` (request translation, buffered answer,+ event sequence, error mapping) and translate or refuse every captured Codex+ request as its vector says.+- The OpenCode example's `tests/test_fake_engine.py` runs+ `conformance.py --api responses` against this repository's `sie-server` on+ the fake engine and asserts the table above.+- The OpenCode example's `tests/test_responses_conformance.py` checks the+ `--api responses` checker against a scripted Responses stub that plays a+ conforming stream, then breaks one thing per test: an accepted hosted tool,+ a refusal at another field, an image request refused for another reason, a+ further `view_image` call instead of an answer, a done item whose+ `call_id`, name or arguments differ from the streamed call, a terminal+ output whose name or arguments differ, a buffered answer that is not an+ object, a gap in the sequence numbers, busy refusals and a loading model.+- `tests/test_run_gate.py` runs `run_gate.sh` with a scripted stand-in for+ `npx`: a real fix, no change, a failed run, a failed turn, an error event,+ no input tokens, no command, no turn completed, edited tests, an added+ `conftest.py`, a run past its deadline, the three recipes, the config each writes, and the arguments and+ environment Codex is started with. It also sources a recipe the way a user+ does and checks that it writes its own `CODEX_HOME` and runs the pinned+ Codex.++```sh+uv run pytest+```++## What this does NOT establish++- **Not supported or endorsed by OpenAI.** OpenAI does not endorse models+ other than its own behind Codex. A Codex release can change what it sends,+ which is why the recipe pins 0.167.0. The capture above is how to re-check a+ new version.+- **One live model.** The gate and the conformance check ran against+ `sie-server` serving one 4B model on a GPU. Neither SIE Cloud nor a cluster+ has run them.+- **Not a coding benchmark.** The fixture is two failing tests in a+ twenty-line module.+- **Compaction seen only against a stub.** Codex 0.167.0 compacts with an+ ordinary `POST /v1/responses` request without tools, which SIE serves. That+ was checked with a 6,000-token window against a stub, not in a long live+ session.+- **Images need a model that reads them.** On a model without image input, a+ `view_image` call is refused, and Codex ends the turn.+- **Two sandboxes.** The stub runs used Codex's macOS sandbox. The live run+ used its Linux sandbox under gVisor, with network allowed. The Linux sandbox+ without network has not run the gate.diff --git a/examples/coding-agent-codex/gate_verdict.py b/examples/coding-agent-codex/gate_verdict.pynew file mode 100644index 000000000..2d2179c56--- /dev/null+++ b/examples/coding-agent-codex/gate_verdict.py@@ -0,0 +1,86 @@+"""Judge a headless Codex run from its ``codex exec --json`` events.++ python gate_verdict.py run-output/gate-.../codex-events.jsonl++The run passes when Codex completed its turn with no failed turn and no error+event, ran at least ``MIN_COMMANDS`` commands, and read a non-zero input token+count from the endpoint's usage. A dropped stream that Codex retries is an+error event whose message starts with ``Reconnecting...``; those are counted,+not failed. Items of type ``error``, such as the warning that Codex has no+metadata for the model, are warnings. Prints a JSON summary of the run either+way.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path+from typing import Any++MIN_COMMANDS = 1+RECONNECTING = "Reconnecting..."+++def _events(lines: list[str]) -> tuple[list[dict[str, Any]], int]:+ events: list[dict[str, Any]] = []+ unreadable = 0+ for line in lines:+ line = line.strip()+ if not line:+ continue+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ unreadable += 1+ continue+ if isinstance(event, dict):+ events.append(event)+ return events, unreadable+++def judge(lines: list[str]) -> tuple[bool, dict[str, Any]]:+ events, unreadable = _events(lines)+ completed = [event for event in events if event.get("type") == "turn.completed"]+ failed = [event for event in events if event.get("type") == "turn.failed"]+ errors = [str(event.get("message")) for event in events if event.get("type") == "error"]+ reconnects = [message for message in errors if message.startswith(RECONNECTING)]+ others = [message for message in errors if not message.startswith(RECONNECTING)]+ items = [event.get("item") or {} for event in events if event.get("type") == "item.completed"]+ commands = [item for item in items if item.get("type") == "command_execution"]+ usage = (completed[-1].get("usage") if completed else None) or {}+ problems = []+ if failed:+ problems.append(f"the turn failed: {str((failed[-1].get('error') or {}).get('message'))[:200]}")+ elif others:+ problems.append(f"{len(others)} error event(s): {others[0][:200]}")+ if not completed:+ problems.append("no turn.completed event")+ else:+ if len(commands) < MIN_COMMANDS:+ problems.append(f"{len(commands)} commands run, fewer than {MIN_COMMANDS}")+ if not usage.get("input_tokens"):+ problems.append("Codex read no input tokens from the endpoint's usage")+ summary = {+ "commands": len(commands),+ "items": [item.get("type") for item in items],+ "usage": {key: usage.get(key) for key in ("input_tokens", "cached_input_tokens", "output_tokens")},+ "reconnects": len(reconnects),+ "warnings": [str(item.get("message"))[:200] for item in items if item.get("type") == "error"],+ "unreadable_lines": unreadable,+ "problems": problems,+ }+ return not problems, summary+++def main() -> int:+ if len(sys.argv) != 2:+ print(__doc__, file=sys.stderr)+ return 2+ passed, summary = judge(Path(sys.argv[1]).read_text(encoding="utf-8").splitlines())+ print(json.dumps(summary, indent=2))+ return 0 if passed else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/examples/coding-agent-codex/pyproject.toml b/examples/coding-agent-codex/pyproject.tomlnew file mode 100644index 000000000..7e3abd896--- /dev/null+++ b/examples/coding-agent-codex/pyproject.toml@@ -0,0 +1,23 @@+[project]+name = "superlinked-sie-coding-agent-codex-example"+version = "0.1.0"+description = "Codex CLI recipes and a seeded gate for SIE's OpenAI Responses endpoint"+requires-python = ">=3.12,<3.13"+dependencies = []++[tool.uv]+package = false++[dependency-groups]+dev = [+ "pytest>=8",+ "ruff>=0.14",+]++[tool.pytest.ini_options]+testpaths = ["tests"]+pythonpath = ["."]++[tool.ruff]+line-length = 120+target-version = "py312"diff --git a/examples/coding-agent-codex/recipes/cloud.sh b/examples/coding-agent-codex/recipes/cloud.shnew file mode 100644index 000000000..d029631c8--- /dev/null+++ b/examples/coding-agent-codex/recipes/cloud.sh@@ -0,0 +1,28 @@+export CODEX_HOME="${SIE_CODEX_HOME:-$HOME/.codex-sie}"+mkdir -p "$CODEX_HOME"+cat > "$CODEX_HOME/config.toml" <<TOML+model = "zai-org/GLM-5.3-Flash:relay"+model_provider = "sie"+model_context_window = 131072+model_auto_compact_token_limit = 81920+web_search = "disabled"++[features]+multi_agent = false+goals = false+plugins = false++[analytics]+enabled = false++[shell_environment_policy]+exclude = ["SIE_API_KEY"]++[model_providers.sie]+name = "SIE"+base_url = "$SIE_BASE_URL/v1"+env_key = "SIE_API_KEY"+wire_api = "responses"+stream_idle_timeout_ms = 1800000+TOML+codex() { npx -y @openai/[email protected] "$@"; }diff --git a/examples/coding-agent-codex/recipes/cluster.sh b/examples/coding-agent-codex/recipes/cluster.shnew file mode 100644index 000000000..7901e69fe--- /dev/null+++ b/examples/coding-agent-codex/recipes/cluster.sh@@ -0,0 +1,28 @@+export CODEX_HOME="${SIE_CODEX_HOME:-$HOME/.codex-sie}"+mkdir -p "$CODEX_HOME"+cat > "$CODEX_HOME/config.toml" <<TOML+model = "$SIE_MODEL"+model_provider = "sie"+model_context_window = $SIE_CONTEXT_TOKENS+model_auto_compact_token_limit = $(( SIE_CONTEXT_TOKENS * 3 / 4 < SIE_CONTEXT_TOKENS * 7 / 8 - SIE_OUTPUT_TOKENS ? SIE_CONTEXT_TOKENS * 3 / 4 : SIE_CONTEXT_TOKENS * 7 / 8 - SIE_OUTPUT_TOKENS ))+web_search = "disabled"++[features]+multi_agent = false+goals = false+plugins = false++[analytics]+enabled = false++[shell_environment_policy]+exclude = ["SIE_API_KEY"]++[model_providers.sie]+name = "SIE"+base_url = "$SIE_BASE_URL/v1"+env_key = "SIE_API_KEY"+wire_api = "responses"+stream_idle_timeout_ms = 1800000+TOML+codex() { npx -y @openai/[email protected] "$@"; }diff --git a/examples/coding-agent-codex/recipes/laptop.sh b/examples/coding-agent-codex/recipes/laptop.shnew file mode 100644index 000000000..a5f18b141--- /dev/null+++ b/examples/coding-agent-codex/recipes/laptop.sh@@ -0,0 +1,32 @@+export SIE_BASE_URL="${SIE_BASE_URL:-http://localhost:8080}"+export SIE_API_KEY="${SIE_API_KEY:-local}"+export SIE_CONTEXT_TOKENS="${SIE_CONTEXT_TOKENS:-32768}"+export SIE_OUTPUT_TOKENS="${SIE_OUTPUT_TOKENS:-4096}"+export CODEX_HOME="${SIE_CODEX_HOME:-$HOME/.codex-sie}"+mkdir -p "$CODEX_HOME"+cat > "$CODEX_HOME/config.toml" <<TOML+model = "${SIE_MODEL:-Qwen/Qwen3.5-4B:long-context}"+model_provider = "sie"+model_context_window = $SIE_CONTEXT_TOKENS+model_auto_compact_token_limit = $(( SIE_CONTEXT_TOKENS * 3 / 4 < SIE_CONTEXT_TOKENS * 7 / 8 - SIE_OUTPUT_TOKENS ? SIE_CONTEXT_TOKENS * 3 / 4 : SIE_CONTEXT_TOKENS * 7 / 8 - SIE_OUTPUT_TOKENS ))+web_search = "disabled"++[features]+multi_agent = false+goals = false+plugins = false++[analytics]+enabled = false++[shell_environment_policy]+exclude = ["SIE_API_KEY"]++[model_providers.sie]+name = "SIE"+base_url = "$SIE_BASE_URL/v1"+env_key = "SIE_API_KEY"+wire_api = "responses"+stream_idle_timeout_ms = 1800000+TOML+codex() { npx -y @openai/[email protected] "$@"; }diff --git a/examples/coding-agent-codex/run_gate.sh b/examples/coding-agent-codex/run_gate.shnew file mode 100755index 000000000..0f525df92--- /dev/null+++ b/examples/coding-agent-codex/run_gate.sh@@ -0,0 +1,135 @@+#!/usr/bin/env bash+# Seeded gate: Codex CLI works the shared fixture headless through SIE's /v1/responses,+# then pytest judges it.+#+# SIE_BASE_URL=https://... SIE_API_KEY=sk-sie-... ./run_gate.sh # SIE Cloud (recipes/cloud.sh)+# SIE_BASE_URL=https://... SIE_API_KEY=... SIE_MODEL=... SIE_CONTEXT_TOKENS=... \+# SIE_OUTPUT_TOKENS=... ./run_gate.sh cluster # your gateway (recipes/cluster.sh)+# ./run_gate.sh laptop # sie-server on this machine (recipes/laptop.sh)+#+# Needs npx and uv on PATH. The recipe runs Codex CLI 0.167.0 through npx. The fixture is the+# OpenCode example's, unchanged. Writes run-output/gate-<timestamp>-<suffix>/ with the worked+# copy of the fixture, Codex's config and JSON events, a summary of the run and the pytest+# verdict.+#+# Codex runs with its own CODEX_HOME in the run directory, so no user config, profile or+# session takes part. Its commands run in the workspace-write sandbox, which allows no network+# and writes only in the worked copy and the temporary directory, so the worked copy's+# environment is synced before the run and uv's cache for the run is inside it. A run still+# going after GATE_DEADLINE_SECONDS (default 1800) is stopped and fails.+set -euo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+FIXTURE="$HERE/../coding-agent-opencode/fixture"+RECIPE="${1:-cloud}"+ENV_FILE="$HERE/recipes/$RECIPE.sh"+if [[ ! -f "$ENV_FILE" ]]; then+ echo "unknown recipe '$RECIPE'; pick cloud, cluster or laptop" >&2+ exit 2+fi+for tool in npx uv; do+ if ! command -v "$tool" >/dev/null; then+ echo "$tool is not on PATH" >&2+ exit 2+ fi+done+GATE_DEADLINE_SECONDS="${GATE_DEADLINE_SECONDS:-1800}"+if [[ ! "$GATE_DEADLINE_SECONDS" =~ ^[1-9][0-9]*$ ]]; then+ echo "GATE_DEADLINE_SECONDS must be a positive whole number" >&2+ exit 2+fi+case "$RECIPE" in+ cloud) REQUIRED=(SIE_BASE_URL SIE_API_KEY) ;;+ cluster) REQUIRED=(SIE_BASE_URL SIE_API_KEY SIE_MODEL SIE_CONTEXT_TOKENS SIE_OUTPUT_TOKENS) ;;+ *) REQUIRED=() ;;+esac+for var in ${REQUIRED[@]+"${REQUIRED[@]}"}; do+ if [[ -z "${!var:-}" ]]; then+ echo "$var is not set" >&2+ exit 2+ fi+done++mkdir -p "$HERE/run-output"+OUT="$(mktemp -d "$HERE/run-output/gate-$(date -u +%Y%m%dT%H%M%SZ)-XXXXXX")"+WORK="$OUT/fixture"+cp -R "$FIXTURE" "$WORK"+rm -rf "$WORK/.venv" "$WORK/uv.lock"+git -C "$WORK" init -q+TASK="$(cat "$WORK/README.md")"++seeded_tests() {+ (cd "$WORK" && unset PYTEST_ADDOPTS PYTEST_PLUGINS && uv tool run --quiet --isolated --no-config --python 3.12 --from 'pytest>=8' pytest -q -c pyproject.toml tests)+}++echo "== before: the seeded tests"+seeded_tests 2>&1 | tail -n 3 || true++echo "== the worked copy's environment, for the tests Codex runs in its sandbox"+(cd "$WORK" && unset VIRTUAL_ENV && UV_LINK_MODE=copy uv sync --quiet --python 3.12)++echo "== codex run, recipe $RECIPE, up to $GATE_DEADLINE_SECONDS s"+set -m+{+ (+ cd "$WORK"+ export SIE_CODEX_HOME="$OUT/codex-home"+ source "$ENV_FILE"+ export UV_CACHE_DIR="$WORK/.uv-cache"+ codex exec --json --skip-git-repo-check --sandbox workspace-write "$TASK" </dev/null+ ) | tee "$OUT/codex-events.jsonl"+} &+RUN=$!+{+ sleep "$GATE_DEADLINE_SECONDS"+ touch "$OUT/deadline-passed"+ kill -TERM -- "-$RUN"+ for _ in 1 2 3 4 5 6 7 8 9 10; do+ sleep 1+ kill -0 -- "-$RUN" || exit 0+ done+ kill -KILL -- "-$RUN"+} >/dev/null 2>&1 &+WATCHDOG=$!+set +m+trap 'kill -- "-$RUN" "-$WATCHDOG" 2>/dev/null || true' EXIT+trap 'exit 130' INT+trap 'exit 143' TERM+CODEX_STATUS=0+wait "$RUN" || CODEX_STATUS=$?+[[ -e "$OUT/deadline-passed" ]] || kill -- "-$WATCHDOG" 2>/dev/null || true+wait "$WATCHDOG" 2>/dev/null || true+trap - EXIT INT TERM+if [[ -e "$OUT/deadline-passed" ]]; then+ echo "GATE FAIL: codex run passed its ${GATE_DEADLINE_SECONDS}s deadline and was stopped ($OUT)"+ exit 1+fi+if [[ "$CODEX_STATUS" -ne 0 ]]; then+ echo "GATE FAIL: codex run exited $CODEX_STATUS ($OUT)"+ exit 1+fi++echo "== the run"+if ! uv run --quiet --no-project --python 3.12 python "$HERE/gate_verdict.py" "$OUT/codex-events.jsonl" | tee "$OUT/run-summary.json"; then+ echo "GATE FAIL: the Codex run did not finish cleanly ($OUT)"+ exit 1+fi++echo "== after: the seeded tests must be untouched"+if ! diff -r -x __pycache__ "$FIXTURE/tests" "$WORK/tests" || ! diff "$FIXTURE/pyproject.toml" "$WORK/pyproject.toml"; then+ echo "GATE FAIL: the tests or pyproject.toml were changed ($OUT)"+ exit 1+fi+ADDED_CONFTEST="$(find "$WORK" -name conftest.py -not -path '*/.venv/*' -not -path '*/.uv-cache/*' -print -quit)"+if [[ -n "$ADDED_CONFTEST" ]]; then+ echo "GATE FAIL: a conftest.py was added ($OUT)"+ exit 1+fi++echo "== after: pytest in a fresh environment, pinned to the seeded config and tests"+if seeded_tests 2>&1 | tee "$OUT/pytest.txt"; then+ echo "GATE PASS ($OUT)"+else+ echo "GATE FAIL ($OUT)"+ exit 1+fidiff --git a/examples/coding-agent-codex/tests/test_run_gate.py b/examples/coding-agent-codex/tests/test_run_gate.pynew file mode 100644index 000000000..dd0bd055b--- /dev/null+++ b/examples/coding-agent-codex/tests/test_run_gate.py@@ -0,0 +1,310 @@+"""run_gate.sh end to end, with a scripted stand-in for ``npx`` on PATH.++Everything but the agent is real: the script copies the shared fixture, syncs+its environment, sources the recipe, which writes Codex's config and runs Codex+through ``npx``, runs the seeded tests before and after, judges the JSON+events, checks the tests were left alone and prints the verdict. Each stand-in+plays one kind of Codex run.+"""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import tomllib+from pathlib import Path+from typing import Any++import pytest++import gate_verdict++EXAMPLE = Path(__file__).resolve().parents[1]+FIXTURE = EXAMPLE.parent / "coding-agent-opencode" / "fixture"+PINNED = ["-y", "@openai/[email protected]"]+METADATA_WARNING = (+ "Model metadata for `m` not found. Defaulting to fallback metadata; this can degrade performance and cause issues."+)++FIXED_AMOUNTS = """+from decimal import Decimal+++def parse_amount(text: str) -> Decimal:+ cleaned = text.strip()+ negative = cleaned.startswith("(") and cleaned.endswith(")")+ value = Decimal(cleaned.strip("()").replace("$", "").replace(",", ""))+ return -value if negative else value+++def total(cells: list[str]) -> Decimal:+ return sum((parse_amount(cell) for cell in cells), Decimal(0))+"""++FIX = f"cat > invoice_totals/amounts.py <<'PY'\n{FIXED_AMOUNTS}\nPY"+++def _command(n: int) -> dict[str, Any]:+ item = {"id": f"item_{n}", "type": "command_execution", "command": "ls", "exit_code": 0, "status": "completed"}+ return {"type": "item.completed", "item": item}+++def _events(commands: int = 2, input_tokens: int = 4000, ending: str = "completed") -> str:+ lines: list[dict[str, Any]] = [+ {"type": "thread.started", "thread_id": "thread"},+ {"type": "item.completed", "item": {"id": "item_0", "type": "error", "message": METADATA_WARNING}},+ {"type": "turn.started"},+ *[_command(n + 1) for n in range(commands)],+ {"type": "item.completed", "item": {"id": "item_9", "type": "agent_message", "text": "Done."}},+ ]+ if ending == "completed":+ usage = {"input_tokens": input_tokens, "cached_input_tokens": 0, "output_tokens": 40}+ lines.append({"type": "turn.completed", "usage": usage})+ elif ending == "failed":+ message = '{"error": {"message": "tools[4].type: \'namespace\' tools are not supported"}}'+ lines += [{"type": "error", "message": message}, {"type": "turn.failed", "error": {"message": message}}]+ elif ending == "error":+ lines += [{"type": "error", "message": "unexpected status 500"}, {"type": "turn.completed", "usage": {}}]+ return "\n".join(json.dumps(line) for line in lines)+++def _stand_in(body: str) -> str:+ return f"""#!/usr/bin/env bash+set -eu+printf '%s\\n' "$@" > "$GATE_TEST_RECORD/args"+env | grep -E '^(CODEX_HOME|SIE_[A-Z_]+|UV_CACHE_DIR)=' | sort > "$GATE_TEST_RECORD/env" || true+cp "$CODEX_HOME/config.toml" "$GATE_TEST_RECORD/config.toml"+if [ -x .venv/bin/python ]; then echo synced > "$GATE_TEST_RECORD/environment"; fi+{body}+"""+++def _env(tmp_path: Path, agent: str, extra_env: dict[str, str] | None, unset: tuple[str, ...]) -> dict[str, str]:+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir(exist_ok=True)+ npx = bin_dir / "npx"+ npx.write_text(_stand_in(agent))+ npx.chmod(0o755)+ record = tmp_path / "record"+ record.mkdir(exist_ok=True)+ env = {+ key: value+ for key, value in os.environ.items()+ if not key.startswith(("CODEX_", "SIE_", "GATE_", "PYTEST_", "OPENAI_"))+ }+ env.update(+ {+ "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}",+ "SIE_BASE_URL": "https://sie.example",+ "SIE_API_KEY": "sk-test",+ "GATE_TEST_RECORD": str(record),+ **(extra_env or {}),+ }+ )+ for name in unset:+ env.pop(name, None)+ return env+++def _gate(+ tmp_path: Path,+ agent: str,+ recipe: str = "cloud",+ extra_env: dict[str, str] | None = None,+ unset: tuple[str, ...] = (),+) -> tuple[int, str, Path]:+ root = tmp_path / "examples"+ example = root / "coding-agent-codex"+ if not example.exists():+ example.mkdir(parents=True)+ for name in ("run_gate.sh", "gate_verdict.py"):+ shutil.copy(EXAMPLE / name, example)+ shutil.copytree(EXAMPLE / "recipes", example / "recipes")+ ignored = shutil.ignore_patterns(".venv", "uv.lock", "__pycache__", ".pytest_cache")+ shutil.copytree(FIXTURE, root / "coding-agent-opencode" / "fixture", ignore=ignored)+ completed = subprocess.run(+ ["bash", str(example / "run_gate.sh"), recipe],+ capture_output=True,+ text=True,+ env=_env(tmp_path, agent, extra_env, unset),+ timeout=300,+ check=False,+ )+ return completed.returncode, completed.stdout + completed.stderr, tmp_path / "record"+++def _recorded_env(record: Path) -> dict[str, str]:+ return dict(line.split("=", 1) for line in (record / "env").read_text().splitlines())+++def _recorded_config(record: Path) -> dict[str, Any]:+ return tomllib.loads((record / "config.toml").read_text())+++def test_a_fixing_run_passes_with_the_pinned_codex_and_the_recipe(tmp_path: Path) -> None:+ status, output, record = _gate(tmp_path, f"{FIX}\ncat <<'EOF'\n{_events()}\nEOF")+ assert status == 0, output+ assert "GATE PASS" in output+ args = (record / "args").read_text().split("\n")+ assert args[:7] == [*PINNED, "exec", "--json", "--skip-git-repo-check", "--sandbox", "workspace-write"]+ assert "Make the tests pass." in "\n".join(args[7:])+ config = _recorded_config(record)+ assert config["model"] == "zai-org/GLM-5.3-Flash:relay"+ assert config["model_provider"] == "sie"+ assert config["model_context_window"] == 131072+ assert config["model_auto_compact_token_limit"] == 81920+ assert config["web_search"] == "disabled"+ assert config["features"] == {"multi_agent": False, "goals": False, "plugins": False}+ assert config["analytics"] == {"enabled": False}+ assert config["shell_environment_policy"] == {"exclude": ["SIE_API_KEY"]}+ assert config["model_providers"]["sie"] == {+ "name": "SIE",+ "base_url": "https://sie.example/v1",+ "env_key": "SIE_API_KEY",+ "wire_api": "responses",+ "stream_idle_timeout_ms": 1800000,+ }+ env = _recorded_env(record)+ run = Path(env["CODEX_HOME"]).parent+ assert env["CODEX_HOME"] == str(run / "codex-home")+ assert "/run-output/gate-" in env["CODEX_HOME"]+ assert env["UV_CACHE_DIR"] == str(run / "fixture" / ".uv-cache")+ assert env["SIE_API_KEY"] == "sk-test"+ assert (record / "environment").read_text().strip() == "synced"+++def test_the_cluster_recipe_takes_the_model_and_window_from_the_environment(tmp_path: Path) -> None:+ extra = {+ "SIE_MODEL": "org/model:long",+ "SIE_CONTEXT_TOKENS": "65536",+ "SIE_OUTPUT_TOKENS": "16384",+ "SIE_BASE_URL": "http://gateway:8080",+ }+ status, output, record = _gate(tmp_path, f"{FIX}\ncat <<'EOF'\n{_events()}\nEOF", "cluster", extra)+ assert status == 0, output+ config = _recorded_config(record)+ assert config["model"] == "org/model:long"+ assert config["model_context_window"] == 65536+ assert config["model_auto_compact_token_limit"] == 40960+ assert config["model_providers"]["sie"]["base_url"] == "http://gateway:8080/v1"++[email protected]("missing", ["SIE_MODEL", "SIE_CONTEXT_TOKENS", "SIE_OUTPUT_TOKENS"])+def test_the_cluster_recipe_needs_the_model_and_window(tmp_path: Path, missing: str) -> None:+ extra = {"SIE_MODEL": "m", "SIE_CONTEXT_TOKENS": "65536", "SIE_OUTPUT_TOKENS": "8192", missing: ""}+ status, output, _ = _gate(tmp_path, "exit 0", "cluster", extra)+ assert status == 2+ assert f"{missing} is not set" in output+++def test_the_laptop_recipe_defaults_to_the_local_server_and_its_32k_profile(tmp_path: Path) -> None:+ unset = ("SIE_BASE_URL", "SIE_API_KEY")+ status, output, record = _gate(tmp_path, f"{FIX}\ncat <<'EOF'\n{_events()}\nEOF", "laptop", unset=unset)+ assert status == 0, output+ config = _recorded_config(record)+ assert config["model"] == "Qwen/Qwen3.5-4B:long-context"+ assert config["model_context_window"] == 32768+ assert config["model_auto_compact_token_limit"] == 24576+ assert config["model_providers"]["sie"]["base_url"] == "http://localhost:8080/v1"+ assert _recorded_env(record)["SIE_API_KEY"] == "local"+++def test_the_laptop_recipe_takes_the_server_key_and_model_from_the_environment(tmp_path: Path) -> None:+ extra = {+ "SIE_BASE_URL": "http://127.0.0.1:9000",+ "SIE_API_KEY": "server-token",+ "SIE_MODEL": "sie-fake:chat",+ "SIE_CONTEXT_TOKENS": "131072",+ }+ status, output, record = _gate(tmp_path, f"{FIX}\ncat <<'EOF'\n{_events()}\nEOF", "laptop", extra)+ assert status == 0, output+ config = _recorded_config(record)+ assert config["model"] == "sie-fake:chat"+ assert config["model_context_window"] == 131072+ assert config["model_auto_compact_token_limit"] == 98304+ assert config["model_providers"]["sie"]["base_url"] == "http://127.0.0.1:9000/v1"+ assert _recorded_env(record)["SIE_API_KEY"] == "server-token"+++def test_an_unknown_recipe_is_refused(tmp_path: Path) -> None:+ status, output, _ = _gate(tmp_path, "exit 0", "desktop")+ assert status == 2+ assert "unknown recipe 'desktop'; pick cloud, cluster or laptop" in output+++def test_no_change_fails_on_the_seeded_tests(tmp_path: Path) -> None:+ status, output, _ = _gate(tmp_path, f"cat <<'EOF'\n{_events()}\nEOF")+ assert status == 1+ assert output.rstrip().splitlines()[-1].startswith("GATE FAIL (")+++def test_a_failed_run_fails(tmp_path: Path) -> None:+ status, output, _ = _gate(tmp_path, "exit 3")+ assert status == 1+ assert "GATE FAIL: codex run exited 3" in output+++ ("events", "problem"),+ [+ (_events(ending="failed"), "the turn failed: "),+ (_events(ending="error"), "1 error event(s): unexpected status 500"),+ (_events(input_tokens=0), "read no input tokens"),+ (_events(commands=0), "0 commands run, fewer than 1"),+ ("", "no turn.completed event"),+ ],+)+def test_an_unclean_run_fails_before_pytest(tmp_path: Path, events: str, problem: str) -> None:+ status, output, _ = _gate(tmp_path, f"{FIX}\ncat <<'EOF'\n{events}\nEOF")+ assert status == 1+ assert "GATE FAIL: the Codex run did not finish cleanly" in output+ assert problem in output+++def test_edited_tests_fail(tmp_path: Path) -> None:+ edit = "echo 'def test_nothing(): pass' > tests/test_amounts.py"+ status, output, _ = _gate(tmp_path, f"{FIX}\n{edit}\ncat <<'EOF'\n{_events()}\nEOF")+ assert status == 1+ assert "GATE FAIL: the tests or pyproject.toml were changed" in output+++def test_an_added_conftest_fails(tmp_path: Path) -> None:+ plant = "printf 'import pytest\\n' > conftest.py"+ status, output, _ = _gate(tmp_path, f"{FIX}\n{plant}\ncat <<'EOF'\n{_events()}\nEOF")+ assert status == 1+ assert "GATE FAIL: a conftest.py was added" in output+++def test_a_run_past_its_deadline_is_stopped(tmp_path: Path) -> None:+ status, output, _ = _gate(tmp_path, "sleep 60", extra_env={"GATE_DEADLINE_SECONDS": "2"})+ assert status == 1+ assert "passed its 2s deadline" in output+++def test_the_verdict_counts_reconnects_and_keeps_warnings() -> None:+ reconnect = {"type": "error", "message": "Reconnecting... 1/5 (stream disconnected before completion)"}+ passed, summary = gate_verdict.judge([json.dumps(reconnect), *_events().splitlines(), "not json"])+ assert passed, summary+ assert summary["reconnects"] == 1+ assert summary["unreadable_lines"] == 1+ assert summary["commands"] == 2+ assert summary["items"] == ["error", "command_execution", "command_execution", "agent_message"]+ assert summary["warnings"] == [METADATA_WARNING]+ assert summary["usage"] == {"input_tokens": 4000, "cached_input_tokens": 0, "output_tokens": 40}+++def test_sourcing_a_recipe_writes_its_own_codex_home_and_runs_the_pinned_codex(tmp_path: Path) -> None:+ home = tmp_path / "home"+ home.mkdir()+ env = _env(tmp_path, "", {"HOME": str(home)}, ())+ recipe = str(EXAMPLE / "recipes" / "cloud.sh")+ command = ["bash", "-c", 'source "$1" && codex --version', "bash", recipe]+ completed = subprocess.run(command, env=env, capture_output=True, text=True, check=False)+ assert completed.returncode == 0, completed.stderr+ record = tmp_path / "record"+ assert (record / "args").read_text().split("\n")[:3] == [*PINNED, "--version"]+ assert _recorded_env(record)["CODEX_HOME"] == str(home / ".codex-sie")+ assert (home / ".codex-sie" / "config.toml").read_text() == (record / "config.toml").read_text()+ assert not (home / ".codex").exists()diff --git a/examples/coding-agent-codex/uv.lock b/examples/coding-agent-codex/uv.locknew file mode 100644index 000000000..79699812f--- /dev/null+++ b/examples/coding-agent-codex/uv.lock@@ -0,0 +1,107 @@+version = 1+requires-python = "==3.12.*"++[[package]]+name = "colorama"+version = "0.4.6"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335 },+]++[[package]]+name = "iniconfig"+version = "2.3.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552 },+]++[[package]]+name = "packaging"+version = "26.3"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956 },+]++[[package]]+name = "pluggy"+version = "1.7.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082 },+]++[[package]]+name = "pygments"+version = "2.21.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147 },+]++[[package]]+name = "pytest"+version = "9.1.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "colorama", marker = "sys_platform == 'win32'" },+ { name = "iniconfig" },+ { name = "packaging" },+ { name = "pluggy" },+ { name = "pygments" },+]+sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536 },+]++[[package]]+name = "ruff"+version = "0.17.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/f9/e7/e6d5749983b020e6cb1055abec0a6f361a8e94f0184cdcf56d4760995f02/ruff-0.17.1.tar.gz", hash = "sha256:5bb796c5112e9fb9527f2ef2faa0a130d6312d19de92bcfaddd70dbb2d41020f", size = 5323349 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/2e/78/90c46ca6250709f7c37e397b60d06061adee8d0f7d13959ed6a8e49b14fd/ruff-0.17.1-py3-none-linux_armv6l.whl", hash = "sha256:1796c41eafec66f4635125dd1e074a7aa27b8d20c187d484360acf11d247fc4a", size = 10147528 },+ { url = "https://files.pythonhosted.org/packages/aa/d2/a2e28bc35b083ae51fa07dfba5280a667c8b01ecaee7802fc8849dcd5c46/ruff-0.17.1-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:8eadb09a788010be29c895418bdfa513e4e1c65e64b94e5b19e4cd381f6cc7fb", size = 10225974 },+ { url = "https://files.pythonhosted.org/packages/8e/71/7a9029a81c8206ee01a98f6cfeeb56e6c095af86857581a37045c46d7e94/ruff-0.17.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:29b454f18ca3eeaf37fbf140841dcf27d36109e29dee9aae8acecb68c26c6f74", size = 9270361 },+ { url = "https://files.pythonhosted.org/packages/c0/8c/e075e9c917cb0575297880c96768304e881240171c870cbd8d9b7b54bec2/ruff-0.17.1-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:872e03dd231744d6c5ec5c8af6be52b71323fc6ee096e4c8b34d9f844ee3b978", size = 9938300 },+ { url = "https://files.pythonhosted.org/packages/87/27/0b4bb926a49de2383f161272b4d863571a4c7ecdbf595a6bc58813a13367/ruff-0.17.1-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4c0d6cb5f8fbac77eec9af49f4fc0eaf856b05545e372b0694d24b4e76b1c640", size = 9948464 },+ { url = "https://files.pythonhosted.org/packages/14/27/518d57e0e02aecb8ea4acac6b57b51a53173d25fa734952bfdd7d531e88e/ruff-0.17.1-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:78beced4a3c94dfedbee4b999b95b6a27b35820fdc0afbacc6d37a8da26c1cd1", size = 10638639 },+ { url = "https://files.pythonhosted.org/packages/01/82/d89a4e498ade59e6cee52d67f8da569019372212b87468c1fdeae884601c/ruff-0.17.1-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7feefc63921202894f0e158b0e32f45a5950d70a7fb693ccb9264816c25b1c05", size = 11337238 },+ { url = "https://files.pythonhosted.org/packages/a2/7c/3b0fdef9352656317c977086fe1d802902406e4f2a0d8578da90c0e6d1c5/ruff-0.17.1-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:684154861a819bf1f433669d2a0ce9c3e54677c65b8ebb866cc2a7ec86345785", size = 10896327 },+ { url = "https://files.pythonhosted.org/packages/62/86/5566290219708ce2928f3a29c4f843a1185b341ec6111c4631a33c5ceced/ruff-0.17.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a6ef98e51de8ef38082f90653ceeb84944bd7673783eea13e1647c5b9b064189", size = 10350811 },+ { url = "https://files.pythonhosted.org/packages/ad/d2/ca8462dabb3c413990d49703ba306c30c862195a75448d080fa8fcce9775/ruff-0.17.1-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:8f9aa5b5bd5fa1937803ea609c8f153b8de39bf3e0e149897ae34b0c5b52f467", size = 10569994 },+ { url = "https://files.pythonhosted.org/packages/e3/ad/dd1864c1f1db17c8cfb297ce70b352388e6977620f66f7182c52855407df/ruff-0.17.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:80e53b0e5faa3c5667f035daaa032893ae42b7cfe708c886d39ed131e54688ab", size = 10059672 },+ { url = "https://files.pythonhosted.org/packages/65/45/3f56cf1d2168c2165cdd5ac6f9668aee66a4cfdd4caf2b2cc5ccb2b1d568/ruff-0.17.1-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:056c5d5fa0ac790051ae165d7035c7bf956d02de2db557f2e9b31d877a505fca", size = 9947803 },+ { url = "https://files.pythonhosted.org/packages/aa/4b/5457cb2be4c1d1ea5e919558131a0f197a4a454a0530d9e30820e8206e4c/ruff-0.17.1-py3-none-musllinux_1_2_i686.whl", hash = "sha256:bd8f5a55b10f371642eacd0e8665a42a8b97da15c9a7187c79e697b77b5e0ce4", size = 10351807 },+ { url = "https://files.pythonhosted.org/packages/49/fb/db15b4f8fa24a1e36b99e1401f42ef6df16ee299a48670d5d262b771e7d7/ruff-0.17.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:ce05e6f3973611d9550a600e04bb531061e368baba31610eb57c1509a8f21a0a", size = 10765716 },+ { url = "https://files.pythonhosted.org/packages/0a/e8/1e186578076aff7a80735f625005fde678412ab609cd323ed182eb7d6b87/ruff-0.17.1-py3-none-win32.whl", hash = "sha256:1de0030a8aa78c65c5fecb84b2e5c390ac684c0452875a02afc7c083d49a496a", size = 9895093 },+ { url = "https://files.pythonhosted.org/packages/6a/2e/da3d9589bae8e8b58f3a48bd5bc0b980232fb14a83bf02c3be7660f87c1b/ruff-0.17.1-py3-none-win_amd64.whl", hash = "sha256:5df76f16580fab58d0f6c98a3ac254a4abceb7b2489b8b678335869cff77b3d7", size = 10097955 },+ { url = "https://files.pythonhosted.org/packages/df/c9/0f2a4dea06a5e12c1191ee3d96b1e1233797d0d5e18f97a2b909a95a9836/ruff-0.17.1-py3-none-win_arm64.whl", hash = "sha256:42400b9a6ff8515ff27796f07f92e0195be011c86e81e381606f58ea5502fef4", size = 9853542 },+]++[[package]]+name = "superlinked-sie-coding-agent-codex-example"+version = "0.1.0"+source = { virtual = "." }++[package.dev-dependencies]+dev = [+ { name = "pytest" },+ { name = "ruff" },+]++[package.metadata]++[package.metadata.requires-dev]+dev = [+ { name = "pytest", specifier = ">=8" },+ { name = "ruff", specifier = ">=0.14" },+]diff --git a/examples/coding-agent-opencode/README.md b/examples/coding-agent-opencode/README.mdindex 2f793847a..a0c767ce9 100644--- a/examples/coding-agent-opencode/README.md+++ b/examples/coding-agent-opencode/README.md@@ -53,6 +53,11 @@ surface is the right instrument.[The Claude Code example](../coding-agent-claude-code/README.md) lists itscases and runs Claude Code on this directory's fixture.+`conformance.py --api responses` checks the OpenAI Responses endpoint,+`/v1/responses`, the way Codex CLI speaks it, reading the raw event stream.+[The Codex example](../coding-agent-codex/README.md) lists its cases and runs+Codex on this directory's fixture.+## Run it### Against SIE Cloud@@ -940,7 +945,8 @@ What runs anywhere, and in this repository's CI, is the test suite:same usage without it, the long prompt's size against the window, and`max_tokens: 8` spending exactly 8 tokens. It also runs`conformance.py --api messages` against the same server, whose- `/v1/messages` translates onto that chat route, and asserts that table. It+ `/v1/messages` translates onto that chat route, and asserts that table, and+ `conformance.py --api responses` the same way through `/v1/responses`. Itneeds the repository's environment, from `mise run sync` at the root, and isskipped without it outside CI.- `tests/test_conformance.py` starts a scripted OpenAI-compatible stub that@@ -971,6 +977,13 @@ What runs anywhere, and in this repository's CI, is the test suite:`message_delta`, a delta before its block, an accepted `output_config.effort`,a system-turn refusal without the wording Claude Code resends on, busyrefusals and a loading model.+- `tests/test_responses_conformance.py` runs `conformance.py --api responses`+ against a scripted Responses stub in the same way: an accepted hosted tool,+ a refusal at another field, an image request refused for another reason, a+ further `view_image` call instead of an answer, a done item whose+ `call_id`, name or arguments differ from the streamed call, a terminal+ output whose name or arguments differ, a buffered answer that is not an+ object, a gap in the sequence numbers, busy refusals and a loading model.- `tests/test_run_gate.py` runs `run_gate.sh` with a scripted stand-in for`opencode`: a real fix, no change, a failed `opencode run`, edited tests, anenvironment planted in the worked copy, a caller's `PYTEST_ADDOPTS` or@@ -1009,8 +1022,8 @@ uv run pytest`tests/test_conformance.py`, `tests/test_session_load.py` and`tests/test_run_gate.py` check the checkers,-`tests/test_fake_engine.py` checks SIE's chat and Messages routes with a-scripted model, and `tests/test_openrouter_recipe.py` checks the OpenRouter+`tests/test_fake_engine.py` checks SIE's chat, Messages and Responses routes+with a scripted model, and `tests/test_openrouter_recipe.py` checks the OpenRouterrecipe against a scripted stand-in for OpenRouter.A model's endpoint is only checked by running `conformance.py` against it.diff --git a/examples/coding-agent-opencode/conformance.py b/examples/coding-agent-opencode/conformance.pyindex d67297923..64fc846c3 100755--- a/examples/coding-agent-opencode/conformance.py+++ b/examples/coding-agent-opencode/conformance.py@@ -23,6 +23,12 @@ that Claude Code speaks: the same agent-loop cases over ``tool_use`` and``tool_result`` blocks, plus the event grammar, the inert fields Claude Codesends and the refusal wording it recovers from. It reads the raw event streamwith ``httpx``, because the event sequence is what the client depends on.++``--api responses`` checks ``/v1/responses``, the OpenAI Responses wire that+Codex CLI speaks: a plain answer, a function tool loop sent with the fields+Codex sends, an image in a tool output, the event order, and the refusals of a+hosted tool and of ``previous_response_id``. It reads the raw event stream+with ``httpx`` as well."""from __future__ import annotations@@ -1640,6 +1646,542 @@ def run_messages(base_url: str, api_key: str, model: str) -> dict[str, Any]:}+# --- OpenAI Responses (`--api responses`) ----------------------------------++RESPONSES_TOOL = {+ "type": "function",+ "name": "get_weather",+ "description": WEATHER_TOOL["function"]["description"],+ "strict": False,+ "parameters": WEATHER_TOOL["function"]["parameters"],+}+VIEW_IMAGE_TOOL = {+ "type": "function",+ "name": "view_image",+ "description": "View a local image file from the filesystem.",+ "strict": False,+ "parameters": {+ "type": "object",+ "properties": {"path": {"type": "string", "description": "Local filesystem path to an image file."}},+ "required": ["path"],+ "additionalProperties": False,+ },+}+CODEX_FIELDS: dict[str, Any] = {+ "tool_choice": "auto",+ "parallel_tool_calls": True,+ "reasoning": {"summary": "auto"},+ "store": False,+ "include": ["reasoning.encrypted_content"],+ "prompt_cache_key": "sie-conformance",+ "client_metadata": {"session_id": "sie-conformance"},+}+DEVELOPER_MESSAGE = {+ "type": "message",+ "role": "developer",+ "content": [{"type": "input_text", "text": "You are a coding agent. Use the tools when they help."}],+}+RED_SQUARE_PNG = (+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAKklEQVR42mO4IydHU8QwasGoBaMWjFowasGoBaMWjFowa"+ "sGoBaMWDBULAJI2YD30P/0LAAAAAElFTkSuQmCC"+)+RESPONSES_TERMINAL = frozenset({"response.completed", "response.incomplete", "response.failed"})+RESPONSES_HOSTED_TOOL = {"type": "web_search"}+IMAGE_INPUT_REFUSAL = re.compile(r"does not support (image input|media messages)")+++@dataclass+class ResponsesResult(StreamResult):+ """A ``/v1/responses`` answer. ``finish_reason`` holds the response ``status``."""++ events: list[dict[str, Any]] = field(default_factory=list)+ done_items: dict[int, dict[str, Any]] = field(default_factory=dict)+ response: dict[str, Any] | None = None+ status: int | None = None++ def observed(self) -> dict[str, Any]:+ observed = super().observed()+ observed["response_status"] = observed.pop("finish_reason")+ observed.pop("usage_on_last_chunk")+ observed["status"] = self.status+ observed["events"] = len(self.events)+ observed["output"] = [item.get("type") for item in (self.response or {}).get("output") or []]+ return observed+++def _responses_error(status: int | None, body: Any, headers: httpx.Headers | None) -> dict[str, Any]:+ error = body.get("error") if isinstance(body, dict) and isinstance(body.get("error"), dict) else {}+ sie_code = headers.get("x-sie-error-code") if headers is not None else None+ retry_after = _retry_after(headers.get("retry-after")) if headers is not None else None+ return {+ "status": status,+ "code": error.get("code") or sie_code,+ "type": error.get("type"),+ "param": error.get("param"),+ "message": error.get("message") or (json.dumps(body)[:200] if body else None),+ "retry_after_s": retry_after,+ }+++def _responses_output(result: ResponsesResult, response: dict[str, Any]) -> None:+ result.response = response+ result.finish_reason = response.get("status")+ result.usage = response.get("usage")+++def _responses_event(result: ResponsesResult, name: str, data: dict[str, Any]) -> None:+ summary: dict[str, Any] = {"event": name, "type": data.get("type"), "sequence_number": data.get("sequence_number")}+ item = data.get("item") if isinstance(data.get("item"), dict) else None+ if "output_index" in data:+ summary["output_index"] = data["output_index"]+ if "item_id" in data or item is not None:+ summary["item_id"] = data["item_id"] if "item_id" in data else item.get("id")+ index = data.get("output_index", 0)+ if name == "response.output_item.added" and item is not None and item.get("type") == "function_call":+ result.tool_calls[index] = ToolCall(+ index=index,+ id=item.get("call_id"),+ name=item.get("name"),+ first_delta_complete=bool(item.get("call_id")) and bool(item.get("name")),+ )+ elif name == "response.output_item.done" and item is not None:+ result.done_items[index] = item+ elif name == "response.function_call_arguments.delta":+ call = result.tool_calls.setdefault(index, ToolCall(index=index))+ call.arguments += data.get("delta", "")+ call.deltas += 1+ elif name == "response.output_text.delta":+ result.content += data.get("delta", "")+ elif name in RESPONSES_TERMINAL:+ _responses_output(result, data.get("response") or {})+ if name == "response.failed":+ error = (data.get("response") or {}).get("error") or {}+ result.error = _responses_error(None, {"error": error}, None)+ elif name == "error":+ result.error = _responses_error(None, {"error": data}, None)+ result.events.append(summary)+++def _json_object(value: Any) -> dict[str, Any]:+ if not isinstance(value, dict):+ raise TypeError(f"expected a JSON object, got {type(value).__name__}")+ return value+++def _responses_answer(result: ResponsesResult, response: dict[str, Any]) -> None:+ _responses_output(result, response)+ for item in response.get("output") or []:+ if item.get("type") == "message":+ result.content += "".join(part.get("text", "") for part in item.get("content") or [])+ elif item.get("type") == "function_call":+ index = len(result.tool_calls)+ result.tool_calls[index] = ToolCall(+ index=index,+ id=item.get("call_id"),+ name=item.get("name"),+ arguments=item.get("arguments") or "",+ first_delta_complete=True,+ )+++def _responses_once(client: httpx.Client, body: dict[str, Any]) -> ResponsesResult:+ result = ResponsesResult()+ try:+ with client.stream("POST", "/responses", json=body) as response:+ result.status = response.status_code+ result.headers = {name: response.headers[name] for name in RECORDED_HEADERS if name in response.headers}+ if response.status_code != 200:+ response.read()+ try:+ payload = response.json()+ except ValueError:+ payload = None+ result.error = _responses_error(response.status_code, payload, response.headers)+ return result+ if not body.get("stream"):+ response.read()+ _responses_answer(result, _json_object(response.json()))+ return result+ name = ""+ for line in response.iter_lines():+ if not line:+ name = ""+ elif line.startswith("event:"):+ name = line[len("event:") :].strip()+ elif line.startswith("data:"):+ result.chunks += 1+ _responses_event(result, name, _json_object(json.loads(line[len("data:") :])))+ except (httpx.HTTPError, ValueError, TypeError, AttributeError) as exc:+ result.error = {+ "status": None,+ "code": type(exc).__name__,+ "type": None,+ "param": None,+ "message": str(exc),+ "retry_after_s": None,+ }+ return result+++@dataclass+class ResponsesSession:+ """The client for one run, and every answer it got, for the event-order check."""++ client: httpx.Client+ results: list[ResponsesResult] = field(default_factory=list)++ def send(self, body: dict[str, Any]) -> ResponsesResult:+ result = cast(ResponsesResult, _retrying(lambda: _responses_once(self.client, body)))+ self.results.append(result)+ return result+++def _responses_body(model: str, text: str, **params: Any) -> dict[str, Any]:+ params.setdefault("stream", True)+ return {"model": model, "input": text, **params}+++def _user_message(text: str) -> dict[str, Any]:+ return {"type": "message", "role": "user", "content": [{"type": "input_text", "text": text}]}+++def responses_event_problems(events: list[dict[str, Any]]) -> list[str]:+ """What breaks the Responses event order a Responses client parses."""+ if not events:+ return ["no events"]+ names = [event["event"] for event in events]+ problems = []+ if names[:2] != ["response.created", "response.in_progress"]:+ problems.append(f"starts with {names[:2]}, not response.created then response.in_progress")+ for event in events:+ if event["type"] != event["event"]:+ problems.append(f"event {event['event']} carries type {event['type']!r}")+ break+ numbers = [event["sequence_number"] for event in events]+ if numbers != list(range(len(events))):+ problems.append(f"sequence_number runs {numbers[:8]}, not 0, 1, 2 and on")+ open_item: tuple[Any, Any] | None = None+ next_index = 0+ for event in events:+ name = event["event"]+ if name == "response.output_item.added":+ if open_item is not None:+ problems.append(f"item {event.get('item_id')} added while {open_item[1]} is open")+ if event.get("output_index") != next_index:+ problems.append(f"output_index {event.get('output_index')}, expected {next_index}")+ open_item = (event.get("output_index"), event.get("item_id"))+ next_index += 1+ elif name == "response.output_item.done":+ if open_item is None or (event.get("output_index"), event.get("item_id")) != open_item:+ problems.append(f"item {event.get('item_id')} done while {open_item and open_item[1]} is open")+ open_item = None+ elif "item_id" in event and (event.get("output_index"), event["item_id"]) != open_item:+ where = f"{event['item_id']} at output_index {event.get('output_index')}"+ problems.append(f"{name} for item {where} while {open_item and open_item[1]} is open")+ terminal = [position for position, name in enumerate(names) if name in RESPONSES_TERMINAL]+ if terminal != [len(names) - 1]:+ problems.append(f"ends with {names[-1]}, not one terminal event last")+ elif names[-1] != "response.failed" and open_item is not None:+ problems.append(f"item {open_item[1]} never done")+ return problems+++def responses_case_plain_answer(session: ResponsesSession, model: str) -> Case:+ name = "plain_answer"+ result = session.send(_responses_body(model, "Reply with the single word: ready.", temperature=0))+ failed = _fail_on_error(name, result)+ if failed:+ return failed+ usage = result.usage or {}+ problems = []+ if result.finish_reason != "completed":+ problems.append(f"status is {result.finish_reason!r}, expected 'completed'")+ if not result.content.strip():+ problems.append("no output_text came back")+ missing = [key for key in ("input_tokens", "output_tokens") if not usage.get(key)]+ if missing:+ problems.append(f"usage lacks {missing}: {usage}")+ if problems:+ return Case(name, "fail", "; ".join(problems), result.observed())+ return Case(+ name, "pass", f"status=completed after {result.content.strip()[:40]!r}; usage {usage}", result.observed()+ )+++def responses_case_function_call(session: ResponsesSession, model: str) -> tuple[Case, ResponsesResult]:+ name = "function_call"+ body = {+ "model": model,+ "input": [+ DEVELOPER_MESSAGE,+ _user_message("What is the weather in Paris right now? Use the get_weather tool."),+ ],+ "tools": [RESPONSES_TOOL],+ "stream": True,+ **CODEX_FIELDS,+ }+ result = session.send(body)+ failed = _fail_on_error(name, result)+ if failed:+ return failed, result+ calls = result.calls()+ problems = []+ if not calls:+ problems.append("no function_call item came back")+ for call in calls:+ if not call.first_delta_complete:+ problems.append(f"item {call.index}: output_item.added lacks call_id or name")+ if call.name != "get_weather":+ problems.append(f"item {call.index} named {call.name!r}")+ parsed = call.parsed_arguments()+ if parsed is None:+ problems.append(f"item {call.index} arguments are not a JSON object: {call.arguments[:80]!r}")+ elif "city" not in parsed:+ problems.append(f"item {call.index} arguments lack 'city': {parsed}")+ done = result.done_items.get(call.index) or {}+ if done.get("arguments") != call.arguments:+ problems.append(f"item {call.index}: output_item.done arguments differ from the streamed ones")+ if done.get("name") != call.name:+ problems.append(f"item {call.index}: output_item.done name differs from the streamed one")+ if done.get("call_id") != call.id:+ problems.append(f"item {call.index}: output_item.done call_id differs from the streamed one")+ final = [+ item+ for item in (result.response or {}).get("output") or []+ if item.get("type") == "function_call" and item.get("call_id") == call.id+ ]+ if [(item.get("name"), item.get("arguments")) for item in final] != [(call.name, call.arguments)]:+ problems.append(f"item {call.index}: the terminal response's output differs from the streamed call")+ if result.finish_reason != "completed":+ problems.append(f"status is {result.finish_reason!r}, expected 'completed'")+ if problems:+ return Case(name, "fail", "; ".join(problems), result.observed()), result+ deltas = sum(call.deltas for call in calls)+ detail = f"{len(calls)} function_call: {_describe_calls(result)}; {deltas} arguments deltas; status=completed"+ return Case(name, "pass", detail, result.observed()), result+++def responses_case_tool_output_round_trip(session: ResponsesSession, model: str, first: ResponsesResult) -> Case:+ name = "tool_output_round_trip"+ calls = first.calls()+ if _is_busy(first.error):+ return Case(name, "capacity", "not run, function_call stayed busy", first.observed())+ if first.error or not calls:+ return Case(name, "fail", "no function_call from the function_call case to answer", first.observed())+ history: list[dict[str, Any]] = [+ {+ "type": "function_call",+ "id": f"fc_{position}",+ "status": "completed",+ "call_id": call.id,+ "name": call.name,+ "arguments": call.arguments,+ }+ for position, call in enumerate(calls)+ ]+ history += [+ {+ "type": "function_call_output",+ "id": f"fco_{position}",+ "call_id": call.id,+ "output": json.dumps({"city": "Paris", "temperature_c": 18, "conditions": "overcast"}),+ }+ for position, call in enumerate(calls)+ ]+ question = _user_message("What is the weather in Paris right now? Use the get_weather tool.")+ body = {+ "model": model,+ "input": [DEVELOPER_MESSAGE, question, *history],+ "tools": [RESPONSES_TOOL],+ "stream": True,+ "temperature": 0,+ **CODEX_FIELDS,+ }+ result = session.send(body)+ failed = _fail_on_error(name, result)+ if failed:+ return failed+ problems = []+ if result.calls():+ problems.append(f"answered with another function_call: {_describe_calls(result)}")+ if result.finish_reason != "completed":+ problems.append(f"status is {result.finish_reason!r}, expected 'completed'")+ if not result.content.strip():+ problems.append("empty final answer")+ elif "18" not in result.content:+ problems.append(f"final answer does not carry the tool's 18: {result.content[:120]!r}")+ if problems:+ return Case(name, "fail", "; ".join(problems), result.observed())+ detail = f"final answer used the tool output: {result.content.strip()[:100]!r}"+ return Case(name, "pass", detail, result.observed())+++def responses_case_image_in_tool_output(session: ResponsesSession, model: str) -> Case:+ name = "image_in_tool_output"+ call = {+ "type": "function_call",+ "id": "fc_image",+ "status": "completed",+ "call_id": "call_view_image",+ "name": "view_image",+ "arguments": json.dumps({"path": "red.png"}),+ }+ output = {+ "type": "function_call_output",+ "id": "fco_image",+ "call_id": "call_view_image",+ "output": [{"type": "input_image", "image_url": RED_SQUARE_PNG, "detail": "high"}],+ }+ question = _user_message("Look at red.png with the view_image tool, then name its colour in one word.")+ body = {+ "model": model,+ "input": [DEVELOPER_MESSAGE, question, call, output],+ "tools": [VIEW_IMAGE_TOOL],+ "stream": True,+ "temperature": 0,+ **CODEX_FIELDS,+ }+ result = session.send(body)+ observed = result.observed()+ observed["mentions_red"] = "red" in result.content.lower()+ error = result.error+ if error is not None and _is_refusal(error) and IMAGE_INPUT_REFUSAL.search(str(error.get("message") or "")):+ detail = f"the model takes no image input: {error['status']} {error['code']}: {error['message']}"+ return Case(name, "recorded", detail, observed)+ failed = _fail_on_error(name, result)+ if failed:+ failed.observed = observed+ return failed+ problems = []+ if result.calls():+ problems.append(f"answered with another function_call: {_describe_calls(result)}")+ if result.finish_reason != "completed":+ problems.append(f"status is {result.finish_reason!r}, expected 'completed'")+ if not result.content.strip():+ problems.append("no text answer to the image")+ if problems:+ return Case(name, "fail", "; ".join(problems), observed)+ return Case(name, "pass", f"image accepted and answered: {result.content.strip()[:60]!r}", observed)+++def responses_case_buffered(session: ResponsesSession, model: str) -> Case:+ name = "buffered_response"+ result = session.send(_responses_body(model, "Reply with the single word: ready.", stream=False, temperature=0))+ failed = _fail_on_error(name, result)+ if failed:+ return failed+ response = result.response or {}+ usage = result.usage or {}+ problems = []+ if response.get("object") != "response":+ problems.append(f"object is {response.get('object')!r}, expected 'response'")+ if result.finish_reason != "completed":+ problems.append(f"status is {result.finish_reason!r}, expected 'completed'")+ if not result.content.strip():+ problems.append("no output_text came back")+ if not usage.get("input_tokens") or not usage.get("output_tokens"):+ problems.append(f"usage lacks tokens: {usage}")+ if problems:+ return Case(name, "fail", "; ".join(problems), result.observed())+ return Case(name, "pass", f"status=completed, usage {usage}", result.observed())+++def _responses_refusal_case(name: str, result: ResponsesResult, param: str) -> Case:+ observed = result.observed()+ error = result.error+ if error is None:+ return Case(name, "fail", f"accepted, expected a 400 at {param}", observed)+ if _is_busy(error):+ return Case(name, "capacity", _still_busy(result), observed)+ if error["status"] != 400 or error["type"] != "invalid_request_error":+ return Case(+ name, "fail", f"answered {error['status']} {error['type']}, expected 400 invalid_request_error", observed+ )+ if error["param"] != param:+ return Case(name, "fail", f"400 at {error['param']!r}, expected {param!r}: {error['message']}", observed)+ return Case(name, "pass", f"400 {error['code']}: {error['message']}", observed)+++def responses_case_hosted_tool_refusal(session: ResponsesSession, model: str) -> Case:+ body = _responses_body(model, "Say hello.", tools=[RESPONSES_TOOL, RESPONSES_HOSTED_TOOL])+ return _responses_refusal_case("hosted_tool_refusal", session.send(body), "tools[1].type")+++def responses_case_previous_response_refusal(session: ResponsesSession, model: str) -> Case:+ body = _responses_body(model, "Say hello.", previous_response_id="resp_sie_conformance")+ return _responses_refusal_case("previous_response_id_refusal", session.send(body), "previous_response_id")+++def responses_case_event_order(results: list[ResponsesResult]) -> Case:+ name = "event_order"+ streams = [result for result in results if result.events]+ problems = {+ f"stream {position}": responses_event_problems(result.events) for position, result in enumerate(streams)+ }+ problems = {key: value for key, value in problems.items() if value}+ observed = {"streams": len(streams), "problems": problems}+ if not streams:+ return Case(name, "fail", "no stream to check", observed)+ if problems:+ first = next(iter(problems.values()))+ return Case(name, "fail", f"{len(problems)} of {len(streams)} streams break the order: {first[0]}", observed)+ detail = (+ f"{len(streams)} streams: created, in_progress, one item at a time, "+ "sequence numbers from 0, one terminal event last"+ )+ return Case(name, "pass", detail, observed)+++def wait_until_responses_served(client: httpx.Client, model: str) -> dict[str, Any]:+ started = time.monotonic()+ attempts = 0+ body = _responses_body(model, "Reply with the single word: ready.", stream=False, max_output_tokens=4)+ while True:+ attempts += 1+ result = _responses_once(client, body)+ elapsed = time.monotonic() - started+ code = str((result.error or {}).get("code") or "").upper()+ if code not in MESSAGES_WARM_UP_CODES or elapsed > WARM_UP_TIMEOUT_S:+ return {"attempts": attempts, "seconds": round(elapsed, 1), "error": result.error}+ time.sleep(WARM_UP_POLL_S)+++def run_responses(base_url: str, api_key: str, model: str) -> dict[str, Any]:+ headers = {"authorization": f"Bearer {api_key}"} if api_key else {}+ client = httpx.Client(base_url=base_url.rstrip("/"), headers=headers, timeout=REQUEST_TIMEOUT_S)+ started = datetime.now(UTC)+ entry = model_entry(base_url, api_key, model)+ warm_up = wait_until_responses_served(client, model)+ session = ResponsesSession(client)+ cases: list[Case] = []++ cases.append(responses_case_plain_answer(session, model))+ tool_case, tool_result = responses_case_function_call(session, model)+ cases.append(tool_case)+ cases.append(responses_case_tool_output_round_trip(session, model, tool_result))+ cases.append(responses_case_image_in_tool_output(session, model))+ cases.append(responses_case_buffered(session, model))+ cases.append(responses_case_hosted_tool_refusal(session, model))+ cases.append(responses_case_previous_response_refusal(session, model))+ cases.append(responses_case_event_order(session.results))+ client.close()++ statuses = ("pass", "fail", "recorded", "capacity")+ counts = {status: sum(1 for case in cases if case.status == status) for status in statuses}+ return {+ "api": "responses",+ "base_url": base_url,+ "model": model,+ "model_entry": entry,+ "started_at": started.isoformat(),+ "finished_at": datetime.now(UTC).isoformat(),+ "served_by": tool_result.headers.get("x-sie-served-by"),+ "warm_up": warm_up,+ "cases": [{**case.__dict__, "retries": _retries_in(case.observed)} for case in cases],+ "summary": counts,+ }++def main() -> int:parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)parser.add_argument(@@ -1652,13 +2194,13 @@ def main() -> int:)parser.add_argument("--api",- choices=("chat", "messages"),+ choices=("chat", "messages", "responses"),default="chat",- help="wire to check: chat completions, as OpenCode speaks it (default), or Anthropic Messages",+ help="wire to check: chat completions, as OpenCode speaks it (default), Anthropic Messages or OpenAI Responses",)args = parser.parse_args()- check = run_messages if args.api == "messages" else run+ check = {"chat": run, "messages": run_messages, "responses": run_responses}[args.api]report = check(args.base_url, args.api_key, args.model)args.report.parent.mkdir(parents=True, exist_ok=True)args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")diff --git a/examples/coding-agent-opencode/tests/test_fake_engine.py b/examples/coding-agent-opencode/tests/test_fake_engine.pyindex a0d9cacff..cc4449076 100644--- a/examples/coding-agent-opencode/tests/test_fake_engine.py+++ b/examples/coding-agent-opencode/tests/test_fake_engine.py@@ -18,6 +18,11 @@ The same server answers ``conformance.py --api messages``: ``/v1/messages``on ``sie-server`` translates each request onto the chat route above and theanswer back, so the Messages cases check that translation over the samescripted turns.++It answers ``conformance.py --api responses`` the same way: ``/v1/responses``+translates each request onto the chat route and the answer back. The fake+takes no image input, so the image in a tool output is refused by the chat+route and recorded."""from __future__ import annotations@@ -256,3 +261,69 @@ def test_the_messages_refusals_use_the_anthropic_wording(messages_report: dict[sassert cases["unknown_model"]["observed"]["error"]["type"] == "not_found_error"assert cases["count_tokens"]["observed"]["status"] == 404assert cases["count_tokens"]["observed"]["body"]["error"]["type"] == "not_found_error"++[email protected](scope="module")+def responses_report(server: str) -> dict[str, Any]:+ return conformance.run_responses(f"{server}/v1", "", MODEL)+++def test_each_responses_case_against_the_fake(responses_report: dict[str, Any]) -> None:+ statuses = {name: case["status"] for name, case in _cases(responses_report).items()}+ assert statuses == {+ "plain_answer": "pass",+ "function_call": "pass",+ "tool_output_round_trip": "pass",+ "image_in_tool_output": "recorded",+ "buffered_response": "pass",+ "hosted_tool_refusal": "pass",+ "previous_response_id_refusal": "pass",+ "event_order": "pass",+ }, responses_report["cases"]+ assert responses_report["served_by"] == "local"+ assert responses_report["warm_up"]["error"] is None+++def test_the_function_call_item_streams_the_scripted_call(responses_report: dict[str, Any]) -> None:+ observed = _cases(responses_report)["function_call"]["observed"]+ [call] = observed["tool_calls"]+ question = "What is the weather in Paris right now? Use the get_weather tool."+ assert call["first_delta_has_id_and_name"] is True+ assert json.loads(call["arguments"]) == {"city": question}+ assert observed["response_status"] == "completed"+ assert observed["output"] == ["function_call"]+++def test_the_tool_output_reaches_the_responses_answer(responses_report: dict[str, Any]) -> None:+ observed = _cases(responses_report)["tool_output_round_trip"]["observed"]+ assert observed["content"] == f"Tool result: {json.dumps(TOOL_RESULT)}"+ assert observed["output"] == ["message"]+++def test_responses_usage_is_the_chat_usage_translated(responses_report: dict[str, Any]) -> None:+ cases = _cases(responses_report)+ usage = cases["plain_answer"]["observed"]["usage"]+ assert usage["input_tokens"] > 0+ assert usage["total_tokens"] == usage["input_tokens"] + usage["output_tokens"]+ assert usage["input_tokens_details"] == {"cached_tokens": 0}+ assert usage["output_tokens_details"] == {"reasoning_tokens": 0}+ assert cases["buffered_response"]["observed"]["usage"] == usage+++def test_the_chat_route_refuses_the_image_for_a_model_without_image_input(responses_report: dict[str, Any]) -> None:+ error = _cases(responses_report)["image_in_tool_output"]["observed"]["error"]+ assert error["status"] == 400+ assert error["param"] == "messages"+ assert error["message"] == f"Model '{MODEL}' does not support image input"+++def test_the_responses_refusals_name_the_field_sent(responses_report: dict[str, Any]) -> None:+ cases = _cases(responses_report)+ hosted = cases["hosted_tool_refusal"]["observed"]["error"]+ previous = cases["previous_response_id_refusal"]["observed"]["error"]+ assert (hosted["code"], hosted["param"]) == ("unsupported_field", "tools[1].type")+ assert hosted["message"] == "tools[1].type: 'web_search' tools are not supported; send function or custom tools"+ assert (previous["code"], previous["param"]) == ("unsupported_field", "previous_response_id")+ assert previous["message"] == (+ "previous_response_id: SIE does not store responses; send the full conversation in input"+ )diff --git a/examples/coding-agent-opencode/tests/test_responses_conformance.py b/examples/coding-agent-opencode/tests/test_responses_conformance.pynew file mode 100644index 000000000..ea1943758--- /dev/null+++ b/examples/coding-agent-opencode/tests/test_responses_conformance.py@@ -0,0 +1,360 @@+"""``conformance.py --api responses`` against a scripted OpenAI Responses stub.++The stub plays the wire a conforming ``/v1/responses`` sends, events and+refusals included, and each knob breaks one thing, so every verdict is checked+both for what it accepts and for what it refuses. This checks the checker;+an endpoint is checked by running ``conformance.py --api responses`` against+it.+"""++from __future__ import annotations++import json+import threading+from collections.abc import Iterator+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import Any++import pytest++import conformance++KNOBS: dict[str, Any] = {}+++def _texts(body: dict[str, Any]) -> str:+ if isinstance(body["input"], str):+ return body["input"]+ out = []+ for item in body["input"]:+ content = item.get("content")+ if isinstance(content, list):+ out += [part.get("text", "") for part in content]+ return " ".join(out)+++def _refusal(body: dict[str, Any]) -> tuple[int, str, str, str] | None:+ if body.get("previous_response_id") is not None:+ param = KNOBS.get("previous_param", "previous_response_id")+ return 400, "unsupported_field", param, f"{param}: SIE does not store responses"+ for position, tool in enumerate(body.get("tools") or []):+ if tool["type"] != "function" and not KNOBS.get("accept_hosted"):+ param = f"tools[{position}].type"+ return 400, "unsupported_field", param, f"{param}: '{tool['type']}' tools are not supported"+ return None+++def _reply(body: dict[str, Any]) -> dict[str, Any]:+ items = body["input"] if isinstance(body["input"], list) else []+ last = items[-1] if items else {}+ if last.get("type") == "function_call_output" and isinstance(last["output"], list):+ if KNOBS.get("image_calls_again"):+ return {"call": ("view_image", {"path": "red.png"})}+ return {"text": "Red."}+ if last.get("type") == "function_call_output":+ return {"text": "It is 18 degrees and overcast in Paris."}+ if body.get("tools") and "weather" in _texts(body):+ return {"call": ("get_weather", {"city": "Paris"})}+ return {"text": "ready"}+++def _response(body: dict[str, Any], status: str, output: list[dict[str, Any]], usage: Any) -> dict[str, Any]:+ return {+ "id": "resp-stub",+ "object": "response",+ "created_at": 0,+ "model": body["model"],+ "status": status,+ "output": output,+ "usage": usage,+ }+++class Handler(BaseHTTPRequestHandler):+ def log_message(self, *args: Any) -> None:+ pass++ def _json(self, status: int, payload: Any, headers: dict[str, str] | None = None) -> None:+ raw = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("content-type", "application/json")+ self.send_header("content-length", str(len(raw)))+ for name, value in (headers or {}).items():+ self.send_header(name, value)+ self.end_headers()+ self.wfile.write(raw)++ def _error(self, status: int, code: str, param: str | None, message: str, **headers: str) -> None:+ error = {"message": message, "type": "invalid_request_error", "param": param, "code": code}+ self._json(status, {"error": error}, {name.replace("_", "-"): value for name, value in headers.items()})++ def do_GET(self) -> None:+ self._json(200, {"models": [{"name": "stub-model", "max_sequence_length": 131072}]})++ def do_POST(self) -> None:+ body = json.loads(self.rfile.read(int(self.headers["content-length"])))+ KNOBS["_posts"] = KNOBS.get("_posts", 0) + 1+ if KNOBS["_posts"] <= KNOBS.get("loading", 0):+ self._error(503, "MODEL_LOADING", None, "loading", retry_after="1")+ return+ if KNOBS.get("busy", 0) > len(KNOBS.setdefault("_busy", [])) and body.get("tools"):+ KNOBS["_busy"].append(body)+ self._error(503, "RESOURCE_EXHAUSTED", None, "busy", retry_after="0")+ return+ refusal = _refusal(body)+ if refusal:+ self._error(refusal[0], refusal[1], refusal[2], refusal[3])+ return+ items = body["input"] if isinstance(body["input"], list) else []+ if items and isinstance(items[-1].get("output"), list) and "image_refusal" in KNOBS:+ self._error(400, "unsupported_field", *KNOBS["image_refusal"])+ return+ reply = _reply(body)+ usage = {"input_tokens": 12, "output_tokens": 3, "total_tokens": 15}+ if "call" in reply:+ tool, arguments = reply["call"]+ item = {"type": "function_call", "id": "fc-0", "call_id": "call_0", "name": tool}+ output = [{**item, "arguments": json.dumps(arguments), "status": "completed"}]+ else:+ part = {"type": "output_text", "text": reply["text"], "annotations": []}+ output = [{"type": "message", "id": "msg-0", "role": "assistant", "status": "completed", "content": [part]}]+ if not body.get("stream"):+ self._json(200, [] if KNOBS.get("buffered_list") else _response(body, "completed", output, usage))+ return+ self.send_response(200)+ self.send_header("content-type", "text/event-stream")+ self.send_header("x-sie-served-by", "stub")+ self.end_headers()+ events: list[tuple[str, dict[str, Any]]] = [+ ("response.created", {"response": _response(body, "in_progress", [], None)}),+ ("response.in_progress", {"response": _response(body, "in_progress", [], None)}),+ ]+ done = output[0]+ if "call" in reply:+ ids = {"item_id": "fc-0", "output_index": 0}+ done_arguments = '{"city": "Lyon"}' if KNOBS.get("done_differs") else done["arguments"]+ done_name = "get_time" if KNOBS.get("done_name_differs") else done["name"]+ done_call_id = "call_other" if KNOBS.get("done_call_id_differs") else done["call_id"]+ events += [+ ("response.output_item.added", {"output_index": 0, "item": {**item, "arguments": ""}}),+ ("response.function_call_arguments.delta", {**ids, "delta": done["arguments"]}),+ ("response.function_call_arguments.done", {**ids, "arguments": done["arguments"]}),+ (+ "response.output_item.done",+ {+ "output_index": 0,+ "item": {**done, "call_id": done_call_id, "name": done_name, "arguments": done_arguments},+ },+ ),+ ]+ else:+ ids = {"item_id": "msg-0", "output_index": 0, "content_index": 0}+ empty = {"type": "output_text", "text": "", "annotations": []}+ events += [+ ("response.output_item.added", {"output_index": 0, "item": {**done, "content": []}}),+ ("response.content_part.added", {**ids, "part": empty}),+ ("response.output_text.delta", {**ids, "delta": reply["text"]}),+ ("response.output_text.done", {**ids, "text": reply["text"]}),+ ("response.content_part.done", {**ids, "part": done["content"][0]}),+ ("response.output_item.done", {"output_index": 0, "item": done}),+ ]+ final = output+ if "call" in reply and KNOBS.get("final_differs"):+ final = [{**output[0], "arguments": "{}"}]+ if "call" in reply and KNOBS.get("final_name_differs"):+ final = [{**output[0], "name": "get_time"}]+ events.append(("response.completed", {"response": _response(body, "completed", final, usage)}))+ for number, (name, data) in enumerate(events):+ if KNOBS.get("sequence_gap") and number >= 3:+ number += 1+ payload = {"type": name, "sequence_number": number, **data}+ self.wfile.write(f"event: {name}\ndata: {json.dumps(payload)}\n\n".encode())++[email protected](scope="module")+def base_url() -> Iterator[str]:+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_address[1]}/v1"+ finally:+ server.shutdown()++[email protected](autouse=True)+def reset_knobs(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:+ monkeypatch.setattr(conformance.time, "sleep", lambda _seconds: None)+ KNOBS.clear()+ yield+ KNOBS.clear()+++def _cases(base_url: str, **knobs: Any) -> dict[str, dict[str, Any]]:+ KNOBS.update(knobs)+ report = conformance.run_responses(base_url, "", "stub-model")+ return {case["name"]: case for case in report["cases"]}+++def test_a_conforming_endpoint_passes(base_url: str) -> None:+ cases = _cases(base_url)+ assert {name: case["status"] for name, case in cases.items()} == dict.fromkeys(cases, "pass")+ assert cases["function_call"]["observed"]["tool_calls"][0]["first_delta_has_id_and_name"]+ assert cases["image_in_tool_output"]["observed"]["mentions_red"] is True+ assert cases["event_order"]["observed"]["streams"] == 4+++def test_an_image_refused_for_a_model_without_image_input_is_recorded(base_url: str) -> None:+ refusal = ("messages", "Model 'stub-model' does not support image input")+ case = _cases(base_url, image_refusal=refusal)["image_in_tool_output"]+ assert case["status"] == "recorded"+ assert case["detail"].startswith("the model takes no image input: 400 unsupported_field")+++ "refusal",+ [+ ("input[3].output[0].type", "input[3].output[0].type: parts of type 'input_image' are not supported"),+ ("tools[0].parameters", "tools[0].parameters: invalid schema"),+ ],+)+def test_any_other_refusal_of_the_image_request_fails(base_url: str, refusal: tuple[str, str]) -> None:+ case = _cases(base_url, image_refusal=refusal)["image_in_tool_output"]+ assert case["status"] == "fail"+ assert refusal[1] in case["detail"]+++def test_another_view_image_call_is_not_an_answer_to_the_image(base_url: str) -> None:+ case = _cases(base_url, image_calls_again=True)["image_in_tool_output"]+ assert case["status"] == "fail"+ assert "answered with another function_call: view_image" in case["detail"]+ assert "no text answer to the image" in case["detail"]+++def test_an_accepted_hosted_tool_fails_the_refusal_case(base_url: str) -> None:+ case = _cases(base_url, accept_hosted=True)["hosted_tool_refusal"]+ assert case["status"] == "fail"+ assert case["detail"] == "accepted, expected a 400 at tools[1].type"+++def test_a_refusal_at_another_field_fails(base_url: str) -> None:+ case = _cases(base_url, previous_param="input")["previous_response_id_refusal"]+ assert case["status"] == "fail"+ assert "400 at 'input', expected 'previous_response_id'" in case["detail"]+++def test_done_arguments_that_differ_from_the_stream_fail(base_url: str) -> None:+ case = _cases(base_url, done_differs=True)["function_call"]+ assert case["status"] == "fail"+ assert "output_item.done arguments differ" in case["detail"]+++def test_a_done_call_id_that_differs_from_the_stream_fails(base_url: str) -> None:+ case = _cases(base_url, done_call_id_differs=True)["function_call"]+ assert case["status"] == "fail"+ assert "output_item.done call_id differs" in case["detail"]+++def test_a_terminal_output_that_differs_from_the_stream_fails(base_url: str) -> None:+ case = _cases(base_url, final_differs=True)["function_call"]+ assert case["status"] == "fail"+ assert "the terminal response's output differs from the streamed call" in case["detail"]+++def test_a_done_name_that_differs_from_the_stream_fails(base_url: str) -> None:+ case = _cases(base_url, done_name_differs=True)["function_call"]+ assert case["status"] == "fail"+ assert "output_item.done name differs" in case["detail"]+++def test_a_terminal_name_that_differs_from_the_stream_fails(base_url: str) -> None:+ case = _cases(base_url, final_name_differs=True)["function_call"]+ assert case["status"] == "fail"+ assert "the terminal response's output differs from the streamed call" in case["detail"]+++def test_a_buffered_answer_that_is_not_an_object_fails_its_case(base_url: str) -> None:+ case = _cases(base_url, buffered_list=True)["buffered_response"]+ assert case["status"] == "fail"+ assert "expected a JSON object, got list" in case["detail"]+++def test_a_gap_in_the_sequence_numbers_breaks_the_order(base_url: str) -> None:+ case = _cases(base_url, sequence_gap=True)["event_order"]+ assert case["status"] == "fail"+ assert "sequence_number runs" in case["detail"]+++def test_busy_refusals_are_retried(base_url: str) -> None:+ case = _cases(base_url, busy=2)["function_call"]+ assert case["status"] == "pass"+ assert case["retries"] == 2+++def test_the_warm_up_waits_out_a_loading_model(base_url: str) -> None:+ KNOBS.update(loading=2)+ report = conformance.run_responses(base_url, "", "stub-model")+ assert report["warm_up"]["attempts"] == 3+ assert report["summary"]["fail"] == 0+++def _event(name: str, number: int, **fields: Any) -> dict[str, Any]:+ return {"event": name, "type": name, "sequence_number": number, **fields}+++ ("events", "problem"),+ [+ ([_event("response.in_progress", 0)], "not response.created then response.in_progress"),+ (+ [+ _event("response.created", 0),+ _event("response.in_progress", 1),+ _event("response.output_text.delta", 2, output_index=0, item_id="msg-0"),+ _event("response.completed", 3),+ ],+ "response.output_text.delta for item msg-0 at output_index 0 while None is open",+ ),+ (+ [+ _event("response.created", 0),+ _event("response.in_progress", 1),+ _event("response.output_item.added", 2, output_index=0, item_id="msg-0"),+ _event("response.output_text.delta", 3, output_index=1, item_id="msg-0"),+ _event("response.output_item.done", 4, output_index=0, item_id="msg-0"),+ _event("response.completed", 5),+ ],+ "response.output_text.delta for item msg-0 at output_index 1 while msg-0 is open",+ ),+ (+ [+ _event("response.created", 0),+ _event("response.in_progress", 1),+ _event("response.output_item.added", 2, output_index=0, item_id="msg-0"),+ _event("response.completed", 3),+ ],+ "item msg-0 never done",+ ),+ (+ [_event("response.created", 0), _event("response.in_progress", 1), _event("response.output_item.added", 2)],+ "not one terminal event last",+ ),+ (+ [{**_event("response.created", 0), "type": "response.in_progress"}, _event("response.completed", 1)],+ "carries type 'response.in_progress'",+ ),+ ],+)+def test_event_order_problems(events: list[dict[str, Any]], problem: str) -> None:+ assert any(problem in found for found in conformance.responses_event_problems(events))+++def test_a_failed_response_may_leave_an_item_open() -> None:+ events = [+ _event("response.created", 0),+ _event("response.in_progress", 1),+ _event("response.output_item.added", 2, output_index=0, item_id="msg-0"),+ _event("response.output_text.delta", 3, output_index=0, item_id="msg-0"),+ _event("response.failed", 4),+ ]+ assert conformance.responses_event_problems(events) == []