Unified Agent Backends
Overview
The backend layer under unified_agent/backends/ is the adapter boundary between UnifiedAgent and provider-specific agent runtimes. unified_agent/…/base.py defines the AgentBackend protocol: a backend has a name and a stream(prompt, opts) method that yields normalized AgentEvent values and must terminate the turn with TurnCompleted. unified_agent/agent.py lazy-loads the concrete backend from the user-facing backend name ("claude" or "codex"), prepares a workspace/tool-server RunOptions, renders the task for that backend, and folds the event stream into UnifiedResult.
unified_agent/…/claude_code.py adapts claude-agent-sdk/Claude Code. build_options() maps RunOptions into ClaudeAgentOptions: it sets the working directory, model, resume id, max turns, output schema, reasoning effort, extra environment, and text streaming. Claude Code does not provide the same OS sandbox semantics as Codex, so SandboxPolicy.READ_ONLY is implemented by permission_mode="dontAsk", allow-listing only Read, Glob, and Grep, and explicitly disallowing write and shell tools; WORKSPACE_WRITE uses acceptEdits, while FULL_ACCESS uses bypassPermissions. If RunOptions.tool_server is present, it is registered as a stdio MCP server and mcp__<server>__* is added to the allowed tool list. The system prompt always uses the native claude_code preset, appending RunOptions.instructions when supplied, because replacing it would remove Claude Code's working-directory context.
Claude event normalization happens in normalize_message() in unified_agent/…/claude_code.py. Init SystemMessage events produce SessionStarted and also check configured MCP server statuses, raising ToolServerError if the requested server reports a failed/auth/error state. Assistant text, thinking blocks, tool uses, and tool results become AssistantText, Reasoning, ToolCall, and ToolResult; SDK stream deltas become TextDelta only when RunOptions.stream_text is true. ResultMessage is the terminal event and is converted into TurnCompleted with success, final text, Claude usage fields, cost, session id, duration, structured output, stop reason, and error text. ClaudeCodeBackend.stream() drives query() and converts CLINotFoundError to BackendUnavailableError, authentication-looking process failures to AgentAuthError, and other ProcessErrors to AgentRunError.
unified_agent/…/codex.py adapts the official openai-codex SDK and codex app-server. build_thread_kwargs() maps workspace, model, developer instructions, and sandbox into Codex thread creation/resume arguments using SANDBOX_MAP, where all three SandboxPolicy values are delegated to Codex's OS sandbox modes. build_turn_kwargs() passes output_schema and validates RunOptions.effort against Codex's generated ReasoningEffort enum, raising AgentRunError with valid values on mismatch. build_config_overrides() injects the shared stdio MCP tool server through Codex config override strings (mcp_servers.<name>.*), including command, args, env, startup/tool timeouts, required=true, and automatic tool approval.
Codex normalization is stateful because usage arrives separately from turn completion. _TurnState tracks the thread id, whether SessionStarted was already emitted, latest assistant text, latest token usage, and accumulated errors. CodexBackend.stream() builds CodexConfig, starts or resumes a thread, emits SessionStarted as soon as a thread id is known, starts a turn, and normalizes every streamed notification through normalize_notification(). thread/started may also establish the session id; item/completed delegates to _normalize_item() for completed agent messages, reasoning summaries, command executions, MCP tool calls/results, and file changes; item/agentMessage/delta produces TextDelta when requested; thread/tokenUsage/updated updates _TurnState.usage; error records an error and emits RawEvent; turn/completed emits the terminal TurnCompleted with the last agent text, latest usage, thread id, duration, parsed structured output when an output schema was requested, status, and combined error text. Codex transport/JSON-RPC exceptions are wrapped as AgentAuthError when they look authentication-related, otherwise as AgentRunError.
unified_agent/…/__init__.py is intentionally empty; backend selection is centralized in unified_agent/agent.py rather than through package exports.
Coupling
- If unified_agent/types.py changes
RunOptions, update both unified_agent/…/claude_code.py and unified_agent/…/codex.py: each backend manually maps options such asworkspace,model,sandbox,instructions,effort,tool_server,output_schema,resume,max_turns,extra_env, andstream_textinto provider-native configuration. - If unified_agent/events.py changes the normalized event dataclasses, update
normalize_message()in unified_agent/…/claude_code.py,normalize_notification()/_normalize_item()in unified_agent/…/codex.py, and the folding logic in unified_agent/agent.py;AgentBackend.stream()promises a normalized event stream ending inTurnCompleted. - If the shared MCP tool server contract changes in unified_agent/types.py or unified_agent/tools.py, verify both MCP registration paths: Claude uses
ClaudeAgentOptions.mcp_serversplus an allowed-tool wildcard in unified_agent/…/claude_code.py, while Codex uses TOML-style config overrides and explicitly serializes the server environment in unified_agent/…/codex.py. - If sandbox semantics are changed or documented differently, check both adapters rather than assuming symmetry: Claude implements read-only by permission/tool allow-lists in unified_agent/…/claude_code.py, while Codex receives native sandbox enum values in unified_agent/…/codex.py.
Risks
- unified_agent/…/claude_code.py relies on Claude Code permission modes and tool allow/disallow lists for
SandboxPolicy.READ_ONLY; if Claude tool names or permission behavior change, a supposedly read-only run may regain write or shell capability because there is no OS sandbox in this adapter. - unified_agent/…/codex.py parses structured output from
state.last_agent_textonturn/completed; if Codex emits schema-conformant output somewhere other than the final agent message text,UnifiedResult.structured_outputwill beNoneeven though the backend produced valid structured data. - unified_agent/…/codex.py keeps only the latest
thread/tokenUsage/updatedpayload beforeturn/completed; if the SDK changes usage notifications from cumulative snapshots to deltas, reportedUnifiedUsagewill undercount tokens.