# Codex transport

| Turn | Transport | Body |
| --- | --- | --- |
| ChatGPT sign-in, carries on from the last reply | kept WebSocket | only new input, with `previous_response_id` |
| ChatGPT sign-in, anything else | kept WebSocket | whole |
| ChatGPT sign-in, socket unavailable | HTTP | zstd level 3, no checksum, `Content-Encoding: zstd` |
| API key | HTTP | plain |

Endpoint `chatgpt.com/backend-api/codex/responses`. Both ways end in one consumer, `openai_codex._consume`, under `read_budget.ReadBudget`: no bytes for `STREAM_IDLE_TIMEOUT_S`, no data for `STREAM_DATA_STALL_TIMEOUT_S`, caller deadline and Stop polled at 4 Hz.

## WebSocket

`open_turn` dials with the HTTP headers plus `OpenAI-Beta: responses_websockets=2026-02-06`, sends one `{"type":"response.create", …body}`, and reads frames that are the SSE events' JSON. `codex.rate_limits` goes to the [quota store](https://fzkuji.github.io/OpenProgram/docs/reference/design/providers/provider-quota.html), not the reply; `codex.response.metadata` and `responsesapi.websocket_timing` are skipped.

| Delta rule | Value |
| --- | --- |
| Socket key | Event loop, URL, authorization, account, `prompt_cache_key` |
| Remembered | Shape (all but `input`); digest of each input item and reply output item |
| Delta when | Same shape, and input starts with exactly those items |
| Digest ignores | ids, status, a message's `phase`, empty annotations and logprobs; `arguments` compared as parsed JSON |
| Resent whole on a new socket | `previous_response_not_found`, or a reused socket fails before the reply starts |

## Cache routing

The backend caches a prompt prefix on one replica. A new connection reaches that replica only when the request names its conversation in the `session_id` and `conversation_id` headers as well as in `prompt_cache_key` (`CONVERSATION_HEADERS`). With the body key alone, a fresh socket missed the whole prefix.

| Request | Key |
| --- | --- |
| In a conversation | The session id |
| Runtime call (title, topic sort, program run) | `op-` and a digest of provider, model, system prompt and tool names, the same for every Runtime that sends them. A new Runtime per call used to get a random key and read 0 of about 3,000 tokens; now the second call reads about 2,800 |
| No conversation (memory, background call) | `op-` and a digest of provider, model, instructions and tool names (`providers.shared.cache_key`, the derivation a Runtime call uses too), so repeated side calls find their prefix |
| Retry routed elsewhere | `op-retry-` key; the headers follow it |
| Caller set the headers | Kept |

## Loading a deferred tool

The backend renders the tools array ahead of the instructions and the conversation. Any change to the array, a tool appended at its end included, makes it read the whole request uncached. A deferred tool is therefore loaded where it was searched for, as the Responses API's client-executed tool search places it.

| Piece | On the wire |
| --- | --- |
| `tool_search` in the tools | `{"type":"tool_search","execution":"client"}` with its own parameters |
| The model's search | A `tool_search_call` item, run as the `tool_search` tool and sent back without its id |
| Its result | A `tool_search_output` item carrying the definitions from the result's load record, `details["loads"]`: one `{name, definition}` per tool, written by `record_loads` when the tools were loaded. The result text is not read, so the item is the same bytes on every later request, and a schema changed after the load does not reach it. A tool the turn no longer offers stays in the item; calling it is refused like any tool the turn does not have |
| What it did not load | The item has no place for words, and `tools: []` alone reads as "no such tool". The search's note, `details["note"]` (a tool already in the array is callable, a name is unknown, nothing matched), follows as a user item in `<tool-search-result>` ([Deferred tools](https://fzkuji.github.io/OpenProgram/docs/reference/design/function/deferred-tools.html#codex)) |
| The stored result | The tool node keeps the load record in its metadata beside the text, and rendering history puts it back on the tool result, so a request built from history matches the one built in the turn |
| Which requests | Those whose provider declares the `responses` form for the request's API under `tool_search` in its `provider.json`, and whose model does not opt out (`Model.tool_search = False`). Only `openai-codex` declares it; every other provider and API, Bedrock Converse and the Anthropic-compatible ones included, loads a searched tool into the array |
| The loaded set | Read from the request's own messages on every provider (`loaded_tools`): the load records of its tool results and the names a compaction summary among them carries. Nothing else holds it, so a nested run, another branch or an edit from before the search does not see the load |
| A loaded tool | Left out of the array while a `tool_search_output` in the input carries it |
| After a compaction | The summary node keeps `carried_tool_names`: the tools its covered turns loaded, most recently loaded or called first, cut where their definitions would pass 5% of the window. On Codex one `tool_search_call` / `tool_search_output` pair goes in front of the summary, its call id taken from the names and each definition the one the conversation first sent, so the array stays as it was; any other provider offers the carried tools in its array |

| Request, one real conversation | Tools in the array | Uncached / cached input |
| --- | --- | --- |
| Right after the search, tool added to the array | changed | 8,664 / 0 |
| Right after the search, tool in `tool_search_output` | unchanged | 896 / 7,040 |
| Next turn, prompt listing only unloaded tools | unchanged | 3,211 / 6,144 |
| Next turn, prompt listing every deferred tool | unchanged | 309 / 8,320 |
| Next turn after a keyword load of three tools, stored result cut at 4,000 characters | two tools put back | 9,398 / 0 |
| Next turn after the same load, stored result whole | unchanged | 311 / 9,088 |

Same tools array, instructions and kept-socket shape on every request of the conversation, so WebSocket deltas carry on through a load. The prompt's deferred list names every deferred tool, loaded or not.

Two other ways a tool becomes loaded still put it into the array, ahead of the conversation: a guide that activates a tool when it is delivered (the `self_update` guide activates `worktree_create`), whose load record goes on the result that delivered the guide, and an application opened in the conversation, whose tools become resident at the next turn.

Neither writes a `tool_search_output`, so each costs one full re-read, as a tool search did before. In the stable instance's last 30 days there were 77 tool searches and no `self_update` call.

## Falling back to HTTP

| Cause of `SocketUnavailable` | Note |
| --- | --- |
| `OPENPROGRAM_CODEX_WEBSOCKET=0` | Tests set it, except the transport's own, which use a local server |
| Handshake fails | Host shunned `SHUN_S`, 10 min, except after 401, 429 or 5xx |
| Close 1009, message too big | Remembered for the host |
| Connection limit | Refused by the backend |

Through an HTTP proxy the handshake first sends `CONNECT`:

- a refusal, a timeout or a dropped proxy connection fails the handshake like any other, so the turn goes over HTTP;
- a tunnel the far end resets or closes during the TLS handshake inside it fails the handshake the same way;
- a dial given up before the proxy answers (the turn stopped) closes the proxy connection at once and changes nothing else.

websockets 16 itself left that connection open and logged `InvalidStateError` when the late answer came, and ended the answer's stream twice when the proxy closed before answering, so `_install_proxy_protocol` replaces its proxy protocol.

websockets also starts TLS in the tunnel before the WebSocket connection is made, while asyncio counts that connection as made; a tunnel lost then calls `connection_lost` on it, which `_Connection` ignores because nothing was set up.

A socket cut after the reply starts is an ordinary retryable stream break. `OPENPROGRAM_CODEX_ZSTD=0` turns compression off.

- **Idle limit**: `KEEP_IDLE_S`, 10 min
- **Age limit**: `KEEP_AGE_S`, 55 min
- **Kept at most**: `KEEP_MAX`, 32
- **Closed by**: `drain()`, through `http_client.register_loop_closer`, on a thread of its own once the turn has ended, so the reply and final state never wait for it
- **Stopped mid-reply**: Closed, never kept; the close ends on that same thread before the loop closes ([Stopping a call](https://fzkuji.github.io/OpenProgram/docs/reference/design/providers/reliability/error-and-timeout-mechanism.html#stopping))
- **Close ends**: When the backend answers this end's close frame; this end then drops the TCP connection instead of waiting about 2 s for the backend to

**Code**

| File | Holds |
| --- | --- |
| `openai_codex/openai_codex.py` | `_run`, shared consumer |
| `shared/openai_responses.py` | `tool_search_call` and `tool_search_output` in and out, `carried_tool_names`, `native_tool_search` |
| `shared/tool_loads.py` | The load record: its shape, reading it, the details a tool node keeps |
| `settings/tool_search_spec.py` | `tool_search_form(provider, api, model)` |
| `openai_codex/websocket_transport.py` | Dialing, kept sockets, deltas, shunning |
| `openai_codex/read_budget.py` | Read budgets |
| `openai_codex/request_compression.py` | `encode_turn` |
| `providers/utils/http_transport/http_proxy.py` | `proxy_for_url`, shared with HTTP |

Deltas and zstd are confirmed against the live backend for plain and tool turns. Follows magpie's Codex WebSocket support (yetone/magpie, MIT).

## Implementation status

- A summary written before `carried_tool_names` existed carries what its covered turns loaded, uncut; on Codex its first request after this change sends the new pair instead of the old kept search, so the prefix breaks once.
- The checkpoint journal still has its `loaded_deferred_tools` field; nothing reads it for loading any more, and it goes in a later version.
- The cached share right after a compaction on Codex is not yet measured against the instructions and tools token count.
- Results stored before load records existed have none, so on Codex their item carries no tools and the model searches again.
