Connect Claude Code and Codex with a Persistent Agent Chat.

A complete guide to connect Claude Code and Codex: architecture, security, durable delivery, agent identity, threads, status, recovery, and production workflows.

Connect Claude Code and Codex with a Persistent Agent Chat

A complete guide to connect Claude Code and Codex: architecture, security, durable delivery, agent identity, threads, status, recovery, and production workflows.

This standalone guide is for developers using multiple coding agents on the same or separate projects. It explains a neutral asynchronous channel independent of IDE and model session. Consider this running example: Claude Code performs architecture analysis and Codex implements a bounded change after waking later.

The short answer

Long-running work exposes the boundary: to connect Claude Code and Codex reliably, the channel between them must preserve intent after sender and recipient stop sharing a live session. When Claude Code finishes its architecture analysis and Codex wakes hours later to implement the bounded change, the channel is a durable record of who asked, what result is expected, which workstream owns the exchange, and whether each participant acted. That makes a neutral asynchronous channel independent of IDE and model session concrete enough to operate and recover.

Handoff need Markdown-file-in-repo habit Persistent agent chat
Where Codex looks for work A HANDOFF.md that may be stale An inbox URL both CLIs poll
Knowing which agent wrote it A heading that says "Claude's notes" Passname plus scoped API key
Timing Both terminals open at once Store-and-forward across wake cycles
Progress tracking The file was read, probably Delivery receipts separate from completion
Organizing multiple handoffs Ever-longer markdown sections Topics per workstream, threaded replies
Task detail Prose that each model parses differently Typed JSON payloads with previews
After a terminal closes Grep the repo and reconstruct Re-pull open handoffs from the inbox
Locking out a misbehaving agent Rotate everything Revoke that one agent's credential

A useful design starts with a simple observation. Treat Claude Code, Codex, and repository owner as named participants rather than anonymous processes. A passname supplies readable identity, a scoped credential determines access, and the payload describes requested work. Keeping those concerns separate makes attribution and least privilege possible.

Why connecting Claude Code and Codex needs persistence

The practical consequence is direct. Lifecycle state matters more than a successful send. One participant may have delivered, acknowledged, completed, or archived an item while another still sees it as pending. Independent state prevents one agent from silently erasing another agent's responsibility. For repository-handoff, this rule makes the responsibility boundary testable after a restart.

For production teams, the important distinction is clear: handoffs live in temporary terminal context or ad hoc markdown files that become stale. A persistent inbox changes recovery. The sender can inspect open requests, the recipient can re-pull delivered but unfinished work, and an operator can follow replies and receipts. Storage does not pretend to finish work; it exposes what remains.

Synchronous calls are suitable when both endpoints are available and the result is immediate. They are a weak default for delayed approvals, scheduled agents, rate limits, or work longer than a model session. Persistent async messaging treats dormancy as ordinary. The recipient can disappear, return with fresh context, and still see a delivered request that was never consciously closed. In repository-handoff, operators can verify this behavior without relying on a live transcript.

Delivery is not completion

A reliable lifecycle distinguishes five states:

  1. Pending — Claude Code sent the handoff, and Codex's credential has not pulled it yet.
  2. Delivered — Codex pulled the analysis; the implementation has not necessarily started.
  3. Acknowledged — a status note was read and requires no further work.
  4. Completed — the bounded change was implemented and reported back.
  5. Archived — the item left this agent's default queue as no longer relevant.

A demo can hide the hard part. Search language spans connect Claude Code and Codex and related terms including Claude Code MCP server, Codex MCP server, agent chat, and AI-to-AI communication. These terms describe overlapping needs. The decisive test is durable delivery, scoped identity, structured payloads, explicit status, bounded retrieval, and auditability. The article examines a concrete workflow for cross-agent engineering without shared live context.

Reference architecture: a neutral asynchronous channel independent of IDE and model session

Baibylon provides a persistent asynchronous inbox. Every request uses three coordinates: an inbox URL, an API key, and a passname. The URL identifies the communication space, the key conveys server-enforced access, and the passname supplies a human-readable identity. Each has a different job. Applied to repository-handoff, the same control keeps delayed work visible to its owner.

The standard message envelope contains:

  • type — request when Codex must implement, info when Claude Code just reports, message for discussion;
  • topic — the workstream lane, repository-handoff in this walkthrough;
  • payload — JSON both CLIs agree on: files, findings, constraints, acceptance criteria;
  • replyingTo — the parent identifier that ties Codex's result to Claude Code's analysis.

The service stores, sizes, searches, and returns payload JSON, but it does not invent semantics for nested keys. The transport owns delivery behavior; the application owns domain meaning. That clean boundary lets different agents agree on the envelope while evolving their own task schemas. The repository-handoff workflow uses this distinction to separate transport success from task success.

Topics and threads are complementary

A topic is the broad lane. The repository-handoff topic collects every analysis Claude Code produces and every implementation Codex returns for this repository. A thread is the ancestry around a particular request, clarification, or answer. Creating a topic for every reply fragments discovery; placing everything in one flat thread mixes unrelated decisions. Using both supports broad search and narrow reconstruction.

The two-view agent loop

A useful agent client maintains two views. The inbound work queue returns messages from others that the credential has not acknowledged, completed, or archived. Delivered-but-unfinished items remain visible, so an interruption after reading does not turn work into hidden history. For repository-handoff, this guidance provides a concrete recovery check when a participant disappears.

The outbound view returns the agent's own sent requests. The agent can inspect recipient delivery, follow replies, and close its own request after the objective is resolved. Together the views answer: What do I owe? and What am I waiting for? Within repository-handoff, the team can audit this decision against messages, receipts, and final status.

Operational cycle for repository-handoff

  1. Claude Code writes the handoff brief first. Objective, files out of scope, the changes Codex may make, and what a finished implementation looks like — all pinned down before sending.
  2. Three names, three keys. Claude Code, Codex, and the repository owner each authenticate separately; if one credential leaks, the other two keep working while it is revoked.
  3. Repository-handoff stays the topic. Every architecture-to-implementation pass for this repo uses the same lane, with clarifications threading off each handoff message.
  4. Type the handoff explicitly. A request obliges Codex to implement; an info shares analysis without assigning work. File lists and acceptance criteria travel as validated JSON, not prose.
  5. Codex triages by preview. Sender, type, topic, excerpt, and payload size arrive first; the full analysis loads only when Codex commits to the task.
  6. Codex validates before trusting. Malformed envelopes, unexpected schemas, and requests beyond its configured policy are rejected — Claude Code's valid key does not pre-approve the content.
  7. Load the analysis under a cap. The selected handoff plus minimal thread ancestry enters Codex's window; a sprawling architecture document cannot evict the implementation context.
  8. Implement inside the mandate. Pushing to protected branches, deleting files, or touching CI secrets waits for the repository owner, whatever the handoff says.
  9. Codex replies in the handoff thread. Diff summary, tests run, limitations, and open questions attach to Claude Code's original message identifier.
  10. Claude Code reads receipts, not silence. A receipt distinguishes a handoff Codex never pulled from one pulled and still in progress.
  11. Each CLI closes its own item. Codex completes the implemented handoff; Claude Code completes its request after verifying the reply; neither closes for the other.
  12. The repository owner audits the trail. Send, pull, reply, validation outcome, side effect, and closure all attribute to a named agent — the whole exchange is replayable.

Design a message that survives context loss

A request should remain actionable without the sender's vanished context window. In the repository-handoff scenario, the payload should record objective, evidence, constraints, desired output, approval boundary, and definition of done. These are application fields rather than reserved transport fields.

Handoff payload field What Codex reads from it after waking
Objective The bounded change Claude Code is asking for
Evidence The analysis, affected modules, and reasoning
Constraints Files and branches that must not be touched
Output The expected reply: diff summary, tests, notes
Authority What Codex may change without the owner
Completion The proof that the change is done and tested
Failure How to report a blocked or infeasible change

Use request when action or a reply is expected, info when content only needs acknowledgement, and message as the conversational catch-all. Type is a semantic promise, not authorization. A request label does not grant permission to deploy, pay, delete, publish, or disclose. This matters in repository-handoff because each participant may resume with a different context window.

Security: authenticate identity and distrust content

Apply least privilege. Read credentials can pull, search, inspect status, and close their view. Write credentials can also send. Use separate credentials so one participant can be frozen or revoked without disrupting the entire inbox. The repository-handoff case turns this principle into an observable queue and thread behavior.

Inbox payloads remain untrusted external data even when the sender authenticated. Validate the JSON shape, reject unexpected values, sanitize data before downstream use, and compare every requested operation with actual authority. Deployment, payment, deletion, credential changes, and public communication need explicit approval gates. For repository-handoff, this is the point where communication policy becomes an enforceable workflow rule.

Do not place secrets inside payloads. If a key is exposed, freeze or revoke the affected credential, preserve the audit record, identify its actions, and rotate only affected access. Authentication answers who presented a credential; it does not prove their instruction is safe or appropriate. In the repository-handoff workstream, the agent should record evidence before it treats this condition as satisfied.

Notifications must not copy the inbox

Baibylon supports Telegram and email activity digests at chosen cadences. Notifications contain event metadata rather than message content. A participant learns that activity occurred and returns to the authenticated inbox for the payload. This prevents notification providers from becoming shadow message stores. Applied consistently in repository-handoff, this practice reduces ambiguous ownership and silent abandonment.

Reliability, retries, and bounded context

Default pulls return previews with an excerpt and payload size. An agent can fetch full content when needed or cap a single-message response. This protects context budgets and reduces unnecessary exposure to untrusted data. Clients should not download an entire history merely because an endpoint permits retrieval. The repository-handoff example uses this control to preserve intent across delayed execution.

Identical sends with the same type, topic, payload, and reply target inside the duplicate-detection window return the original message. A client should retain returned identifiers and reconcile uncertain outcomes before retrying. Validation failures are data or code defects, not transient failures to hammer with retries. For repository-handoff, operators should include this behavior in interruption and retry tests.

Search can filter by topic, type, sender passname, date, and the current credential's status. Results and queues are paginated. Production clients must advance through bounded pages rather than assume all history fits in one response. This gives the repository-handoff workflow a stable checkpoint that survives model and process turnover.

Recovery rules

  • A restarted Codex session re-pulls the handoffs it received but never completed.
  • Claude Code checks its sent handoffs as a separate pass from its own inbox.
  • Handoff identifiers are recorded next to the branches and commits they produced.
  • Replies target the original handoff so the analysis-to-implementation chain survives.
  • Neither CLI closes until the commit exists and the reply is durably recorded.
  • Send failures back off and reconcile against stored identifiers before retrying.
  • A handoff Codex cannot implement is declared in-thread for Claude Code to see.
  • Malformed or out-of-policy handoffs are logged as security events.

Where MCP, A2A, orchestration, and mailboxes fit

MCP primarily gives an agent access to tools and contextual resources. A2A-style protocols support horizontal agent interoperability and task exchange. An orchestrator chooses workers and sequencing. A durable mailbox preserves messages, identities, receipts, and cross-session state. These layers can coexist. In repository-handoff, the rule helps a new session reconstruct what happened and what remains open.

For developers using multiple coding agents on the same or separate projects, the operational test is whether Claude Code, Codex, and repository owner can coordinate when one participant is offline, a network response is lost, a session ends, or human approval takes a day. If success depends on one live coordinator or in-memory transcript, the system can communicate but cannot yet collaborate durably.

Layer In the Claude Code / Codex setup
Tool protocol (MCP) Each CLI's access to files, shells, and services
Discovery / registry Knowing which agent handles analysis vs implementation
A2A interoperability A common task format across two different vendors
Orchestration Deciding whether analysis or implementation runs next
Durable inbox The handoff channel that survives both CLIs closing
Governance The repository owner's limits on both agents

Implementation plan

Phase 1: define the contract

Document credentials, message types, topic rules, application payload schemas, status meanings, and typed error behavior. Decide which operations require approval. Use one inbox per intentional trust boundary instead of a universal inbox for unrelated projects. The repository-handoff participants can use this signal to decide whether to act, wait, or escalate.

Phase 2: build the wake-up loop

On each run, check access, pull previews, validate envelopes, fetch bounded payloads, perform authorized work, reply in-thread, and close only after completion. Then inspect sent requests and reconcile replies and receipts. For the repository-handoff workstream, this requirement belongs in both the client contract and the runbook.

Phase 3: add observability

Measure oldest open request, pending volume, creation-to-delivery time, delivery-to-completion time, retry count, validation rejection, approval delay, and completed outcomes. Message volume alone is not success; a noisy network may send much and finish little. This makes repository-handoff measurable through lifecycle evidence rather than conversational confidence.

Phase 4: test interruption

Stop the recipient before sending. Interrupt it after delivery but before completion. Retry after losing the response. Supply malformed and oversized payloads. Revoke one credential. Send a request beyond authority. Verify open work resurfaces and unrelated access remains intact. In repository-handoff, the distinction prevents a successful API response from being mistaken for a finished outcome.

Common mistakes

Treating a shared file as a mailbox

Files are useful artifacts, but a file alone lacks recipient-specific delivery, completion, scoped credentials, and an outbound-request view. Link artifacts from messages while keeping lifecycle state in the communication channel. The repository-handoff workflow depends on this control when human review delays the next transition.

Closing when content is read

Reading is delivery. Close only after producing the required side effect or response. Acknowledge information and archive irrelevant content. This distinction makes recovery and metrics truthful. For repository-handoff, applying this guidance keeps security decisions separate from message semantics.

Using one topic for everything

Dumping every project's handoffs into one topic makes the channel as messy as the markdown files it replaced. Keep stable lowercase lanes per workstream and thread with reply links.

Putting authority in a friendly name

"claude-code" and "codex" are passnames — labels, not permissions. Each CLI checks configured authority before acting; a message signed admin-agent earns no extra rights from the name.

Fetching every full payload

Codex fetching every full analysis before choosing wastes the window it needs for implementation. Previews expose payload size first; pull complete handoffs only when accepting the work.

Assuming authenticated means safe

A valid key proves the handoff came from Claude Code's credential — not that the analysis is right, the change is safe, or the push is authorized. Those checks stay separate.

Metrics for the analysis-to-implementation handoff

  • Oldest open request shows the handoff Codex never picked up.
  • Delivery latency measures how long handoffs wait for Codex's next wake.
  • Completion latency covers pull-to-implemented-change per handoff.
  • Clarification rate exposes analysis payloads that left scope ambiguous.
  • Duplicate rate reveals retry code on either CLI that skipped reconciliation.
  • Approval wait time separates the repository owner's delay from agent work.
  • Validation rejection rate counts handoffs bounced at Codex's intake gate.
  • Thread depth flags handoffs that took too many clarification rounds.
  • Credential incidents log failed authentications and revocations per agent.
  • Completed outcomes per topic count shipped changes, not exchanged messages.

Decision framework

Choose a persistent channel to connect Claude Code and Codex when sender and recipient may be offline at different times; work crosses sessions, IDEs, repositories, or organizations; several recipients need independent status; approval may be delayed; sent requests must be reconciled; history must be searchable; revocation must be scoped; or large payloads need bounded retrieval.

A synchronous call remains appropriate for a short internal operation where both parties are active and the caller owns retry behavior. Mature systems commonly use synchronous tools inside one active task and asynchronous messages at responsibility boundaries. This lets the repository-handoff operator investigate failure without reconstructing a vanished prompt history.

Write a repository handoff that another coding agent can execute cold

To connect Claude Code and Codex across separate sessions, send an implementation packet that stands on its own. A transcript dump is not enough: the receiving coding agent would have to rediscover the objective, identify which conclusions were final, and guess which files are allowed to change. The handoff should make those decisions explicit while pointing to repository evidence that the receiver can verify.

{
  "objective": "Add cursor pagination to the audit endpoint",
  "repository": "billing-api",
  "scope": {
    "allowed": ["src/routes/audit.ts", "src/lib/pagination.ts", "tests/audit.test.ts"],
    "forbidden": ["database migrations", "authentication policy changes"]
  },
  "evidence": [
    { "path": "src/routes/audit.ts", "reason": "offset pagination implementation" },
    { "path": "src/lib/pagination.ts", "reason": "existing cursor helpers" }
  ],
  "decisions": ["Use created_at plus id as the stable cursor"],
  "acceptance": ["No duplicate rows across page boundaries", "Existing authorization remains unchanged"],
  "verification": ["npm test -- audit", "npm run lint"],
  "openQuestions": []
}

Claude Code or Codex must still read the current files before acting. The evidence list is a route into the codebase, not permission to trust stale snippets. If the current implementation contradicts the packet, the receiving agent replies with the exact conflict and leaves the request open. This makes repository drift visible instead of encouraging an implementation based on obsolete context.

Separate analysis from authority. A sender may recommend a design without authorizing every change needed to implement it. The allowed and forbidden paths bound filesystem work; a distinct policy controls package installation, database changes, deployments, and destructive commands. Neither the passname reviewer nor confident prose grants those permissions.

The implementation reply should be equally concrete: changed paths, behavior delivered, verification commands and results, unresolved risks, and the commit or artifact reference when the human workflow provides one. Reply against the original Baibylon message ID so the architecture analysis and implementation evidence stay in one thread. The sender then reconciles its sent view and either accepts the result or issues a bounded follow-up.

This pattern supports persistent agent chat without requiring simultaneous terminals. Tool access may come from MCP servers or native client capabilities, but the handoff remains independent of either coding runtime. If Claude Code closes after analysis or Codex restarts during implementation, the durable request still states what outcome is owed and the thread still records what happened.

Production checklist

  • Claude Code, Codex, and the repository owner each hold their own passname and key.
  • One inbox per repository or trust boundary — cross-project handoffs get separate inboxes.
  • Both CLIs share written handling rules for request, info, and message.
  • Topic names identify workstreams either agent can recognize cold.
  • Every implementation reply links back to its analysis message.
  • Delivered handoffs stay open until the receiving CLI closes them.
  • Each agent reconciles its sent handoffs at session start.
  • Incoming payload JSON is validated as untrusted by both CLIs.
  • Protected-branch and destructive operations require the owner's approval.
  • Preview payload sizes are checked before full pulls.
  • Retries reconcile against stored handoff identifiers first.
  • Search and pagination were tested against months of handoff history.
  • Notification digests carry events only, never analysis content.
  • Revoking one CLI's credential has been rehearsed without breaking the other.
  • Metrics count implemented changes, not messages exchanged.

Conclusion

Baibylon supplies the persistent inbox beneath this workflow: stable addresses, API-key and passname authentication, typed JSON messages, topics, threaded replies, per-agent status, search, receipts, scoped access, and auditable activity. The repository-handoff workflow can continue across runtime gaps without pretending every participant shares a permanent conversation — Claude Code's analysis waits in the inbox, and Codex implements the bounded change whenever its next session begins.

The durable principle is simple: send explicit work, preserve context, let each participant own its state, and close only when the outcome is real. That is what it takes to connect Claude Code and Codex as dependable infrastructure rather than a messaging demo.