Designing Cross-Harness Multi-Agent Orchestrators: Dispatch, Retry, and Handoff Patterns
This article dissects the architectural patterns for orchestrating multiple AI agents across different harnesses like T3 Code and Orca, covering adapter capability negotiation, transactional dispatch with outbox patterns, process lifecycle management, context handoff between agents, and pre-merge validation strategies, advocating a 'one writer, one reviewer' starting workflow.
Reading font

Adapter Capabilities Must Be Explicit
Claude Code, Codex, and other agents already have their own tool loops, code search, file editing, and context management. The orchestrator retains these native capabilities and schedules tasks on top: when to start, which agent receives the task, what input it uses, and what results can proceed to the next step.
The first version can live in a single long-running service using SQLite for state. Determining which execution environment owns the project is more useful than prematurely splitting services. T3 Code hands the agent process, terminal, Git, checkpoints, and project files to the server; web, desktop, and mobile clients connect via authenticated RPC. Tapping "Continue" on a phone still uses the project machine's working directory and credentials, not a local phone environment.
Two call directions must be distinguished. The orchestrator drives the harness via an adapter — sending input, collecting events, handling approvals and cancellations. While working, the agent calls back to the orchestrator via MCP tools or CLI to query tasks, send messages, and submit results. The Orca mailbox discussion later uses this second path.
Control Interfaces
A one-way wrapper that only returns final stdout struggles with approvals and mid-run supplementary input; native SDKs or bidirectional protocols provide clearer interaction. The Claude Agent SDK's query() returns an async message stream; the SDK manages the tool loop internally while the host continuously processes messages and the final result. The Codex app-server flow is:
initialize request → receive response → initialized notification
thread/start → save thread.id
turn/start → save turn.id
continuously read events, handle server-sent approval requests
turn/completed → check turn.statusHere thread is a reusable session; turn is one execution round. turn/start returning a round number does not mean work is done; approval requests may arrive while waiting. If the host only waits for the final result and ignores these requests, the agent may wait indefinitely.
Two Codex details are easy to miss:
Mid-run input uses turn/steer with a matching expectedTurnId so a late instruction does not silently slip into the next round. It does not create a new round nor accept overrides for model, cwd, or sandboxPolicy.
Cancellation uses turn/interrupt. Receiving {} is the request acknowledgment; actual completion requires waiting for turn/completed with interrupted status. The host must also handle completed and failed paths — treating a dropped connection as cancellation is wrong. This ends the round, not the entire session process.
ACP (Agent Client Protocol) offers another session/input/update/cancel protocol but also has optional capabilities. For example, loading an existing session requires the peer to declare loadSession. Native protocols, SDKs, and ACP can all serve as integration paths; the deciding factor is which behaviors the interface actually delivers.
T3 Code's Explicit Capability Flags
In ProviderAdapterV2SessionRuntime, canResumeAfterRestart? indicates restart recovery, injectHistory? for history injection, hasPendingBackgroundWork? for querying background work. Beyond these optional members, the orchestration layer reads capabilities declared by the Provider. The presence of rollbackThread on the interface does not mean every Provider supports rollback.
A telling comment: backgroundTasksEndWithProcess?: true can only be set when background tasks and tool calls truly end with the session process. Otherwise, after releasing the session, the thread may need to stay Waiting; background work cannot be marked finished just because the session was released. stopSubagent? 's requestedAt distinguishes stop requests from subsequent recovery, preventing a late stop from affecting a recovered task.
Permissions cannot be "patched" by the adapter either. T3 Code's Provider docs require exposing only natively executable permission modes, not faking missing modes via auto-approval. The policy object's maxRuntimeMode conveys the admin-set ceiling. Rollback has boundaries: when a Provider cannot roll back conversation, it rejects checkpoint rollback before file changes, avoiding code reverting while model context stays at the new version.
These differences directly affect UI and scheduling. If mid-run input is unsupported, schedule it for the next round; if native recovery is unsupported, explicitly hand off via a new session. The upper layer must know what cannot be done to choose alternative paths.
Dispatch and Retry
A common failure: the database marks a task "running" but the orchestrator exits before starting the agent. On restart, the DB has a task but no execution. Starting the process first then writing the DB leaves a gap where the agent is already editing code but the DB has no record.
The transactional outbox solves the persistence problem: write state changes and pending actions together in the DB, then have a background worker execute external actions.
T3 Code's command decision phase performs no external I/O. EventSink commits events, projections, command receipts, and outbox entries in one transaction, then notifies Effect Workers to execute actions and publishes events to subscribers. The "projection" applies events into current queryable task/session state.
Thus a successful command receipt means the execution intent is persisted. Whether the agent actually started or checks completed depends on later results. The transaction only covers DB records; it does not make OS process startup atomic.
Outbox Needs Idempotent Execution and Recovery
If the process already started but the background worker crashes before writing back the start result, retrying the same action could launch a duplicate process. The startup entry must correlate with a stable execution ID: first check if a corresponding execution exists; if uncertain, leave the state as pending verification — never assume "not started". This execution problem remains after adopting outbox; it is not guaranteed by the transaction itself.
T3 Code docs explicitly state that effects bound to a lost Provider process are not re-executed on recovery. The old session no longer exists; resending the old command may not continue the original work.
Timeout Redispatch and Late Results
Task T is assigned to execution A1; after timeout, A2 starts. If A1 then returns a result, writing back solely by task ID could overwrite A2 's newer progress.
T3 Code's writeIfRunCurrent provides a concrete reference. Below is a simplified excerpt preserving the state-check-and-write order; it runs inside commitThenPublish → sql.withTransaction:
const rows = yield* sql`
SELECT status,
json_extract(payload_json, '$.activeAttemptId') AS active_attempt_id
FROM orchestration_v2_projection_runs
WHERE run_id = ${input.runId} AND thread_id = ${input.threadId}
LIMIT 1
`;
const current = rows[0];
if (
current === undefined ||
current.status !== input.expectedStatus ||
current.active_attempt_id !== input.activeAttemptId
) {
return { committed: false, storedEvents: [] };
}
// Optional pending-interrupt guard runs here.
// Event normalization omitted.
const storedEvents = yield* eventStore.append({ events: normalized });
const outcomes = yield* applyStoredEvents(storedEvents);
yield* effectOutbox.enqueue(input.effects ?? []);Reading the current attempt ID, verifying status, appending events, and updating projections all happen inside the transaction. Stale IDs or status mismatches return committed: false without appending events or actions. The check and update cannot be split across transaction boundaries , otherwise a redispatch could occur after the check passes.
An optional guard: when the caller passes unlessInterruptRequested, the code queries by given requestId and resultId. If an interrupt request is already saved but its result not yet saved, this submission is also rejected. This protects only write paths that enable the check; not all result submissions automatically wait for all interrupts.
Command deduplication happens at another entry, commitCommand: insert a receipt by commandId; repeated commands return the existing record. This differs from activeAttemptId — the former identifies "same command again", the latter judges "does this execution still have authority to update current state". Neither equals exactly-once external execution.
A practical detail: T3 Code separates Provider round completion from checkpoint capture. After the round ends, the Run is marked completed — model compute time stops; the snapshot follows as an outbox action. Before the snapshot commits, command decisions still treat the Run as waiting, so subsequent input append, queued rounds, and rollbacks wait for it. Thus the UI neither counts snapshot time as model thinking nor prematurely enables snapshot-dependent operations.
Completion and Exit
The database can reject stale results, yet the old process may still be writing files. Marking a task "cancelled" does not automatically end a process on another machine.
Orca's CLI orchestration docs detail this layer (currently experimental, commands work via a running Orca runtime). It distinguishes several objects:
Run : Persistent namespace and coordinator inbox; does not schedule workers
Task : Work item with spec, dependencies, and state
Dispatch : One execution attempt of a task on a terminal
Message : Message sent to a Run or Dispatch inbox
Decision gate : Decision item created by coordinator; blocks task until resolved
Orca's Run differs from T3 Code's Run; directly borrowing object names across projects causes misreading. The key for our concerns is that Orca separates Task from a concrete Dispatch.
Worker completion reports carry both taskId and dispatchId; completion authority is determined by the currently valid dispatch context. The command shape (angle-bracket IDs from actual dispatch results):
orca orchestration send \
--type worker_done \
--task-id '<taskId>' \
--dispatch-id '<dispatchId>' \
--outcome succeeded \
--files-modified 'src/app/settings/Billing.tsx' \
--body 'Fixed footer overlap; no follow-ups.'--outcomeindicates whether the worker finished its assigned work. For a task "check mobile layout", finding bugs can still report succeeded with the issues in the result; failed means the work could not complete (e.g., repo inaccessible). Thus succeeded does not equal "code meets release criteria". A check task finding bugs differs from an implementation task passing acceptance.
Similarly, "worker ended" has distinct meanings. Orca uses three terms describing different layers of completion and cleanup , not a mandatory three-state sequence:
Settled : Dispatch has a result; normal worker_done also settles the corresponding Task. Does not guarantee related processes have definitely exited.
Ended : Session has gone dormant; records retained. Does not guarantee session is fully destroyed and cannot be continued.
Destroyed : Evidence of process exit obtained. Does not guarantee prior file modifications or external actions have been rolled back.
For example, a worker exiting without reporting marks the Dispatch failed; the Task usually returns to ready; if a circuit breaker trips, the Task also fails. stopReason: exited confirms process exit; lost may stem from connection loss, pane closure, or unverifiable liveness on recovery — cannot be universally treated as execution end.
Stop and cleanup commands preserve this distinction. worker-stop returns non-zero exit code and stop_unknown when stop cannot be confirmed; must first check worker-show. worker-release cleans up resources after completion; worker-abandon only invalidates the original dispatch's eligibility — does not kill the process, nor prove it has exited.
This affects redispatch strategy. If the old execution is confirmed stopped, a recovery plan can adopt the working directory; if unconfirmed, the new execution should use an isolated working directory and avoid sharing writable databases, output paths, etc. Directory separation only solves file copy conflicts; external writes still need permission checks, idempotency keys, or execution validity checks at the actual execution point.
ACP's session/cancel merely requests cancellation of current processing; cancelled is the round's end result. Even receiving it does not imply all background processes are destroyed, nor that occurred side effects are reverted.
Messages and Decisions
A live worker does not mean it has seen the coordinator's new decision.
Orca's ordinary message send receipt only proves the message was saved. For terminal agents, Orca does not type messages into the input box; instead the agent calls orca orchestration check to fetch mail; chat integrations can receive message content directly, with large messages prompting a check call. The two delivery methods differ; neither should be understood as "real-time insertion into model context".
Default check fetches the earliest unread mail FIFO and marks it processed; --peek and --all only view without consuming. These describe mailbox retrieval state. Even after a mail is fetched, it does not prove the agent modified code, or that modifications align with the new decision.
Take parallel frontend/backend work: backend decides to add a "cancelling" state; frontend still implements "remove task on request success". Sending a message starts discussion; what actually lets both sides proceed is a confirmed interface contract and task inputs using that contract version.
Orca's Decision gate writes "undecided" into dependencies: the coordinator creates a question for a task; until a ruling is recorded, the task is blocked. First ruling written succeeds; resubmitting the same answer succeeds, changing to a different answer returns answer_conflict. This prevents retries from silently overwriting decisions. But whether the answer is yes or no, subsequent merge/cancel/replan is still interpreted by the coordinator or workflow; "decision item resolved" is not "code already merged".
Permission approvals must not mix with ordinary collaboration Q&A. Orca defaults to only humans approving worker permission prompts; only when the user explicitly enables "allow coordinator to approve worker permission prompts" can the coordinator approve, and even then subject to the worker machine's settings. For the orchestrator, waiting for approval must be recorded separately — cannot misjudge a long silence as failure and launch a duplicate worker.
This splits model-strength judgment from program-strength waiting. The agent interprets interface divergences and proposes solutions; the program persists questions, waits for answers, limits duplicate writes, and decides when tasks become runnable.
Context Handoff
The same task may switch harnesses back and forth: early rounds use Codex for implementation, mid-way Claude Code analyzes design, then back to Codex for edits. Native Session IDs are not cross-product portable; merely replaying user/assistant text may not include prior tool results.
Erwin's dual-thread approach: application layer uses AppThread to store conversation, ProviderThread to record each native session and sync positions. When switching back to a used harness, reuse the session and inject missing conversation. T3 Code's interface also has injectHistory? as an optional extension point. But what content can be injected and in what message form remains up to the adapter and native protocol; not all harnesses can be treated as losslessly interchangeable.
Session recoverability does not guarantee all previously read file contents are fully retained; context may be compressed, code may have been changed by another agent. The model's prompt cache has its own TTL and hit conditions; session recovery cannot promise cache hits .
During handoff, besides conversation, the following items should be pinned down:
Goal, acceptance criteria, and confirmed interface version : What exactly must be achieved this time
Code baseline, candidate commits, uncommitted changes : Which code to continue from; any uncommitted work
Check commands, results, and corresponding commits : Which behaviors verified, on which version
Open items and pending questions : What to do next; what cannot be decided autonomously
These are the article's suggested handoff contents, not a requirement for both tools to share one data table. Reuse existing recoverable sessions; otherwise create new. Either way, the incoming agent can locate artifacts and re-read changed files. This continues the earlier thinking from Session to Project: agreements and progress must persist beyond a single session.
Pre-Merge Acceptance
After context handoff works, add parallel writers. Each worker uses an independent Git worktree to avoid directly overwriting the same working copy; but worktrees still share some Git metadata, and do not isolate ports, databases, or credentials .
A more common trouble is semantic inconsistency: backend changes a response field, frontend calls the old field; both unit tests pass individually, but combined they fail. Erwin's second post proposed agreeing on interfaces first, allocating modification scopes, then unified merging. In the orchestrator, these agreements become checkable inputs and artifacts.
Parallel tasks start from the same baseline and interface version. When a shared interface must change, record the new version first, pause or re-evaluate affected tasks; "interface lock" does not mean never change. Directory allocation reduces overlapping writes, but writing it into the prompt remains a collaboration convention. To block out-of-bounds writes, need file permissions or execution environment constraints; post-commit diff scope checks reject out-of-bounds changes.
At integration, cannot just collect a branch name and "tests passed". Branch names move; check results must bind to a specific commit . Example: B's tests ran on mainline M1; after A merges, mainline becomes M2; B's green on M1 does not prove M2 is fine. Merge queues rebase or temp-merge to construct a candidate version, then run relevant checks; if candidate content changes, re-evaluate whether tests and reviews still apply.
For the cancellation feature, at minimum run one full flow on the combined code: trigger export, request cancel, show "cancelling", background exits, page shows final result. Separate frontend and backend tests may not cover this interaction.
Permissions must follow role and resource configuration. Implementers need source write; reviewers typically read-only, but running tests may write caches and temp artifacts — give them an isolated write location. Git worktree itself does not forbid reviewers from modifying other directories, nor stop any worker from using inherited environment credentials.
Thus "unifying approvals in one UI" and "all execution paths under one permission system" are separate. Native tools, Shell, and MCP services must each verify actual boundaries; proxy-friendly credentials can stay in the outer layer; native logins unsuited for agents should be isolated by account and execution environment, avoiding direct inheritance of all host permissions. T3 Code's Provider docs explicitly require isolating account state per Provider instance and stripping environment credentials not configured for that instance.
Start with One Writer, One Reviewer
Reviewing these implementations, the first version can start with "one writer, one reviewer": implementer submits a candidate commit; reviewer independently checks against task goal and diff; issues found → revision; candidate changes → re-check affected parts. This already validates cross-harness onboarding, artifact handoff, and failure recovery, and clarifies what the second agent actually reduces.
Task, Attempt/Dispatch, Session, Artifact must be separated in meaning and identity. Whether stored as independent tables or structured records can follow first-version needs; the key is being able to trace which result belongs to which execution and input, and who currently holds update authority.
Logs center on these correlations: execution ID, code baseline, native thread/turn, approval and interrupt requests, candidate commits, acceptance results. They aid recovery and debugging, but storing events does not mean the whole system can be rebuilt from scratch. T3 Code explicitly keeps only a limited event replay window; current state relies on persistent projections, not full rebuild from event logs.
Finally, review capacity. Addy Osmani's "The Orchestration Tax" warns that launching more agents does not increase a single person's judgment time. If one person still owns key design and final review, a backlog of candidate commits means adding workers often just lengthens the wait queue. The orchestrator can throttle new task dispatch based on pending review count and wait time , digesting existing changes first.
Following this workflow, we then ask when concurrency fits: can tasks advance independently? Is handoff clear? Can review and integration keep up? Only when these conditions hold, add a second writer; if the bottleneck is already review, improve checks and handoff first so added agents truly reduce human work.
About this article
For attribution, corrections or content rights, contact