Unrolling the Codex agent loop
# How Codex's Agent Loop Works OpenAI's Codex CLI runs on a core agent loop that coordinates the user, the model, and the tools the model invokes to make software changes. The loop repeats model inference and tool execution until the model emits a final assistant message, and the harness manages the prompt structure, prompt caching, and context window to keep this process efficient and reliable. The post is the first in a series that will also cover the CLI architecture, tool implementation, and sandboxing. ## The Basic Loop - The agent turns user input into a prompt and sends it to the model for inference. - If the model requests a tool call, the agent executes it, appends the output to the prompt, and queries the model again. - The loop ends when the model produces an assistant message with no tool calls, which returns control to the user. - Each conversation turn can contain many inference and tool-call iterations, and the full history is resent with each new user message. ## Model Inference via the Responses API - Codex sends HTTP requests to the Responses API. The endpoint is configurable: ChatGPT login uses `chatgpt.com/backend-api/codex/responses`, API-key auth uses `api.openai.com/v1/responses`, and `--oss` mode defaults to a local `localhost:11434` endpoint for gpt-oss models run through Ollama or LM Studio. - The server responds with a Server-Sent Events stream. Codex republishes these events internally, using text deltas to drive UI streaming and completed output items to extend the input for later calls. ## Building the Prompt - The request includes three main parameters: `instructions` (system or developer message), `tools` (available tool definitions), and `input` (the message items). - Instructions come from a `model_instructions_file` in `~/.codex/config.toml` if set, otherwise from the model's bundled base instructions. - Tools include Codex's built-in `shell` and `update_plan` tools, Responses API tools such as web search, and user-configured MCP server tools. - Before the user's message, Codex inserts several items into `input`: - A developer message describing the sandbox and approval rules. This applies only to Codex's shell tool, since MCP tools enforce their own guardrails. - An optional developer message from `developer_instructions` in `config.toml`. - An optional user message aggregating instructions from `AGENTS.override.md` and `AGENTS.md` files, capped at 32 KiB, plus skill metadata when skills are configured. - A user message with the environment context, including the current working directory and shell. ## Multi-Turn Conversations and Performance - Because the full history is resent, the total work across a conversation grows quadratically unless prompt caching is effective. - Codex does not use `previous_response_id`. This keeps requests stateless and supports Zero Data Retention customers. Reasoning from prior turns is still usable through `encrypted_content`, which the server can decrypt. - Caching only works for exact prefix matches, so Codex avoids changes that break the prefix: - Changing tools mid-conversation, switching models, or changing the sandbox, approval mode, or working directory can all cause cache misses. - An early bug in MCP support enumerated tools in an inconsistent order, which caused misses. MCP `tools/list_changed` notifications can also invalidate the cache mid-conversation. - Instead of editing earlier messages, Codex appends new developer or user messages that describe configuration changes. ## Context Window Management - Codex compacts the conversation once it passes a token threshold, replacing the history with a smaller set of items that preserve the agent's understanding. - Compaction started as a manual `/compact` command that asked the model to summarize the conversation. - It now uses the Responses API's `/responses/compact` endpoint, which returns an opaque compaction item. Codex calls it automatically when the `auto_compact_limit` is exceeded. ## Practical Takeaways - For anyone building an agent loop on the Responses API, keep static content such as instructions and tool definitions at the start of the prompt and append dynamic changes at the end. - Keep tool ordering deterministic and avoid changing tools mid-conversation to preserve prompt caching. - Plan for context growth with a compaction strategy rather than letting the window fill up.