claude -p "Reply with exactly the word READY." --output-format json --tools "" \
| jq '{ok: (.type=="result" and .subtype=="success" and .is_error==false), result, session_id}'
This prints one JSON object on stdout. The answer is in .result. The run succeeded only when all four of these hold:
type == "result"subtype == "success"is_error == falseFor each request, the board's Claude seat starts one short-lived process. This is the exact argv, from claude/adapter.py:
["claude", "-p", prompt,
"--model", selected_model("claude"), # chosen at container boot: opus, then fable, then best
"--effort", os.environ.get("CLAUDE_EFFORT", "medium"),
"--output-format", "json", # one result envelope on stdout
"--dangerously-skip-permissions"] # acceptable ONLY because the container is the sandbox
It treats the result as successful only when it can parse the envelope and every check passes:
out = json.loads(stdout)
completed = (out.get("type") == "result" and out.get("subtype") == "success"
and out.get("is_error") is False)
ok = completed and returncode == 0
answer = out.get("result")
models = out.get("modelUsage") or {}
actual_model = next(iter(models)) if len(models) == 1 else None # the model that actually answered
The process is the easy part. Most of the design is the isolation around it:
| Concern | What the board does |
|---|---|
| Container | The process runs non-root, with a read-only root filesystem and all capabilities dropped. It has no bind mounts of the host's home or project directories. |
| Per-request HOME | Each request gets a fresh empty HOME. The board copies in only ~/.claude/.credentials.json (the saved subscription login) and the output contract as ~/.claude/CLAUDE.md. Transcripts are deleted afterwards. |
| Credentials | The login lives in a named Docker volume. If Claude refreshed the token during the run, the board copies the refreshed file back, but only when it is valid JSON with the same structure. |
| Environment | The child process gets a whitelist of environment variables (PATH, locale, CA bundle, HOME/TMPDIR/XDG paths). Server secrets are never passed. |
| Filesystem | A Linux Landlock policy, inherited by every child process, allows reads of program files plus this request's inputs and source path, and writes only to its own HOME, temp and output directories. If the policy cannot be applied, the request fails rather than running unconfined. |
| Source code | There is no host mount. A separate read-only source service reads the code, with an audit log, using a short-lived token scoped to this one request. |
| Limits | One execution per seat at a time. The default deadline is 900 s and the maximum 3600 s. On timeout the whole process group is killed. |
--dangerously-skip-permissions is safe there only because of the confinement listed above. On a normal host it lets Claude run any shell command and edit any file without asking. Use the safe defaults instead.| Pattern | Use when | Processes | Conversation state |
|---|---|---|---|
| A. One-shot | A single question with a single answer. The board uses this. | One per question | None needed |
| B. Resume by session ID | Multi-turn, where turns are minutes or hours apart, or come from different programs. | One per turn | Saved on disk by Claude Code and resumed with --resume <session_id> |
| C. Live stream-json | A real back-and-forth conversation with low overhead per turn. | One long-lived process | Held in the running process |
claude -p "Summarize README.md in three bullets" --output-format json --tools "Read"
Prompt sources:
cat log.txt | claude -p "explain the root cause".| Field in the result envelope | Meaning |
|---|---|
type, subtype, is_error | The success test: "result", "success" and false. |
result | The final answer text. |
session_id | Pass this to --resume to continue the conversation. |
structured_output | Present only with --json-schema '<schema>' and only when the output validated. Check that it exists before using it. |
num_turns, duration_ms, usage, modelUsage, total_cost_usd | Metrics. modelUsage keys are the model IDs that actually ran. The cost figure is a client-side estimate. |
permission_denials | Tool calls that were refused. A non-empty list explains a partial answer. |
When something fails inside the run, such as missing authentication, the failure is still printed as the result on stdout. Parse stdout even when the exit code is non-zero, and never parse stderr as JSON.
sid=$(claude -p "Remember the number 42. Reply only: OK" --output-format json --tools "" | jq -r .session_id)
claude -p "What number did I give you? Reply with the number only." --resume "$sid" --output-format json --tools "" | jq -r .result
# prints: 42
--session-id <uuid> lets you choose the session ID up front, so you don't have to capture it.--fork-session, used with --resume, branches the conversation into a new ID.--resume finds a session by its ID from any directory on the same machine and user.--continue picks the most recent conversation in the current directory. Avoid it on a shared host, where another agent's session may be the most recent.--no-session-persistence saves nothing to disk, so the session cannot be resumed. The board effectively gets this by discarding each per-request HOME.Start one process and keep it running:
claude -p --input-format stream-json --output-format stream-json --verbose --tools "" --permission-prompts none
To send, write one JSON object per line to stdin and flush:
{"type":"user","message":{"role":"user","content":"Your message here"}}
To receive, read newline-delimited JSON events from stdout until a "type":"result" event arrives. That event completes the turn and carries the same fields as the Pattern A envelope. Each message you send produces exactly one result. Event types seen per turn include:
system with subtype initassistant (message content blocks)user (tool results)rate_limit_eventsystem with subtype api_retrystream_event (token deltas, with --include-partial-messages)Key only on result and ignore event types you don't use. New types appear between versions.
Closing stdin ends the session, and the process exits with code 0. The script below was run as published:
#!/usr/bin/env python3
"""Hold a multi-turn conversation with one headless Claude Code process over stdin/stdout."""
import json
import subprocess
import sys
CMD = ["claude", "-p",
"--input-format", "stream-json", "--output-format", "stream-json", "--verbose",
"--model", "haiku", # any alias or full model name
"--tools", "", # no tools: pure conversation
"--permission-prompts", "none", # never wait for a human
"--safe-mode"] # skip CLAUDE.md, hooks, plugins, MCP; login still works
def send(proc, text):
line = {"type": "user", "message": {"role": "user", "content": text}}
proc.stdin.write(json.dumps(line) + "\n")
proc.stdin.flush()
def receive(proc):
"""Read events until this turn's result; ignore event types you don't use."""
for raw in proc.stdout:
event = json.loads(raw)
if event.get("type") == "result":
ok = event.get("subtype") == "success" and event.get("is_error") is False
return ok, event.get("result"), event.get("session_id")
raise RuntimeError("claude exited before sending a result")
proc = subprocess.Popen(CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1)
try:
for question in ["Remember the word PLUM. Reply only: OK",
"What word did I ask you to remember? Reply with the word only."]:
send(proc, question)
ok, answer, session = receive(proc) # stdin is still open here
print(f"ok={ok} answer={answer!r}")
if not ok: sys.exit(1)
finally:
proc.stdin.close() # EOF ends the session
print("exit code", proc.wait(timeout=60))
Expected output:
ok=True answer='OK'
ok=True answer='PLUM'
exit code 0
--include-partial-messages and read stream_event events whose event.delta.type is text_delta. To get typed message objects and callbacks in Python or TypeScript code rather than a subprocess, use the Claude Agent SDK, which runs the same agent loop.| Credential | How | Notes |
|---|---|---|
| Saved subscription login | Run claude auth login once as the same user. On Linux it is stored in ~/.claude/.credentials.json (mode 0600). | The board uses this: one login per seat, copied into each request's fresh HOME. Default for Pro, Max, Ultra, Team and Enterprise. |
| Long-lived subscription token | claude setup-token prints a one-year token and does not save it. Export it as CLAUDE_CODE_OAUTH_TOKEN. | For CI or hosts without a browser. The token can only make model requests. |
| API key (per-token billing) | ANTHROPIC_API_KEY | In -p mode the key is always used when present, ahead of the subscription login. Unset it if you meant to use the subscription. |
claude auth status prints JSON. Read loggedIn and authMethod from it, not the exit code. This is the board's readiness probe.is_error on every call.--bare accepts only an API key. It reads ANTHROPIC_API_KEY or an apiKeyHelper and never the login or CLAUDE_CODE_OAUTH_TOKEN. Subscription users who want a clean, reproducible run should use --safe-mode, which keeps auth working (verified), or a fresh HOME as the board does.-p shows no workspace-trust dialog. Without --bare or --safe-mode, it runs the hooks in the current directory's .claude/settings.json and connects the servers in its .mcp.json. It also loads CLAUDE.md files and your ~/.claude configuration. Run it from a directory you trust, ideally an empty temporary directory.-p starts in Manual permission mode when nothing sets a mode. Any tool call that needs approval is denied unless you allowed it.| Need | Flags |
|---|---|
| Pure Q&A, no tools | --tools "" |
| Read-only analysis | --tools "Read,Grep,Glob" |
| Specific commands only | --allowedTools "Bash(git diff *),Read" --permission-mode dontAsk (anything not allowed is denied) |
| Nobody to answer prompts | --permission-prompts none (denies instead of waiting, and tells Claude not to retry) |
| Isolation from host configuration | --safe-mode (subscription) or --bare (API key) |
| Spend cap | --max-budget-usd <amount> |
| Replace or extend the system prompt | --system-prompt "..." or --append-system-prompt "..." |
| Machine-checkable output | --output-format json --json-schema '<JSON Schema>', then read .structured_output |
system/api_retry events report retries, including error and retry_delay_ms. A subscription limit appears as a failed result.--model, then confirm which one actually answered from the modelUsage keys.Waiting for background work to finish go to stderr. Do not parse stderr./review-board skill or the dispatch_to_reviewboard MCP tool (code-executor). Gemini, Codex and Claude review independently, then a synthesis pass combines them./administrators and /developers).| Claim | Source |
|---|---|
-p usage, output formats, --resume, --bare, trust behaviour, Manual mode from 2.1.302, --permission-prompts, SIGTERM exit 143, 10 MB stdin cap | code.claude.com/docs/en/headless |
claude setup-token, CLAUDE_CODE_OAUTH_TOKEN, credential precedence, API key always used in -p, --bare ignores OAuth | code.claude.com/docs/en/authentication |
Flag names and choices (--tools, --safe-mode, --input-format, --permission-mode, …) | claude --help, Claude Code 2.1.322 |
| Board argv, success test, per-request HOME, credential copy-back, environment whitelist, Landlock | claude/adapter.py, shared/review_session.py (administrators/reviewboard) |
stream-json input line shape, one result per message, turn-by-turn with stdin open, --resume recall, --safe-mode with a subscription login | Live runs, 2026-11-10, Claude Code 2.1.322 |