Skip to content
◀ Blog

How to design a CLI for AI agents

Adding --json is the start. An agent-friendly CLI also needs stable event streams, parsed failures with file and line, and error codes that name the fix.

Riley Hilliard9 min read

agentscli

To design a CLI for AI agents, treat its output as an API. The usual advice is to add a --json flag, and that’s the first step. An agent like Claude Code or Codex succeeds on the second try instead of the fifth when the CLI also gives it a stable stream of events it can read while the command runs, test failures parsed into file and line, errors that carry a code and the fix, exit codes with one meaning each, and help it can read without a person in the loop.

We build two CLIs that agents call more than people do: rr, which runs test suites on remote machines, and Stacks, which starts projects for coding agents and checks them. The examples below are their real flags and output.

Why is designing a CLI for AI agents different?

An agent reads every byte you print, pays for it in context, and acts on it literally. A person skims past a spinner, a progress line redrawn on every tick, or a stack trace above the line with the actual error. An agent gets all of it as text, and the redraws come through as escape codes.

These are the usual problems:

  • Output meant for eyes. Color codes, live progress lines and tables wrapped to the terminal width are noise in a pipe.
  • Prose errors. “Something went wrong connecting to host” leaves the agent guessing whether to retry, fix a config, or ask the user.
  • Ambiguous success. Exit 0 from a test command that matched no tests looks exactly like a pass.

Interactive prompts hang. An agent’s shell has no terminal on stdin, so a command that stops to ask “Overwrite? [y/N]” hangs until it times out.

Should a CLI output JSON for agents?

Yes, but pick the shape on purpose. A single JSON object at the end works for short commands. For anything that runs long, emit one JSON object per line as the work progresses, so the agent can tell a slow sync from a hung SSH connection.

rr defaults to structured output, since its usual caller is an agent. Phase events go to stderr as JSON lines, the command’s own stdout and stderr pass through untouched, and a single result event ends the run. A person adds --pretty for spinners and colors:

$ rr run "go test ./..."
{"type":"phase","phase":"connect","status":"complete","host":"m4-mini","duration_s":0.21,...}
{"type":"phase","phase":"sync","status":"complete","host":"m4-mini","duration_s":0.84,...}
ok      github.com/you/project/internal/api    3.112s
{"type":"result","status":"success","host":"m4-mini","duration_s":4.9,"exit_code":0,"details":{...}}

Because rr leaves the command’s output unmodified, the test runner’s text reads the same as it would locally, and the agent finds rr’s own events by their type key.

Stacks takes the other route and picks an audience per invocation. With --json, stdout holds one result object. Without it, output goes to a person only when stdout is a terminal, no agent is detected (it checks markers such as CLAUDECODE and AI_AGENT) and CI is unset. Every other caller gets agent text: the same result, without log lines, progress or color. Agent and JSON output never carry ANSI escapes, even when color is forced.

Both tools publish the shapes. stacks schema lists every JSON shape the CLI prints, and stacks schema <name> prints one as a JSON Schema. Once a field ships, treat it like a public API: add fields, don’t rename them. rr still accepts its old --machine flag as a no-op, so scripts written for it keep working.

How should errors tell an agent what to do next?

An error for an agent needs a stable code to branch on, a message for the person reading the transcript, and the next step written out. rr’s error envelope has all three:

{
  "success": false,
  "error": {
    "code": "SSH_AUTH_FAILED",
    "message": "probe m1-mini failed: authentication failed (ssh: handshake failed: ...)",
    "suggestion": "Deploy SSH key: ssh-copy-id m1-mini",
    "details": { "reason": "authentication failed", "alias": "m1-mini" }
  }
}

The codes are a closed list (CONFIG_NOT_FOUND, HOST_NOT_FOUND, SSH_TIMEOUT, LOCK_HELD, DEPENDENCY_MISSING, INTERRUPTED and a few more), and rr sets each code where the error is created, never by matching the message afterward. Matching on message text breaks the first time someone rewords a message.

Stacks puts the same idea in its envelope, the last line of stderr under --json:

{
  "error": {
    "tag": "NotFound",
    "message": "Not found.",
    "retryable": false,
    "next": "run this command again from inside a project stacks new created, or create one with stacks new <stack> <dir>.",
    "details": { "kind": "project", "looked": "/path", "suggestions": [] }
  }
}

message is fixed per tag, so it’s safe to match on, and retryable tells the agent whether trying again can work.

Errors can also tell an agent what not to do. rr’s INTERRUPTED means the user stopped the run while it waited for a lock, and the documented action is to not retry. Stacks’ verify, when it finds its steps were edited, says in next not to edit them back, and to ask the user to accept or undo the change.

Why parse test failures instead of printing logs?

A failing test run can print thousands of lines, and the agent needs three facts from them: which test, which file and line, and the message. If the CLI only streams the log, the agent scrolls back through it, burns context, and sometimes fixes the first error it sees instead of the one that failed.

rr recognizes pytest, Jest and Go test output and puts the counts and failures into its result event:

{
  "type": "result",
  "status": "failed",
  "exit_code": 1,
  "host": "mini",
  "duration_s": 14.2,
  "details": {
    "exec_duration_s": 11.8,
    "log_file": "/home/me/.rr/logs/test-20260101-120000/output.log",
    "summary": { "passed": 41, "failed": 1, "skipped": 0, "errors": 0 },
    "failures": [
      {
        "name": "test_login",
        "file": "tests/test_auth.py:42",
        "message": "AssertionError: ..."
      }
    ]
  }
}

The full log is still on disk at log_file when the agent needs more. Parsing also catches the quiet failures. A run that collected no tests keeps its exit code but sets details.no_tests, so a path filter that matched nothing doesn’t read as a passing suite. When zero tests ran and the command has a pipe, rr sets piped_exit_code, because the exit status may have come from a later stage of the pipe.

Stacks doesn’t parse test output; it reports per step. stacks verify gives each failed step its exit code, a failureKind (step, env or timeout) and the last lines of its output. Exit 127 becomes a missing command with failureKind: "env", which tells the agent to look at the machine instead of the code.

What should exit codes mean?

Each exit code should map to one next action, and a published code should never change meaning. Stacks documents its table this way:

Exit Next action
0 Success. For verify, check the outcome: partial is not done
1 A bug in Stacks; not retryable
2 Fix the input
3 Fix the configuration or manifest
4 Retry later
5 Read the verify report on stdout
6 Ask a person
130 The run was stopped; cleanup ran

The exit code also has to survive a pipe. A closed stdout pipe makes Stacks exit quietly with 0, except after a failure that keeps its report, so a failed verify piped into head still exits 5 and never reads as a pass.

A wrapper passes through the exit code of the command it runs. rr’s exit code is your command’s exit code, and a parallel task exits 1 if any subtask failed. When rr fails before the command runs (config, SSH, lock, sync, missing tools), it also exits 1, but writes an error envelope instead of a result event. The docs tell agents to look for a "type":"result" line to tell the two apart. A command cut off by a dropped connection exits 255 with exit_code: -1 in the result. Being interrupted while waiting for a lock exits 130.

How should a CLI behave when several agents run it at once?

Parallel agents in separate worktrees will run the same command at the same moment, and a CLI that assumes one caller lets them collide. rr takes a lock on a host before it syncs. If the host is busy, rr tries the next one. When it has to wait, it emits one event that names the holder:

{
  "type": "phase",
  "phase": "lock",
  "status": "waiting",
  "host": "dev",
  "details": {
    "message": "Waiting up to 5m0s for the lock on dev: 'make test' held by me@laptop (pid 4242, started 1m0s ago, this machine)",
    "holders": [
      {
        "host": "dev",
        "user": "me",
        "pid": 4242,
        "command": "make test",
        "age_s": 60,
        "same_machine": true
      }
    ],
    "wait_timeout_s": 300
  }
}

A silent wait looks like a hang, and an agent that thinks the command hung will kill it and try something worse. If waiting times out, the error is LOCK_HELD. rr also gives each git worktree its own remote directory, so two agents on different branches never sync over each other’s files.

Any fallback should be loud. If rr can’t reach any host and local_fallback is on, it runs locally but emits a warning event and sets details.fallback on the result, listing who holds each lock when every host was busy. A test run that quietly ran on the laptop should never look like the run on the host you asked for.

How does an agent discover what a CLI can do?

Agents learn a CLI the way people do, from --help, so put everything there: flags, examples and exit codes. stacks <command> --help prints all three, and --help --json returns { "help": "..." }. Running stacks with no arguments prints a short guide written for agents, including the two verify runs to finish with before calling the work done.

Typos should come back with a correction. Stacks’ error for an unknown flag lists up to three close flags the command accepts, and can point out a positional argument instead: new --dir suggests <dir> (positional argument). rr suggests the nearest command or task name for an unknown one, using Cobra’s built-in suggestions.

List commands should have JSON too. rr tasks --json lists the project’s named tasks, rr host list --json the configured hosts, and rr test --dry-run shows the plan without running anything.

Every prompt needs a flag form: rr init --non-interactive --host dev-box sets up a project with no questions. Stacks asks for missing arguments only when a person is at both ends of a terminal; under an agent, --json, CI or a pipe, new and add exit 2 (Usage) instead of asking a question nobody can answer.

For Claude Code specifically, rr also ships a plugin with a skill that documents its JSON events and error codes, so the agent arrives knowing the contract. Install it with /plugin marketplace add https://github.com/rileyhilliard/rr, then /plugin install rr@rr.