Codex CLI(osclaíonn i bhfuinneog nua) is our cross-platform local software agent, designed to produce high-quality, reliable software changes while operating safely and efficiently on your machine. We’ve learned a tremendous amount about how to build a world-class software agent since we first launched the CLI in April. To unpack those insights, this is the first post in an ongoing series where we’ll explore various aspects of how Codex works, as well as hard-earned lessons. (For an even more granular view on how the Codex CLI is built, check out our open source repository at https://github.com/openai/codex(osclaíonn i bhfuinneog nua). Many of the finer details of our design decisions are memorialized in GitHub issues and pull requests if you’d like to learn more.)
To kick off, we’ll focus on the agent loop, which is the core logic in Codex CLI that is responsible for orchestrating the interaction between the user, the model, and the tools the model invokes to perform meaningful software work. We hope this post gives you a good view into the role our agent (or “harness”) plays in making use of an LLM.
Before we dive in, a quick note on terminology: at OpenAI, “Codex” encompasses a suite of software agent offerings, including Codex CLI, Codex Cloud, and the Codex VS Code extension. This post focuses on the Codex harness, which provides the core agent loop and execution logic that underlies all Codex experiences and is surfaced through the Codex CLI. For ease here, we’ll use the terms “Codex” and “Codex CLI” interchangeably.
At the heart of every AI agent is something called “the agent loop.” A simplified illustration of the agent loop looks like this:
To start, the agent takes input from the user to include in the set of textual instructions it prepares for the model known as a prompt.
The next step is to query the model by sending it our instructions and asking it to generate a response, a process known as inference. During inference, the textual prompt is first translated into a sequence of input tokens(osclaíonn i bhfuinneog nua)—integers that index into the model’s vocabulary. These tokens are then used to sample the model, producing a new sequence of output tokens.
The output tokens are translated back into text, which becomes the model’s response. Because tokens are produced incrementally, this translation can happen as the model runs, which is why many LLM-based applications display streaming output. In practice, inference is usually encapsulated behind an API that operates on text, abstracting away the details of tokenization.
As the result of the inference step, the model either (1) produces a final response to the user’s original input, or (2) requests a tool call that the agent is expected to perform (e.g., “run ls and report the output”). In the case of (2), the agent executes the tool call and appends its output to the original prompt. This output is used to generate a new input that’s used to re-query the model; the agent can then take this new information into account and try again.
This process repeats until the model stops emitting tool calls and instead produces a message for the user (referred to as an assistant message in OpenAI models). In many cases, this message directly answers the user’s original request, but it may also be a follow-up question for the user.
Because the agent can execute tool calls that modify the local environment, its “output” is not limited to the assistant message. In many cases, the primary output of a software agent is the code it writes or edits on your machine. Nevertheless, each turn always ends with an assistant message—such as “I added the architecture.md you asked for”—which signals a termination state in the agent loop. From the agent’s perspective, its work is complete and control returns to the user.
The journey from user input to agent response shown in the diagram is referred to as one turn of a conversation (a thread in Codex). Though this conversation turn can include many iterations between the model inference and tool calls. Every time you send a new message to an existing conversation, the conversation history is included as part of the prompt for the new turn, which includes the messages and tool calls from previous turns:
This means that as the conversation grows, so does the length of the prompt used to sample the model. This length matters because every model has a context window, which is the maximum number of tokens it can use for one inference call. Note this window includes both input and output tokens. As you might imagine, an agent could decide to make hundreds of tool calls in a single turn, potentially exhausting the context window. For this reason, context window management is one of the agent’s many responsibilities. Now, let’s dive in to see how Codex runs the agent loop.
The Codex CLI sends HTTP requests to the Responses API(osclaíonn i bhfuinneog nua) to run model inference. We’ll examine how information flows through Codex, which uses the Responses API to drive the agent loop.
The Responses API endpoint that the Codex CLI uses is configurable(osclaíonn i bhfuinneog nua), so it can be used with any endpoint that implements the Responses API(osclaíonn i bhfuinneog nua):
- When using ChatGPT login(osclaíonn i bhfuinneog nua) with the Codex CLI, it uses
https://chatgpt.com/backend-api/codex/responsesas the endpoint - When using API-key authentication(osclaíonn i bhfuinneog nua) with OpenAI hosted models, it uses
https://api.openai.com/v1/responsesas the endpoint - When running Codex CLI with
--ossto use gpt-oss with ollama 0.13.4+(osclaíonn i bhfuinneog nua) or LM Studio 0.3.39+(osclaíonn i bhfuinneog nua), it defaults tohttp://localhost:11434/v1/responsesrunning locally on your computer - Codex CLI can be used with the Responses API hosted by a cloud provider such as Azure
Let’s explore how Codex creates the prompt for the first inference call in a conversation.
As an end user, you don’t specify the prompt used to sample the model verbatim when you query the Responses API. Instead, you specify various input types as part of your query, and the Responses API server decides how to structure this information into a prompt that the model is designed to consume. You can think of the prompt as a “list of items”; this section will explain how your query gets transformed into that list.
In the initial prompt, every item in the list is associated with a role. The role indicates how much weight the associated content should have and is one of the following values (in decreasing order of priority): system, developer, user, assistant.
The Responses API(osclaíonn i bhfuinneog nua) takes a JSON payload with many parameters. We’ll focus on these three:
instructions(osclaíonn i bhfuinneog nua): system (or developer) message inserted into the model’s contexttools(osclaíonn i bhfuinneog nua): a list of tools the model may call while generating a responseinput(osclaíonn i bhfuinneog nua): a list of text, image, or file inputs to the model
In Codex, the instructions field is read from the model_instructions_file(osclaíonn i bhfuinneog nua) in ~/.codex/config.toml, if specified; otherwise, the base_instructions associated with a model(osclaíonn i bhfuinneog nua) are used. Model-specific instructions live in the Codex repo and are bundled into the CLI (e.g., gpt-5.2-codex_prompt.md(osclaíonn i bhfuinneog nua)).
The tools field is a list of tool definitions that conform to a schema defined by the Responses API. For Codex, this includes tools that are provided by the Codex CLI, tools that are provided by the Responses API that should be made available to Codex, as well as tools provided by the user, usually via MCP servers:
Finally, the input field of the JSON payload is a list of items. Codex inserts the following items(osclaíonn i bhfuinneog nua) into the input before adding the user message:
1. A message with role=developer that describes the sandbox that applies only to the Codex-provided shell tool defined in the tools section. That is, other tools, such as those provided from MCP servers, are not sandboxed by Codex and are responsible for enforcing their own guardrails.
The message is built from a template where the key pieces of content come from snippets of Markdown bundled into the Codex CLI, such as workspace_write.md(osclaíonn i bhfuinneog nua) and on_request.md(osclaíonn i bhfuinneog nua):
2. (Optional) A message with role=developer whose contents are the developer_instructions value read from the user’s config.toml file.
3. (Optional) A message with role=user whose contents are the “user instructions,” which are not sourced from a single file but are aggregated across multiple sources(osclaíonn i bhfuinneog nua). In general, more specific instructions appear later:
- Contents of
AGENTS.override.mdandAGENTS.mdin$CODEX_HOME - Subject to a limit (32 KiB, by default), look in each folder from the Git/project root of the
cwd(if it it exists) up to thecwditself: add the contents of any ofAGENTS.override.md,AGENTS.md, or any filename specified byproject_doc_fallback_filenames in config.toml - If any skills(osclaíonn i bhfuinneog nua) have been configured:
- a short preamble about skills
- the skill metadata(osclaíonn i bhfuinneog nua) for each skill
- a section on how to use skills(osclaíonn i bhfuinneog nua)
4. A message with role=user that describes the local environment in which the agent is currently operating. This specifies the current working directory and the user’s shell(osclaíonn i bhfuinneog nua):
Nuair a bheidh an ríomh go léir thuas déanta ag Codex chun an input a thúsú, cuireann sé teachtaireacht an úsáideora leis chun an comhrá a thosú.
Dhírigh na samplaí roimhe seo ar ábhar gach teachtaireachta, ach tabhair faoi deara gur réad JSON é gach eilimint de input le type, role(osclaíonn i bhfuinneog nua), agus content mar seo a leanas:
Nuair a bhíonn an pálasta iomlán JSON tógtha ag Codex lena sheoladh chuig an Responses API, déanann sé an t-iarratas HTTP POST ansin le ceanntásc Authorization ag brath ar an gcaoi a bhfuil deireadhphointe an Responses API cumraithe i ~/.codex/config.toml (cuirtear ceanntásca HTTP breise agus paraiméadair cheiste leis má shonraítear iad).
Nuair a fhaigheann freastalaí Responses API OpenAI an t-iarratas, úsáideann sé an JSON chun an leid don tsamhail a dhíorthú mar seo a leanas (le bheith cinnte, d’fhéadfadh cur i bhfeidhm saincheaptha den Responses API rogha eile a dhéanamh):
Mar a fheiceann tú, is é an freastalaí, ní an cliant, a chinneann ord na gcéad trí mhír sa leid. É sin ráite, de na trí mhír sin, níl ach ábhar na teachtaireachta system faoi rialú an fhreastalaí freisin, ós rud é gurb é an cliant a chinneann tools agus instructions. Leanann an input ón bpálasta JSON iad sin chun an leid a chomhlánú.
Anois go bhfuil ár leid againn, táimid réidh leis an tsamhail a shampláil.
Tosaíonn an t-iarratas HTTP seo chuig an Responses API an chéad “chas” de chomhrá i Codex. Freagraíonn an freastalaí le sruth Server-Sent Events (SSE(osclaíonn i bhfuinneog nua)). Is pálasta JSON é data gach imeachta le "type" a thosaíonn le "response", a d’fhéadfadh a bheith cosúil leis seo (is féidir liosta iomlán imeachtaí a fháil inár gcáipéisí API(osclaíonn i bhfuinneog nua)):
Déanann Codex sruth na n-imeachtaí a thomhaltas(osclaíonn i bhfuinneog nua) agus athfhoilsíonn sé iad mar réada imeachta inmheánacha ar féidir le cliant a úsáid. Úsáidtear imeachtaí cosúil le response.output_text.delta chun tacú le sruthú sa chomhéadan úsáideora, ach claochlaítear imeachtaí eile cosúil le response.output_item.added ina réada a chuirtear leis an input do ghlaonna Responses API ina dhiaidh sin.
Cuir i gcás go n-áiríonn an chéad iarratas chuig an Responses API dhá imeacht response.output_item.done: ceann le type=reasoning agus ceann le type=function_call. Caithfear na himeachtaí seo a léiriú sa réimse input den JSON nuair a cheistímid an tsamhail arís le freagra ar an nglao uirlise:
Bheadh an leid dá bharr a úsáidtear chun an tsamhail a shampláil mar chuid den cheist ina dhiaidh sin cosúil leis seo:
Go háirithe, tabhair faoi deara conas atá an seanteid ina réimír bheacht den leid nua. Tá sé seo d’aon ghnó, mar déanann sé iarratais ina dhiaidh sin i bhfad níos éifeachtúla toisc go gcuireann sé ar ár gcumas leas a bhaint as taisceadh leide (a phléifimid sa chéad rannóg eile ar fheidhmíocht).
Ag féachaint siar ar ár gcéad léaráid den lúb ghníomhaire, feicimid go bhféadfadh go leor atriallta a bheith idir inference agus glaoch uirlise. Seans go leanfaidh an leid ag fás go dtí go bhfaighimid teachtaireacht chúntóra ar deireadh, a léiríonn deireadh an chasa:
I Codex CLI, cuirimid an teachtaireacht chúntóra i láthair an úsáideora agus dírímid an cumadóir chun a chur in iúl don úsáideoir gurb é a “chas” é leanúint den chomhrá. Má fhreagraíonn an t-úsáideoir, ní mór an teachtaireacht chúntóra ón gcas roimhe seo, chomh maith le teachtaireacht nua an úsáideora, a chur leis an input san iarratas Responses API chun an cas nua a thosú:
Arís eile, toisc go bhfuilimid ag leanúint comhrá, leanann fad an input a sheolaimid chuig an Responses API ag méadú:
Déanaimis scrúdú ar a bhfuil i gceist leis an leid seo atá ag fás de shíor don fheidhmíocht.
Seans go bhfuil tú ag fiafraí díot féin, “Fan, nach bhfuil an lúb ghníomhaire cearnach i dtéarmaí an mhéid JSON a sheoltar chuig an Responses API le linn an chomhrá?” Agus bheadh an ceart agat. Cé go dtacaíonn an Responses API le paraiméadar roghnach previous_response_id(osclaíonn i bhfuinneog nua) chun an fhadhb seo a mhaolú, ní úsáideann Codex é inniu, go príomha chun iarratais a choinneáil go hiomlán gan staid agus chun cumraíochtaí gan coinneáil sonraí (ZDR) a thacú.
Déantar rudaí a shimpliú do sholáthraí an Responses API trí previous_response_id a sheachaint mar cinntíonn sé go bhfuil gach iarratas gan staid. Fágann sé seo freisin go bhfuil sé simplí tacú le custaiméirí a roghnaigh Gan coinneáil sonraí (ZDR)(osclaíonn i bhfuinneog nua), ós rud é go mbeadh stóráil na sonraí is gá chun tacú le previous_response_id ag teacht salach ar ZDR. Tabhair faoi deara nach n-íobartaíonn custaiméirí ZDR an cumas leas a bhaint as teachtaireachtaí réasúnaíochta dílseánaigh ó chasanna roimhe seo, mar is féidir an encrypted_content gaolmhar a dhíchriptiú ar an bhfreastalaí. (Seasmhaíonn OpenAI eochair dhíchriptithe custaiméara ZDR, ach ní a gcuid sonraí.) Féach PRs #642(osclaíonn i bhfuinneog nua) agus #1641(osclaíonn i bhfuinneog nua) do na hathruithe gaolmhara ar Codex chun tacú le ZDR.
Go ginearálta, bíonn costas samplála na samhla i réim ar chostas an tráchta líonra, rud a fhágann gurb é sampláil an príomhsprioc dár n-iarrachtaí éifeachtúlachta. Sin é an fáth go bhfuil taisceadh leide chomh tábhachtach, mar cuireann sé ar ár gcumas ríomh ó ghlao inference roimhe seo a athúsáid. Nuair a fhaighimid amas taisce, bíonn sampláil na samhla líneach seachas cearnach. Míníonn ár ndoiciméadú ar thaisceadh leide(osclaíonn i bhfuinneog nua) é seo níos mine:
Ní féidir amas taisce a dhéanamh ach do mheaitseálacha beachta réimíre laistigh de leid. Chun tairbhí taisce a bhaint amach, cuir ábhar statach ar nós treoracha agus samplaí ag tús do leide, agus cuir ábhar athraitheach, ar nós faisnéis shonrach d’úsáideoir, ag an deireadh. Baineann sé seo le híomhánna agus uirlisí freisin, agus ní mór dóibh a bheith comhionann idir iarratais.
Agus é seo san áireamh, déanaimis smaoineamh ar na cineálacha oibríochtaí a d’fhéadfadh “caillteanas taisce” a chur faoi deara i Codex:
- Athrú ar na
toolsatá ar fáil don tsamhail i lár an chomhrá. - Athrú ar an
modelatá mar sprioc don iarratas Responses API (go praiticiúil, athraíonn sé seo an tríú mír sa leid bhunaidh, ós rud é go bhfuil treoracha sainiúla don tsamhail inti). - Athrú ar chumraíocht an bhosca ghainimh, ar an mód ceadaithe, nó ar an gcomhadlann oibre reatha.
Caithfidh foireann Codex a bheith dúthrachtach agus gnéithe nua á dtabhairt isteach acu i Codex CLI a d’fhéadfadh taisceadh leide a chur i mbaol. Mar shampla, chuir ár dtacaíocht tosaigh d’uirlisí MCP fabht isteach nuair nár éirigh linn na huirlisí a áireamh in ord comhsheasmhach(osclaíonn i bhfuinneog nua), rud a d’fhág caillteanais taisce. Tabhair faoi deara gur féidir le huirlisí MCP a bheith thar a bheith casta toisc gur féidir le freastalaithe MCP liosta na n-uirlisí a sholáthraíonn siad a athrú ar an eitilt trí fhógra notifications/tools/list_changed(osclaíonn i bhfuinneog nua). D’fhéadfadh sé a bheith costasach an fógra seo a urramú i lár comhrá fada agus caillteanas taisce a chruthú.
Nuair is féidir, déanaimid láimhseáil ar athruithe cumraíochta a tharlaíonn i lár comhrá trí theachtaireacht nua a chur leis an input chun an t-athrú a léiriú seachas teachtaireacht níos luaithe a mhodhnú:
- Má athraíonn cumraíocht an bhosca ghainimh nó an mód ceadaithe, cuirimid(osclaíonn i bhfuinneog nua) teachtaireacht nua
role=developeristeach leis an bhformáid chéanna leis an mír bhunaidh<permissions instructions>. - Má athraíonn an chomhadlann oibre reatha, cuirimid(osclaíonn i bhfuinneog nua) teachtaireacht nua
role=useristeach leis an bhformáid chéanna leis an mbunmhír<environment_context>.
Téimid i bhfad chun amas taisce a chinntiú ar mhaithe le feidhmíocht. Tá acmhainn thábhachtach eile ann atá le bainistiú againn: an fhuinneog chomhthéacs.
Is é ár straitéis ghinearálta chun rith amach as an bhfuinneog chomhthéacs a sheachaint ná an comhrá a chomhdhlúthú nuair a sháraíonn líon na dtéacschomharthaí tairseach éigin. Go sonrach, cuirimid liosta nua míreanna níos lú in ionad an input atá ionadaíoch don chomhrá, rud a chuireann ar chumas an ghníomhaire leanúint ar aghaidh le tuiscint ar a bhfuil tarlaithe go dtí seo. Bhí ar an úsáideoir glaoch de láimh ar an ordú /compact i gcur i bhfeidhm luath den chomhdhlúthú(osclaíonn i bhfuinneog nua), a cheistigh an Responses API ag úsáid an chomhrá atá ann cheana móide treoracha saincheaptha le haghaidh achoimithe(osclaíonn i bhfuinneog nua). D’úsáid Codex an teachtaireacht chúntóra a tháinig as agus a raibh an achoimre inti mar an input nua(osclaíonn i bhfuinneog nua) do chasanna comhrá ina dhiaidh sin.
Ó shin i leith, tá an Responses API tagtha chun cinn chun tacú le deireadhphointe /responses/compact(osclaíonn i bhfuinneog nua) speisialta a dhéanann comhdhlúthú níos éifeachtúla. Cuireann sé liosta míreanna(osclaíonn i bhfuinneog nua) ar ais is féidir a úsáid in ionad an input roimhe seo chun an comhrá a leanúint agus an fhuinneog chomhthéacs a shaoradh ag an am céanna. Áiríonn an liosta seo mír speisialta type=compaction le mír dhofheicthe encrypted_content a chaomhnaíonn tuiscint fholaithe na samhla ar an gcomhrá bunaidh. Anois, úsáideann Codex an deireadhphointe seo go huathoibríoch chun an comhrá a chomhdhlúthú nuair a sháraítear an auto_compact_limit(osclaíonn i bhfuinneog nua).
Tá lúb ghníomhaire Codex curtha i láthair againn agus shiúlamar trí conas a chumann agus a bhainistíonn Codex a chomhthéacs agus é ag ceistiú samhla. Ar an mbealach, leagamar béim ar bhreithnithe praiticiúla agus ar dhea-chleachtais a bhaineann le duine ar bith atá ag tógáil lúb ghníomhaire ar bharr an Responses API.
Cé go soláthraíonn an lúb ghníomhaire bunús do Codex, níl anseo ach an tús. I bpoist atá le teacht, déanfaimid tochailt níos doimhne in ailtireacht an CLI, scrúdóimid conas a chuirtear úsáid uirlise i bhfeidhm, agus féachfaimid níos géire ar shamhaltán bosca gainimh Codex.


