Back to Insights
AI & Machine Learning•Taming the Coding Agent Fleet: How to Orchestrate Claude Code, Codex, and Gemini CLI from One TUI—or Your Phone•tutorial•November 22, 2026•32 min read

Taming the Coding Agent Fleet: Orchestrating Claude Code, Codex, and Gemini CLI from One TUI

A hands-on guide to running Claude Code, Codex, and Gemini CLI in one terminal, with mobile control, session orchestration, and production-safe workflows.

T
Tamiz UddinFull-Stack Engineer

Most teams do not have an AI coding problem. They have an AI coding coordination problem.

One engineer opens Claude Code for a refactor. Another runs Codex in a terminal multiplexer. A third triggers Gemini CLI from a phone while a build runs. Each agent works alone, and every agent has its own context, permissions, and session state. When the work spans repositories, the coordination tax grows faster than the token bill.

The good news: Claude Code, OpenAI Codex CLI, and Gemini CLI are all usable as separate processes. That means you do not need to replace them, wrap them in a proprietary platform, or rebuild your own agent runtime. You need a control plane that treats them as interchangeable workers.

This tutorial builds that control plane: a terminal multiplexer-based fleet manager with a single TUI for launching, observing, and steering agents, plus an optional phone bridge for approvals and status checks. The approach is deliberately boring—Tmux, SSH, and small scripts—because infrastructure you can read is easier to operate at 2 a.m. than a black-box orchestrator.

Table of Contents

1. The Core Idea: Agents as Processes

Each CLI is already a long-running process that reads from stdin, writes to a terminal, and manages its own conversation state. The orchestration problem reduces to four primitives:

  1. Spawn an agent process in an isolated terminal pane.
  2. Attach to that pane to observe or type.
  3. Capture output for logs, summaries, and audit trails.
  4. Escalate to a human when the agent needs permission or a decision.

Tmux gives you all four. A tmux session is a persistent terminal server. Panes and windows inside it hold agent processes that survive SSH disconnects. tmux capture-pane extracts recent output without interrupting the process. tmux send-keys injects input. That is enough to build a fleet control plane today, with no daemon to deploy and no API keys to add to a third-party service.

The architecture looks like this:

sql
                    ┌─────────────────────────┐
   laptop TUI  ───▶ │  tmux server (host)      │
   phone TUI   ───▶ │  ├─ window: claude      │
   CI trigger  ───▶ │  ├─ window: codex       │
                    │  └─ window: gemini      │
                    └───────────┬─────────────┘
                                │
                    ┌───────────▼─────────────┐
                    │  agent processes         │
                    │  (each owns its context) │
                    └─────────────────────────┘

The important design decision: the orchestrator never tries to merge agent contexts. Claude Code keeps its context. Codex keeps its context. Gemini keeps its context. The fleet manager only coordinates processes, not prompts. Trying to unify conversations by concatenating transcripts produces a mess: model-specific tool formats, divergent system prompts, and stale state.

Coordinate at the process boundary, and each vendor's strengths stay intact.

Scope note. This tutorial orchestrates the CLIs you already have. It does not attempt to unify their model APIs, swap providers behind a single interface, or benchmark which agent writes better code. Those are different problems with different trade-offs.

2. Prerequisites and Compatibility

You need:

  • A Unix-like host: Linux, macOS, or WSL2 on Windows.
  • tmux 3.0 or newer.
  • bash 4.x or newer, plus jq and curl.
  • Node.js 20+ (for the agent CLIs themselves).
  • An SSH client on the machine you want to control from.
  • Authenticated accounts for whichever agents you plan to run.

Install the system dependencies:

bash
# Debian / Ubuntu
sudo apt-get update
sudo apt-get install -y tmux jq curl git

# macOS
brew install tmux jq curl git

Verify tmux is new enough:

bash
tmux -V
# tmux next-3.4 or tmux 3.3a

Tmux 3.2+ adds tmux new-session -d -P -F conveniences and improved capture-pane behavior, but the scripts below work on 3.0+ with minor adjustments.

Agent CLI installation

Install each CLI using its vendor-documented method. The commands below are the common paths as of the current releases; always check each tool's official docs if a flag has moved.

bash
# Claude Code (Anthropic)
npm install -g @anthropic-ai/claude-code

# OpenAI Codex CLI
npm install -g @openai/codex

# Gemini CLI (Google)
npm install -g @google/gemini-cli

Confirm all three are on your PATH:

bash
command -v claude && claude --version
command -v codex  && codex  --version
command -v gemini && gemini --version

Authenticate before you start orchestrating. Run each CLI once interactively and complete its login flow:

bash
claude
codex
 gemini

Exit each with Ctrl+C or /exit once you see the prompt. Authentication tokens are stored per-user on the host, so the fleet runs as your account and inherits your permissions. If you want a non-interactive CI-style run, each CLI also supports a one-shot prompt mode (for example claude -p "..." or codex exec "..."); the fleet design below prefers interactive sessions because that is where human-in-the-loop steering matters.

3. Install the Three Agent CLIs

Before building the launcher, pin the versions. Agent CLIs change flags and prompt behavior quickly, and a fleet that breaks because one CLI renamed a subcommand is a fleet you will stop trusting.

bash
npm ls -g --depth=0 | grep -E 'claude-code|codex|gemini-cli'

For reproducible environments, generate a lockfile of your global tool versions:

bash
mkdir -p ~/.agent-fleet
npm ls -g --depth=0 --json \
  | jq -r '.dependencies | to_entries[] | "\(.key)@\(.value.version)"' \
  | grep -E 'claude-code|codex|gemini-cli' \
  | sort > ~/.agent-fleet/versions.lock
cat ~/.agent-fleet/versions.lock

In CI, you can assert against that file:

bash
while read -r pkg; do
  name="${pkg%@*}"
  want="${pkg##*@}"
  got="$(npm ls -g --depth=0 --json | jq -r --arg n "$name" '.dependencies[$n].version // "missing"')"
  if [ "$got" != "$want" ]; then
    echo "version drift: $name want=$want got=$got" >&2
    exit 1
  fi
done < ~/.agent-fleet/versions.lock

This is not ceremony. It turns "the fleet mysteriously stopped working" into a one-line diff.

4. Build a Unified Agent Launcher

Now create the launcher script. This is the heart of the system: a small wrapper that normalizes how you start an agent without pretending the agents are the same underneath.

Create the directory and the script:

bash
mkdir -p ~/.agent-fleet/bin ~/.agent-fleet/logs

Write ~/.agent-fleet/bin/fleet:

bash
#!/usr/bin/env bash
# fleet — launch and manage a multi-agent coding session in tmux
set -euo pipefail

FLEET_DIR="${FLEET_DIR:-$HOME/.agent-fleet}"
LOG_DIR="$FLEET_DIR/logs"
SESSION="${FLEET_SESSION:-fleet}"

mkdir -p "$LOG_DIR"

usage() {
  cat <<'EOF'
Usage:
  fleet start <name> <claude|codex|gemini> [args...]   Start an agent in a tmux window
  fleet list                                        List windows and agents
  fleet attach <name>                               Attach to an agent's window
  fleet send <name> <text...>                       Send a prompt to an agent
  fleet capture <name> [lines]                      Show recent output
  fleet kill <name>                                 Stop an agent window
  fleet logs <name>                                 Tail the agent's log file
EOF
}

die() { echo "fleet: $*" >&2; exit 1; }

require_tmux() {
  command -v tmux >/dev/null 2>&1 || die "tmux not found"
}

agent_command() {
  local agent="$1"; shift
  case "$agent" in
    claude) command -v claude >/dev/null 2>&1 || die "claude CLI not installed"; echo "claude" ;;
    codex)  command -v codex  >/dev/null 2>&1 || die "codex CLI not installed";  echo "codex"  ;;
    gemini) command -v gemini >/dev/null 2>&1 || die "gemini CLI not installed"; echo "gemini" ;;
    *) die "unknown agent: $agent (expected claude, codex, or gemini)" ;;
  esac
}

ensure_session() {
  if ! tmux has-session -t "$SESSION" 2>/dev/null; then
    tmux new-session -d -s "$SESSION" -n "_shell"
    tmux set-option -t "$SESSION" status-interval 5
    tmux set-option -t "$SESSION" history-limit 10000
  fi
}

cmd_start() {
  local name="${1:-}" agent="${2:-}"; shift 2 || true
  [ -n "$name" ] && [ -n "$agent" ] || { usage; exit 1; }
  require_tmux
  ensure_session

  if tmux list-windows -t "$SESSION" -F '#{window_name}' | grep -Fxq "$name"; then
    die "window '$name' already exists"
  fi

  local bin
  bin="$(agent_command "$agent")"
  local log="$LOG_DIR/$name.log"

  # Wrap the agent so its raw output is also written to a log file.
  local cmd="cd \"\$PWD\" && $bin $* 2>&1 | tee -a \"$log\""

  tmux new-window -t "$SESSION" -n "$name" "$cmd"
  echo "started $name ($agent) in session '$SESSION'"
  echo "log: $log"
}

cmd_list() {
  require_tmux
  tmux list-windows -t "$SESSION" -F '#{window_index}:#{window_name} [#{pane_current_command}] #{?window_active,(active),}' 2>/dev/null \
    || echo "no fleet session '$SESSION'"
}

cmd_attach() {
  local name="${1:-}"; [ -n "$name" ] || die "name required"
  require_tmux
  tmux select-window -t "$SESSION:$name"
  tmux attach-session -t "$SESSION"
}

cmd_send() {
  local name="${1:-}"; shift || true
  [ -n "$name" ] && [ "$#" -gt 0 ] || die "name and text required"
  require_tmux
  tmux send-keys -t "$SESSION:$name" -l -- "$*"
  tmux send-keys -t "$SESSION:$name" Enter
  echo "sent to $name"
}

cmd_capture() {
  local name="${1:-}" lines="${2:-80}"
  [ -n "$name" ] || die "name required"
  require_tmux
  tmux capture-pane -p -t "$SESSION:$name" -S "-$lines"
}

cmd_kill() {
  local name="${1:-}"; [ -n "$name" ] || die "name required"
  require_tmux
  tmux kill-window -t "$SESSION:$name"
  echo "killed $name"
}

cmd_logs() {
  local name="${1:-}"; [ -n "$name" ] || die "name required"
  tail -f "$LOG_DIR/$name.log"
}

main() {
  local cmd="${1:-}"; shift || true
  case "$cmd" in
    start)   cmd_start "$@" ;;
    list)    cmd_list "$@" ;;
    attach)  cmd_attach "$@" ;;
    send)    cmd_send "$@" ;;
    capture) cmd_capture "$@" ;;
    kill)    cmd_kill "$@" ;;
    logs)    cmd_logs "$@" ;;
    *)       usage; exit 1 ;;
  esac
}

main "$@"

Make it executable and add it to your PATH:

bash
chmod +x ~/.agent-fleet/bin/fleet
export PATH="$HOME/.agent-fleet/bin:$PATH"

Persist that in ~/.bashrc or ~/.zshrc:

bash
cat >> ~/.bashrc <<'EOF'
export PATH="$HOME/.agent-fleet/bin:$PATH"
export FLEET_SESSION="fleet"
EOF

Test the launcher

Start one agent per vendor in the same repository:

bash
mkdir -p ~/work/demo-service && cd ~/work/demo-service
git init -q
fleet start claude claude
fleet start codex  codex
fleet start gemini gemini
fleet list

Expected output:

bash
started claude (claude) in session 'fleet'
log: /root/.agent-fleet/logs/claude.log
started codex (codex) in session 'fleet'
log: /root/.agent-fleet/logs/codex.log
started gemini (gemini) in session 'fleet'
log: /root/.agent-fleet/logs/gemini.log
0:_shell [bash]
1:claude [node]
2:codex [node]
3:gemini [node]

Attach and watch:

bash
fleet attach claude

Detach with Ctrl+B, then D. The agents keep running.

Why a wrapper instead of calling the binaries directly

The wrapper adds three things you will want immediately:

  • Logging. Every agent's stdout and stderr is teed to a file, so you can grep history later without scrolling a terminal.
  • Uniform lifecycle. Start, list, capture, send, kill behave the same regardless of vendor.
  • Isolation of quirks. When a CLI needs a different flag or environment variable, you change it in one case statement.

5. Run a Fleet in Tmux

A fleet is a set of windows in one tmux session, each running a different agent against the same repository. The critical operational rule: give each agent its own git worktree unless you specifically want them editing the same files.

Worktree-per-agent

Shared working directories cause the fastest path to lost work: two agents apply patches to the same file, one rebases, and the other's changes vanish in a conflict you did not see.

Create a helper that provisions a worktree per agent:

bash
cat > ~/.agent-fleet/bin/fleet-worktree <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

repo="${1:-}"; name="${2:-}"; agent="${3:-}"; branch="${4:-}"
[ -n "$repo" ] && [ -n "$name" ] && [ -n "$agent" ] || {
  echo "usage: fleet-worktree <repo> <name> <agent> [branch]" >&2; exit 1; }

repo="$(cd "$repo" && pwd)"
branch="${branch:-agent/$name}"
wt="$(dirname "$repo")/$(basename "$repo")-$name"

if [ ! -d "$wt" ]; then
  git -C "$repo" worktree add -b "$branch" "$wt" main
fi

cd "$wt"
fleet start "$name" "$agent"
echo "worktree: $wt (branch $branch)"
EOF
chmod +x ~/.agent-fleet/bin/fleet-worktree

Usage:

bash
cd ~/work/demo-service
git add -A && git commit -qm "initial commit"
fleet-worktree . claude-wt claude
fleet-worktree . codex-wt  codex
fleet-worktree . gemini-wt gemini

Now each agent has an isolated branch and directory. When one finishes, you review the diff and merge deliberately:

bash
git -C ~/work/demo-service-claude-wt diff main...agent/claude-wt
git -C ~/work/demo-service-claude-wt log --oneline main..agent/claude-wt

Sending prompts across the fleet

You can steer an agent without attaching:

bash
fleet send codex-wt "Run the failing unit tests and report the root cause. Do not modify files yet."
fleet send gemini-wt "Summarize the public API surface of this package."

send-keys -l sends the text literally, which avoids interpreting characters like ; or $(...) as shell input. The trailing Enter submits it.

Capturing output for summaries

bash
fleet capture codex-wt 120 > /tmp/codex-transcript.txt
grep -n -i -E 'error|fail|permission' /tmp/codex-transcript.txt | head -20

This is how you build lightweight monitoring: capture the tail of each window periodically, and flag windows whose output contains approval prompts or repeated errors.

A lightweight status TUI

A full-screen dashboard is nice, but a good first version is a single command that prints the state of every window:

bash
cat > ~/.agent-fleet/bin/fleet-status <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
SESSION="${FLEET_SESSION:-fleet}"

if ! tmux has-session -t "$SESSION" 2>/dev/null; then
  echo "fleet '$SESSION' is not running"
  exit 0
fi

printf '%-14s %-10s %-8s %s\n' WINDOW PROCESS ALIVE LAST
printf '%-14s %-10s %-8s %s\n' '--------------' '----------' '--------' '--------------------------------'

while IFS='|' read -r idx name; do
  proc="$(tmux list-panes -t "$SESSION:$name" -F '#{pane_current_command}' 2>/dev/null || echo '-')"
  alive="$(tmux list-panes -t "$SESSION:$name" -F '#{pane_dead}' 2>/dev/null || echo 1)"
  [ "$alive" = "0" ] && alive="yes" || alive="no"
  last="$(tmux capture-pane -p -t "$SESSION:$name" -S -3 2>/dev/null | grep -v '^$' | tail -1 | cut -c1-40 || echo '-')"
  printf '%-14s %-10s %-8s %s\n' "$name" "$proc" "$alive" "$last"
done < <(tmux list-windows -t "$SESSION" -F '#{window_index}|#{window_name}')
EOF
chmod +x ~/.agent-fleet/bin/fleet-status

Run it:

bash
fleet-status
sql
WINDOW         PROCESS    ALIVE    LAST
-------------- ---------- -------- --------------------------------
claude-wt      node      yes      > implement the retry logic
codex-wt       node      yes      ✓ 24 tests passed
gemini-wt      node      yes      Waiting for user confirmation...

The LAST column is a heuristic, but it is enough to tell you which window needs attention. For a richer dashboard, wrap this in fzf or gum—the underlying primitives do not change.

6. Drive the Fleet from a Phone

The phone requirement is real: long agent runs frequently finish while you are away from a desk. You need status, approvals, and the ability to send a correction—not a full terminal emulator on a 6-inch screen.

There are three practical tiers.

Tier 1: SSH from any terminal app

The lowest-effort option. Install Termius, Blink, or JuiceSSH on your phone, connect to the host, and run:

bash
fleet-status
fleet capture codex-wt 60
fleet send codex-wt "Stop. Revert the last edit and explain what you found."

This works with zero extra infrastructure. It is also the safest default because it uses the same authentication path you already trust.

Tier 2: A push-notification bridge

For proactive notifications, run a small watcher on the host that detects approval prompts and posts to a webhook. A generic implementation using ntfy.sh needs no account on your side beyond installing the CLI:

bash
# On the host
sudo apt-get install -y ntfy
ntfy subscribe --topic 'my-agent-fleet' > /tmp/fleet-events.txt &

Then a watcher script that polls windows and publishes notable events:

bash
cat > ~/.agent-fleet/bin/fleet-watch <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
SESSION="${FLEET_SESSION:-fleet}"
TOPIC="${FLEET_TOPIC:-my-agent-fleet}"
STATE_DIR="${FLEET_DIR:-$HOME/.agent-fleet}/watch-state"
mkdir -p "$STATE_DIR"

while true; do
  if tmux has-session -t "$SESSION" 2>/dev/null; then
    while IFS='|' read -r name; do
      out="$(tmux capture-pane -p -t "$SESSION:$name" -S -20 2>/dev/null || true)"
      sig="$(printf '%s' "$out" | grep -i -E 'permission|approve|allow|confirm|y/n' | tail -1 || true)"
      [ -z "$sig" ] && continue
      hash="$(printf '%s' "$sig" | md5sum | cut -c1-12)"
      last="$(cat "$STATE_DIR/$name" 2>/dev/null || echo '')"
      if [ "$hash" != "$last" ]; then
        echo "$hash" > "$STATE_DIR/$name"
        ntfy publish --title "fleet: $name needs you" "$sig" || true
      fi
    done < <(tmux list-windows -t "$SESSION" -F '#{window_name}')
  fi
  sleep 15
done
EOF
chmod +x ~/.agent-fleet/bin/fleet-watch

Start it under a supervisor so it survives disconnects:

bash
cat > ~/.config/systemd/user/fleet-watch.service <<'EOF'
[Unit]
Description=Agent fleet approval watcher

[Service]
ExecStart=%h/.agent-fleet/bin/fleet-watch
Restart=always
RestartSec=5

[Install]
WantedBy=default.target
EOF

systemctl --user daemon-reload
systemctl --user enable --now fleet-watch.service

Install the ntfy app on your phone and subscribe to the same topic. You now get a push when an agent asks for permission.

Tier 3: A purpose-built mobile control surface

If you want buttons instead of raw text, add a minimal HTTP control service bound to a private interface or an SSH tunnel. Do not expose it directly to the public internet without authentication.

bash
cat > ~/.agent-fleet/bin/fleet-api.py <<'PY'
#!/usr/bin/env python3
"""Minimal fleet control API. Bind to localhost; reach it via SSH tunnel or mTLS."""
import http.server
import json
import os
import socketserver
import subprocess

SESSION = os.environ.get("FLEET_SESSION", "fleet")
TOKEN = os.environ.get("FLEET_API_TOKEN", "")


def tmux(*args, check=True):
    return subprocess.run(
        ["tmux", *args], capture_output=True, text=True, check=check
    )


class Handler(http.server.BaseHTTPRequestHandler):
    def _authorized(self):
        if not TOKEN:
            return False
        header = self.headers.get("Authorization", "")
        return header == f"Bearer {TOKEN}"

    def _json(self, code, payload):
        body = json.dumps(payload).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if not self._authorized():
            return self._json(401, {"error": "unauthorized"})
        if self.path == "/status":
            out = tmux("list-windows", "-t", SESSION, "-F", "#{window_name}|#{pane_current_command}", check=False)
            windows = []
            for line in out.stdout.strip().splitlines():
                if not line:
                    continue
                name, proc = line.split("|", 1)
                tail = tmux("capture-pane", "-p", "-t", f"{SESSION}:{name}", "-S", "-3", check=False)
                windows.append({"name": name, "process": proc, "tail": tail.stdout.strip().splitlines()[-3:]})
            return self._json(200, {"session": SESSION, "windows": windows})
        if self.path.startswith("/capture/"):
            name = self.path.split("/", 2)[2]
            out = tmux("capture-pane", "-p", "-t", f"{SESSION}:{name}", "-S", "-200", check=False)
            return self._json(200, {"name": name, "output": out.stdout})
        return self._json(404, {"error": "not found"})

    def do_POST(self):
        if not self._authorized():
            return self._json(401, {"error": "unauthorized"})
        if not self.path.startswith("/send/"):
            return self._json(404, {"error": "not found"})
        name = self.path.split("/", 2)[2]
        length = int(self.headers.get("Content-Length", 0))
        body = json.loads(self.rfile.read(length) or b"{}")
        text = body.get("text", "").strip()
        if not text:
            return self._json(400, {"error": "text required"})
        tmux("send-keys", "-t", f"{SESSION}:{name}", "-l", "--", text)
        tmux("send-keys", "-t", f"{SESSION}:{name}", "Enter")
        return self._json(200, {"sent": text})

    def log_message(self, *args):
        pass


class Server(socketserver.ThreadingTCPServer):
    allow_reuse_address = True


if __name__ == "__main__":
    with Server(("127.0.0.1", 8787), Handler) as httpd:
        print("fleet API on http://127.0.0.1:8787")
        httpd.serve_forever()
PY
chmod +x ~/.agent-fleet/bin/fleet-api.py

Run it with a token from an environment file:

bash
cat > ~/.agent-fleet/api.env <<'EOF'
FLEET_API_TOKEN=$(openssl rand -hex 24)
FLEET_SESSION=fleet
EOF
chmod 600 ~/.agent-fleet/api.env

set -a; . ~/.agent-fleet/api.env; set +a
nohup python3 ~/.agent-fleet/bin/fleet-api.py > ~/.agent-fleet/logs/api.log 2>&1 &

From your phone's SSH client, open a tunnel:

bash
ssh -L 8787:127.0.0.1:8787 you@your-host

Then query status with curl:

bash
curl -s -H "Authorization: Bearer $FLEET_API_TOKEN" http://127.0.0.1:8787/status | jq
json
{
  "session": "fleet",
  "windows": [
    { "name": "claude-wt", "process": "node", "tail": ["All tests passed."] },
    { "name": "codex-wt", "process": "node", "tail": ["Allow command? [y/n]"] }
  ]
}

And steer an agent:

bash
curl -s -X POST http://127.0.0.1:8787/send/codex-wt \
  -H "Authorization: Bearer $FLEET_API_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"text":"Yes, run the migration in a transaction and show me the rollback plan."}' | jq

For a real mobile UI, point a simple PWA or a service like ntfy/ntfy-based dashboards at this API. The API surface is intentionally tiny: GET /status, GET /capture/<name>, POST /send/<name>.

Security rules for phone access

  • Bind the API to 127.0.0.1 and reach it through SSH or a Tailscale/WireGuard tunnel. Never bind to 0.0.0.0 on a public IP.
  • Use a long random bearer token, stored with chmod 600.
  • Prefer SSH keys with ed25519 and a passphrase; disable password auth on the host.
  • Add AllowUsers and Match User restrictions in sshd_config if the host is shared.
  • Rate-limit the API if you expose it beyond localhost. fail2ban plus SSH intrusion detection covers most of the risk for the SSH path.
  • Audit every send call. You are granting a language model the ability to run commands; that deserves a trail.

7. Add Approval Gates and Audit Logging

The single most important production feature is a gate that prevents an agent from doing something destructive without a human decision. Two layers work well together.

Layer 1: CLI-level permission modes

Each agent CLI has its own approval model. Configure them to require confirmation for risky operations:

bash
# Claude Code: deny-list sensitive commands in project settings
mkdir -p ~/work/demo-service/.claude
cat > ~/work/demo-service/.claude/settings.json <<'EOF'
{
  "permissions": {
    "deny": [
      "Bash(rm -rf *)",
      "Bash(git push *)",
      "Bash(curl * | sh)",
      "Read(./.env)",
      "Read(./secrets/**)"
    ]
  }
}
EOF
bash
# Codex CLI: use approval mode and sandboxing
codex --help | grep -i -A2 'approval'
codex -a on-request --sandbox workspace-write
bash
# Gemini CLI: check available approval / sandbox flags
gemini --help | grep -i -E 'approval|sandbox|yolo'

Flag names move between releases; verify with --help on your installed version and record the chosen configuration in ~/.agent-fleet/versions.lock alongside the binary versions.

Layer 2: A wrapper-level gate

Do not rely solely on CLI permissions. Wrap dangerous operations in a script that checks a signed allowlist file:

bash
cat > ~/.agent-fleet/bin/fleet-approve <<'EOF'
#!/usr/bin/env bash
# fleet-approve <operation-id> — grant one operation once
set -euo pipefail
STATE="${FLEET_DIR:-$HOME/.agent-fleet}/approvals"
mkdir -p "$STATE"
op="${1:-}"
[ -n "$op" ] || { echo "usage: fleet-approve <operation-id>" >&2; exit 1; }

# Only allow ops that were explicitly proposed by the watcher.
if [ ! -f "$STATE/$op.proposed" ]; then
  echo "no pending proposal for '$op'" >&2
  exit 1
fi

printf '%s %s\n' "$(date -u +%FT%TZ)" "$(whoami)" >> "$STATE/audit.log"
date -u +%FT%TZ > "$STATE/$op.approved"
echo "approved: $op"
EOF
chmod +x ~/.agent-fleet/bin/fleet-approve

The watcher writes *.proposed files when it detects an approval prompt; your phone flow becomes: read the notification, run fleet-approve <id> over SSH, and the agent continues.

Audit log

Record what happened, not just what was approved:

bash
cat >> ~/.agent-fleet/bin/fleet-watch <<'EOF'
EOF

# Add to the watcher loop, right after publishing a notification
cat > ~/.agent-fleet/bin/fleet-audit <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
SESSION="${FLEET_SESSION:-fleet}"
LOG="${FLEET_DIR:-$HOME/.agent-fleet}/audit.log"

while true; do
  if tmux has-session -t "$SESSION" 2>/dev/null; then
    tmux list-windows -t "$SESSION" -F '#{window_name}' | while read -r name; do
      out="$(tmux capture-pane -p -t "$SESSION:$name" -S -5 2>/dev/null || true)"
      sig="$(printf '%s' "$out" | grep -i -E 'permission|approve|confirm' | tail -1 || true)"
      [ -z "$sig" ] && continue
      printf '%s\t%s\t%s\n' "$(date -u +%FT%TZ)" "$name" "$sig" >> "$LOG"
    done
  fi
  sleep 30
done
EOF
chmod +x ~/.agent-fleet/bin/fleet-audit

Rotate the log so it does not grow without bound:

bash
cat > ~/.agent-fleet/bin/fleet-audit-rotate <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
LOG="${FLEET_DIR:-$HOME/.agent-fleet}/audit.log"
[ -f "$LOG" ] || exit 0
size="$(stat -c%s "$LOG" 2>/dev/null || stat -f%z "$LOG")"
[ "$size" -gt 5242880 ] && mv "$LOG" "$LOG.$(date -u +%Y%m%dT%H%M%SZ)"
EOF
chmod +x ~/.agent-fleet/bin/fleet-audit-rotate

8. Production Patterns and Edge Cases

Pattern: one agent per concern, not one agent per vendor

The most effective fleet assignments are usually functional:

bash
fleet start implementer  claude   # writes the code
fleet start reviewer     codex    # reviews the diff, proposes fixes
fleet start test-writer  gemini   # expands test coverage

Then you sequence them:

bash
fleet send implementer "Implement the retry logic described in docs/adr-014.md. Open a PR when tests pass."
fleet send reviewer   "Wait for the implementer branch, then review agent/implementer for correctness and edge cases."

Parallel vendors on the same task are useful for comparison—two independent implementations reveal different blind spots—but they double token cost and review burden. Use them on high-risk changes, not routine work.

Edge case: agents competing for the same port

If your task requires a dev server, two agents will collide on localhost:3000. Use per-worktree ports:

bash
# In each worktree's .env.local
PORT=3101   # claude-wt
PORT=3102   # codex-wt
PORT=3103   # gemini-wt

Or run each agent's commands inside a container with its own network namespace. Container-per-agent is the more robust answer for shared infrastructure (databases, message brokers):

bash
docker run --rm -it \
  --name agent-codex \
  --network agent-net \
  -v "$PWD":/workspace" \
  -w /workspace \
  -e ANTHROPIC_API_KEY="$ANTHROPIC_API_KEY" \
  node:20 bash -lc "codex"

Run that inside a tmux window and you get isolation plus a familiar lifecycle.

Edge case: context window exhaustion

Long-running agents degrade when their context fills with tool output. Mitigations:

  • Split work into smaller tasks with explicit acceptance criteria.
  • Ask agents to summarize findings into a file before continuing:
bash
fleet send implementer "Write your current findings to NOTES.md, then start a fresh sub-task with only that file as context."
  • Use each CLI's built-in compaction or session-resume features rather than replaying an entire transcript.
  • Capture the final summary before killing the window; the log file preserves it.

Edge case: the agent waits forever for input

A window showing a prompt is not the same as an agent working. Distinguish the two:

bash
fleet capture implementer 40 | grep -q -E 'Do you want|\[y/n\]|Waiting for' \
  && echo "needs input" \
  || echo "likely working"

This heuristic is imperfect—agent CLIs re-render prompts in different formats—but it catches the common case. Pair it with the notification watcher for reliability.

Edge case: tmux server dies

If the tmux server crashes, every agent dies with it. Mitigate with:

  • tmux set-option -g history-limit 50000 for larger scrollback.
  • Running agents inside tmux inside a container or a persistent VM with its own supervision.
  • Keeping a systemd unit that restarts the fleet session and re-launches windows from a declarative manifest.

A declarative manifest makes recovery trivial:

yaml
# ~/.agent-fleet/fleet.yaml
session: fleet
agents:
  - name: implementer
    agent: claude
    worktree: ~/work/demo-service-implementer
    task: "Implement retry logic per docs/adr-014.md"
  - name: reviewer
    agent: codex
    worktree: ~/work/demo-service-reviewer
    task: "Review agent/implementer and report findings"
  - name: test-writer
    agent: gemini
    worktree: ~/work/demo-service-test-writer
    task: "Add integration tests for the retry path"

Parse it with yq (or jq after converting YAML) and drive fleet start from it. Now "recover the fleet" is a script, not a memory exercise.

Edge case: cost control

A fleet multiplies spend. Guardrails that actually work:

  • Cap concurrent agents per repository (fleet list | wc -l).
  • Give each agent a bounded task with a definition of done.
  • Use the cheapest capable model for mechanical tasks (test generation, doc updates) and reserve frontier models for design and review.
  • Set provider-side spend limits in each vendor's account settings, not just in prompts.
  • Log token usage per window if your CLI exposes it; fleet capture can extract it.

When to graduate to a real orchestrator

The tmux approach is excellent up to a point. Move to a heavier platform when you need:

  • Durable, queryable task state across machines.
  • Automatic retries with idempotency guarantees.
  • Fan-out across dozens of repositories.
  • Programmatic tool calls (not just terminal input).
  • Fine-grained RBAC and per-agent identity.

At that point, keep the same mental model: agents are processes with context, permissions, and a lifecycle. Whether the scheduler is tmux, Temporal, Kubernetes Jobs, or a managed agent platform, the questions stay the same: who is running, on what, with which permissions, and who approves the risky step.

9. Frequently Asked Questions

Can I run Claude Code, Codex, and Gemini CLI in the same terminal at the same time?

Yes—each runs in its own tmux window, so each gets its own TTY and interactive prompt. The fleet wrapper gives them a uniform start/list/send/capture interface without changing how any of them work internally.

How do I prevent agents from deleting files or pushing to production?

Use three layers: CLI-level permission denials (deny-lists for rm, git push, secret reads), worktree isolation so changes are reviewable before merge, and a wrapper-level approval gate that requires a human to grant one operation at a time. Never let an agent run directly against a production credential.

Is the phone bridge safe to expose over the internet?

Not as written. The API binds to 127.0.0.1 and is reached through an SSH tunnel or a private mesh network (Tailscale/WireGuard). If you must expose it, put it behind TLS with a strong bearer token, add rate limiting, and log every request.

Should all three agents work on the same branch?

No. Use one git worktree and branch per agent. Parallel edits to a shared working tree create conflicts that are hard to attribute and easy to lose. Merge deliberately, one reviewed diff at a time.

What is the best first step?

Start with two agents and one repository. Run one implementation and one review pass, capture the transcripts, and measure how much time you spend on coordination. If coordination cost stays low, add the third vendor and the phone bridge.