Unified Agent Core
Overview
The unified agent core is the public orchestration layer that lets callers run the same task through Claude Code, Codex, or several configured agents at once. unified_agent/__init__.py is the package entrypoint: it re-exports UnifiedAgent, SuperAgent, Task, normalized event classes, shared result/configuration types, and adjacent skills/tools helpers so callers can stay on the top-level unified_agent API instead of importing backend-specific modules.
unified_agent/agent.py owns backend coordination. _make_backend() accepts either a backend name ("claude" or "codex") or an AgentBackend instance; named backends are imported lazily from unified_agent.backends.claude_code and unified_agent.backends.codex, and import failures are converted to BackendUnavailableError. The runtime backend contract is intentionally small: unified_agent/…/base.py defines AgentBackend.stream(prompt, opts) as an async iterator of normalized AgentEvents that must end with TurnCompleted.
UnifiedAgent represents one configured agent unit. Its constructor records the backend, workspace, model, SandboxPolicy, optional ToolRegistry or registry spec, optional skills source directory, prompt instructions, reasoning effort, extra environment, and whether text deltas should stream. Before the first run, _prepare() creates the workspace, installs skills from skills_dir into both host discovery locations through install_skills(), and turns tools into a ToolServerSpec through build_tool_server_spec(). _run_options() then packages this prepared state into a RunOptions dataclass for the backend.
The task lifecycle starts in UnifiedAgent.stream(). It coerces strings into Task objects with Task.coerce(), renders the task for the selected backend via Task.render(self.backend.name), builds RunOptions, and yields every normalized backend event unchanged. UnifiedAgent.run() wraps stream() to accumulate events; backend exceptions do not escape from run(), but are folded into a UnifiedResult with success=False by collect(). run_sync() is a synchronous convenience wrapper around asyncio.run().
SuperAgent in unified_agent/agent.py coordinates multiple UnifiedAgent instances supplied as a name-to-agent mapping. run(name, task, ...) delegates to one named agent. run_all(task, only=None, ...) fans the same task and keyword options out concurrently with asyncio.gather() and returns a name-keyed result map; run_all_sync() wraps that flow for synchronous callers.
unified_agent/task.py defines the shared input envelope. A Task has a required plain-text instruction, optional context_files, optional free-form context, and an optional skill name. render() reads each context file at call time, truncates individual files at MAX_FILE_CHARS (200,000 characters), appends additional context, and renders skill invocation hints differently for Codex (Use the $name skill) versus other backends (invoke it with the Skill tool). This means task rendering is part of orchestration, before backend execution starts.
unified_agent/events.py defines the normalized event model that all backends emit. Events cover session start (SessionStarted), incremental and completed assistant text (TextDelta, AssistantText), reasoning, tool calls and results, shell command executions, file changes, run completion (TurnCompleted), and backend-native fallback payloads (RawEvent). AgentEvent is a union of those dataclasses. TurnCompleted is the summary event: it carries success, final text, UnifiedUsage, cost, session id, duration, structured output, stop reason, and error text.
unified_agent/types.py contains the shared data types passed between orchestration and backends. SandboxPolicy is the backend-independent policy (read_only, workspace_write, full_access). RunOptions is the full backend run configuration built by UnifiedAgent, including workspace, model, sandbox, instructions, effort, tool server launch spec, output schema, resume token, max turns, environment, and streaming preference. UnifiedResult is the collected output returned to callers; it includes summary text, structured output, usage, cost, session and duration, extracted ToolCall and FileChanged events, the complete event list, and an optional error string. Package-level errors (UnifiedAgentError, BackendUnavailableError, ToolRegistryError, SkillError, ToolServerError, AgentRunError, AgentAuthError) also live here so core and adjacent modules share one exception hierarchy.
Result collection is centralized in collect() in unified_agent/agent.py. It scans the event list for the last TurnCompleted, last AssistantText, and first SessionStarted. The result text prefers TurnCompleted.final_text, falls back to the last assistant message, and finally to an empty string. Success requires a successful TurnCompleted and no wrapper-captured exception. Tool calls and file changes are filtered out of the full event stream into convenience lists while preserving the original events for consumers that need exact ordering.
Coupling
- If a backend implementation changes what it emits, verify
unified_agent/agent.py::collect()and unified_agent/events.py:collect()relies onTurnCompletedfor success, usage, structured output, cost, duration, and final text, and falls back toAssistantText/SessionStartedonly for text and session id. - If
RunOptionsin unified_agent/types.py gains, renames, or changes semantics for a field, updateUnifiedAgent._run_options()in unified_agent/agent.py and both backend adapters. Backends receive only this dataclass, not theUnifiedAgentinstance. - If skill invocation syntax changes in either backend, update
Task.render()in unified_agent/task.py and the skills installation path used byUnifiedAgent._prepare()in unified_agent/agent.py; the sameTask.skillvalue is rendered into backend-specific prompt text whileinstall_skills()makes the skill discoverable to both hosts. - If tool server launch behavior changes, check both
UnifiedAgent._prepare()in unified_agent/agent.py andToolServerSpecin unified_agent/types.py. The core stores a single preparedToolServerSpecand passes it throughRunOptions; backend adapters are responsible for launching it consistently. - If the public API changes, update unified_agent/__init__.py exports alongside the implementation. Callers are expected to import orchestration classes, event classes, result/configuration types, skills helpers, and tools helpers from the package root.
Risks
- unified_agent/task.py reads
Task.context_filesduring prompt rendering without checking theUnifiedAgent.workspace. If a caller passes a missing, very large, or unintended path, the run can fail before the backend starts or inline content outside the intended workspace;UnifiedAgent.run()will report that as a failedUnifiedResult, whileUnifiedAgent.stream()lets the exception propagate. - unified_agent/types.py documents that
SandboxPolicymaps asymmetrically: Codex uses an OS sandbox, while Claude Code is mapped through its permission system. Code that treatsSandboxPolicy.READ_ONLYorWORKSPACE_WRITEas identical enforcement across backends can permit different real-world behavior when the sameTaskis run throughSuperAgent.run_all()in unified_agent/agent.py.