Codex Harness Architecture: Embed AI Agents Without Rebuilding the Loop
From the publisher’s feed, collected in the ZeroLabs newsroom.
Codex Harness ArchitectureA practical guide for developers choosing between codex exec, the Codex SDK, and Codex App Server.Most AI agent failures do not start with the model. They start one layer lower, where the model meets files, tools, approvals, context, memory, logs, and the product your users actually work in.That layer is the harness.If you are building with OpenAI Codex, this matters more than it sounds. Codex is no longer only something developers use in a terminal, an IDE, or a desktop app. OpenAI now describes Codex as a platform built on an open-source harness that can gather context, use tools, run inside boundaries, request approvals, stream progress, and carry work forward. That makes the harness the reusable runtime, not just an implementation detail.The mistake is assuming every Codex integration needs the same shape. A CI job that reviews a pull request does not need the same runtime contract as a dashboard that lets a support engineer investigate an account and approve a remediation step. A background migration task does not need the same user experience as a rich IDE panel with live diffs and human approval prompts.This guide gives you a practical way to choose the right Codex harness architecture: codex exec for bounded automation, the Codex SDK for programmatic agent workflows, and Codex App Server for deeply embedded product experiences.What a Harness Actually DoesA model predicts text and tool calls. A harness turns those predictions into work.In a coding or operations agent, the harness usually owns the loop that keeps asking, acting, observing, and deciding whether the task is done. It decides what context enters the prompt, which tools are available, how shell commands run, what file changes are allowed, when approvals are required, how progress is streamed, and what evidence is returned to the user.That is why two products using a similar model can feel completely different. One agent burns context, runs vague commands, loses track of the task, and asks for approval at the wrong time. Another agent reads the right files, proposes a plan, makes a small diff, runs the relevant tests, explains the evidence, and stops. The model matters, but the harness shapes the model’s behavior.The useful question is not “Can the model do this?” It is “What runtime will make the model do this safely, repeatedly, and in the right product context?”For Codex, the harness idea becomes more concrete because there are now multiple integration surfaces. You can run a bounded agent task from the command line. You can use an SDK to create and resume agent threads in code. Or you can drive the same kind of rich, eventful experience that powers IDE-style clients through App Server.The Three Codex Integration LayersThink of Codex integration as a ladder. Each step gives you more control, but also more responsibility.Use codex exec for Bounded Automationcodex exec is the simplest fit when the job is mostly non-interactive. You give Codex a scoped task, a working directory, permissions, and a desired output. It runs, finishes, and returns a result.This is a good match for CI checks, repository audits, documentation refreshes, maintenance jobs, and background tasks where the system of record is outside the agent session. You care about final output, changed files, logs, and exit behavior, not a custom UI for every event.Good exec tasks sound like this:Review this pull request for risky auth changes and return JSON.Update deprecated API usage in this package and run the targeted tests.Find flaky tests matching this failure signature and propose the smallest fix.Generate a migration report without modifying files.The key is boundedness. If your task needs a long conversation, live approvals, or a custom product surface, exec becomes a squeeze.Use the Codex SDK for Programmatic Agent WorkflowsThe Codex SDK is the right middle layer when your application needs to start, continue, or resume Codex tasks from code. Official docs describe the Python SDK as controlling the local Codex app-server over JSON-RPC, with a pinned Codex CLI runtime dependency. That gives you a stable programmatic interface without making you implement the full rich-client protocol yourself.The SDK is a good fit for developer portals, internal automation services, custom CI actions, pull request review flows, issue triage bots, scheduled repository maintenance, and scripts that need thread reuse or structured output.A typical SDK-shaped workflow has four moves:Create or resume a thread with the right sandbox and model settings.Pass a focused task brief and any structured input.Collect the final response, changed files, tool trace, and usage data.Store the result in your own system: a pull request comment, issue, job log, dashboard, or audit record.Here is the shape, simplified:from openai_codex import Codex, Sandboxwith Codex() as codex: thread = codex.thread_start( model="gpt-5.6-terra", sandbox=Sandbox.workspace_write, ) result = thread.run( "Inspect the failed CI logs, make the smallest safe fix, " "run the targeted test, and summarize the diff." ) print(result.final_response)The SDK is not just a wrapper around a chat completion. It lets you treat an agent task as a controlled workflow object: define inputs, run the task, capture outputs, and let existing infrastructure handle retries, scheduling, permissions, and notifications.Use Codex App Server for Embedded Product ExperiencesCodex App Server is for rich clients. Official documentation describes it as the interface Codex uses to power clients such as the Codex VS Code extension. Use it when your product needs authentication, conversation history, approvals, and streamed agent events.This is the right layer when the agent is part of your product experience, not just a backend job. A user may start a task from a dashboard, watch progress, inspect files, approve a command, decline a risky tool call, add context mid-task, pause the run, resume later, or review a timeline of what happened.App Server uses bidirectional JSON-RPC communication. Agent work is not simple request-response. A single action can produce a plan, tool calls, shell commands, file changes, approvals, progress events, retries, diffs, and a final message. Your client needs to render those events clearly.Choose App Server when your integration needs:Live progress streaming instead of only final output.Inline approval dialogs for commands, file writes, network access, MCP tools, or permission changes.Thread lifecycle control, including start, resume, fork, list, read, and archive patterns.Deep UI integration with a code editor, operational dashboard, task board, support console, or security workbench.Evaluation of rich trajectory behavior, not just final assistant text.The Decision FrameworkYou can make the integration choice with five questions.Does the User Need to Watch the Work Unfold?If no, start with codex exec or the SDK. Many agent tasks should feel like normal automation: launch the job, collect the result, review the diff, move on.If yes, App Server becomes more attractive. Live event streams matter when trust depends on seeing the agent’s command path, file changes, approvals, and recovery behavior. This is common in IDEs, security tooling, incident response dashboards, and operations workflows.Is the Agent a Backend Worker or a Product Feature?Backend workers should use boring interfaces. If a nightly task updates docs, generates migration plans, or audits a repo, the product surface can be a job log and a notification. Use exec or the SDK.Product features need a stronger contract. If users will interact with the agent inside your app, you need user identity, session state, UI events, approvals, and graceful interruption. Use App Server.Who Owns Approval?Approval design is where many agent products get sloppy.If your task runs in read-only mode and produces advisory output, approval is simple. If it edits files, runs commands, opens network access, calls MCP tools, or writes to systems of record, approval becomes part of the core architecture. You need to decide which actions are always allowed, which are blocked, which need session-scoped approval, and which need a human every time.Do not bury approval in a generic “are you sure?” dialog. The user needs the command, target files, permission delta, expected side effect, and a clear way to decline. App Server is designed for inline approval flow. The SDK can be enough when conservative defaults keep risky operations out of scope.What Must Be Observable?Final answer logging is not observability. For real agent workflows, you usually want to know:Which prompt and instruction sources were loaded.Which tools were available and which were called.Which files changed and why.Which commands ran, with exit codes and relevant output.Which approvals were requested, granted, or denied.How many turns, tokens, retries, and failures occurred.Whether the acceptance checks actually passed.If your team only needs a job artifact, the SDK can capture enough metadata. If your product needs a replayable event timeline, App Server is the more natural base.Will You Evaluate the Path or Only the Answer?For simple tasks, final output may be enough. For production agents, the path matters. An answer can be correct for the wrong reason. A code diff can pass tests while violating architecture. A command can succeed while touching data it should not touch.That is why harness evaluation should include trajectory checks. Did the agent read the right files, avoid broad rewrites, run targeted tests, request approval before side effects, and stop after meeting the acceptance criteria?This is also why the emerging evaluation ecosystem is paying attention to Codex App Server behavior. Rich harness events are easier to evaluate when the protocol exposes them directly.A Practical Reference ArchitectureFor most teams, a good Codex harness architecture has seven parts.1. Task IntakeStart with a structured task brief. The agent should know the goal, scope, files or systems involved, acceptance criteria, constraints, and stop condition. Scoped tasks create testable work.{ "goal": "Fix the failing billing webhook test", "scope": ["services/billing", "tests/billing"], "acceptance": [ "Only change the minimal code path", "Run the failing test file", "Return a short diff summary" ], "stop": "Stop after tests pass or after one failed fix attempt"}2. Context AssemblyThe harness should collect the smallest useful context. That may include issue text, stack traces, relevant docs, repository instructions, recent diffs, test output, and system state. Do not dump the whole workspace into the prompt. Context bloat raises cost and makes the model worse at focusing.3. Permission ProfilePick permissions before the run starts. Read-only tasks should stay read-only. Workspace edits should stay inside the workspace. Network access should be rare and justified. Production writes should not be bundled into normal coding-agent permissions.4. Tool BoundaryExpose tools by workflow, not by excitement. The agent does not need every internal API. It needs the few actions required to complete the job. For a support investigation, that may mean account history, logs, entitlement lookup, and draft-response creation. For a code task, that may mean file search, edit, test, lint, and pull request metadata.5. Event StreamEvents are how humans build trust. Show meaningful states: planning, reading, editing, testing, waiting for approval, blocked, retrying, and complete. Avoid a fake typing indicator that hides real work. If the agent is running commands, show the command. If it changed files, show the diff.6. Approval FlowApproval should be tied to the risky action, not the whole task. The user should approve “run this command with network access” or “apply this file change outside the workspace,” not “let the agent do whatever it wants for a while.”7. Result ContractEnd every run with evidence. A useful final response includes the change summary, files touched, tests or checks run, unresolved risks, and next suggested action. If the run failed, it should say where it got stuck and what evidence it gathered.Common Architecture MistakesMistake 1: Building a Chat Box When the User Needs a WorkflowChat is flexible, but many professional tasks already have a natural interface. Developers understand diffs, tests, issues, branches, and review comments. Support teams understand cases, customers, timelines, and entitlements. Security teams understand findings, severity, affected assets, and remediation status.Embedding an agent into those objects is often better than forcing the user into a blank chat window. The harness should make the existing workflow more capable, not replace every product surface with conversation.Mistake 2: Treating the SDK as a UI ProtocolThe SDK is excellent for programmatic workflows. It is not the best fit when your app needs every intermediate event, approval request, and lifecycle operation as a first-class UI object. If your product needs the user to watch, interrupt, approve, and resume agent work, use the interface designed for rich clients.Mistake 3: Letting the Agent Discover Policy at RuntimeDo not make the model infer your security model from scattered prose. Encode the policy in the runtime: sandbox mode, approval policy, tool availability, MCP server configuration, network access, and filesystem roots. Instructions are useful, but runtime boundaries are stronger.Mistake 4: Measuring Only “Did It Finish?”A coding agent can finish and still create expensive cleanup work. Track cost per accepted change, test pass rate after review, revert rate, files touched per task, approval-denial rate, and human review time. These metrics expose whether the harness is improving work or merely producing more activity.Rollout Plan for a TeamStart with one narrow workflow. Do not embed a general-purpose agent into every product surface first.Pick a task with clear acceptance criteria and low blast radius. Good first candidates include pull request summarization, test failure diagnosis, dependency upgrade planning, documentation drift detection, or issue-to-plan generation.Run it in read-only mode first. Capture the final response, tool trace, files inspected, and suggested actions. Review ten to twenty runs manually. Look for repeated failure patterns: missing context, wrong files, overbroad plans, unnecessary tool calls, weak stop conditions, or vague summaries.Then allow controlled writes in a disposable branch or workspace. Require tests. Keep network access off unless needed. Add approvals only where they create real safety value. Too many prompts train users to click through; too few hide risk.Finally, decide whether the workflow deserves a richer surface. If users keep asking “what is it doing now?” or “can I approve this one step?” that is a signal for App Server. If they only need the completed artifact, stay with exec or the SDK.How to Think About Cost and QualityDevelopers often compare coding agents by model name. That misses the point. Cost and quality depend on the whole loop: static instructions, context size, tool schema, retry behavior, sandbox friction, approval delays, test strategy, and stop conditions.A strong harness can reduce waste by giving the model fewer irrelevant options and better evidence. A weak harness can make even a frontier model wander. The practical metric is not tokens per message. It is cost per accepted outcome.For a Codex workflow, track these numbers from the start:Successful runs divided by total runs.Accepted changes divided by generated changes.Average tool calls per accepted run.Average tokens per accepted run.Average review minutes saved or added.Post-merge defect or revert rate.Approval requests per run and denial rate.These numbers tell you whether to tune the prompt, trim context, change permissions, add a tool, remove a tool, switch integration layers, or abandon the workflow.The Bottom LineCodex harness architecture is not a branding detail. It is the control layer that decides whether an AI agent becomes useful software or an impressive demo that nobody trusts.Use codex exec when you need a bounded job. Use the Codex SDK when you need programmatic agent workflows with clean inputs and outputs. Use Codex App Server when the agent is part of a real product surface with streamed events, approvals, session history, and human-in-the-loop control.The strongest teams will not build one universal agent interface. They will build the smallest runtime surface that matches each workflow, then measure whether it produces accepted outcomes with less risk, less waste, and less human cleanup.FAQWhat is Codex harness architecture?Codex harness architecture is the runtime design around Codex: how it receives context, calls tools, runs in a sandbox, handles approvals, streams events, stores thread state, and returns evidence. It is the system that turns model output into controlled work.When should I use codex exec instead of the Codex SDK?Use codex exec for bounded, non-interactive tasks such as CI checks, one-off audits, migration reports, and scripted maintenance. Use the SDK when your application needs to create, resume, or manage Codex threads from code.When should I use Codex App Server?Use Codex App Server when you are building a rich client or embedded product experience. It is the better fit for live progress, approval prompts, conversation history, thread lifecycle control, and event-level UI updates.Is an agent harness the same as an agent framework?No. A framework helps you build or orchestrate agent logic. A harness is the runtime around a model that lets it act: tools, memory, context, sandboxing, approvals, state, and feedback. Some frameworks include a harness, but the concepts are not identical.How do I evaluate a Codex harness?Evaluate both the final result and the path. Check whether the agent read the right context, used allowed tools, requested approval for risky actions, made a focused diff, ran the right tests, stopped at the right time, and returned enough evidence for review.Should every AI agent product use App Server?No. App Server is powerful, but it is not required for simple automation. Start with the smallest layer that matches the job. Move to App Server when the user experience needs streamed events, approvals, live interaction, and durable session control.Sources and Further ReadingOpenAI Developers: Codex as a platformChatGPT Learn: Codex App ServerChatGPT Learn: Codex SDKOpenAI Codex GitHub: App Server READMEOpenAI: Unrolling the Codex agent loopPromptfoo: OpenAI Codex App Server providerCodex Harness Architecture: Embed AI Agents Without Rebuilding the Loop was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.