Andrew Neumann

·Thinking out loud

scaling to hundreds of agents on a single machine

Key Points

  • Name agents like infrastructure. Every session is project-function-provider: ypp-build-ant, cic-questions-oai. You can tell what an agent is for, where it lives and whose model it runs before you open it
  • Split the work by function, not by task. A build agent changes code, a questions agent answers and investigates without touching the build
  • Processes die, conversations don’t. A reboot kills every agent. What survives is the conversation on disk, so recovery is “resume by name”, not “restore the window”
  • One registry, one command. A small text file says which agents exist, where they run, and on which model and effort
  • The terminal is the host, the phone is the remote. tmux holds the sessions, Ghostty is just the window, and Remote Control lets me pick any of them up from the Claude or ChatGPT app

In my last post I said working with AI means thinking in outcomes and being a player/coach at every position. This is what it looks like when “the team” is a dozen and a half agents running at once, running dozens of agents themselves.

The problem

I run an app studio along with a couple SaaS products. Generally the structure is:

  • one building: branches, tests, deploys
  • one answering questions: without stepping on the build
  • one on the marketing site, if the product has one
  • bonus points for one agent per major feature, with multiple feature agents useing “build” as repo/project orchestrator

Often, I use more than one provider. I usually use the native harness for the models. I haven’t found local models overly useful for agentic coding when factoring time and cost.

The naming scheme

<project>-<function>-<provider>

Part Values
project a short code: ypp, ci, nt, ops…
function build, questions, site (feature)
provider ant (Claude), oai (Codex), agy (Antigravity)

So ypp-build-ant is the Claude agent building YourPods Pro, and cic-build-oai is Codex building the Couldi connector (coming soon ;-)).

The build process

It really depends on what you’re building, the maturity of your codebase, and your technical knowledge for “how to build” with AI. It’s still very much an art and a science. Generally I find frontier models that best for build orchestration (fable/astra/carbon). Build manages sub agents for coding generally (opus:sonnet/sol/neon). Your native harness is pretty good at managing this, check your settings to enable larger sub agent teams/pools/swarms.

Agents build in branches or worktrees, with whatever CI/CD the project uses. It can be helpful to have agent instructions, however I generally leave things pretty default, outside some general ways of working rules. Tough problems sometimes require specific agent persona’s, but the orchestration models are usually quite good at telling agents and subagents what to do and checking that it’s done for most work.

Plan your build/feature if needed and execute. If you have larger work, kick off another feature agent with a stronger model. Models from the same company can generally communicate. Scaling all of this and getting proper cross talk is a bit of a challenge still. More on that in a future post.

Manage the horde/swarm/team

I didn’t want to give up my terminal or have dozens of terminals to sort though, so the answer is to put tmux underneath it:

  • Every agent is one tmux session with the same name as the agent, on its own tmux socket
  • Your terminal is only a window onto them. Close it and agents keep running
  • When an agent exits, its session falls back to a shell in that repo, so there’s always a terminal where I need one

Ctrl-b s gives a menu of every agent, and Ctrl-b d steps back out.

Bringing them back: a registry and resume-by-name

The registry is a plain text table:

# name             dir            provider  model   effort  auto
ypp-build-ant      yourpods-pro   ant       fable   medium  yes
ypp-questions-ant  yourpods-pro   ant       opus    medium  yes
cic-build-oai      couldi-connect oai       astra   high    yes
blog-site-ant      blog-site      agy       neon    medium  no

agents up walks the table and, for each missing agent, starts the right CLI in the right folder with the right model and effort. It resumes the newest conversation carrying that agent’s name, or starts fresh if there isn’t one. auto: no rows only start when asked: agents blog-site starts that one and drops me into it. It’s pretty easy to automate this process to survive a reboot.

Two details make it work:

  • Resume by name, never “continue the last one”
  • Don’t start a second copy. If an agent is already running in some other terminal, agents up skips it and says so

Model preferences live in the table rather than in global settings, because the right model depends on the job.

Driving them from the phone

Every Claude agent starts with Remote Control on, under its own name, so the Claude app on my phone lists ypp-build-ant, ci-questions-ant and the rest, and I can pick any of them up where the terminal left off. Codex sessions join Codex’s remote-control server and show up in the ChatGPT app. Lookin’ at you Google…

What I’d tell you if you’re starting

  • Pick the naming scheme first. Make it make sense to you
  • Separate “changes code” from “answers questions”
    • Other agents/projects will also use questions when build is ‘busy’
  • Assume the processes will die, and make getting the conversations back a single command
  • Keep the registry boring: a text file you can read in five seconds
  • You’re likely going to run into decision fatigue before you get to technical scale problems, more on this in the future

The script is about 250 lines of Python over tmux. AI generated code because of course it is.

#!/usr/bin/env python3
"""Hold agent sessions in tmux and bring them back after a reboot.  (Linux + macOS)

  agents <filter>         start what matches; if that is one session, open it
  agents up [filter...]   start every missing session (bare: the auto=yes rows)
  agents a [name]         attach (unique prefix is enough: `agents a proj-b`); no name = pick from a menu
  agents ls               registry with live status
  agents down <name>      close one tmux session (the conversation is kept)
  agents cmd <name>       print the command a session would be started with

A filter is a full name, a project code (`proj`), a directory under $AGENTS_CODE_ROOT
(default ~/code; e.g. `example-app`), or a provider (`oai`).
Registry: $AGENTS_REGISTRY, default registry.tsv beside this script. Each agent is one tmux session of the
same name, on the `agents` tmux socket, so a lost display does not take it down.
"""
import glob, json, os, shlex, subprocess, sys

DARWIN = sys.platform == "darwin"

HOME = os.path.expanduser("~")
# Resolved: ~/code may be a symlink, and Claude keys ~/.claude/projects
# by the real path, so the slug, tmux -c and codex -C must all use the real one.
CODE = os.path.realpath(os.path.expanduser(os.environ.get("AGENTS_CODE_ROOT", os.path.join(HOME, "code"))))
HERE = os.path.dirname(os.path.realpath(__file__))
REGISTRY = os.environ.get("AGENTS_REGISTRY") or os.path.join(HERE, "registry.tsv")
SOCKET = "agents"
PROVIDERS = ("ant", "oai", "agy")


def clean_env():
    """Environment for launched agents. `agents up` is often run by an agent, and its own
    session variables must not leak into the sessions it starts."""
    drop = ("CLAUDE_CODE_", "CLAUDECODE", "CLAUDE_PID", "CLAUDE_EFFORT", "CODEX_", "TMUX")
    return {k: v for k, v in os.environ.items() if not k.startswith(drop)}


def tmux(*args, **kw):
    return subprocess.run(["tmux", "-L", SOCKET, *args], text=True, capture_output=True, **kw)


def rows():
    out = []
    for line in open(REGISTRY):
        line = line.split("#", 1)[0].split()
        if not line:
            continue
        if len(line) != 7:
            sys.exit(f"registry.tsv: expected 7 columns, got {len(line)}: {' '.join(line)}")
        name, d, prov, model, effort, auto, was = line
        if prov not in PROVIDERS or not name.endswith("-" + prov):
            sys.exit(f"registry.tsv: {name}: name must end in its provider (-{prov})")
        blank = lambda v: "" if v == "-" else v
        out.append(dict(name=name, dir=os.path.join(CODE, d), prov=prov, model=blank(model),
                        effort=blank(effort), auto=auto == "yes",
                        was=blank(was) or name[: -len(prov) - 1]))
    return out


def select(filters):
    all_rows = rows()
    if not filters:
        return [r for r in all_rows if r["auto"]]
    picked = [r for r in all_rows if any(
        f == r["name"] or f == r["prov"] or r["name"].startswith(f + "-")
        or f.rstrip("/") == os.path.basename(r["dir"]) for f in filters)]
    if not picked:
        sys.exit(f"nothing in the registry matches: {' '.join(filters)}")
    return picked


def live_tmux():
    r = tmux("list-sessions", "-F", "#{session_name}")
    return set(r.stdout.split()) if r.returncode == 0 else set()


# ---- Claude Code -----------------------------------------------------------

def claude_live():
    """Claude sessions running right now, in any terminal.

    ~/.claude/sessions/<pid>.json can outlive a hard reboot and pids get reused, so a
    record only counts when that pid is a claude process with the recorded start time.
    """
    live = []
    for f in glob.glob(os.path.join(HOME, ".claude/sessions/*.json")):
        try:
            d = json.load(open(f))
            pid = int(d["pid"])
        except (OSError, ValueError, KeyError, TypeError):
            continue
        if (_pid_is_claude_darwin if DARWIN else _pid_is_claude_linux)(pid, d.get("procStart")):
            live.append(d)
    return live


def _pid_is_claude_linux(pid, proc_start):
    try:
        if open(f"/proc/{pid}/comm").read().strip() != "claude":
            return False
        started = open(f"/proc/{pid}/stat").read().rsplit(")", 1)[1].split()[19]
    except (OSError, IndexError):
        return False
    return proc_start is None or str(proc_start) == started


def lstart_matches(proc_start, lstart):
    """darwin procStart is `ps -o lstart=` rendered in UTC ('Tue Dec  1 16:14:37 2026');
    compare ignoring runs of spaces. A record without procStart cannot be checked: match."""
    return proc_start is None or str(proc_start).split() == lstart.split()


def _pid_is_claude_darwin(pid, proc_start):
    """No /proc on macOS, so ask ps. Verified on darwin: comm is "claude" for the native
    binary, and procStart equals `TZ=UTC LC_ALL=C ps -o lstart=`. When ps itself cannot be
    run this fails toward live (`up` skips: recoverable; a double launch is not)."""
    env = dict(os.environ, TZ="UTC", LC_ALL="C")
    try:
        comm = subprocess.run(["ps", "-o", "comm=", "-p", str(pid)], text=True,
                              capture_output=True, env=env).stdout.strip()
        if not comm:
            return False                 # no such pid
        if os.path.basename(comm) != "claude":
            return False                 # pid reused by something else
        # lstart has spaces, so query it on its own.
        lstart = subprocess.run(["ps", "-o", "lstart=", "-p", str(pid)], text=True,
                                capture_output=True, env=env).stdout.strip()
    except OSError:
        return True                      # cannot tell: assume live
    if not lstart:
        return False                     # exited between the two calls
    return lstart_matches(proc_start, lstart)


def claude_running(names, session_id=None):
    """A live Claude session carrying one of these names or this conversation -> (pid, name)."""
    for d in claude_live():
        if d.get("name") in names or (session_id and d.get("sessionId") == session_id):
            return d["pid"], d.get("name")
    return None


def claude_slug(d):
    """~/.claude/projects/<slug>: every non-alphanumeric character of the absolute dir becomes -."""
    return "".join(c if c.isalnum() else "-" for c in d)


def claude_last_session(r):
    """Newest saved conversation in the agent's directory whose title is its name."""
    files = sorted(glob.glob(os.path.join(HOME, ".claude/projects", claude_slug(r["dir"]), "*.jsonl")),
                   key=os.path.getmtime, reverse=True)
    for wanted in (r["name"], r["was"]):
        for f in files:
            title = None
            with open(f, errors="replace") as fh:
                for line in fh:
                    if '"customTitle"' in line:
                        try:
                            title = json.loads(line).get("customTitle", title)
                        except ValueError:
                            pass
            if title == wanted:
                return os.path.basename(f)[:-6]
    return None


def claude_cmd(r):
    cmd = ["claude", "--name", r["name"], "--remote-control", r["name"]]
    if r["model"]:
        cmd += ["--model", r["model"]]
    if r["effort"]:
        cmd += ["--effort", r["effort"]]
    sid = claude_last_session(r)
    if sid:
        cmd += ["--resume", sid]
    return cmd, ("resume " + sid[:8] if sid else "new")


# ---- Codex -----------------------------------------------------------------

def codex_thread_id(name):
    """Id of the newest Codex thread named `name`, or None. Resume goes by id: over
    `--remote unix://`, `codex resume NAME` fails ("No saved session found with ID NAME")."""
    found = None
    try:
        for l in open(os.path.join(HOME, ".codex/session_index.jsonl")):
            try:
                d = json.loads(l)
            except ValueError:
                continue
            if d.get("thread_name") == name and d.get("id"):
                found = d["id"]          # file is append-ordered: last match is newest
    except OSError:
        pass
    return found


def codex_cmd(r):
    opts = ["-C", r["dir"]]
    if r["model"]:
        opts += ["-m", r["model"]]
    if r["effort"]:
        opts += ["-c", f'model_reasoning_effort="{r["effort"]}"']
    # --remote unix:// joins the remote-control daemon, so the phone sees the same thread.
    opts = ["--remote", "unix://", *opts]
    tid = codex_thread_id(r["name"])
    if tid:
        return ["codex", "resume", *opts, tid], "resume " + tid
    return ["codex", *opts], f"new (run /rename {r['name']} inside it so it resumes next time)"


# ---- Antigravity -----------------------------------------------------------

def agy_cmd(r):
    cmd = ["agy", "--remote-control"]
    if r["model"]:
        cmd += ["--model", r["model"]]
    return cmd, "new (agy has no named resume; use /resume inside it)"


def command(r):
    return {"ant": claude_cmd, "oai": codex_cmd, "agy": agy_cmd}[r["prov"]](r)


# ---- commands --------------------------------------------------------------

def up(filters):
    live = live_tmux()
    if DARWIN and not live and os.environ.get("SSH_CONNECTION") and not os.environ.get("AGENTS_ALLOW_SSH"):
        # A server started from SSH sits outside the Aqua session: no login Keychain,
        # codesign/xcodebuild/Simulator misbehave. Start it from the GUI or a LaunchAgent.
        sys.exit("refusing to start the agents tmux server from SSH on macOS "
                 "(set AGENTS_ALLOW_SSH=1 to override); start it from the GUI session")
    codex_remote = False
    for r in select(filters):
        n = r["name"]
        if n in live:
            print(f"  up       {n}")
            continue
        if not os.path.isdir(r["dir"]):
            print(f"  SKIP     {n}: no directory {r['dir']}")
            continue
        if r["prov"] == "ant":
            busy = claude_running({n, r["was"]}, claude_last_session(r))
            if busy:
                print(f"  SKIP     {n}: still running outside tmux as '{busy[1]}' (pid {busy[0]}); exit it, then rerun")
                continue
        if r["prov"] == "oai" and not codex_remote:
            codex_remote = True
            s = subprocess.run(["codex", "remote-control", "start"], text=True, capture_output=True)
            if s.returncode:
                print(f"  warn     codex remote-control did not start: {(s.stderr or s.stdout).strip().splitlines()[-1:]}")
        cmd, how = command(r)
        # Falling back to a shell keeps the tmux session (and a terminal in the repo) if the agent exits.
        shell = f"{shlex.join(cmd)}; exec \"${{SHELL:-bash}}\" -l"
        new = ["tmux", "-L", SOCKET, "new-session", "-d", "-s", n, "-c", r["dir"],
               "--", "bash", "-c", shell]
        if not live_tmux() and not DARWIN:
            # First session starts the tmux server. Put it in its own user-manager scope so
            # it is not a child of the interactive login session and outlives it.
            scoped = ["systemd-run", "--user", "--scope", "--quiet", "--collect",
                      "--unit", f"agents-tmux-{os.getpid()}", *new]
            res = subprocess.run(scoped, text=True, capture_output=True, env=clean_env())
            if res.returncode:
                res = subprocess.run(new, text=True, capture_output=True, env=clean_env())
        else:
            # macOS: start it from an interactive GUI terminal rather than launchd so it
            # outlives the window and retains TCC permissions for external volumes.
            res = subprocess.run(new, text=True, capture_output=True, env=clean_env())
        if res.returncode:
            print(f"  FAIL     {n}: {res.stderr.strip()}")
        else:
            print(f"  started  {n}  ({how})")
    print("attach with: agents a <name>    detach: Ctrl-b d")


def resolve(prefix):
    live = sorted(live_tmux())
    hit = [s for s in live if s == prefix] or [s for s in live if s.startswith(prefix)]
    if len(hit) != 1:
        sys.exit(f"'{prefix}' matches {hit or 'no running session'}; see `agents ls`")
    return hit[0]


def attach(prefix):
    name = resolve(prefix)
    verb = "switch-client" if os.environ.get("TMUX") else "attach-session"
    os.execvp("tmux", ["tmux", "-L", SOCKET, verb, "-t", "=" + name])


def ls():
    live = live_tmux()
    w = max([20] + [len(r["name"]) for r in rows()] + [len(s) for s in live])
    print(f"{'NAME':<{w}} {'STATE':<8} {'MODEL':<15} {'EFFORT':<7} {'AUTO':<5} DIR")
    for r in rows():
        state = "up" if r["name"] in live else "-"
        if state == "-" and r["prov"] == "ant" and claude_running({r["name"], r["was"]}):
            state = "outside"
        print(f"{r['name']:<{w}} {state:<8} {r['model'] or '-':<15} {r['effort'] or '-':<7} "
              f"{'yes' if r['auto'] else 'no':<5} {os.path.relpath(r['dir'], CODE)}")
    extra = live - {r["name"] for r in rows()}
    for s in sorted(extra):
        print(f"{s:<{w}} up       (not in registry)")


def main():
    args = sys.argv[1:]
    verb = args[0] if args else "ls"
    if verb == "up":
        up(args[1:])
    elif verb in ("a", "attach") and len(args) == 2:
        attach(args[1])
    elif verb in ("a", "attach") and len(args) == 1:
        # No name: open tmux on a menu of every agent session (arrows + Enter).
        if not live_tmux():
            sys.exit("no agent sessions are running; `agents up` starts them")
        verb = "switch-client" if os.environ.get("TMUX") else "attach-session"
        os.execvp("tmux", ["tmux", "-L", SOCKET, verb, ";", "choose-tree", "-s", "-Z"])
    elif verb == "ls":
        ls()
    elif verb == "down" and len(args) == 2:
        name = resolve(args[1])
        tmux("kill-session", "-t", "=" + name)
        print(f"closed {name}; its conversation is saved and `agents up {name}` resumes it")
    elif verb == "cmd" and len(args) == 2:
        for r in select([args[1]]):
            cmd, how = command(r)
            print(f"{r['name']}: cd {r['dir']} && {shlex.join(cmd)}   # {how}")
    elif verb in ("-h", "--help", "help"):
        print(__doc__)
    else:
        # `agents example-app`: start whatever matches, and open it if it is a single session.
        picked = select(args)
        up(args)
        if len(picked) == 1 and sys.stdout.isatty() and picked[0]["name"] in live_tmux():
            attach(picked[0]["name"])


if __name__ == "__main__":
    main()
#registry.tsv
# Agent session registry for THIS Mac. Read by ./agents. 
# name = <project>-<function>-<provider> provider: ant (Claude Code) | oai (Codex) | agy (Antigravity) 
# auto = yes: started by a bare `agents up` (run it from Ghostty after login/reboot). no: only when named. 
# was = the session's name before this scheme; `agents up` resumes that conversation under the new name. 
# "-" means "the name without its provider suffix" (yp-ios-build-ant <- yp-ios-build). 
# dir is relative to $AGENTS_CODE_ROOT (default ~/code, resolved -> /Volumes/<name>). 
# model/effort "-" = the provider's own default (~/.claude/settings.json, ~/.codex/config.toml). 
# APFS is case-insensitive: no names differing only by case. 
# 
# name dir provider model effort auto was
ops-mac-ant ops ant opus - yes -