modified
--- a/headless.md +++ b/headless.md @@ -144,7 +144,7 @@ claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages -Find each [`result` message](</docs/en/agent-sdk/typescript#sdkresultmessage>) by `type`, because a message such as a task notification can follow a result and start another turn. A successful `result` message holds any final response text, the running cost total, and session metadata. If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display only the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: +Find each [`result` message](</docs/en/agent-sdk/typescript#sdkresultmessage>) by `type`, because a message such as a task notification can follow a result and start another turn. A successful `result` message holds any final response text, the running cost total, and session metadata. If your program reads the stream slowly, Claude Code waits up to 30 seconds for queued output to drain before exiting. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display only the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \ jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text' @@ -153,7 +153,7 @@ #### Follow subagent messages -Messages from [subagents](</docs/en/sub-agents>) and from skills that [run in a subagent](</docs/en/skills#run-skills-in-a-subagent>) appear in the stream as `assistant` and `user` messages. Their `parent_tool_use_id` field says which run each one belongs to. Messages from the main conversation carry `null` in that field. The first message from a forked skill, or from a subagent running in the [foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>), is a `user` message carrying the prompt or skill content that drives it. After that first message, Claude Code emits: +Messages from [subagents](</docs/en/sub-agents>) and from skills that [run in a subagent](</docs/en/skills#run-skills-in-a-subagent>) appear in the stream as `assistant` and `user` messages. Their `parent_tool_use_id` field says which run each one belongs to. Messages from the main conversation carry `null` in that field. The first message from a forked skill, or from a [foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) subagent other than a [fork](</docs/en/sub-agents#fork-the-current-conversation>), is a `user` message with the subagent’s prompt or the skill’s content. After that first message, Claude Code emits: * **By default** : the run’s `tool_use` and `tool_result` blocks. * **With[`--forward-subagent-text`](</docs/en/cli-reference#cli-flags>) or [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>)**: the run’s text and thinking blocks too, so you can reconstruct each run’s transcript.
modified
--- a/headless.md +++ b/headless.md @@ -34,7 +34,7 @@ [Custom agents](</docs/en/sub-agents#choose-the-subagent-scope>)| `--agents <file-or-json>` A plugin| `--plugin-dir <path>`, `--plugin-url <url>` -Hooks still don’t run in bare mode when you pass them with `--settings`, or in the [`hooks/hooks.json`](</docs/en/plugins/components#hooks>) or [`hooks` manifest key](</docs/en/plugins/manifest-reference#hooks>) of a plugin you load with a flag. Don’t use bare mode for a run that needs them. Bare mode also limits what happens while the session runs: +Hooks still don’t run in bare mode when you pass them with `--settings`, or in the [`hooks/hooks.json`](</docs/en/plugins/components#hooks>) or [`hooks` manifest key](</docs/en/plugins/manifest-reference#hooks>) of a plugin you load with a flag. [Agent SDK hook callbacks](</docs/en/agent-sdk/hooks>) don’t run either. Don’t use bare mode for a run that needs these hooks. Bare mode also limits what happens while the session runs: * **MCP servers** : only servers supplied on the command line connect, for example with `--mcp-config`. In an interactive session, Claude Code also skips the automatic IDE connection unless you pass `--ide`. * **System reminders** : Claude receives your prompts and the tool results without the [system reminders](</docs/en/glossary#system-reminder>) Claude Code would add alongside them. For example, Claude isn’t told when a file it edited earlier changes on disk, and it doesn’t get the list of available skills, including skills from an `--add-dir` folder. @@ -42,7 +42,7 @@ Before v2.1.286, these limits held only partly: an interactive `--bare` session connected the MCP servers that a normal session would, every `--bare` session sent system reminders, and background tasks stayed available. -`--bare` is the recommended mode for scripted and SDK calls, and will become the default for `-p` in a future release. +`--bare` is the recommended mode for scripted and SDK calls that don’t need hooks, and will become the default for `-p` in a future release. ### Background tasks at exit @@ -205,7 +205,7 @@ Field| Type| Description ---|---|--- `plugins`| array| plugins that loaded successfully, each with `name` and `path` -`plugin_errors`| array| plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. A plugin that didn’t load is absent from `plugins`. The key is omitted when there are no errors +`plugin_errors`| array| plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. The key is omitted when there are no errors When a `--plugin-dir` directory or archive itself fails to load, its `plugin_errors` entry includes the resolved absolute path as `path`. Use it to tell which of several `--plugin-dir` values failed. The `path` field requires Claude Code v2.1.283 or later. Use the MCP server fields the same way. When you pass [`--mcp-config`](</docs/en/cli-reference#cli-flags>) with `-p`, Claude Code waits for still-pending servers before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default. A remote server with a [cached tool list](</docs/en/agent-sdk/mcp#connection-timing>) skips the wait, shows `pending` in `system/init`, and connects on its first tool call. In a [self-hosted environment](</docs/en/self-hosted-environments-configuration#connection-timing>), a shorter wait applies instead. The wait requires Claude Code v2.1.221 or later. Claude Code validates each `--mcp-config` entry at startup and skips entries that fail validation, for example a `url` entry with no `type`. The run continues and exits cleanly, so check these fields to catch a server that never loaded:
modified
--- a/headless.md +++ b/headless.md @@ -144,7 +144,7 @@ claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages -The last line of the stream is a `result` message with the final response text, cost, and session metadata. If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display only the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: +Find each [`result` message](</docs/en/agent-sdk/typescript#sdkresultmessage>) by `type`, because a message such as a task notification can follow a result and start another turn. A successful `result` message holds any final response text, the running cost total, and session metadata. If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display only the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \ jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text' @@ -273,6 +273,7 @@ Command support differs in `-p` mode: * User-invoked [skills](</docs/en/skills>) and custom commands work. Include `/skill-name` in the prompt string and Claude Code expands it before running. + * [Skills from MCP servers](</docs/en/mcp#requirements-for-skills-from-mcp-servers>) aren’t supported. * Built-in commands that only run in the terminal interface, such as `/login`, aren’t available. * `/model`, `/effort`, `/fast`, `/color`, and `/rename` accept the value as an argument, for example `/model sonnet`, and `/mcp` with no argument prints a text summary of server status. These forms follow each command’s [availability notes](</docs/en/commands#all-commands>). * To change a setting, pass `key=value` to `/config`, for example `/config verbose=true`.
modified
--- a/headless.md +++ b/headless.md @@ -249,7 +249,7 @@ ### Turn off permission prompts in unattended runs -Pass `--permission-prompts none` when nobody is available to answer permission prompts, for example in a scheduled job. The flag matters most when your run has a permission host: an Agent SDK app with a [`canUseTool` callback](</docs/en/agent-sdk/user-input>), or an MCP tool you pass with [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>). Without the flag or the [`permissions.denyInsteadOfPrompting`](</docs/en/settings-reference#permissions-denyinsteadofprompting>) setting, your run waits for that host to answer each permission request. With the flag, your run doesn’t consult the host or wait on it. Anything that would prompt is denied unless a `PermissionRequest` hook allows it, Claude is told that nobody can approve the request and not to retry it, and the run continues. In a `-p` run with no host, these requests are denied either way, and the flag also tells Claude not to retry them. Permission rules, [`PermissionRequest` hooks](</docs/en/hooks#permissionrequest>), and the permission mode you set still decide every call first; Claude Code denies only the requests that nothing else resolves. +Pass `--permission-prompts none` when nobody is available to answer permission prompts, for example in a scheduled job. The flag matters most when your run has a permission host: an Agent SDK app with a [`canUseTool` callback](</docs/en/agent-sdk/user-input>), or an MCP tool you pass with [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>). Without the flag or the [`permissions.denyInsteadOfPrompting`](</docs/en/settings-reference#permissions-denyinsteadofprompting>) setting, your run waits for that host to answer each permission request. With the flag, your run doesn’t consult the host or wait on it. Anything that would prompt is denied unless a `PermissionRequest` hook allows it, Claude is told that nobody can approve the request and not to retry it, and the run continues. Permission rules, [`PermissionRequest` hooks](</docs/en/hooks#permissionrequest>), and the permission mode you set still decide every call first; Claude Code denies only the requests that nothing else resolves. The `--permission-prompts none` flag lasts for one run. To deny calls that would wait on a permission prompt in later runs too, set [`permissions.denyInsteadOfPrompting`](</docs/en/settings-reference#permissions-denyinsteadofprompting>) to `true` in your user or managed settings.
modified
--- a/headless.md +++ b/headless.md @@ -20,7 +20,7 @@ ### Start faster with bare mode -Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, [subagents](</docs/en/sub-agents>), installed plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` discovers and loads them as an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. A directory you name with `--add-dir` is a partial exception: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](</docs/en/skills#skills-from-additional-directories>) covers what does and doesn’t load. Without `--bare`, a `-p` session runs the hooks in a project’s `.claude/settings.json` and connects the servers in its `.mcp.json`, even in a folder you’ve never trusted. A `-p` session shows no workspace trust dialog and no per-server approval prompt. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: +Add `--bare` to reduce startup time by skipping auto-discovery of your hooks, skills, custom commands, [subagents](</docs/en/sub-agents>), installed plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` discovers and loads them as an interactive session would, including anything configured in the working directory or `~/.claude`. In bare mode, Claude Code still reads settings files and their [permission rules](</docs/en/permissions#what-runs-before-you-trust-a-folder>), but a hook in `~/.claude/settings.json` or an MCP server in the project’s `.mcp.json` won’t run. A directory you name with `--add-dir` is a special case: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](</docs/en/skills#skills-from-additional-directories>) covers what does and doesn’t load. Without `--bare`, a `-p` session runs the hooks in a project’s `.claude/settings.json` and connects the servers in its `.mcp.json`, even in a folder you’ve never trusted. A `-p` session shows no workspace trust dialog and no per-server approval prompt. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: claude --bare -p "Summarize README.md" --allowedTools "Read"
modified
--- a/headless.md +++ b/headless.md @@ -85,7 +85,7 @@ ### Pipe data through Claude -Non-interactive mode reads stdin, so you can pipe data in and redirect the response out like any other command-line tool. This example pipes a build log into Claude and writes the explanation to a file: +Non-interactive mode reads stdin, so you can pipe data in and redirect the response out. This example pipes a build log into Claude and writes the explanation to a file: cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt @@ -268,7 +268,7 @@ claude -p "Look at my staged changes and create an appropriate commit" \ --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)" -The `--allowedTools` flag uses [permission rule syntax](</docs/en/settings-reference#permission-rule-syntax>). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`. +The `--allowedTools` flag uses [permission rule syntax](</docs/en/settings-reference#permission-rule-syntax>). With the trailing ` *`, `Bash(git diff *)` matches `git diff` with or without arguments. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`. Command support differs in `-p` mode:
modified
--- a/headless.md +++ b/headless.md @@ -37,7 +37,7 @@ Hooks still don’t run in bare mode when you pass them with `--settings`, or in the [`hooks/hooks.json`](</docs/en/plugins/components#hooks>) or [`hooks` manifest key](</docs/en/plugins/manifest-reference#hooks>) of a plugin you load with a flag. Don’t use bare mode for a run that needs them. Bare mode also limits what happens while the session runs: * **MCP servers** : only servers supplied on the command line connect, for example with `--mcp-config`. In an interactive session, Claude Code also skips the automatic IDE connection unless you pass `--ide`. - * **System reminders** : Claude gets your prompts and the tool results without the [system reminders](</docs/en/glossary#system-reminder>) Claude Code would add alongside them. For example, Claude isn’t told when a file it read earlier changes on disk, and it doesn’t get the list of available skills, including skills from an `--add-dir` folder. + * **System reminders** : Claude receives your prompts and the tool results without the [system reminders](</docs/en/glossary#system-reminder>) Claude Code would add alongside them. For example, Claude isn’t told when a file it edited earlier changes on disk, and it doesn’t get the list of available skills, including skills from an `--add-dir` folder. * **Background tasks** : Claude can’t run background commands or background subagents, and the other features that [`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`](</docs/en/env-vars>) turns off are off too. A command that reaches its [timeout](</docs/en/tools-reference#timeout-and-output-limits>) stops instead of [moving to the background](</docs/en/tools-reference#background-commands>). Before v2.1.286, these limits held only partly: an interactive `--bare` session connected the MCP servers that a normal session would, every `--bare` session sent system reminders, and background tasks stayed available.
modified
--- a/headless.md +++ b/headless.md @@ -49,11 +49,15 @@ After Claude finishes its turn and stdin has closed, a `claude -p` run can stay open to wait for background work that Claude started. Unless a background command that the main conversation started is still running, Claude Code stops whatever is still running after 10 minutes of continuous idle waiting by default and drops its partial result. To change the 10-minute cap, set [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without one. The run waits for background work such as background commands, subagents and workflows, Monitor watches, and pending `/loop` wakeups: * **[Background commands](</docs/en/tools-reference#background-commands>)** : for a command that the main conversation started, for example a dev server or a watch build, the run waits until the command exits or reaches its [time limit](</docs/en/tools-reference#time-limit-for-background-commands>). Claude then takes one more turn with the outcome. While the command runs, the 10-minute cap doesn’t end the wait. - * **Background[subagents](</docs/en/sub-agents>) and workflows**: the run stays open until that work completes, because its result is part of the final output. + * **Background[subagents](</docs/en/sub-agents>) and workflows**: the run stays open until each one finishes or the 10-minute cap ends the wait. * **[Monitor](</docs/en/tools-reference#monitor-tool>) watches**: the run waits until the watch times out or the 10-minute cap ends the wait, whichever comes first. While it waits, Claude keeps responding to what the watch reports. By default, a watch times out five minutes after Claude starts it. * **Pending wakeups** : in a run whose prompt you passed as text rather than with `--input-format stream-json`, when Claude has scheduled a [self-paced `/loop` wakeup](</docs/en/scheduled-tasks#let-claude-choose-the-interval>), the run waits for each wakeup to fire and runs its iteration until the [loop ends](</docs/en/scheduled-tasks#stop-a-loop>), even past the 10-minute cap. When stderr is a terminal and the run has waited five seconds, Claude Code prints a line to stderr that starts with `Waiting for background work to finish` and names the work. With `json` or `stream-json` output, the line prints only when stdout isn’t a terminal, so the JSON your script reads never carries it. If the run reaches its [`--max-budget-usd`](</docs/en/cli-reference#cli-flags>) cap, Claude Code stops the remaining background work instead of waiting. When background work starts another turn, the run prints each turn’s result with the default `text` output and the last turn’s result with `json` output. Before v2.1.295, the run printed only the last turn’s result with `text` output too. + +#### Give a long subagent command more time + +When a subagent’s long command [moves to the background](</docs/en/tools-reference#foreground-commands-that-move-to-the-background>) at its timeout, a `claude -p` run can exit with code 0 before the command finishes. To raise the default timeout above the command’s run time, set [`BASH_DEFAULT_TIMEOUT_MS`](</docs/en/env-vars>), for example `BASH_DEFAULT_TIMEOUT_MS=300000 claude -p "<prompt>"` for five minutes. For a background subagent’s command over 10 minutes, also raise the 10-minute cap. #### MCP work when a non-interactive run ends @@ -245,7 +249,11 @@ ### Turn off permission prompts in unattended runs -Pass `--permission-prompts none` when nobody is available to answer permission prompts, for example in a scheduled job. The flag matters most when your run has a permission host: an Agent SDK app with a [`canUseTool` callback](</docs/en/agent-sdk/user-input>), or an MCP tool you pass with [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>). Without the flag, your run waits for that host to answer each permission request. With the flag, your run doesn’t consult the host or wait on it. Anything that would prompt is denied unless a `PermissionRequest` hook allows it, Claude is told that nobody can approve the request and not to retry it, and the run continues. In a `-p` run with no host, these requests are denied either way, and the flag also tells Claude not to retry them. Permission rules, [`PermissionRequest` hooks](</docs/en/hooks#permissionrequest>), and the permission mode you set still decide every call first; Claude Code denies only the requests that nothing else resolves. This example runs an unattended task in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). The classifier reviews each action as usual, and Claude Code denies anything that would have fallen back to a prompt: +Pass `--permission-prompts none` when nobody is available to answer permission prompts, for example in a scheduled job. The flag matters most when your run has a permission host: an Agent SDK app with a [`canUseTool` callback](</docs/en/agent-sdk/user-input>), or an MCP tool you pass with [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>). Without the flag or the [`permissions.denyInsteadOfPrompting`](</docs/en/settings-reference#permissions-denyinsteadofprompting>) setting, your run waits for that host to answer each permission request. With the flag, your run doesn’t consult the host or wait on it. Anything that would prompt is denied unless a `PermissionRequest` hook allows it, Claude is told that nobody can approve the request and not to retry it, and the run continues. In a `-p` run with no host, these requests are denied either way, and the flag also tells Claude not to retry them. Permission rules, [`PermissionRequest` hooks](</docs/en/hooks#permissionrequest>), and the permission mode you set still decide every call first; Claude Code denies only the requests that nothing else resolves. + +The `--permission-prompts none` flag lasts for one run. To deny calls that would wait on a permission prompt in later runs too, set [`permissions.denyInsteadOfPrompting`](</docs/en/settings-reference#permissions-denyinsteadofprompting>) to `true` in your user or managed settings. + +This example runs an unattended task in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). The classifier reviews each action as usual, and Claude Code denies anything that would have fallen back to a prompt: claude -p "Update the dependency pins and run the tests" --permission-mode auto --permission-prompts none @@ -267,7 +275,7 @@ * User-invoked [skills](</docs/en/skills>) and custom commands work. Include `/skill-name` in the prompt string and Claude Code expands it before running. * Built-in commands that only run in the terminal interface, such as `/login`, aren’t available. * `/model`, `/effort`, `/fast`, `/color`, and `/rename` accept the value as an argument, for example `/model sonnet`, and `/mcp` with no argument prints a text summary of server status. These forms follow each command’s [availability notes](</docs/en/commands#all-commands>). - * To change a setting, pass `key=value` to `/config`, for example `/config thinking=false`. + * To change a setting, pass `key=value` to `/config`, for example `/config verbose=true`. * `/output-style <style>` switches [output styles](</docs/en/output-styles>) and `/output-style` alone lists them. Requires Claude Code v2.1.269 or later. ### Customize the system prompt
modified
Show diff (279 lines)
--- a/headless.md +++ b/headless.md @@ -4,11 +4,7 @@ This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](</docs/en/agent-sdk/overview>). -## - -​ - -Basic usage +## Basic usage Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. Not every [CLI option](</docs/en/cli-reference>) combines with `-p`. Claude Code rejects `--bg`, and rejects `--cloud` with a task description, with an error naming the conflict; `--cloud` with a session ID and `-p` instead [queues a message into that cloud session](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>) and exits. Options you’ll combine with `-p` often include: @@ -22,11 +18,7 @@ Claude Code exits with code 0 on success and a non-zero code when the run fails, so your scripts can branch on the exit status. If you pass an invalid flag, Claude Code reports the error to stderr before the run starts. When a failure happens inside the run, such as missing authentication, Claude Code prints the failure as the result on stdout. -### - -​ - -Start faster with bare mode +### Start faster with bare mode Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, [subagents](</docs/en/sub-agents>), installed plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` discovers and loads them as an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. A directory you name with `--add-dir` is a partial exception: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](</docs/en/skills#skills-from-additional-directories>) covers what does and doesn’t load. Without `--bare`, a `-p` session runs the hooks in a project’s `.claude/settings.json` and connects the servers in its `.mcp.json`, even in a folder you’ve never trusted. A `-p` session shows no workspace trust dialog and no per-server approval prompt. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: @@ -52,11 +44,7 @@ `--bare` is the recommended mode for scripted and SDK calls, and will become the default for `-p` in a future release. -### - -​ - -Background tasks at exit +### Background tasks at exit After Claude finishes its turn and stdin has closed, a `claude -p` run can stay open to wait for background work that Claude started. Unless a background command that the main conversation started is still running, Claude Code stops whatever is still running after 10 minutes of continuous idle waiting by default and drops its partial result. To change the 10-minute cap, set [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without one. The run waits for background work such as background commands, subagents and workflows, Monitor watches, and pending `/loop` wakeups: @@ -67,22 +55,14 @@ When stderr is a terminal and the run has waited five seconds, Claude Code prints a line to stderr that starts with `Waiting for background work to finish` and names the work. With `json` or `stream-json` output, the line prints only when stdout isn’t a terminal, so the JSON your script reads never carries it. If the run reaches its [`--max-budget-usd`](</docs/en/cli-reference#cli-flags>) cap, Claude Code stops the remaining background work instead of waiting. When background work starts another turn, the run prints each turn’s result with the default `text` output and the last turn’s result with `json` output. Before v2.1.295, the run printed only the last turn’s result with `text` output too. -#### - -​ - -MCP work when a non-interactive run ends +#### MCP work when a non-interactive run ends A `claude -p` run doesn’t wait for MCP work in the background: * **[MCP tasks](</docs/en/mcp#mcp-tasks-that-run-on-the-server>)** : on a remote server the job goes on. To follow it again, [resume that session](</docs/en/mcp#exit-clear-or-resume-while-an-mcp-task-runs>), not as a one-shot `claude -p "<prompt>"` run. * **MCP calls that[automatic backgrounding](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>) moved**: the call’s result is lost. -### - -​ - -Stop a run with SIGTERM +### Stop a run with SIGTERM If you stop a `claude -p` run with SIGTERM, for example with `kill` or from a process supervisor, Claude Code exits with code 143. Claude Code leaves the turn that was in progress unfinished and records no result for it. To end the turn instead, send SIGINT, or call the Agent SDK’s `interrupt()`, before you stop the process. On SIGTERM, Claude Code terminates the process tree of any Bash command that is still running. Claude Code then runs [`SessionEnd` hooks](</docs/en/hooks#sessionend>) and exits. While exiting, Claude Code starts no new tool call, sends no new model request, and runs no hook other than `SessionEnd`. If the run was in the middle of a command or waiting on a permission prompt when the signal arrived, Claude Code handles that step as follows: @@ -91,27 +71,15 @@ When you resume the session, Claude Code leaves the interrupted turn as it is, and your next prompt drives the conversation. To have Claude Code continue the interrupted turn on resume instead, set [`CLAUDE_CODE_RESUME_INTERRUPTED_TURN=1`](</docs/en/env-vars>). -### - -​ - -If the working directory is deleted +### If the working directory is deleted If the working directory of a `claude -p` or Agent SDK session is deleted mid-session, the session keeps running. When a turn starts while the directory is missing, Claude Code emits a [warning message](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) in `stream-json` output, and shell commands fail until the directory exists again. -## - -​ - -Examples +## Examples These examples highlight common CLI patterns. Where a command names a file such as `auth.py` or `build-error.txt`, substitute a file from your own project. In CI or other scripted environments, add `--bare` so Claude Code starts without loading the host’s hooks, plugins, auto memory, or `CLAUDE.md`. -### - -​ - -Pipe data through Claude +### Pipe data through Claude Non-interactive mode reads stdin, so you can pipe data in and redirect the response out like any other command-line tool. This example pipes a build log into Claude and writes the explanation to a file: @@ -123,11 +91,7 @@ If Claude Code can’t read stdin, for example because the process that started it disconnected its end, Claude Code prints a warning to stderr and continues with the prompt from the command line. -### - -​ - -Add Claude to a build script +### Add Claude to a build script You can wrap a non-interactive call in a script to use Claude as a project-specific linter or reviewer. This `package.json` script pipes the diff against `main` into Claude and asks it to report typos. Piping the diff means Claude doesn’t need Bash permission to read it, and the escaped double quotes keep the script portable to Windows: @@ -139,11 +103,7 @@ Run it with `npm run lint:claude`. -### - -​ - -Get structured output +### Get structured output Use `--output-format` to control how responses are returned: @@ -174,11 +134,7 @@ --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \ | jq '.structured_output' -### - -​ - -Stream responses +### Stream responses Use `--output-format stream-json` with `--verbose` and `--include-partial-messages` to receive tokens as they’re generated. Each line is a JSON object representing an event: @@ -191,11 +147,7 @@ For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](</docs/en/agent-sdk/streaming-output>) in the Agent SDK documentation. -#### - -​ - -Follow subagent messages +#### Follow subagent messages Messages from [subagents](</docs/en/sub-agents>) and from skills that [run in a subagent](</docs/en/skills#run-skills-in-a-subagent>) appear in the stream as `assistant` and `user` messages. Their `parent_tool_use_id` field says which run each one belongs to. Messages from the main conversation carry `null` in that field. The first message from a forked skill, or from a subagent running in the [foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>), is a `user` message carrying the prompt or skill content that drives it. After that first message, Claude Code emits: @@ -216,11 +168,7 @@ * **Messages of subagents that a forked skill spawns, and of forked skills started inside a subagent or another forked skill** : v2.1.275 or later * **Messages of a forked skill you start by passing`/<skill-name>` as the prompt**: v2.1.287 or later -#### - -​ - -Handle API retries +#### Handle API retries When an API request fails with a retryable error, Claude Code emits a `system/api_retry` event before retrying. On v2.1.246 or later, when a `401` or `403` rejects an [`apiKeyHelper`](</docs/en/settings-reference#apikeyhelper>) credential, Claude Code makes the first two retries quietly with no event, then emits the event as usual from the third consecutive retry onward. The quiet retries still count toward `attempt`. You can use the event to show retry progress in your own interface. @@ -237,11 +185,7 @@ `uuid`| string| unique event identifier `session_id`| string| session the event belongs to -#### - -​ - -Read session metadata +#### Read session metadata The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless startup events precede it: @@ -250,11 +194,7 @@ The event also carries an optional `capabilities` array of strings naming the protocol behaviors this Claude Code version implements, such as `interrupt_receipt_v1` or `interrupt_cancel_queued_v1`. Check it to feature-detect instead of comparing version strings, and ignore values you don’t recognize. See [`SDKSystemMessage`](</docs/en/agent-sdk/typescript#sdksystemmessage>) for the capability list. -#### - -​ - -Fail CI when a plugin or MCP server doesn’t load +#### Fail CI when a plugin or MCP server doesn’t load Use the plugin fields in the `system/init` event to catch a plugin that didn’t load: @@ -272,11 +212,7 @@ When you run the command yourself in a terminal, Claude Code also prints a startup warning to stderr, such as `Warning: 1 MCP server skipped due to invalid config:`, followed by the reason for each skipped entry. When you redirect stderr, or when a program such as a CI runner or an SDK host captures it, Claude Code prints no warning. It reports the skipped entries only in the `mcp_server_errors` field. -#### - -​ - -Track plugin installs +#### Track plugin installs When [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set, Claude Code emits `system/plugin_install` events while marketplace plugins install before the first turn. Use these to surface install progress in your own UI. @@ -290,11 +226,7 @@ `uuid`| string| unique event identifier `session_id`| string| session the event belongs to -### - -​ - -Auto-approve tools +### Auto-approve tools Use `--allowedTools` to let Claude use certain tools without prompting. Listing `Read` and `Edit` lets Claude read and edit files without asking for permission, apart from reads from [network paths](</docs/en/permissions#network-paths>). Listing `Bash` does the same for shell commands, except in a run that starts in [auto mode](</docs/en/permission-modes#how-auto-mode-evaluates-actions>), where Claude Code drops a bare `Bash` entry as a broad allow rule and auto mode evaluates each command instead. This example runs a test suite and fixes failures with those three tools listed: @@ -311,11 +243,7 @@ claude -p "Apply the lint fixes" --permission-mode acceptEdits -### - -​ - -Turn off permission prompts in unattended runs +### Turn off permission prompts in unattended runs Pass `--permission-prompts none` when nobody is available to answer permission prompts, for example in a scheduled job. The flag matters most when your run has a permission host: an Agent SDK app with a [`canUseTool` callback](</docs/en/agent-sdk/user-input>), or an MCP tool you pass with [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>). Without the flag, your run waits for that host to answer each permission request. With the flag, your run doesn’t consult the host or wait on it. Anything that would prompt is denied unless a `PermissionRequest` hook allows it, Claude is told that nobody can approve the request and not to retry it, and the run continues. In a `-p` run with no host, these requests are denied either way, and the flag also tells Claude not to retry them. Permission rules, [`PermissionRequest` hooks](</docs/en/hooks#permissionrequest>), and the permission mode you set still decide every call first; Claude Code denies only the requests that nothing else resolves. This example runs an unattended task in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). The classifier reviews each action as usual, and Claude Code denies anything that would have fallen back to a prompt: @@ -325,11 +253,7 @@ The `--permission-prompts` flag requires Claude Code v2.1.259 or later. Earlier versions reject it with an unknown-option error. -### - -​ - -Create a commit +### Create a commit This example reviews staged changes and creates a commit with an appropriate message: @@ -346,11 +270,7 @@ * To change a setting, pass `key=value` to `/config`, for example `/config thinking=false`. * `/output-style <style>` switches [output styles](</docs/en/output-styles>) and `/output-style` alone lists them. Requires Claude Code v2.1.269 or later. -### - -​ - -Customize the system prompt +### Customize the system prompt Use `--append-system-prompt` to add instructions while keeping Claude Code’s default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities. Save it as a shell script, for example `review.sh`: @@ -360,11 +280,7 @@ In the script, `"$1"` stands for the first argument you pass on the command line. Run `bash review.sh 123` and the shell replaces `"$1"` with `123`, so the script fetches the diff for PR 123. Claude Code prints the review as JSON, with the text in the `result` field. See [system prompt flags](</docs/en/cli-reference#system-prompt-flags>) for more options including `--system-prompt` to fully replace the default prompt. If you replace it, the run also starts without the [git status snapshot](</docs/en/settings-reference#includegitinstructions>). -### - -​ - -Continue conversations +### Continue conversations Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. On Claude Code v2.1.257 or later, when you pass `--continue`, Claude Code opens a [background session](</docs/en/sessions#where-the-session-picker-looks>) that has finished, but not one that is still running. This example runs a review, then sends follow-up prompts: @@ -382,11 +298,7 @@ You can run the two commands from different directories: Claude Code [finds the session by its ID](</docs/en/sessions#where-the-session-picker-looks>) in any project on this machine. In place of the session ID, you can pass `--resume` the absolute path to a session’s `.jsonl` [transcript file](</docs/en/sessions#where-transcripts-are-stored>), and Claude Code continues the conversation stored in that file. -## - -​ - -Next steps +## Next steps * [Agent SDK quickstart](</docs/en/agent-sdk/quickstart>): build your first agent with Python or TypeScript * [CLI reference](</docs/en/cli-reference>): all CLI flags and options
modified
--- a/headless.md +++ b/headless.md @@ -32,7 +32,7 @@ claude --bare -p "Summarize README.md" --allowedTools "Read" -In bare mode, Claude Code never reads OAuth credentials or the system keychain. For the Anthropic API, set `ANTHROPIC_API_KEY` in the environment, with a key created in the [Claude Console](<https://platform.claude.com>), or supply an `apiKeyHelper` in the `--settings` JSON. Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry continue to read their own provider credentials as usual. In bare mode Claude has access to the Bash, file read, and file edit tools. Pass any context you need with a flag: +In bare mode, Claude Code never reads OAuth credentials or the system keychain. For the Anthropic API, set `ANTHROPIC_API_KEY` in the environment, with a key created in the [Claude Console](<https://platform.claude.com>), or supply an `apiKeyHelper` in the `--settings` JSON. Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry continue to read their own provider credentials as usual. In bare mode Claude has access to the Bash, file read, and file edit tools. Pass the context you need with a flag: To load| Use ---|--- @@ -42,7 +42,7 @@ [Custom agents](</docs/en/sub-agents#choose-the-subagent-scope>)| `--agents <file-or-json>` A plugin| `--plugin-dir <path>`, `--plugin-url <url>` -Bare mode also limits what happens while the session runs: +Hooks still don’t run in bare mode when you pass them with `--settings`, or in the [`hooks/hooks.json`](</docs/en/plugins/components#hooks>) or [`hooks` manifest key](</docs/en/plugins/manifest-reference#hooks>) of a plugin you load with a flag. Don’t use bare mode for a run that needs them. Bare mode also limits what happens while the session runs: * **MCP servers** : only servers supplied on the command line connect, for example with `--mcp-config`. In an interactive session, Claude Code also skips the automatic IDE connection unless you pass `--ide`. * **System reminders** : Claude gets your prompts and the tool results without the [system reminders](</docs/en/glossary#system-reminder>) Claude Code would add alongside them. For example, Claude isn’t told when a file it read earlier changes on disk, and it doesn’t get the list of available skills, including skills from an `--add-dir` folder.
modified
--- a/headless.md +++ b/headless.md @@ -212,7 +212,6 @@ For a forked skill started from the prompt, match `parent_tool_use_id` on the `forked-command-` prefix, because the name after it can differ from the one you typed. If some of these messages are missing from your stream, check your Claude Code version against these minimums: - * **Forwarding at every nesting depth** : v2.1.219 or later * **A forked skill that Claude starts with the Skill tool from the main conversation** : v2.1.86 or later for its `tool_use` and `tool_result` blocks, and v2.1.265 or later for its first `user` message and its text and thinking blocks * **Messages of subagents that a forked skill spawns, and of forked skills started inside a subagent or another forked skill** : v2.1.275 or later * **Messages of a forked skill you start by passing`/<skill-name>` as the prompt**: v2.1.287 or later @@ -269,9 +268,9 @@ Field| Type| Description ---|---|--- `mcp_servers`| array| MCP servers in the session, each with `name` and `status` -`mcp_server_errors`| array| `--mcp-config` entries skipped by config validation, each with `name`, `type`, and `message`. `type` is a skip category such as `unknown_type`, `url_missing_type`, `invalid_config`, or `reserved_name`; treat values you don’t recognize as a generic skip. Affected servers are absent from `mcp_servers`. The key is omitted when there are no errors, so a CI gate can fail on a non-empty array. Requires Claude Code v2.1.219 or later - -When you run the command by hand in a terminal, Claude Code also prints a startup warning to stderr, such as `Warning: 1 MCP server skipped due to invalid config:`, followed by the reason for each skipped entry. When you redirect stderr, or when a program such as a CI runner or an SDK host captures it, Claude Code prints no warning and reports the skipped entries only in the `mcp_server_errors` field. The warning requires Claude Code v2.1.219 or later. +`mcp_server_errors`| array| `--mcp-config` entries skipped by config validation, each with `name`, `type`, and `message`. `type` is a skip category such as `unknown_type`, `url_missing_type`, `invalid_config`, or `reserved_name`; treat values you don’t recognize as a generic skip. Affected servers are absent from `mcp_servers`. The key is omitted when there are no errors, so a CI gate can fail on a non-empty array + +When you run the command yourself in a terminal, Claude Code also prints a startup warning to stderr, such as `Warning: 1 MCP server skipped due to invalid config:`, followed by the reason for each skipped entry. When you redirect stderr, or when a program such as a CI runner or an SDK host captures it, Claude Code prints no warning. It reports the skipped entries only in the `mcp_server_errors` field. ####
modified
--- a/headless.md +++ b/headless.md @@ -46,7 +46,7 @@ * **MCP servers** : only servers supplied on the command line connect, for example with `--mcp-config`. In an interactive session, Claude Code also skips the automatic IDE connection unless you pass `--ide`. * **System reminders** : Claude gets your prompts and the tool results without the [system reminders](</docs/en/glossary#system-reminder>) Claude Code would add alongside them. For example, Claude isn’t told when a file it read earlier changes on disk, and it doesn’t get the list of available skills, including skills from an `--add-dir` folder. - * **Background tasks** : none run. A command that reaches its [timeout](</docs/en/tools-reference#timeout-and-output-limits>) stops instead of [moving to the background](</docs/en/tools-reference#background-commands>). + * **Background tasks** : Claude can’t run background commands or background subagents, and the other features that [`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`](</docs/en/env-vars>) turns off are off too. A command that reaches its [timeout](</docs/en/tools-reference#timeout-and-output-limits>) stops instead of [moving to the background](</docs/en/tools-reference#background-commands>). Before v2.1.286, these limits held only partly: an interactive `--bare` session connected the MCP servers that a normal session would, every `--bare` session sent system reminders, and background tasks stayed available. @@ -66,6 +66,17 @@ * **Pending wakeups** : in a run whose prompt you passed as text rather than with `--input-format stream-json`, when Claude has scheduled a [self-paced `/loop` wakeup](</docs/en/scheduled-tasks#let-claude-choose-the-interval>), the run waits for each wakeup to fire and runs its iteration until the [loop ends](</docs/en/scheduled-tasks#stop-a-loop>), even past the 10-minute cap. When stderr is a terminal and the run has waited five seconds, Claude Code prints a line to stderr that starts with `Waiting for background work to finish` and names the work. With `json` or `stream-json` output, the line prints only when stdout isn’t a terminal, so the JSON your script reads never carries it. If the run reaches its [`--max-budget-usd`](</docs/en/cli-reference#cli-flags>) cap, Claude Code stops the remaining background work instead of waiting. When background work starts another turn, the run prints each turn’s result with the default `text` output and the last turn’s result with `json` output. Before v2.1.295, the run printed only the last turn’s result with `text` output too. + +#### + +​ + +MCP work when a non-interactive run ends + +A `claude -p` run doesn’t wait for MCP work in the background: + + * **[MCP tasks](</docs/en/mcp#mcp-tasks-that-run-on-the-server>)** : on a remote server the job goes on. To follow it again, [resume that session](</docs/en/mcp#exit-clear-or-resume-while-an-mcp-task-runs>), not as a one-shot `claude -p "<prompt>"` run. + * **MCP calls that[automatic backgrounding](</docs/en/mcp#automatic-backgrounding-of-long-tool-calls>) moved**: the call’s result is lost. ###
modified
--- a/headless.md +++ b/headless.md @@ -150,7 +150,7 @@ --output-format json \ --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' -If the value isn’t a valid JSON Schema, `claude` exits with `Error: --json-schema is not a valid JSON Schema` followed by the validator’s diagnostic. Claude Code accepts schemas that use the `format` keyword, such as `"format": "email"`, but treats `format` as an annotation and doesn’t enforce it. +If the value isn’t a valid JSON Schema, `claude` exits with `Error: --json-schema is not a valid JSON Schema` followed by the validator’s diagnostic. Claude Code accepts schemas that use the `format` keyword, such as `"format": "email"`, but treats `format` as an annotation and doesn’t enforce it. If a run ends without valid structured output, for example because Claude declined the request, the response has no `structured_output` field. Before your script uses `structured_output`, check that the field is present. Use a tool like [jq](<https://jqlang.org/>) to parse the response and extract specific fields:
modified
--- a/headless.md +++ b/headless.md @@ -110,7 +110,7 @@ Piped stdin is capped at 10MB. If you exceed the cap, Claude Code exits with a clear error and a non-zero status. To work with larger inputs, write the content to a file and reference the file path in your prompt instead of piping it. -If Claude Code can’t read stdin, for example because the process that started it disconnected its end, Claude Code prints a warning to stderr and continues with the prompt from the command line. Before v2.1.211, an unreadable stdin on Windows crashed the session or made it exit silently with no output. +If Claude Code can’t read stdin, for example because the process that started it disconnected its end, Claude Code prints a warning to stderr and continues with the prompt from the command line. ### @@ -173,7 +173,7 @@ claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages -The last line of the stream is a `result` message with the final response text, cost, and session metadata. If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. Before v2.1.214 the exit wait was capped at about two seconds, which could cut off the end of a large response. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display only the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: +The last line of the stream is a `result` message with the final response text, cost, and session metadata. If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display only the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \ jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text' @@ -201,7 +201,6 @@ For a forked skill started from the prompt, match `parent_tool_use_id` on the `forked-command-` prefix, because the name after it can differ from the one you typed. If some of these messages are missing from your stream, check your Claude Code version against these minimums: - * **`--forward-subagent-text` and `CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`**: v2.1.211 or later * **Forwarding at every nesting depth** : v2.1.219 or later * **A forked skill that Claude starts with the Skill tool from the main conversation** : v2.1.86 or later for its `tool_use` and `tool_result` blocks, and v2.1.265 or later for its first `user` message and its text and thinking blocks * **Messages of subagents that a forked skill spawns, and of forked skills started inside a subagent or another forked skill** : v2.1.275 or later @@ -292,10 +291,10 @@ claude -p "Run the test suite and fix any failures" \ --allowedTools "Bash,Read,Edit" -To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). A run where nothing sets a permission mode takes the [built-in starting permission mode](</docs/en/permission-modes#which-mode-a-session-starts-in>), which can be `auto`, so pass the one you want: +Calls to tools you didn’t list run if they need no approval. In a [Manual mode](</docs/en/permission-modes#available-modes>) `claude -p` run, a call that needs approval is denied unless something approves it, such as a [`PermissionRequest` hook](</docs/en/hooks#permissionrequest>) or a [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>). With Claude Code v2.1.302 or later, `claude -p` runs start in Manual mode when [nothing sets a permission mode](</docs/en/permission-modes#which-mode-a-non-interactive-run-starts-in>). To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>) with `--permission-mode`, such as `auto`, `dontAsk`, or `acceptEdits`: * **`auto`** : pass `--permission-mode auto` to have a classifier review most actions instead of you - * **`dontAsk`** : Claude Code denies every call that would otherwise prompt, which is useful for locked-down CI runs. Actions that need no approval in Manual mode still run, such as file reads in your working directories and the [read-only command set](</docs/en/permissions#read-only-commands>), and so do actions your `--allowedTools` entries or `permissions.allow` rules cover. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>), and [reads from network paths](</docs/en/permissions#network-paths>) are denied even when an allow rule matches + * **`dontAsk`** : Claude Code denies every call that would otherwise prompt, which is useful for locked-down CI runs, though a [mod](</docs/en/plugins/mods/overview>) you installed can still approve some of those calls. To check which calls a mod can approve, see [Extend permissions with hooks](</docs/en/permissions#precedence-among-rules-hooks-and-mods>). Actions that need no approval in Manual mode still run, such as file reads in your working directories and the [read-only command set](</docs/en/permissions#read-only-commands>). Actions covered by your `--allowedTools` entries or `permissions.allow` rules also run. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>), and [reads from network paths](</docs/en/permissions#network-paths>) are denied even when an allow rule matches * **`acceptEdits`** : Claude writes files without prompting, and Claude Code auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. The [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>) still apply. Apart from the read-only command set, other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule. See [what `acceptEdits` auto-approves](</docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode>) for the full list This example applies lint fixes with `acceptEdits` as the baseline:
modified
--- a/headless.md +++ b/headless.md @@ -28,7 +28,7 @@ Start faster with bare mode -Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, [subagents](</docs/en/sub-agents>), installed plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. A directory you name with `--add-dir` is a partial exception: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](</docs/en/skills#skills-from-additional-directories>) covers what does and doesn’t load. Without `--bare`, a `-p` session runs the hooks in a project’s `.claude/settings.json` and connects the servers in its `.mcp.json`, even in a folder you’ve never trusted. A `-p` session shows no workspace trust dialog and no per-server approval prompt. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: +Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, [subagents](</docs/en/sub-agents>), installed plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` discovers and loads them as an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. A directory you name with `--add-dir` is a partial exception: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](</docs/en/skills#skills-from-additional-directories>) covers what does and doesn’t load. Without `--bare`, a `-p` session runs the hooks in a project’s `.claude/settings.json` and connects the servers in its `.mcp.json`, even in a folder you’ve never trusted. A `-p` session shows no workspace trust dialog and no per-server approval prompt. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: claude --bare -p "Summarize README.md" --allowedTools "Read" @@ -349,7 +349,7 @@ --append-system-prompt "You are a security engineer. Review for vulnerabilities." \ --output-format json -In the script, `"$1"` stands for the first argument you pass on the command line. Run `bash review.sh 123` and the shell replaces `"$1"` with `123`, so the script fetches the diff for PR 123. Claude Code prints the review as JSON, with the text in the `result` field. See [system prompt flags](</docs/en/cli-reference#system-prompt-flags>) for more options including `--system-prompt` to fully replace the default prompt. +In the script, `"$1"` stands for the first argument you pass on the command line. Run `bash review.sh 123` and the shell replaces `"$1"` with `123`, so the script fetches the diff for PR 123. Claude Code prints the review as JSON, with the text in the `result` field. See [system prompt flags](</docs/en/cli-reference#system-prompt-flags>) for more options including `--system-prompt` to fully replace the default prompt. If you replace it, the run also starts without the [git status snapshot](</docs/en/settings-reference#includegitinstructions>). ###
modified
--- a/headless.md +++ b/headless.md @@ -150,7 +150,7 @@ --output-format json \ --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' -If the value isn’t a valid JSON Schema, `claude` exits with `Error: --json-schema is not a valid JSON Schema` followed by the validator’s diagnostic. Claude Code accepts schemas that use the `format` keyword, such as `"format": "email"`, but treats `format` as an annotation and doesn’t enforce it. Before v2.1.205, Claude Code silently ignored an invalid schema and returned unstructured text, and treated any schema containing `format` as invalid. +If the value isn’t a valid JSON Schema, `claude` exits with `Error: --json-schema is not a valid JSON Schema` followed by the validator’s diagnostic. Claude Code accepts schemas that use the `format` keyword, such as `"format": "email"`, but treats `format` as an annotation and doesn’t enforce it. Use a tool like [jq](<https://jqlang.org/>) to parse the response and extract specific fields: @@ -237,9 +237,9 @@ The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless startup events precede it: * `plugin_install` events, when [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set. - * [`hook_started`, `hook_progress`, and `hook_response` events](</docs/en/agent-sdk/typescript#sdkhookstartedmessage>), while a configured [`SessionStart`](</docs/en/hooks#sessionstart>) or [`Setup`](</docs/en/hooks#setup>) hook runs. These stream as the hook produces them. Claude Code v2.1.169 through v2.1.203 delivered them in one batch after the hook completed, still ahead of `system/init`; v2.1.204 restored live delivery. - -The event also carries an optional `capabilities` array of strings naming the protocol behaviors this Claude Code version implements, such as `interrupt_receipt_v1` or `interrupt_cancel_queued_v1`. Check it to feature-detect instead of comparing version strings, and ignore values you don’t recognize. The field requires Claude Code v2.1.205 or later and is absent from earlier versions. See [`SDKSystemMessage`](</docs/en/agent-sdk/typescript#sdksystemmessage>) for the capability list. + * [`hook_started`, `hook_progress`, and `hook_response` events](</docs/en/agent-sdk/typescript#sdkhookstartedmessage>), while a configured [`SessionStart`](</docs/en/hooks#sessionstart>) or [`Setup`](</docs/en/hooks#setup>) hook runs. These stream as the hook produces them. + +The event also carries an optional `capabilities` array of strings naming the protocol behaviors this Claude Code version implements, such as `interrupt_receipt_v1` or `interrupt_cancel_queued_v1`. Check it to feature-detect instead of comparing version strings, and ignore values you don’t recognize. See [`SDKSystemMessage`](</docs/en/agent-sdk/typescript#sdksystemmessage>) for the capability list. #### @@ -333,7 +333,7 @@ * User-invoked [skills](</docs/en/skills>) and custom commands work. Include `/skill-name` in the prompt string and Claude Code expands it before running. * Built-in commands that only run in the terminal interface, such as `/login`, aren’t available. - * `/model`, `/effort`, `/fast`, `/color`, and `/rename` accept the value as an argument, for example `/model sonnet`, and `/mcp` with no argument prints a text summary of server status. These forms require Claude Code v2.1.205 or later and follow each command’s [availability notes](</docs/en/commands#all-commands>). + * `/model`, `/effort`, `/fast`, `/color`, and `/rename` accept the value as an argument, for example `/model sonnet`, and `/mcp` with no argument prints a text summary of server status. These forms follow each command’s [availability notes](</docs/en/commands#all-commands>). * To change a setting, pass `key=value` to `/config`, for example `/config thinking=false`. * `/output-style <style>` switches [output styles](</docs/en/output-styles>) and `/output-style` alone lists them. Requires Claude Code v2.1.269 or later.
modified
--- a/headless.md +++ b/headless.md @@ -287,7 +287,7 @@ Auto-approve tools -Use `--allowedTools` to let Claude use certain tools without prompting. Listing `Read` and `Edit` lets Claude read and edit files without asking for permission. Listing `Bash` does the same for shell commands, except in a run that starts in [auto mode](</docs/en/permission-modes#how-auto-mode-evaluates-actions>), where Claude Code drops a bare `Bash` entry as a broad allow rule and auto mode evaluates each command instead. This example runs a test suite and fixes failures with those three tools listed: +Use `--allowedTools` to let Claude use certain tools without prompting. Listing `Read` and `Edit` lets Claude read and edit files without asking for permission, apart from reads from [network paths](</docs/en/permissions#network-paths>). Listing `Bash` does the same for shell commands, except in a run that starts in [auto mode](</docs/en/permission-modes#how-auto-mode-evaluates-actions>), where Claude Code drops a bare `Bash` entry as a broad allow rule and auto mode evaluates each command instead. This example runs a test suite and fixes failures with those three tools listed: claude -p "Run the test suite and fix any failures" \ --allowedTools "Bash,Read,Edit" @@ -295,7 +295,7 @@ To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). A run where nothing sets a permission mode takes the [built-in starting permission mode](</docs/en/permission-modes#which-mode-a-session-starts-in>), which can be `auto`, so pass the one you want: * **`auto`** : pass `--permission-mode auto` to have a classifier review most actions instead of you - * **`dontAsk`** : Claude Code denies every call that would otherwise prompt, which is useful for locked-down CI runs. Actions that need no approval in Manual mode still run, such as file reads in your working directories and the [read-only command set](</docs/en/permissions#read-only-commands>), and so do actions your `--allowedTools` entries or `permissions.allow` rules cover. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) are denied even when an allow rule matches + * **`dontAsk`** : Claude Code denies every call that would otherwise prompt, which is useful for locked-down CI runs. Actions that need no approval in Manual mode still run, such as file reads in your working directories and the [read-only command set](</docs/en/permissions#read-only-commands>), and so do actions your `--allowedTools` entries or `permissions.allow` rules cover. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>), and [reads from network paths](</docs/en/permissions#network-paths>) are denied even when an allow rule matches * **`acceptEdits`** : Claude writes files without prompting, and Claude Code auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. The [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>) still apply. Apart from the read-only command set, other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule. See [what `acceptEdits` auto-approves](</docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode>) for the full list This example applies lint fixes with `acceptEdits` as the baseline: @@ -357,7 +357,7 @@ Continue conversations -Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. On Claude Code v2.1.257 or later, when you pass `--continue`, Claude Code opens a [background session](</docs/en/sessions#resume-a-session>) that has finished, but not one that is still running. This example runs a review, then sends follow-up prompts: +Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. On Claude Code v2.1.257 or later, when you pass `--continue`, Claude Code opens a [background session](</docs/en/sessions#where-the-session-picker-looks>) that has finished, but not one that is still running. This example runs a review, then sends follow-up prompts: # First request claude -p "Review this codebase for performance issues" @@ -371,7 +371,7 @@ session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id') claude -p "Continue that review" --resume "$session_id" -You can run the two commands from different directories: Claude Code [finds the session by its ID](</docs/en/sessions#resume-a-session>) in any project on this machine. Before v2.1.223, Claude Code looked for the ID only in the current project directory and its git worktrees, so you had to run both commands from the same directory. In place of the session ID, you can pass `--resume` the absolute path to a session’s `.jsonl` [transcript file](</docs/en/sessions#where-transcripts-are-stored>), and Claude Code continues the conversation stored in that file. +You can run the two commands from different directories: Claude Code [finds the session by its ID](</docs/en/sessions#where-the-session-picker-looks>) in any project on this machine. In place of the session ID, you can pass `--resume` the absolute path to a session’s `.jsonl` [transcript file](</docs/en/sessions#where-transcripts-are-stored>), and Claude Code continues the conversation stored in that file. ##
modified
--- a/headless.md +++ b/headless.md @@ -65,7 +65,7 @@ * **[Monitor](</docs/en/tools-reference#monitor-tool>) watches**: the run waits until the watch times out or the 10-minute cap ends the wait, whichever comes first. While it waits, Claude keeps responding to what the watch reports. By default, a watch times out five minutes after Claude starts it. * **Pending wakeups** : in a run whose prompt you passed as text rather than with `--input-format stream-json`, when Claude has scheduled a [self-paced `/loop` wakeup](</docs/en/scheduled-tasks#let-claude-choose-the-interval>), the run waits for each wakeup to fire and runs its iteration until the [loop ends](</docs/en/scheduled-tasks#stop-a-loop>), even past the 10-minute cap. -If the run reaches its [`--max-budget-usd`](</docs/en/cli-reference#cli-flags>) cap, Claude Code stops the remaining background work instead of waiting. When background work starts another turn, the run prints each turn’s result with the default `text` output and the last turn’s result with `json` output. Before v2.1.295, the run printed only the last turn’s result with `text` output too. +When stderr is a terminal and the run has waited five seconds, Claude Code prints a line to stderr that starts with `Waiting for background work to finish` and names the work. With `json` or `stream-json` output, the line prints only when stdout isn’t a terminal, so the JSON your script reads never carries it. If the run reaches its [`--max-budget-usd`](</docs/en/cli-reference#cli-flags>) cap, Claude Code stops the remaining background work instead of waiting. When background work starts another turn, the run prints each turn’s result with the default `text` output and the last turn’s result with `json` output. Before v2.1.295, the run printed only the last turn’s result with `text` output too. ### @@ -254,7 +254,7 @@ `plugins`| array| plugins that loaded successfully, each with `name` and `path` `plugin_errors`| array| plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. A plugin that didn’t load is absent from `plugins`. The key is omitted when there are no errors -When a `--plugin-dir` directory or archive itself fails to load, its `plugin_errors` entry includes the resolved absolute path as `path`. Use it to tell which of several `--plugin-dir` values failed. The `path` field requires Claude Code v2.1.283 or later. Use the MCP server fields the same way. When you pass [`--mcp-config`](</docs/en/cli-reference#cli-flags>) with `-p`, Claude Code waits for still-pending servers before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default. A remote server with a [cached tool list](</docs/en/agent-sdk/mcp#connection-timing>) skips the wait, shows `pending` in `system/init`, and connects on its first tool call. The wait requires Claude Code v2.1.221 or later. Claude Code validates each `--mcp-config` entry at startup and skips entries that fail validation, for example a `url` entry with no `type`. The run continues and exits cleanly, so check these fields to catch a server that never loaded: +When a `--plugin-dir` directory or archive itself fails to load, its `plugin_errors` entry includes the resolved absolute path as `path`. Use it to tell which of several `--plugin-dir` values failed. The `path` field requires Claude Code v2.1.283 or later. Use the MCP server fields the same way. When you pass [`--mcp-config`](</docs/en/cli-reference#cli-flags>) with `-p`, Claude Code waits for still-pending servers before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default. A remote server with a [cached tool list](</docs/en/agent-sdk/mcp#connection-timing>) skips the wait, shows `pending` in `system/init`, and connects on its first tool call. In a [self-hosted environment](</docs/en/self-hosted-environments-configuration#connection-timing>), a shorter wait applies instead. The wait requires Claude Code v2.1.221 or later. Claude Code validates each `--mcp-config` entry at startup and skips entries that fail validation, for example a `url` entry with no `type`. The run continues and exits cleanly, so check these fields to catch a server that never loaded: Field| Type| Description ---|---|---
modified
--- a/headless.md +++ b/headless.md @@ -58,7 +58,14 @@ Background tasks at exit -If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that shell is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. If Claude starts a background [subagent](</docs/en/sub-agents>) or workflow, `claude -p` instead stays open until that work completes, because its result is part of the final output. By default the wait ends after 10 minutes of continuous idle waiting, so a stuck subagent or workflow can’t hold the process open indefinitely. At that point Claude Code stops whatever is still running and drops its partial result. To change the limit, set [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without one. If Claude starts a [Monitor](</docs/en/tools-reference#monitor-tool>) watch during a `claude -p` run, Claude Code waits for the watch until it times out or the ten-minute cap ends the wait, whichever comes first. While it waits, Claude keeps responding to what the watch reports. By default, a watch times out five minutes after Claude starts it. +After Claude finishes its turn and stdin has closed, a `claude -p` run can stay open to wait for background work that Claude started. Unless a background command that the main conversation started is still running, Claude Code stops whatever is still running after 10 minutes of continuous idle waiting by default and drops its partial result. To change the 10-minute cap, set [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without one. The run waits for background work such as background commands, subagents and workflows, Monitor watches, and pending `/loop` wakeups: + + * **[Background commands](</docs/en/tools-reference#background-commands>)** : for a command that the main conversation started, for example a dev server or a watch build, the run waits until the command exits or reaches its [time limit](</docs/en/tools-reference#time-limit-for-background-commands>). Claude then takes one more turn with the outcome. While the command runs, the 10-minute cap doesn’t end the wait. + * **Background[subagents](</docs/en/sub-agents>) and workflows**: the run stays open until that work completes, because its result is part of the final output. + * **[Monitor](</docs/en/tools-reference#monitor-tool>) watches**: the run waits until the watch times out or the 10-minute cap ends the wait, whichever comes first. While it waits, Claude keeps responding to what the watch reports. By default, a watch times out five minutes after Claude starts it. + * **Pending wakeups** : in a run whose prompt you passed as text rather than with `--input-format stream-json`, when Claude has scheduled a [self-paced `/loop` wakeup](</docs/en/scheduled-tasks#let-claude-choose-the-interval>), the run waits for each wakeup to fire and runs its iteration until the [loop ends](</docs/en/scheduled-tasks#stop-a-loop>), even past the 10-minute cap. + +If the run reaches its [`--max-budget-usd`](</docs/en/cli-reference#cli-flags>) cap, Claude Code stops the remaining background work instead of waiting. When background work starts another turn, the run prints each turn’s result with the default `text` output and the last turn’s result with `json` output. Before v2.1.295, the run printed only the last turn’s result with `text` output too. ### @@ -213,10 +220,10 @@ `type`| `"system"`| message type `subtype`| `"api_retry"`| identifies this as a retry event `attempt`| integer| current attempt number, starting at 1 -`max_retries`| integer| total retries permitted for this failure’s cause, which can be fewer than the session-wide budget +`max_retries`| integer| total retries permitted for this failure’s cause `retry_delay_ms`| integer| milliseconds until the next attempt `error_status`| integer or null| HTTP status code of the failed attempt, or `null` when the attempt got no HTTP response from the API -`no_response`| object, optional| present only when the failed attempt got [no response headers in time](</docs/en/errors#no-response-from-api>). `waited_ms` is how long that attempt waited and `retry_wait_ms` is how long the retry will wait. In these events, `max_retries` reflects the one retry this cause normally gets, not the session-wide budget. Requires Claude Code v2.1.261 or later +`no_response`| object, optional| present only when the failed attempt got [no response headers in time](</docs/en/errors#no-response-from-api>). `waited_ms` is how long that attempt waited and `retry_wait_ms` is how long the retry will wait. Requires Claude Code v2.1.261 or later `error`| string| error category: `authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`, `billing_error`, `rate_limit`, `overloaded`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `cloud_credential_error`, or `unknown` `uuid`| string| unique event identifier `session_id`| string| session the event belongs to
modified
--- a/headless.md +++ b/headless.md @@ -179,12 +179,26 @@ Follow subagent messages -Messages from [subagents](</docs/en/sub-agents>) appear in the stream as `assistant` and `user` messages whose `parent_tool_use_id` field is the ID of the tool call that spawned the subagent. Messages from the main conversation carry `null` in that field. The first message from a subagent running in the [foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) is a `user` message carrying the prompt that drives it. After that first message, Claude Code emits: - - * **By default** : the subagent’s `tool_use` and `tool_result` blocks. - * **With[`--forward-subagent-text`](</docs/en/cli-reference#cli-flags>) or [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>)**: the subagent’s text and thinking blocks too, so you can reconstruct each subagent’s transcript. This requires Claude Code v2.1.211 or later. - -When you enable either option, Claude Code forwards messages from [subagents at every nesting depth](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>), whether each one was spawned with the Agent tool or started as a [forked skill](</docs/en/skills#run-skills-in-a-subagent>). Messages of subagents that a forked skill spawns, and of forked skills started inside a subagent or another forked skill, require Claude Code v2.1.275 or later. In `parent_tool_use_id`, the nested subagent’s messages carry the ID of the Agent or Skill tool call that started it, so you can rebuild the full nesting tree by following those IDs. Before v2.1.219, messages from nested subagents didn’t appear in the stream. Skills that [run in a subagent](</docs/en/skills#run-skills-in-a-subagent>) appear in the stream the same way: the forked skill’s first message is a `user` message carrying the skill content that drives the run. If you enable either option, the stream also carries the forked skill’s text and thinking blocks. Before v2.1.265, only a forked skill’s `tool_use` and `tool_result` blocks appeared in the stream. +Messages from [subagents](</docs/en/sub-agents>) and from skills that [run in a subagent](</docs/en/skills#run-skills-in-a-subagent>) appear in the stream as `assistant` and `user` messages. Their `parent_tool_use_id` field says which run each one belongs to. Messages from the main conversation carry `null` in that field. The first message from a forked skill, or from a subagent running in the [foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>), is a `user` message carrying the prompt or skill content that drives it. After that first message, Claude Code emits: + + * **By default** : the run’s `tool_use` and `tool_result` blocks. + * **With[`--forward-subagent-text`](</docs/en/cli-reference#cli-flags>) or [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>)**: the run’s text and thinking blocks too, so you can reconstruct each run’s transcript. + +When you enable either option, Claude Code forwards messages from [subagents at every nesting depth](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>), whether each one was spawned with the Agent tool or started as a forked skill. In `parent_tool_use_id`, the nested subagent’s messages carry the ID of the Agent or Skill tool call that started it, so you can rebuild the full nesting tree by following those IDs. A run that Claude starts with a tool call carries that tool call’s ID. A forked skill that you start by passing `/<skill-name>` as the prompt has no tool call, so its messages carry a `forked-command-` value instead and arrive after it finishes. Find how the run started in the first column: + +How the run starts| `parent_tool_use_id`| When its messages arrive +---|---|--- +Claude calls the Agent tool from the main conversation| The ID of that Agent `tool_use` block| While the subagent works +Claude calls the Skill tool for a forked skill from the main conversation| The ID of that Skill `tool_use` block| While the forked skill works +You pass `/<skill-name>` as the prompt| A value that starts with `forked-command-`| Together and in order after the forked skill finishes + +For a forked skill started from the prompt, match `parent_tool_use_id` on the `forked-command-` prefix, because the name after it can differ from the one you typed. If some of these messages are missing from your stream, check your Claude Code version against these minimums: + + * **`--forward-subagent-text` and `CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`**: v2.1.211 or later + * **Forwarding at every nesting depth** : v2.1.219 or later + * **A forked skill that Claude starts with the Skill tool from the main conversation** : v2.1.86 or later for its `tool_use` and `tool_result` blocks, and v2.1.265 or later for its first `user` message and its text and thinking blocks + * **Messages of subagents that a forked skill spawns, and of forked skills started inside a subagent or another forked skill** : v2.1.275 or later + * **Messages of a forked skill you start by passing`/<skill-name>` as the prompt**: v2.1.287 or later ####
modified
--- a/headless.md +++ b/headless.md @@ -166,7 +166,7 @@ claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages -The last line of the stream is a `result` message with the final response text, cost, and session metadata. If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. Before v2.1.214 the exit wait was capped at about two seconds, which could cut off the end of a large response. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: +The last line of the stream is a `result` message with the final response text, cost, and session metadata. If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. Before v2.1.214 the exit wait was capped at about two seconds, which could cut off the end of a large response. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display only the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \ jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
modified
--- a/headless.md +++ b/headless.md @@ -39,7 +39,7 @@ System prompt additions| `--append-system-prompt`, `--append-system-prompt-file` Settings| `--settings <file-or-json>` MCP servers| `--mcp-config <file-or-json>` -Custom agents| `--agents <json>` +[Custom agents](</docs/en/sub-agents#choose-the-subagent-scope>)| `--agents <file-or-json>` A plugin| `--plugin-dir <path>`, `--plugin-url <url>` Bare mode also limits what happens while the session runs:
modified
--- a/headless.md +++ b/headless.md @@ -41,6 +41,14 @@ MCP servers| `--mcp-config <file-or-json>` Custom agents| `--agents <json>` A plugin| `--plugin-dir <path>`, `--plugin-url <url>` + +Bare mode also limits what happens while the session runs: + + * **MCP servers** : only servers supplied on the command line connect, for example with `--mcp-config`. In an interactive session, Claude Code also skips the automatic IDE connection unless you pass `--ide`. + * **System reminders** : Claude gets your prompts and the tool results without the [system reminders](</docs/en/glossary#system-reminder>) Claude Code would add alongside them. For example, Claude isn’t told when a file it read earlier changes on disk, and it doesn’t get the list of available skills, including skills from an `--add-dir` folder. + * **Background tasks** : none run. A command that reaches its [timeout](</docs/en/tools-reference#timeout-and-output-limits>) stops instead of [moving to the background](</docs/en/tools-reference#background-commands>). + +Before v2.1.286, these limits held only partly: an interactive `--bare` session connected the MCP servers that a normal session would, every `--bare` session sent system reminders, and background tasks stayed available. `--bare` is the recommended mode for scripted and SDK calls, and will become the default for `-p` in a future release.
modified
--- a/headless.md +++ b/headless.md @@ -258,12 +258,12 @@ Auto-approve tools -Use `--allowedTools` to let Claude use certain tools without prompting. This example runs a test suite and fixes failures, allowing Claude to execute Bash commands and read/edit files without asking for permission: +Use `--allowedTools` to let Claude use certain tools without prompting. Listing `Read` and `Edit` lets Claude read and edit files without asking for permission. Listing `Bash` does the same for shell commands, except in a run that starts in [auto mode](</docs/en/permission-modes#how-auto-mode-evaluates-actions>), where Claude Code drops a bare `Bash` entry as a broad allow rule and auto mode evaluates each command instead. This example runs a test suite and fixes failures with those three tools listed: claude -p "Run the test suite and fix any failures" \ --allowedTools "Bash,Read,Edit" -To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). For `-p`, the [built-in starting permission mode](</docs/en/permission-modes#which-mode-a-session-starts-in>) is Manual on every plan, so pass the permission mode you want: +To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). A run where nothing sets a permission mode takes the [built-in starting permission mode](</docs/en/permission-modes#which-mode-a-session-starts-in>), which can be `auto`, so pass the one you want: * **`auto`** : pass `--permission-mode auto` to have a classifier review most actions instead of you * **`dontAsk`** : Claude Code denies every call that would otherwise prompt, which is useful for locked-down CI runs. Actions that need no approval in Manual mode still run, such as file reads in your working directories and the [read-only command set](</docs/en/permissions#read-only-commands>), and so do actions your `--allowedTools` entries or `permissions.allow` rules cover. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) are denied even when an allow rule matches
modified
--- a/headless.md +++ b/headless.md @@ -63,7 +63,15 @@ * **Running a command** : Claude Code records the command as killed in the session. * **Waiting for an answer to a permission prompt** : if you send SIGTERM to the process, Claude Code leaves the prompt unanswered. If your program closes the session through the Agent SDK, the SDK ends Claude Code’s input before sending any signal, and Claude Code cancels the prompt as soon as the input ends. -When you resume the session, Claude Code continues the turn that SIGTERM left unfinished. +When you resume the session, Claude Code leaves the interrupted turn as it is, and your next prompt drives the conversation. To have Claude Code continue the interrupted turn on resume instead, set [`CLAUDE_CODE_RESUME_INTERRUPTED_TURN=1`](</docs/en/env-vars>). + +### + +​ + +If the working directory is deleted + +If the working directory of a `claude -p` or Agent SDK session is deleted mid-session, the session keeps running. When a turn starts while the directory is missing, Claude Code emits a [warning message](</docs/en/agent-sdk/typescript#sdkinformationalmessage>) in `stream-json` output, and shell commands fail until the directory exists again. ## @@ -215,9 +223,9 @@ Field| Type| Description ---|---|--- `plugins`| array| plugins that loaded successfully, each with `name` and `path` -`plugin_errors`| array| plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. Affected plugins are demoted and absent from `plugins`. The key is omitted when there are no errors - -Use the MCP server fields the same way. When you pass [`--mcp-config`](</docs/en/cli-reference#cli-flags>) with `-p`, Claude Code waits for still-pending servers before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default. A remote server with a [cached tool list](</docs/en/agent-sdk/mcp#connection-timing>) skips the wait, shows `pending` in `system/init`, and connects on its first tool call. The wait requires Claude Code v2.1.221 or later. Claude Code validates each `--mcp-config` entry at startup and skips entries that fail validation, for example a `url` entry with no `type`. The run continues and exits cleanly, so check these fields to catch a server that never loaded: +`plugin_errors`| array| plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. A plugin that didn’t load is absent from `plugins`. The key is omitted when there are no errors + +When a `--plugin-dir` directory or archive itself fails to load, its `plugin_errors` entry includes the resolved absolute path as `path`. Use it to tell which of several `--plugin-dir` values failed. The `path` field requires Claude Code v2.1.283 or later. Use the MCP server fields the same way. When you pass [`--mcp-config`](</docs/en/cli-reference#cli-flags>) with `-p`, Claude Code waits for still-pending servers before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default. A remote server with a [cached tool list](</docs/en/agent-sdk/mcp#connection-timing>) skips the wait, shows `pending` in `system/init`, and connects on its first tool call. The wait requires Claude Code v2.1.221 or later. Claude Code validates each `--mcp-config` entry at startup and skips entries that fail validation, for example a `url` entry with no `type`. The run continues and exits cleanly, so check these fields to catch a server that never loaded: Field| Type| Description ---|---|---
modified
--- a/headless.md +++ b/headless.md @@ -28,7 +28,7 @@ Start faster with bare mode -Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, [subagents](</docs/en/sub-agents>), plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. A directory you name with `--add-dir` is a partial exception: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](</docs/en/skills#skills-from-additional-directories>) covers what does and doesn’t load. Without `--bare`, a `-p` session runs the hooks in a project’s `.claude/settings.json` and connects the servers in its `.mcp.json`, even in a folder you’ve never trusted. A `-p` session shows no workspace trust dialog and no per-server approval prompt. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: +Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, [subagents](</docs/en/sub-agents>), installed plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. A directory you name with `--add-dir` is a partial exception: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](</docs/en/skills#skills-from-additional-directories>) covers what does and doesn’t load. Without `--bare`, a `-p` session runs the hooks in a project’s `.claude/settings.json` and connects the servers in its `.mcp.json`, even in a folder you’ve never trusted. A `-p` session shows no workspace trust dialog and no per-server approval prompt. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: claude --bare -p "Summarize README.md" --allowedTools "Read"
modified
--- a/headless.md +++ b/headless.md @@ -83,7 +83,7 @@ cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt -With `--output-format json`, the response payload includes `total_cost_usd` and a per-model cost breakdown, so scripted callers can track spend per invocation without consulting the [usage dashboard](</docs/en/costs>). Both figures are [client-side estimates](</docs/en/agent-sdk/cost-tracking>) and can differ from your actual bill. +With `--output-format json`, the response payload includes `total_cost_usd` and a per-model cost breakdown, so scripted callers can track spend without consulting the [usage dashboard](</docs/en/costs>). When you continue an earlier conversation with `--continue` or `--resume`, the run reports the conversation’s whole total, [earlier runs’ spend included](</docs/en/agent-sdk/cost-tracking#accumulate-costs-across-multiple-calls>). Both figures are [client-side estimates](</docs/en/agent-sdk/cost-tracking>) and can differ from your actual bill. Piped stdin is capped at 10MB. If you exceed the cap, Claude Code exits with a clear error and a non-zero status. To work with larger inputs, write the content to a file and reference the file path in your prompt instead of piping it. @@ -168,7 +168,7 @@ * **By default** : the subagent’s `tool_use` and `tool_result` blocks. * **With[`--forward-subagent-text`](</docs/en/cli-reference#cli-flags>) or [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>)**: the subagent’s text and thinking blocks too, so you can reconstruct each subagent’s transcript. This requires Claude Code v2.1.211 or later. -When you enable either option, Claude Code forwards messages from [subagents at every nesting depth](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>): when a subagent spawns its own subagent, the nested subagent’s messages carry the ID of the Agent tool call that spawned it in `parent_tool_use_id`, so you can rebuild the full nesting tree by following those IDs. Before v2.1.219, messages from nested subagents didn’t appear in the stream. Skills that [run in a subagent](</docs/en/skills#run-skills-in-a-subagent>) appear in the stream the same way: the forked skill’s first message is a `user` message carrying the skill content that drives the run. If you enable either option, the stream also carries the forked skill’s text and thinking blocks. Before v2.1.265, only a forked skill’s `tool_use` and `tool_result` blocks appeared in the stream. +When you enable either option, Claude Code forwards messages from [subagents at every nesting depth](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>), whether each one was spawned with the Agent tool or started as a [forked skill](</docs/en/skills#run-skills-in-a-subagent>). Messages of subagents that a forked skill spawns, and of forked skills started inside a subagent or another forked skill, require Claude Code v2.1.275 or later. In `parent_tool_use_id`, the nested subagent’s messages carry the ID of the Agent or Skill tool call that started it, so you can rebuild the full nesting tree by following those IDs. Before v2.1.219, messages from nested subagents didn’t appear in the stream. Skills that [run in a subagent](</docs/en/skills#run-skills-in-a-subagent>) appear in the stream the same way: the forked skill’s first message is a `user` message carrying the skill content that drives the run. If you enable either option, the stream also carries the forked skill’s text and thinking blocks. Before v2.1.265, only a forked skill’s `tool_use` and `tool_result` blocks appeared in the stream. ####
modified
--- a/headless.md +++ b/headless.md @@ -297,7 +297,7 @@ * User-invoked [skills](</docs/en/skills>) and custom commands work. Include `/skill-name` in the prompt string and Claude Code expands it before running. * Built-in commands that only run in the terminal interface, such as `/login`, aren’t available. * `/model`, `/effort`, `/fast`, `/color`, and `/rename` accept the value as an argument, for example `/model sonnet`, and `/mcp` with no argument prints a text summary of server status. These forms require Claude Code v2.1.205 or later and follow each command’s [availability notes](</docs/en/commands#all-commands>). - * To change a setting, pass `key=value` to `/config`, for example `/config thinking=false`. Requires Claude Code v2.1.181 or later. + * To change a setting, pass `key=value` to `/config`, for example `/config thinking=false`. * `/output-style <style>` switches [output styles](</docs/en/output-styles>) and `/output-style` alone lists them. Requires Claude Code v2.1.269 or later. ###
modified
--- a/headless.md +++ b/headless.md @@ -292,7 +292,13 @@ The `--allowedTools` flag uses [permission rule syntax](</docs/en/settings-reference#permission-rule-syntax>). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`. -User-invoked [skills](</docs/en/skills>) and custom commands work in `-p` mode: include `/skill-name` in the prompt string and Claude Code expands it before running. Built-in commands that only run in the terminal interface, such as `/login`, aren’t available in `-p` mode. `/model`, `/effort`, `/fast`, `/color`, and `/rename` accept the value as an argument, for example `/model sonnet`, and `/mcp` with no argument prints a text summary of server status; these forms require Claude Code v2.1.205 or later and follow each command’s [availability notes](</docs/en/commands#all-commands>). To change a setting from a `-p` invocation, pass `key=value` to `/config`, for example `/config thinking=false`. +Command support differs in `-p` mode: + + * User-invoked [skills](</docs/en/skills>) and custom commands work. Include `/skill-name` in the prompt string and Claude Code expands it before running. + * Built-in commands that only run in the terminal interface, such as `/login`, aren’t available. + * `/model`, `/effort`, `/fast`, `/color`, and `/rename` accept the value as an argument, for example `/model sonnet`, and `/mcp` with no argument prints a text summary of server status. These forms require Claude Code v2.1.205 or later and follow each command’s [availability notes](</docs/en/commands#all-commands>). + * To change a setting, pass `key=value` to `/config`, for example `/config thinking=false`. Requires Claude Code v2.1.181 or later. + * `/output-style <style>` switches [output styles](</docs/en/output-styles>) and `/output-style` alone lists them. Requires Claude Code v2.1.269 or later. ###
modified
--- a/headless.md +++ b/headless.md @@ -258,7 +258,7 @@ To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). For `-p`, the [built-in starting permission mode](</docs/en/permission-modes#which-mode-a-session-starts-in>) is Manual on every plan, so pass the permission mode you want: * **`auto`** : pass `--permission-mode auto` to have a classifier review most actions instead of you - * **`dontAsk`** : Claude Code denies anything not in your `permissions.allow` rules or the [read-only command set](</docs/en/permissions#read-only-commands>), which is useful for locked-down CI runs. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) are denied even when an allow rule matches + * **`dontAsk`** : Claude Code denies every call that would otherwise prompt, which is useful for locked-down CI runs. Actions that need no approval in Manual mode still run, such as file reads in your working directories and the [read-only command set](</docs/en/permissions#read-only-commands>), and so do actions your `--allowedTools` entries or `permissions.allow` rules cover. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) are denied even when an allow rule matches * **`acceptEdits`** : Claude writes files without prompting, and Claude Code auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. The [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>) still apply. Apart from the read-only command set, other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule. See [what `acceptEdits` auto-approves](</docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode>) for the full list This example applies lint fixes with `acceptEdits` as the baseline:
modified
--- a/headless.md +++ b/headless.md @@ -163,7 +163,12 @@ Follow subagent messages -Messages from [subagents](</docs/en/sub-agents>) appear in the stream as `assistant` and `user` messages whose `parent_tool_use_id` field is the ID of the tool call that spawned the subagent. Messages from the main conversation carry `null` in that field. By default, Claude Code emits only subagent `tool_use` and `tool_result` blocks. Pass [`--forward-subagent-text`](</docs/en/cli-reference#cli-flags>) or set [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>) to also emit subagent text and thinking blocks, so you can reconstruct each subagent’s transcript. This requires Claude Code v2.1.211 or later. When you enable either option, Claude Code forwards messages from [subagents at every nesting depth](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>): when a subagent spawns its own subagent, the nested subagent’s messages carry the ID of the Agent tool call that spawned it in `parent_tool_use_id`, so you can rebuild the full nesting tree by following those IDs. Before v2.1.219, messages from nested subagents didn’t appear in the stream. +Messages from [subagents](</docs/en/sub-agents>) appear in the stream as `assistant` and `user` messages whose `parent_tool_use_id` field is the ID of the tool call that spawned the subagent. Messages from the main conversation carry `null` in that field. The first message from a subagent running in the [foreground](</docs/en/sub-agents#run-subagents-in-foreground-or-background>) is a `user` message carrying the prompt that drives it. After that first message, Claude Code emits: + + * **By default** : the subagent’s `tool_use` and `tool_result` blocks. + * **With[`--forward-subagent-text`](</docs/en/cli-reference#cli-flags>) or [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>)**: the subagent’s text and thinking blocks too, so you can reconstruct each subagent’s transcript. This requires Claude Code v2.1.211 or later. + +When you enable either option, Claude Code forwards messages from [subagents at every nesting depth](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>): when a subagent spawns its own subagent, the nested subagent’s messages carry the ID of the Agent tool call that spawned it in `parent_tool_use_id`, so you can rebuild the full nesting tree by following those IDs. Before v2.1.219, messages from nested subagents didn’t appear in the stream. Skills that [run in a subagent](</docs/en/skills#run-skills-in-a-subagent>) appear in the stream the same way: the forked skill’s first message is a `user` message carrying the skill content that drives the run. If you enable either option, the stream also carries the forked skill’s text and thinking blocks. Before v2.1.265, only a forked skill’s `tool_use` and `tool_result` blocks appeared in the stream. #### @@ -178,11 +183,11 @@ `type`| `"system"`| message type `subtype`| `"api_retry"`| identifies this as a retry event `attempt`| integer| current attempt number, starting at 1 -`max_retries`| integer| total retries permitted +`max_retries`| integer| total retries permitted for this failure’s cause, which can be fewer than the session-wide budget `retry_delay_ms`| integer| milliseconds until the next attempt -`error_status`| integer or null| HTTP status code, or `null` for connection errors with no HTTP response +`error_status`| integer or null| HTTP status code of the failed attempt, or `null` when the attempt got no HTTP response from the API `no_response`| object, optional| present only when the failed attempt got [no response headers in time](</docs/en/errors#no-response-from-api>). `waited_ms` is how long that attempt waited and `retry_wait_ms` is how long the retry will wait. In these events, `max_retries` reflects the one retry this cause normally gets, not the session-wide budget. Requires Claude Code v2.1.261 or later -`error`| string| error category: `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `rate_limit`, `overloaded`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, or `unknown` +`error`| string| error category: `authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`, `billing_error`, `rate_limit`, `overloaded`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, `cloud_credential_error`, or `unknown` `uuid`| string| unique event identifier `session_id`| string| session the event belongs to @@ -309,7 +314,7 @@ Continue conversations -Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. `--continue` skips [background sessions](</docs/en/sessions#resume-a-session>). This example runs a review, then sends follow-up prompts: +Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. On Claude Code v2.1.257 or later, when you pass `--continue`, Claude Code opens a [background session](</docs/en/sessions#resume-a-session>) that has finished, but not one that is still running. This example runs a review, then sends follow-up prompts: # First request claude -p "Review this codebase for performance issues" @@ -323,7 +328,7 @@ session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id') claude -p "Continue that review" --resume "$session_id" -You can run the two commands from different directories: Claude Code [finds the session by its ID](</docs/en/sessions#resume-a-session>) in any project on this machine. Before v2.1.223, Claude Code looked for the ID only in the current project directory and its git worktrees, so you had to run both commands from the same directory. +You can run the two commands from different directories: Claude Code [finds the session by its ID](</docs/en/sessions#resume-a-session>) in any project on this machine. Before v2.1.223, Claude Code looked for the ID only in the current project directory and its git worktrees, so you had to run both commands from the same directory. In place of the session ID, you can pass `--resume` the absolute path to a session’s `.jsonl` [transcript file](</docs/en/sessions#where-transcripts-are-stored>), and Claude Code continues the conversation stored in that file. ##
modified
--- a/headless.md +++ b/headless.md @@ -50,7 +50,7 @@ Background tasks at exit -If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that shell is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. Background [subagents](</docs/en/sub-agents>) and workflows are exempt from the five-second grace because their result is part of the final output, so `claude -p` waits for them to complete. From v2.1.182, that wait is capped at ten minutes of continuous idle waiting by default, so a stuck background agent can’t hold the process open indefinitely. Adjust the cap with [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without a limit. +If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that shell is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. If Claude starts a background [subagent](</docs/en/sub-agents>) or workflow, `claude -p` instead stays open until that work completes, because its result is part of the final output. By default the wait ends after 10 minutes of continuous idle waiting, so a stuck subagent or workflow can’t hold the process open indefinitely. At that point Claude Code stops whatever is still running and drops its partial result. To change the limit, set [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without one. If Claude starts a [Monitor](</docs/en/tools-reference#monitor-tool>) watch during a `claude -p` run, Claude Code waits for the watch until it times out or the ten-minute cap ends the wait, whichever comes first. While it waits, Claude keeps responding to what the watch reports. By default, a watch times out five minutes after Claude starts it. ### @@ -181,6 +181,7 @@ `max_retries`| integer| total retries permitted `retry_delay_ms`| integer| milliseconds until the next attempt `error_status`| integer or null| HTTP status code, or `null` for connection errors with no HTTP response +`no_response`| object, optional| present only when the failed attempt got [no response headers in time](</docs/en/errors#no-response-from-api>). `waited_ms` is how long that attempt waited and `retry_wait_ms` is how long the retry will wait. In these events, `max_retries` reflects the one retry this cause normally gets, not the session-wide budget. Requires Claude Code v2.1.261 or later `error`| string| error category: `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `rate_limit`, `overloaded`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, or `unknown` `uuid`| string| unique event identifier `session_id`| string| session the event belongs to
modified
--- a/headless.md +++ b/headless.md @@ -263,6 +263,20 @@ ​ +Turn off permission prompts in unattended runs + +Pass `--permission-prompts none` when nobody is available to answer permission prompts, for example in a scheduled job. The flag matters most when your run has a permission host: an Agent SDK app with a [`canUseTool` callback](</docs/en/agent-sdk/user-input>), or an MCP tool you pass with [`--permission-prompt-tool`](</docs/en/cli-reference#cli-flags>). Without the flag, your run waits for that host to answer each permission request. With the flag, your run doesn’t consult the host or wait on it. Anything that would prompt is denied unless a `PermissionRequest` hook allows it, Claude is told that nobody can approve the request and not to retry it, and the run continues. In a `-p` run with no host, these requests are denied either way, and the flag also tells Claude not to retry them. Permission rules, [`PermissionRequest` hooks](</docs/en/hooks#permissionrequest>), and the permission mode you set still decide every call first; Claude Code denies only the requests that nothing else resolves. This example runs an unattended task in [auto mode](</docs/en/permission-modes#eliminate-prompts-with-auto-mode>). The classifier reviews each action as usual, and Claude Code denies anything that would have fallen back to a prompt: + + claude -p "Update the dependency pins and run the tests" --permission-mode auto --permission-prompts none + +With `--permission-prompts none`, Claude Code removes the tools that need an answer from a person, such as [`AskUserQuestion`](</docs/en/tools-reference#askuserquestion-tool-behavior>), so Claude can’t call them. Any [MCP elicitation request](</docs/en/mcp#respond-to-mcp-elicitation-requests>) that no [`Elicitation` hook](</docs/en/hooks#elicitation>) answers is cancelled. With `--output-format stream-json`, denials appear as `permission_denied` system messages, and the final result message lists them in `permission_denials`. + +The `--permission-prompts` flag requires Claude Code v2.1.259 or later. Earlier versions reject it with an unknown-option error. + +### + +​ + Create a commit This example reviews staged changes and creates a commit with an appropriate message:
modified
--- a/headless.md +++ b/headless.md @@ -50,7 +50,7 @@ Background tasks at exit -If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that shell is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. Background [subagents](</docs/en/sub-agents>) and workflows are exempt from the five-second grace because their result is part of the final output, so `claude -p` waits for them to complete. From v2.1.182, that wait is capped at ten minutes by default so a stuck background agent cannot hold the process open indefinitely. Adjust the cap with [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without a limit. +If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that shell is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. Background [subagents](</docs/en/sub-agents>) and workflows are exempt from the five-second grace because their result is part of the final output, so `claude -p` waits for them to complete. From v2.1.182, that wait is capped at ten minutes of continuous idle waiting by default, so a stuck background agent can’t hold the process open indefinitely. Adjust the cap with [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without a limit. ### @@ -171,7 +171,7 @@ Handle API retries -When an API request fails with a retryable error, Claude Code emits a `system/api_retry` event before retrying. You can use this to surface retry progress or implement custom backoff logic. +When an API request fails with a retryable error, Claude Code emits a `system/api_retry` event before retrying. On v2.1.246 or later, when a `401` or `403` rejects an [`apiKeyHelper`](</docs/en/settings-reference#apikeyhelper>) credential, Claude Code makes the first two retries quietly with no event, then emits the event as usual from the third consecutive retry onward. The quiet retries still count toward `attempt`. You can use the event to show retry progress in your own interface. Field| Type| Description ---|---|---
modified
--- a/headless.md +++ b/headless.md @@ -28,7 +28,7 @@ Start faster with bare mode -Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, [subagents](</docs/en/sub-agents>), plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. A directory you name with `--add-dir` is a partial exception: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](</docs/en/skills#skills-from-additional-directories>) covers what does and doesn’t load. Without `--bare`, Claude Code runs the hooks in a project’s `.claude/settings.json` even in a folder you’ve never trusted, because a `-p` session shows no workspace trust dialog. It also connects the servers in the project’s `.mcp.json`, because a `-p` session can’t show the per-server approval prompt either. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: +Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, [subagents](</docs/en/sub-agents>), plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. A directory you name with `--add-dir` is a partial exception: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](</docs/en/skills#skills-from-additional-directories>) covers what does and doesn’t load. Without `--bare`, a `-p` session runs the hooks in a project’s `.claude/settings.json` and connects the servers in its `.mcp.json`, even in a folder you’ve never trusted. A `-p` session shows no workspace trust dialog and no per-server approval prompt. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: claude --bare -p "Summarize README.md" --allowedTools "Read" @@ -270,7 +270,7 @@ claude -p "Look at my staged changes and create an appropriate commit" \ --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)" -The `--allowedTools` flag uses [permission rule syntax](</docs/en/settings#permission-rule-syntax>). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`. +The `--allowedTools` flag uses [permission rule syntax](</docs/en/settings-reference#permission-rule-syntax>). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`. User-invoked [skills](</docs/en/skills>) and custom commands work in `-p` mode: include `/skill-name` in the prompt string and Claude Code expands it before running. Built-in commands that only run in the terminal interface, such as `/login`, aren’t available in `-p` mode. `/model`, `/effort`, `/fast`, `/color`, and `/rename` accept the value as an argument, for example `/model sonnet`, and `/mcp` with no argument prints a text summary of server status; these forms require Claude Code v2.1.205 or later and follow each command’s [availability notes](</docs/en/commands#all-commands>). To change a setting from a `-p` invocation, pass `key=value` to `/config`, for example `/config thinking=false`. @@ -294,7 +294,7 @@ Continue conversations -Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. This example runs a review, then sends follow-up prompts: +Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. `--continue` skips [background sessions](</docs/en/sessions#resume-a-session>). This example runs a review, then sends follow-up prompts: # First request claude -p "Review this codebase for performance issues"
modified
--- a/headless.md +++ b/headless.md @@ -28,7 +28,7 @@ Start faster with bare mode -Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. Without `--bare`, Claude Code runs the hooks in a project’s `.claude/settings.json` even in a folder you’ve never trusted, because a `-p` session shows no workspace trust dialog. It also connects the servers in the project’s `.mcp.json`, because a `-p` session can’t show the per-server approval prompt either. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: +Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, custom commands, [subagents](</docs/en/sub-agents>), plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. A directory you name with `--add-dir` is a partial exception: bare mode loads skills from its `.claude/skills/` folder, but still skips its `.claude/commands/` and `.claude/agents/` folders. [Skills from additional directories](</docs/en/skills#skills-from-additional-directories>) covers what does and doesn’t load. Without `--bare`, Claude Code runs the hooks in a project’s `.claude/settings.json` even in a folder you’ve never trusted, because a `-p` session shows no workspace trust dialog. It also connects the servers in the project’s `.mcp.json`, because a `-p` session can’t show the per-server approval prompt either. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: claude --bare -p "Summarize README.md" --allowedTools "Read" @@ -50,7 +50,20 @@ Background tasks at exit -If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that shell is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. Background [subagents](</docs/en/sub-agents>) and workflows are exempt from the five-second grace because their result is part of the final output, so `claude -p` waits for them to complete. From v2.1.182, that wait is capped at ten minutes by default so a stuck background agent cannot hold the process open indefinitely. Adjust the cap with [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without a limit. If you stop a `claude -p` run with SIGTERM, for example from `kill`, a process supervisor, or an SDK host closing the session, Claude Code aborts the in-progress turn, terminates the process tree of any running Bash command, runs [`SessionEnd` hooks](</docs/en/hooks#sessionend>), and exits with code 143. +If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that shell is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. Background [subagents](</docs/en/sub-agents>) and workflows are exempt from the five-second grace because their result is part of the final output, so `claude -p` waits for them to complete. From v2.1.182, that wait is capped at ten minutes by default so a stuck background agent cannot hold the process open indefinitely. Adjust the cap with [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without a limit. + +### + +​ + +Stop a run with SIGTERM + +If you stop a `claude -p` run with SIGTERM, for example with `kill` or from a process supervisor, Claude Code exits with code 143. Claude Code leaves the turn that was in progress unfinished and records no result for it. To end the turn instead, send SIGINT, or call the Agent SDK’s `interrupt()`, before you stop the process. On SIGTERM, Claude Code terminates the process tree of any Bash command that is still running. Claude Code then runs [`SessionEnd` hooks](</docs/en/hooks#sessionend>) and exits. While exiting, Claude Code starts no new tool call, sends no new model request, and runs no hook other than `SessionEnd`. If the run was in the middle of a command or waiting on a permission prompt when the signal arrived, Claude Code handles that step as follows: + + * **Running a command** : Claude Code records the command as killed in the session. + * **Waiting for an answer to a permission prompt** : if you send SIGTERM to the process, Claude Code leaves the prompt unanswered. If your program closes the session through the Agent SDK, the SDK ends Claude Code’s input before sending any signal, and Claude Code cancels the prompt as soon as the input ends. + +When you resume the session, Claude Code continues the turn that SIGTERM left unfinished. ##
modified
--- a/headless.md +++ b/headless.md @@ -236,7 +236,13 @@ claude -p "Run the test suite and fix any failures" \ --allowedTools "Bash,Read,Edit" -To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules or the [read-only command set](</docs/en/permissions#read-only-commands>), which is useful for locked-down CI runs. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) are denied even when an allow rule matches. `acceptEdits` lets Claude write files without prompting and also auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. Apart from the [read-only command set](</docs/en/permissions#read-only-commands>), other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule. See [what `acceptEdits` auto-approves](</docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode>) for the full list. This example applies lint fixes with `acceptEdits` as the baseline: +To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). For `-p`, the [built-in starting permission mode](</docs/en/permission-modes#which-mode-a-session-starts-in>) is Manual on every plan, so pass the permission mode you want: + + * **`auto`** : pass `--permission-mode auto` to have a classifier review most actions instead of you + * **`dontAsk`** : Claude Code denies anything not in your `permissions.allow` rules or the [read-only command set](</docs/en/permissions#read-only-commands>), which is useful for locked-down CI runs. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) are denied even when an allow rule matches + * **`acceptEdits`** : Claude writes files without prompting, and Claude Code auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. The [actions no mode auto-approves](</docs/en/permission-modes#actions-no-mode-auto-approves>) still apply. Apart from the read-only command set, other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule. See [what `acceptEdits` auto-approves](</docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode>) for the full list + +This example applies lint fixes with `acceptEdits` as the baseline: claude -p "Apply the lint fixes" --permission-mode acceptEdits
modified
--- a/headless.md +++ b/headless.md @@ -28,7 +28,7 @@ Start faster with bare mode -Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: +Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. Without `--bare`, Claude Code runs the hooks in a project’s `.claude/settings.json` even in a folder you’ve never trusted, because a `-p` session shows no workspace trust dialog. It also connects the servers in the project’s `.mcp.json`, because a `-p` session can’t show the per-server approval prompt either. [What runs before you trust a folder](</docs/en/permissions#what-runs-before-you-trust-a-folder>) covers each kind of repository content under `-p` and how to keep it out. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: claude --bare -p "Summarize README.md" --allowedTools "Read"
modified
--- a/headless.md +++ b/headless.md @@ -236,7 +236,7 @@ claude -p "Run the test suite and fix any failures" \ --allowedTools "Bash,Read,Edit" -To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules or the [read-only command set](</docs/en/permissions#read-only-commands>), which is useful for locked-down CI runs. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) are denied even when an allow rule matches. `acceptEdits` lets Claude write files without prompting and also auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. Other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted: +To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules or the [read-only command set](</docs/en/permissions#read-only-commands>), which is useful for locked-down CI runs. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) are denied even when an allow rule matches. `acceptEdits` lets Claude write files without prompting and also auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. Apart from the [read-only command set](</docs/en/permissions#read-only-commands>), other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule. See [what `acceptEdits` auto-approves](</docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode>) for the full list. This example applies lint fixes with `acceptEdits` as the baseline: claude -p "Apply the lint fixes" --permission-mode acceptEdits
modified
--- a/headless.md +++ b/headless.md @@ -70,7 +70,7 @@ cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt -With `--output-format json`, the response payload includes `total_cost_usd` and a per-model cost breakdown, so scripted callers can track spend per invocation without consulting the [usage dashboard](</docs/en/costs>). +With `--output-format json`, the response payload includes `total_cost_usd` and a per-model cost breakdown, so scripted callers can track spend per invocation without consulting the [usage dashboard](</docs/en/costs>). Both figures are [client-side estimates](</docs/en/agent-sdk/cost-tracking>) and can differ from your actual bill. Piped stdin is capped at 10MB. If you exceed the cap, Claude Code exits with a clear error and a non-zero status. To work with larger inputs, write the content to a file and reference the file path in your prompt instead of piping it.
modified
--- a/headless.md +++ b/headless.md @@ -10,7 +10,7 @@ Basic usage -Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. Not every [CLI option](</docs/en/cli-reference>) combines with `-p`. Claude Code rejects `--bg` and `--cloud` with an error naming the conflict. Options you’ll combine with `-p` often include: +Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. Not every [CLI option](</docs/en/cli-reference>) combines with `-p`. Claude Code rejects `--bg`, and rejects `--cloud` with a task description, with an error naming the conflict; `--cloud` with a session ID and `-p` instead [queues a message into that cloud session](</docs/en/claude-code-on-the-web#send-follow-ups-from-the-cli>) and exits. Options you’ll combine with `-p` often include: * `--continue` for continuing conversations * `--allowedTools` for auto-approving tools @@ -72,7 +72,7 @@ With `--output-format json`, the response payload includes `total_cost_usd` and a per-model cost breakdown, so scripted callers can track spend per invocation without consulting the [usage dashboard](</docs/en/costs>). -As of Claude Code v2.1.128, piped stdin is capped at 10MB. If you exceed the cap, Claude Code exits with a clear error and a non-zero status. To work with larger inputs, write the content to a file and reference the file path in your prompt instead of piping it. +Piped stdin is capped at 10MB. If you exceed the cap, Claude Code exits with a clear error and a non-zero status. To work with larger inputs, write the content to a file and reference the file path in your prompt instead of piping it. If Claude Code can’t read stdin, for example because the process that started it disconnected its end, Claude Code prints a warning to stderr and continues with the prompt from the command line. Before v2.1.211, an unreadable stdin on Windows crashed the session or made it exit silently with no output. @@ -289,7 +289,7 @@ session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id') claude -p "Continue that review" --resume "$session_id" -Run both commands from the same directory: session ID lookup is scoped to the current project directory and its git worktrees. See [Resume a session](</docs/en/sessions#resume-a-session>) for the full scope rules. +You can run the two commands from different directories: Claude Code [finds the session by its ID](</docs/en/sessions#resume-a-session>) in any project on this machine. Before v2.1.223, Claude Code looked for the ID only in the current project directory and its git worktrees, so you had to run both commands from the same directory. ##
modified
--- a/headless.md +++ b/headless.md @@ -1,4 +1,4 @@ -The [Agent SDK](</docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](</docs/en/agent-sdk/python>) and [TypeScript](</docs/en/agent-sdk/typescript>) packages for full programmatic control. To run Claude Code in non-interactive mode, pass `-p` with your prompt and any [CLI options](</docs/en/cli-reference>): +The [Agent SDK](</docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](</docs/en/agent-sdk/python>) and [TypeScript](</docs/en/agent-sdk/typescript>) packages for full programmatic control. To run Claude Code in non-interactive mode, pass `-p` with your prompt and the [CLI options](</docs/en/cli-reference>) you need: claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash" @@ -10,7 +10,7 @@ Basic usage -Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. All [CLI options](</docs/en/cli-reference>) work with `-p`, including: +Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. Not every [CLI option](</docs/en/cli-reference>) combines with `-p`. Claude Code rejects `--bg` and `--cloud` with an error naming the conflict. Options you’ll combine with `-p` often include: * `--continue` for continuing conversations * `--allowedTools` for auto-approving tools @@ -198,7 +198,7 @@ `plugins`| array| plugins that loaded successfully, each with `name` and `path` `plugin_errors`| array| plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. Affected plugins are demoted and absent from `plugins`. The key is omitted when there are no errors -Use the MCP server fields the same way. Claude Code validates each [`--mcp-config`](</docs/en/cli-reference#cli-flags>) entry at startup and skips entries that fail validation, for example a `url` entry with no `type`; the run continues and exits cleanly, so check these fields to catch a server that never loaded: +Use the MCP server fields the same way. When you pass [`--mcp-config`](</docs/en/cli-reference#cli-flags>) with `-p`, Claude Code waits for still-pending servers before running the first turn, up to the [`MCP_TIMEOUT`](</docs/en/env-vars>) startup timeout, 30 seconds by default. A remote server with a [cached tool list](</docs/en/agent-sdk/mcp#connection-timing>) skips the wait, shows `pending` in `system/init`, and connects on its first tool call. The wait requires Claude Code v2.1.221 or later. Claude Code validates each `--mcp-config` entry at startup and skips entries that fail validation, for example a `url` entry with no `type`. The run continues and exits cleanly, so check these fields to catch a server that never loaded: Field| Type| Description ---|---|---
modified
--- a/headless.md +++ b/headless.md @@ -28,11 +28,11 @@ Start faster with bare mode -Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. Only flags you pass explicitly take effect. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: +Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: claude --bare -p "Summarize README.md" --allowedTools "Read" -Bare mode skips OAuth and the system keychain, so Claude Code only sees credentials you pass explicitly. For the Anthropic API, set `ANTHROPIC_API_KEY` in the environment, with a key created in the [Claude Console](<https://platform.claude.com>), or supply an `apiKeyHelper` in the `--settings` JSON. Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry continue to read their own provider credentials as usual. In bare mode Claude has access to the Bash, file read, and file edit tools. Pass any context you need with a flag: +In bare mode, Claude Code never reads OAuth credentials or the system keychain. For the Anthropic API, set `ANTHROPIC_API_KEY` in the environment, with a key created in the [Claude Console](<https://platform.claude.com>), or supply an `apiKeyHelper` in the `--settings` JSON. Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry continue to read their own provider credentials as usual. In bare mode Claude has access to the Bash, file read, and file edit tools. Pass any context you need with a flag: To load| Use ---|--- @@ -58,7 +58,7 @@ Examples -These examples highlight common CLI patterns. Where a command names a file such as `auth.py` or `build-error.txt`, substitute a file from your own project. In CI or other scripted environments, add `--bare` so Claude Code ignores any local configuration on the host. +These examples highlight common CLI patterns. Where a command names a file such as `auth.py` or `build-error.txt`, substitute a file from your own project. In CI or other scripted environments, add `--bare` so Claude Code starts without loading the host’s hooks, plugins, auto memory, or `CLAUDE.md`. ###
modified
--- a/headless.md +++ b/headless.md @@ -20,17 +20,19 @@ claude -p "What does the auth module do?" +Claude Code exits with code 0 on success and a non-zero code when the run fails, so your scripts can branch on the exit status. If you pass an invalid flag, Claude Code reports the error to stderr before the run starts. When a failure happens inside the run, such as missing authentication, Claude Code prints the failure as the result on stdout. + ### ​ Start faster with bare mode -Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. Only flags you pass explicitly take effect. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt: - - claude --bare -p "Summarize this file" --allowedTools "Read" - -In bare mode Claude has access to the Bash, file read, and file edit tools. Pass any context you need with a flag: +Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. Only flags you pass explicitly take effect. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt. Set `ANTHROPIC_API_KEY` before running it, because bare mode doesn’t use your subscription login: + + claude --bare -p "Summarize README.md" --allowedTools "Read" + +Bare mode skips OAuth and the system keychain, so Claude Code only sees credentials you pass explicitly. For the Anthropic API, set `ANTHROPIC_API_KEY` in the environment, with a key created in the [Claude Console](<https://platform.claude.com>), or supply an `apiKeyHelper` in the `--settings` JSON. Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry continue to read their own provider credentials as usual. In bare mode Claude has access to the Bash, file read, and file edit tools. Pass any context you need with a flag: To load| Use ---|--- @@ -40,8 +42,6 @@ Custom agents| `--agents <json>` A plugin| `--plugin-dir <path>`, `--plugin-url <url>` -Bare mode skips OAuth and keychain reads. For Anthropic authentication, set `ANTHROPIC_API_KEY` or configure an `apiKeyHelper` in the JSON you pass to `--settings`. Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry use their usual provider credentials. - `--bare` is the recommended mode for scripted and SDK calls, and will become the default for `-p` in a future release. ### @@ -58,7 +58,7 @@ Examples -These examples highlight common CLI patterns. For CI and other scripted calls, add `--bare` so they don’t pick up whatever happens to be configured locally. +These examples highlight common CLI patterns. Where a command names a file such as `auth.py` or `build-error.txt`, substitute a file from your own project. In CI or other scripted environments, add `--bare` so Claude Code ignores any local configuration on the host. ### @@ -89,6 +89,8 @@ "lint:claude": "git diff main | claude -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\"" } } + +Run it with `npm run lint:claude`. ### @@ -259,13 +261,13 @@ Customize the system prompt -Use `--append-system-prompt` to add instructions while keeping Claude Code’s default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities: +Use `--append-system-prompt` to add instructions while keeping Claude Code’s default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities. Save it as a shell script, for example `review.sh`: gh pr diff "$1" | claude -p \ --append-system-prompt "You are a security engineer. Review for vulnerabilities." \ --output-format json -See [system prompt flags](</docs/en/cli-reference#system-prompt-flags>) for more options including `--system-prompt` to fully replace the default prompt. +In the script, `"$1"` stands for the first argument you pass on the command line. Run `bash review.sh 123` and the shell replaces `"$1"` with `123`, so the script fetches the diff for PR 123. Claude Code prints the review as JSON, with the text in the `result` field. See [system prompt flags](</docs/en/cli-reference#system-prompt-flags>) for more options including `--system-prompt` to fully replace the default prompt. ###
modified
--- a/headless.md +++ b/headless.md @@ -40,7 +40,7 @@ Custom agents| `--agents <json>` A plugin| `--plugin-dir <path>`, `--plugin-url <url>` -Bare mode skips OAuth and keychain reads. Anthropic authentication must come from `ANTHROPIC_API_KEY` or an `apiKeyHelper` in the JSON passed to `--settings`. Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry use their usual provider credentials. +Bare mode skips OAuth and keychain reads. For Anthropic authentication, set `ANTHROPIC_API_KEY` or configure an `apiKeyHelper` in the JSON you pass to `--settings`. Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry use their usual provider credentials. `--bare` is the recommended mode for scripted and SDK calls, and will become the default for `-p` in a future release.
modified
--- a/headless.md +++ b/headless.md @@ -135,10 +135,26 @@ claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages -The last line of the stream is a `result` message with the final response text, cost, and session metadata. If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. Before v2.1.214 the exit wait was capped at about two seconds, which could cut off the end of a large response, and before v2.1.208 piping a large response could truncate the final line and omit the `result` message. Messages from [subagents](</docs/en/sub-agents>) appear in the stream as `assistant` and `user` messages whose `parent_tool_use_id` field is the ID of the tool call that spawned the subagent. Messages from the main conversation carry `null` in that field. By default, Claude Code emits only subagent `tool_use` and `tool_result` blocks. Pass [`--forward-subagent-text`](</docs/en/cli-reference#cli-flags>) or set [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>) to also emit subagent text and thinking blocks, so you can reconstruct each subagent’s transcript. This requires Claude Code v2.1.211 or later. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: +The last line of the stream is a `result` message with the final response text, cost, and session metadata. If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. Before v2.1.214 the exit wait was capped at about two seconds, which could cut off the end of a large response. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \ jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text' + +For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](</docs/en/agent-sdk/streaming-output>) in the Agent SDK documentation. + +#### + +​ + +Follow subagent messages + +Messages from [subagents](</docs/en/sub-agents>) appear in the stream as `assistant` and `user` messages whose `parent_tool_use_id` field is the ID of the tool call that spawned the subagent. Messages from the main conversation carry `null` in that field. By default, Claude Code emits only subagent `tool_use` and `tool_result` blocks. Pass [`--forward-subagent-text`](</docs/en/cli-reference#cli-flags>) or set [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>) to also emit subagent text and thinking blocks, so you can reconstruct each subagent’s transcript. This requires Claude Code v2.1.211 or later. When you enable either option, Claude Code forwards messages from [subagents at every nesting depth](</docs/en/sub-agents#let-subagents-spawn-their-own-subagents>): when a subagent spawns its own subagent, the nested subagent’s messages carry the ID of the Agent tool call that spawned it in `parent_tool_use_id`, so you can rebuild the full nesting tree by following those IDs. Before v2.1.219, messages from nested subagents didn’t appear in the stream. + +#### + +​ + +Handle API retries When an API request fails with a retryable error, Claude Code emits a `system/api_retry` event before retrying. You can use this to surface retry progress or implement custom backoff logic. @@ -154,17 +170,46 @@ `uuid`| string| unique event identifier `session_id`| string| session the event belongs to +#### + +​ + +Read session metadata + The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless startup events precede it: * `plugin_install` events, when [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set. * [`hook_started`, `hook_progress`, and `hook_response` events](</docs/en/agent-sdk/typescript#sdkhookstartedmessage>), while a configured [`SessionStart`](</docs/en/hooks#sessionstart>) or [`Setup`](</docs/en/hooks#setup>) hook runs. These stream as the hook produces them. Claude Code v2.1.169 through v2.1.203 delivered them in one batch after the hook completed, still ahead of `system/init`; v2.1.204 restored live delivery. -The event also carries an optional `capabilities` array of strings naming the protocol behaviors this Claude Code version implements, such as `interrupt_receipt_v1`. Check it to feature-detect instead of comparing version strings, and ignore values you don’t recognize. The field requires Claude Code v2.1.205 or later and is absent from earlier versions. See [`SDKSystemMessage`](</docs/en/agent-sdk/typescript#sdksystemmessage>) for the capability list. Use the plugin fields to fail CI when a plugin did not load: +The event also carries an optional `capabilities` array of strings naming the protocol behaviors this Claude Code version implements, such as `interrupt_receipt_v1` or `interrupt_cancel_queued_v1`. Check it to feature-detect instead of comparing version strings, and ignore values you don’t recognize. The field requires Claude Code v2.1.205 or later and is absent from earlier versions. See [`SDKSystemMessage`](</docs/en/agent-sdk/typescript#sdksystemmessage>) for the capability list. + +#### + +​ + +Fail CI when a plugin or MCP server doesn’t load + +Use the plugin fields in the `system/init` event to catch a plugin that didn’t load: Field| Type| Description ---|---|--- `plugins`| array| plugins that loaded successfully, each with `name` and `path` `plugin_errors`| array| plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. Affected plugins are demoted and absent from `plugins`. The key is omitted when there are no errors + +Use the MCP server fields the same way. Claude Code validates each [`--mcp-config`](</docs/en/cli-reference#cli-flags>) entry at startup and skips entries that fail validation, for example a `url` entry with no `type`; the run continues and exits cleanly, so check these fields to catch a server that never loaded: + +Field| Type| Description +---|---|--- +`mcp_servers`| array| MCP servers in the session, each with `name` and `status` +`mcp_server_errors`| array| `--mcp-config` entries skipped by config validation, each with `name`, `type`, and `message`. `type` is a skip category such as `unknown_type`, `url_missing_type`, `invalid_config`, or `reserved_name`; treat values you don’t recognize as a generic skip. Affected servers are absent from `mcp_servers`. The key is omitted when there are no errors, so a CI gate can fail on a non-empty array. Requires Claude Code v2.1.219 or later + +When you run the command by hand in a terminal, Claude Code also prints a startup warning to stderr, such as `Warning: 1 MCP server skipped due to invalid config:`, followed by the reason for each skipped entry. When you redirect stderr, or when a program such as a CI runner or an SDK host captures it, Claude Code prints no warning and reports the skipped entries only in the `mcp_server_errors` field. The warning requires Claude Code v2.1.219 or later. + +#### + +​ + +Track plugin installs When [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set, Claude Code emits `system/plugin_install` events while marketplace plugins install before the first turn. Use these to surface install progress in your own UI. @@ -178,8 +223,6 @@ `uuid`| string| unique event identifier `session_id`| string| session the event belongs to -For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](</docs/en/agent-sdk/streaming-output>) in the Agent SDK documentation. - ### ​
modified
--- a/headless.md +++ b/headless.md @@ -135,7 +135,7 @@ claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages -The last line of the stream is a `result` message with the final response text, cost, and session metadata. Before v2.1.208, piping a large response could truncate the final line and omit the `result` message. Messages from [subagents](</docs/en/sub-agents>) appear in the stream as `assistant` and `user` messages whose `parent_tool_use_id` field is the ID of the tool call that spawned the subagent. Messages from the main conversation carry `null` in that field. By default, Claude Code emits only subagent `tool_use` and `tool_result` blocks. Pass [`--forward-subagent-text`](</docs/en/cli-reference#cli-flags>) or set [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>) to also emit subagent text and thinking blocks, so you can reconstruct each subagent’s transcript. This requires Claude Code v2.1.211 or later. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: +The last line of the stream is a `result` message with the final response text, cost, and session metadata. If your consumer reads the stream slowly, Claude Code waits for the queued output to drain before exiting, scaling the wait with how much is still queued, capped at 30 seconds. Before v2.1.214 the exit wait was capped at about two seconds, which could cut off the end of a large response, and before v2.1.208 piping a large response could truncate the final line and omit the `result` message. Messages from [subagents](</docs/en/sub-agents>) appear in the stream as `assistant` and `user` messages whose `parent_tool_use_id` field is the ID of the tool call that spawned the subagent. Messages from the main conversation carry `null` in that field. By default, Claude Code emits only subagent `tool_use` and `tool_result` blocks. Pass [`--forward-subagent-text`](</docs/en/cli-reference#cli-flags>) or set [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>) to also emit subagent text and thinking blocks, so you can reconstruct each subagent’s transcript. This requires Claude Code v2.1.211 or later. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \ jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
modified
--- a/headless.md +++ b/headless.md @@ -50,7 +50,7 @@ Background tasks at exit -If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that shell is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. Background [subagents](</docs/en/sub-agents>) and workflows are exempt from the five-second grace because their result is part of the final output, so `claude -p` waits for them to complete. From v2.1.182, that wait is capped at ten minutes by default so a stuck background agent cannot hold the process open indefinitely. Adjust the cap with [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without a limit. +If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that shell is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. Background [subagents](</docs/en/sub-agents>) and workflows are exempt from the five-second grace because their result is part of the final output, so `claude -p` waits for them to complete. From v2.1.182, that wait is capped at ten minutes by default so a stuck background agent cannot hold the process open indefinitely. Adjust the cap with [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without a limit. If you stop a `claude -p` run with SIGTERM, for example from `kill`, a process supervisor, or an SDK host closing the session, Claude Code aborts the in-progress turn, terminates the process tree of any running Bash command, runs [`SessionEnd` hooks](</docs/en/hooks#sessionend>), and exits with code 143. ##
modified
--- a/headless.md +++ b/headless.md @@ -74,6 +74,8 @@ As of Claude Code v2.1.128, piped stdin is capped at 10MB. If you exceed the cap, Claude Code exits with a clear error and a non-zero status. To work with larger inputs, write the content to a file and reference the file path in your prompt instead of piping it. +If Claude Code can’t read stdin, for example because the process that started it disconnected its end, Claude Code prints a warning to stderr and continues with the prompt from the command line. Before v2.1.211, an unreadable stdin on Windows crashed the session or made it exit silently with no output. + ### ​ @@ -112,7 +114,7 @@ If the value isn’t a valid JSON Schema, `claude` exits with `Error: --json-schema is not a valid JSON Schema` followed by the validator’s diagnostic. Claude Code accepts schemas that use the `format` keyword, such as `"format": "email"`, but treats `format` as an annotation and doesn’t enforce it. Before v2.1.205, Claude Code silently ignored an invalid schema and returned unstructured text, and treated any schema containing `format` as invalid. -Use a tool like [jq](<https://jqlang.github.io/jq/>) to parse the response and extract specific fields: +Use a tool like [jq](<https://jqlang.org/>) to parse the response and extract specific fields: # Extract the text result claude -p "Summarize this project" --output-format json | jq -r '.result' @@ -133,7 +135,7 @@ claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages -The last line of the stream is a `result` message with the final response text, cost, and session metadata. Before v2.1.208, piping a large response could truncate the final line and omit the `result` message. The following example uses [jq](<https://jqlang.github.io/jq/>) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: +The last line of the stream is a `result` message with the final response text, cost, and session metadata. Before v2.1.208, piping a large response could truncate the final line and omit the `result` message. Messages from [subagents](</docs/en/sub-agents>) appear in the stream as `assistant` and `user` messages whose `parent_tool_use_id` field is the ID of the tool call that spawned the subagent. Messages from the main conversation carry `null` in that field. By default, Claude Code emits only subagent `tool_use` and `tool_result` blocks. Pass [`--forward-subagent-text`](</docs/en/cli-reference#cli-flags>) or set [`CLAUDE_CODE_FORWARD_SUBAGENT_TEXT`](</docs/en/env-vars>) to also emit subagent text and thinking blocks, so you can reconstruct each subagent’s transcript. This requires Claude Code v2.1.211 or later. The following example uses [jq](<https://jqlang.org/>) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \ jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
modified
--- a/headless.md +++ b/headless.md @@ -189,7 +189,7 @@ claude -p "Run the test suite and fix any failures" \ --allowedTools "Bash,Read,Edit" -To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules or the [read-only command set](</docs/en/permissions#read-only-commands>), which is useful for locked-down CI runs. `acceptEdits` lets Claude write files without prompting and also auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. Other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted: +To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules or the [read-only command set](</docs/en/permissions#read-only-commands>), which is useful for locked-down CI runs. `AskUserQuestion`, connector tools [your organization set to `ask`](</docs/en/mcp#organization-controls-on-connector-tools>), and MCP tools marked [`requiresUserInteraction`](</docs/en/mcp#require-approval-for-a-specific-tool>) are denied even when an allow rule matches. `acceptEdits` lets Claude write files without prompting and also auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. Other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted: claude -p "Apply the lint fixes" --permission-mode acceptEdits
modified
--- a/headless.md +++ b/headless.md @@ -133,7 +133,7 @@ claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages -The following example uses [jq](<https://jqlang.github.io/jq/>) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: +The last line of the stream is a `result` message with the final response text, cost, and session metadata. Before v2.1.208, piping a large response could truncate the final line and omit the `result` message. The following example uses [jq](<https://jqlang.github.io/jq/>) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \ jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'
modified
--- a/headless.md +++ b/headless.md @@ -152,7 +152,12 @@ `uuid`| string| unique event identifier `session_id`| string| session the event belongs to -The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set, in which case `plugin_install` events precede it. The event also carries an optional `capabilities` array of strings naming the protocol behaviors this Claude Code version implements, such as `interrupt_receipt_v1`. Check it to feature-detect instead of comparing version strings, and ignore values you don’t recognize. The field requires Claude Code v2.1.205 or later and is absent from earlier versions. See [`SDKSystemMessage`](</docs/en/agent-sdk/typescript#sdksystemmessage>) for the capability list. Use the plugin fields to fail CI when a plugin did not load: +The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless startup events precede it: + + * `plugin_install` events, when [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set. + * [`hook_started`, `hook_progress`, and `hook_response` events](</docs/en/agent-sdk/typescript#sdkhookstartedmessage>), while a configured [`SessionStart`](</docs/en/hooks#sessionstart>) or [`Setup`](</docs/en/hooks#setup>) hook runs. These stream as the hook produces them. Claude Code v2.1.169 through v2.1.203 delivered them in one batch after the hook completed, still ahead of `system/init`; v2.1.204 restored live delivery. + +The event also carries an optional `capabilities` array of strings naming the protocol behaviors this Claude Code version implements, such as `interrupt_receipt_v1`. Check it to feature-detect instead of comparing version strings, and ignore values you don’t recognize. The field requires Claude Code v2.1.205 or later and is absent from earlier versions. See [`SDKSystemMessage`](</docs/en/agent-sdk/typescript#sdksystemmessage>) for the capability list. Use the plugin fields to fail CI when a plugin did not load: Field| Type| Description ---|---|---
modified
--- a/headless.md +++ b/headless.md @@ -109,6 +109,8 @@ claude -p "Extract the main function names from auth.py" \ --output-format json \ --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' + +If the value isn’t a valid JSON Schema, `claude` exits with `Error: --json-schema is not a valid JSON Schema` followed by the validator’s diagnostic. Claude Code accepts schemas that use the `format` keyword, such as `"format": "email"`, but treats `format` as an annotation and doesn’t enforce it. Before v2.1.205, Claude Code silently ignored an invalid schema and returned unstructured text, and treated any schema containing `format` as invalid. Use a tool like [jq](<https://jqlang.github.io/jq/>) to parse the response and extract specific fields: @@ -150,7 +152,7 @@ `uuid`| string| unique event identifier `session_id`| string| session the event belongs to -The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set, in which case `plugin_install` events precede it. Use the plugin fields to fail CI when a plugin did not load: +The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set, in which case `plugin_install` events precede it. The event also carries an optional `capabilities` array of strings naming the protocol behaviors this Claude Code version implements, such as `interrupt_receipt_v1`. Check it to feature-detect instead of comparing version strings, and ignore values you don’t recognize. The field requires Claude Code v2.1.205 or later and is absent from earlier versions. See [`SDKSystemMessage`](</docs/en/agent-sdk/typescript#sdksystemmessage>) for the capability list. Use the plugin fields to fail CI when a plugin did not load: Field| Type| Description ---|---|--- @@ -199,7 +201,7 @@ The `--allowedTools` flag uses [permission rule syntax](</docs/en/settings#permission-rule-syntax>). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`. -User-invoked [skills](</docs/en/skills>) and custom commands work in `-p` mode: include `/skill-name` in the prompt string and Claude Code expands it before running. Built-in commands that open an interactive dialog, such as `/login`, are not available in `-p` mode. To change a setting from a `-p` invocation, pass `key=value` to `/config`, for example `/config thinking=false`. +User-invoked [skills](</docs/en/skills>) and custom commands work in `-p` mode: include `/skill-name` in the prompt string and Claude Code expands it before running. Built-in commands that only run in the terminal interface, such as `/login`, aren’t available in `-p` mode. `/model`, `/effort`, `/fast`, `/color`, and `/rename` accept the value as an argument, for example `/model sonnet`, and `/mcp` with no argument prints a text summary of server status; these forms require Claude Code v2.1.205 or later and follow each command’s [availability notes](</docs/en/commands#all-commands>). To change a setting from a `-p` invocation, pass `key=value` to `/config`, for example `/config thinking=false`. ###
modified
--- a/headless.md +++ b/headless.md @@ -40,7 +40,7 @@ Custom agents| `--agents <json>` A plugin| `--plugin-dir <path>`, `--plugin-url <url>` -Bare mode skips OAuth and keychain reads. Anthropic authentication must come from `ANTHROPIC_API_KEY` or an `apiKeyHelper` in the JSON passed to `--settings`. Bedrock, Vertex, and Foundry use their usual provider credentials. +Bare mode skips OAuth and keychain reads. Anthropic authentication must come from `ANTHROPIC_API_KEY` or an `apiKeyHelper` in the JSON passed to `--settings`. Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry use their usual provider credentials. `--bare` is the recommended mode for scripted and SDK calls, and will become the default for `-p` in a future release.
modified
--- a/headless.md +++ b/headless.md @@ -50,7 +50,7 @@ Background tasks at exit -If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that task is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. +If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that shell is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. Background [subagents](</docs/en/sub-agents>) and workflows are exempt from the five-second grace because their result is part of the final output, so `claude -p` waits for them to complete. From v2.1.182, that wait is capped at ten minutes by default so a stuck background agent cannot hold the process open indefinitely. Adjust the cap with [`CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS`](</docs/en/env-vars>), or set it to `0` to wait without a limit. ##
modified
--- a/headless.md +++ b/headless.md @@ -199,7 +199,7 @@ The `--allowedTools` flag uses [permission rule syntax](</docs/en/settings#permission-rule-syntax>). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`. -User-invoked [skills](</docs/en/skills>) and custom commands work in `-p` mode: include `/skill-name` in the prompt string and Claude Code expands it before running. Built-in commands that open an interactive dialog, such as `/config` and `/login`, are not available in `-p` mode. +User-invoked [skills](</docs/en/skills>) and custom commands work in `-p` mode: include `/skill-name` in the prompt string and Claude Code expands it before running. Built-in commands that open an interactive dialog, such as `/login`, are not available in `-p` mode. To change a setting from a `-p` invocation, pass `key=value` to `/config`, for example `/config thinking=false`. ###
modified
--- a/headless.md +++ b/headless.md @@ -1,5 +1,3 @@ -Starting June 15, 2026, Agent SDK and `claude -p` usage on subscription plans will draw from a new monthly Agent SDK credit, separate from your interactive usage limits. See [Use the Claude Agent SDK with your Claude plan](<https://support.claude.com/en/articles/15036540-use-the-claude-agent-sdk-with-your-claude-plan>) for details. - The [Agent SDK](</docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](</docs/en/agent-sdk/python>) and [TypeScript](</docs/en/agent-sdk/typescript>) packages for full programmatic control. To run Claude Code in non-interactive mode, pass `-p` with your prompt and any [CLI options](</docs/en/cli-reference>): claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
modified
--- a/headless.md +++ b/headless.md @@ -237,6 +237,8 @@ session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id') claude -p "Continue that review" --resume "$session_id" +Run both commands from the same directory: session ID lookup is scoped to the current project directory and its git worktrees. See [Resume a session](</docs/en/sessions#resume-a-session>) for the full scope rules. + ## ​
modified
--- a/headless.md +++ b/headless.md @@ -52,7 +52,7 @@ Background tasks at exit -If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that task is terminated about five seconds after Claude returns its final result and stdin closes. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. +If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that task is terminated about five seconds after Claude has returned its final result and stdin has closed. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. ## @@ -201,7 +201,7 @@ The `--allowedTools` flag uses [permission rule syntax](</docs/en/settings#permission-rule-syntax>). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`. -User-invoked [skills](</docs/en/skills>) like `/code-review` and [built-in commands](</docs/en/commands>) are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead. +User-invoked [skills](</docs/en/skills>) and custom commands work in `-p` mode: include `/skill-name` in the prompt string and Claude Code expands it before running. Built-in commands that open an interactive dialog, such as `/config` and `/login`, are not available in `-p` mode. ###
modified
--- a/headless.md +++ b/headless.md @@ -45,6 +45,14 @@ Bare mode skips OAuth and keychain reads. Anthropic authentication must come from `ANTHROPIC_API_KEY` or an `apiKeyHelper` in the JSON passed to `--settings`. Bedrock, Vertex, and Foundry use their usual provider credentials. `--bare` is the recommended mode for scripted and SDK calls, and will become the default for `-p` in a future release. + +### + +​ + +Background tasks at exit + +If Claude starts a [background Bash task](</docs/en/tools-reference#bash-tool-behavior>) during a `claude -p` run, for example a dev server or a watch build, that task is terminated about five seconds after Claude returns its final result and stdin closes. The grace period lets a task that finishes right after the result still deliver its output. Before v2.1.163, a never-exiting background process would hold the `claude -p` invocation open indefinitely. ##
modified
--- a/headless.md +++ b/headless.md @@ -1,9 +1,3 @@ -> ## Documentation Index -> -> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt> -> -> Use this file to discover all available pages before exploring further. - Starting June 15, 2026, Agent SDK and `claude -p` usage on subscription plans will draw from a new monthly Agent SDK credit, separate from your interactive usage limits. See [Use the Claude Agent SDK with your Claude plan](<https://support.claude.com/en/articles/15036540-use-the-claude-agent-sdk-with-your-claude-plan>) for details. The [Agent SDK](</docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](</docs/en/agent-sdk/python>) and [TypeScript](</docs/en/agent-sdk/typescript>) packages for full programmatic control. To run Claude Code in non-interactive mode, pass `-p` with your prompt and any [CLI options](</docs/en/cli-reference>): @@ -146,7 +140,7 @@ `max_retries`| integer| total retries permitted `retry_delay_ms`| integer| milliseconds until the next attempt `error_status`| integer or null| HTTP status code, or `null` for connection errors with no HTTP response -`error`| string| error category: `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `rate_limit`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, or `unknown` +`error`| string| error category: `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `rate_limit`, `overloaded`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, or `unknown` `uuid`| string| unique event identifier `session_id`| string| session the event belongs to
modified
--- a/headless.md +++ b/headless.md @@ -199,7 +199,7 @@ The `--allowedTools` flag uses [permission rule syntax](</docs/en/settings#permission-rule-syntax>). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`. -User-invoked [skills](</docs/en/skills>) like `/commit` and [built-in commands](</docs/en/commands>) are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead. +User-invoked [skills](</docs/en/skills>) like `/code-review` and [built-in commands](</docs/en/commands>) are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead. ###
modified
--- a/headless.md +++ b/headless.md @@ -146,7 +146,7 @@ `max_retries`| integer| total retries permitted `retry_delay_ms`| integer| milliseconds until the next attempt `error_status`| integer or null| HTTP status code, or `null` for connection errors with no HTTP response -`error`| string| error category: `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `rate_limit`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` +`error`| string| error category: `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `rate_limit`, `invalid_request`, `model_not_found`, `server_error`, `max_output_tokens`, or `unknown` `uuid`| string| unique event identifier `session_id`| string| session the event belongs to
modified
--- a/headless.md +++ b/headless.md @@ -4,11 +4,9 @@ > > Use this file to discover all available pages before exploring further. -The [Agent SDK](</docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](</docs/en/agent-sdk/python>) and [TypeScript](</docs/en/agent-sdk/typescript>) packages for full programmatic control. - -The CLI was previously called “headless mode.” The `-p` flag and all CLI options work the same way. - -To run Claude Code programmatically from the CLI, pass `-p` with your prompt and any [CLI options](</docs/en/cli-reference>): +Starting June 15, 2026, Agent SDK and `claude -p` usage on subscription plans will draw from a new monthly Agent SDK credit, separate from your interactive usage limits. See [Use the Claude Agent SDK with your Claude plan](<https://support.claude.com/en/articles/15036540-use-the-claude-agent-sdk-with-your-claude-plan>) for details. + +The [Agent SDK](</docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](</docs/en/agent-sdk/python>) and [TypeScript](</docs/en/agent-sdk/typescript>) packages for full programmatic control. To run Claude Code in non-interactive mode, pass `-p` with your prompt and any [CLI options](</docs/en/cli-reference>): claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash"
modified
--- a/headless.md +++ b/headless.md @@ -48,7 +48,7 @@ Settings| `--settings <file-or-json>` MCP servers| `--mcp-config <file-or-json>` Custom agents| `--agents <json>` -A plugin directory| `--plugin-dir <path>` +A plugin| `--plugin-dir <path>`, `--plugin-url <url>` Bare mode skips OAuth and keychain reads. Anthropic authentication must come from `ANTHROPIC_API_KEY` or an `apiKeyHelper` in the JSON passed to `--settings`. Bedrock, Vertex, and Foundry use their usual provider credentials.
modified
--- a/headless.md +++ b/headless.md @@ -73,6 +73,8 @@ cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt With `--output-format json`, the response payload includes `total_cost_usd` and a per-model cost breakdown, so scripted callers can track spend per invocation without consulting the [usage dashboard](</docs/en/costs>). + +As of Claude Code v2.1.128, piped stdin is capped at 10MB. If you exceed the cap, Claude Code exits with a clear error and a non-zero status. To work with larger inputs, write the content to a file and reference the file path in your prompt instead of piping it. ### @@ -155,7 +157,7 @@ Field| Type| Description ---|---|--- `plugins`| array| plugins that loaded successfully, each with `name` and `path` -`plugin_errors`| array| plugin load-time errors such as an unsatisfied dependency version, each with `plugin`, `type`, and `message`. Affected plugins are demoted and absent from `plugins`. The key is omitted when there are no errors +`plugin_errors`| array| plugin load-time errors, each with `plugin`, `type`, and `message`. Includes unsatisfied dependency versions and `--plugin-dir` load failures such as a missing path or invalid archive. Affected plugins are demoted and absent from `plugins`. The key is omitted when there are no errors When [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set, Claude Code emits `system/plugin_install` events while marketplace plugins install before the first turn. Use these to surface install progress in your own UI.
modified
--- a/headless.md +++ b/headless.md @@ -61,6 +61,32 @@ Examples These examples highlight common CLI patterns. For CI and other scripted calls, add `--bare` so they don’t pick up whatever happens to be configured locally. + +### + +​ + +Pipe data through Claude + +Non-interactive mode reads stdin, so you can pipe data in and redirect the response out like any other command-line tool. This example pipes a build log into Claude and writes the explanation to a file: + + cat build-error.txt | claude -p 'concisely explain the root cause of this build error' > output.txt + +With `--output-format json`, the response payload includes `total_cost_usd` and a per-model cost breakdown, so scripted callers can track spend per invocation without consulting the [usage dashboard](</docs/en/costs>). + +### + +​ + +Add Claude to a build script + +You can wrap a non-interactive call in a script to use Claude as a project-specific linter or reviewer. This `package.json` script pipes the diff against `main` into Claude and asks it to report typos. Piping the diff means Claude doesn’t need Bash permission to read it, and the escaped double quotes keep the script portable to Windows: + + { + "scripts": { + "lint:claude": "git diff main | claude -p \"you are a typo linter. for each typo in this diff, report filename:line on one line and the issue on the next. return nothing else.\"" + } + } ###
modified
--- a/headless.md +++ b/headless.md @@ -120,7 +120,7 @@ `max_retries`| integer| total retries permitted `retry_delay_ms`| integer| milliseconds until the next attempt `error_status`| integer or null| HTTP status code, or `null` for connection errors with no HTTP response -`error`| string| error category: `authentication_failed`, `billing_error`, `rate_limit`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` +`error`| string| error category: `authentication_failed`, `oauth_org_not_allowed`, `billing_error`, `rate_limit`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` `uuid`| string| unique event identifier `session_id`| string| session the event belongs to
modified
--- a/headless.md +++ b/headless.md @@ -1,3 +1,9 @@ +> ## Documentation Index +> +> Fetch the complete documentation index at: <https://code.claude.com/docs/llms.txt> +> +> Use this file to discover all available pages before exploring further. + The [Agent SDK](</docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](</docs/en/agent-sdk/python>) and [TypeScript](</docs/en/agent-sdk/typescript>) packages for full programmatic control. The CLI was previously called “headless mode.” The `-p` flag and all CLI options work the same way.
modified
--- a/headless.md +++ b/headless.md @@ -118,6 +118,25 @@ `uuid`| string| unique event identifier `session_id`| string| session the event belongs to +The `system/init` event reports session metadata including the model, tools, MCP servers, and loaded plugins. It is the first event in the stream unless [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set, in which case `plugin_install` events precede it. Use the plugin fields to fail CI when a plugin did not load: + +Field| Type| Description +---|---|--- +`plugins`| array| plugins that loaded successfully, each with `name` and `path` +`plugin_errors`| array| plugin load-time errors such as an unsatisfied dependency version, each with `plugin`, `type`, and `message`. Affected plugins are demoted and absent from `plugins`. The key is omitted when there are no errors + +When [`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`](</docs/en/env-vars>) is set, Claude Code emits `system/plugin_install` events while marketplace plugins install before the first turn. Use these to surface install progress in your own UI. + +Field| Type| Description +---|---|--- +`type`| `"system"`| message type +`subtype`| `"plugin_install"`| identifies this as a plugin install event +`status`| `"started"`, `"installed"`, `"failed"`, or `"completed"`| `started` and `completed` bracket the overall install; `installed` and `failed` report individual marketplaces +`name`| string, optional| marketplace name, present on `installed` and `failed` +`error`| string, optional| failure message, present on `failed` +`uuid`| string| unique event identifier +`session_id`| string| session the event belongs to + For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](</docs/en/agent-sdk/streaming-output>) in the Agent SDK documentation. ### @@ -131,7 +150,7 @@ claude -p "Run the test suite and fix any failures" \ --allowedTools "Bash,Read,Edit" -To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules, which is useful for locked-down CI runs. `acceptEdits` lets Claude write files without prompting and also auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. Other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted: +To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules or the [read-only command set](</docs/en/permissions#read-only-commands>), which is useful for locked-down CI runs. `acceptEdits` lets Claude write files without prompting and also auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. Other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted: claude -p "Apply the lint fixes" --permission-mode acceptEdits
modified
--- a/headless.md +++ b/headless.md @@ -1,4 +1,4 @@ -The [Agent SDK](<https://platform.claude.com/docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](<https://platform.claude.com/docs/en/agent-sdk/python>) and [TypeScript](<https://platform.claude.com/docs/en/agent-sdk/typescript>) packages for full programmatic control. +The [Agent SDK](</docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](</docs/en/agent-sdk/python>) and [TypeScript](</docs/en/agent-sdk/typescript>) packages for full programmatic control. The CLI was previously called “headless mode.” The `-p` flag and all CLI options work the same way. @@ -6,7 +6,7 @@ claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash" -This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](<https://platform.claude.com/docs/en/agent-sdk/overview>). +This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](</docs/en/agent-sdk/overview>). ## @@ -118,7 +118,7 @@ `uuid`| string| unique event identifier `session_id`| string| session the event belongs to -For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](<https://platform.claude.com/docs/en/agent-sdk/streaming-output>) in the Agent SDK documentation. +For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](</docs/en/agent-sdk/streaming-output>) in the Agent SDK documentation. ### @@ -131,7 +131,7 @@ claude -p "Run the test suite and fix any failures" \ --allowedTools "Bash,Read,Edit" -To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules, which is useful for locked-down CI runs. `acceptEdits` lets Claude write files without prompting, but shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted: +To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules, which is useful for locked-down CI runs. `acceptEdits` lets Claude write files without prompting and also auto-approves common filesystem commands such as `mkdir`, `touch`, `mv`, and `cp`. Other shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted: claude -p "Apply the lint fixes" --permission-mode acceptEdits @@ -190,7 +190,7 @@ Next steps - * [Agent SDK quickstart](<https://platform.claude.com/docs/en/agent-sdk/quickstart>): build your first agent with Python or TypeScript + * [Agent SDK quickstart](</docs/en/agent-sdk/quickstart>): build your first agent with Python or TypeScript * [CLI reference](</docs/en/cli-reference>): all CLI flags and options * [GitHub Actions](</docs/en/github-actions>): use the Agent SDK in GitHub workflows * [GitLab CI/CD](</docs/en/gitlab-ci-cd>): use the Agent SDK in GitLab pipelines
modified
--- a/headless.md +++ b/headless.md @@ -131,6 +131,10 @@ claude -p "Run the test suite and fix any failures" \ --allowedTools "Bash,Read,Edit" +To set a baseline for the whole session instead of listing individual tools, pass a [permission mode](</docs/en/permission-modes>). `dontAsk` denies anything not in your `permissions.allow` rules, which is useful for locked-down CI runs. `acceptEdits` lets Claude write files without prompting, but shell commands and network requests still need an `--allowedTools` entry or a `permissions.allow` rule, otherwise the run aborts when one is attempted: + + claude -p "Apply the lint fixes" --permission-mode acceptEdits + ### ​
modified
Show diff (162 lines)
--- a/headless.md +++ b/headless.md @@ -3,12 +3,6 @@ The CLI was previously called “headless mode.” The `-p` flag and all CLI options work the same way. To run Claude Code programmatically from the CLI, pass `-p` with your prompt and any [CLI options](</docs/en/cli-reference>): - -Report incorrect code - -Copy - -Ask AI claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash" @@ -28,12 +22,6 @@ This example asks Claude a question about your codebase and prints the response: -Report incorrect code - -Copy - -Ask AI - claude -p "What does the auth module do?" ### @@ -43,12 +31,6 @@ Start faster with bare mode Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. Only flags you pass explicitly take effect. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt: - -Report incorrect code - -Copy - -Ask AI claude --bare -p "Summarize this file" --allowedTools "Read" @@ -88,33 +70,15 @@ This example returns a project summary as JSON with session metadata, with the text result in the `result` field: -Report incorrect code - -Copy - -Ask AI - claude -p "Summarize this project" --output-format json To get output conforming to a specific schema, use `--output-format json` with `--json-schema` and a [JSON Schema](<https://json-schema.org/>) definition. The response includes metadata about the request (session ID, usage, etc.) with the structured output in the `structured_output` field. This example extracts function names and returns them as an array of strings: - -Report incorrect code - -Copy - -Ask AI claude -p "Extract the main function names from auth.py" \ --output-format json \ --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' Use a tool like [jq](<https://jqlang.github.io/jq/>) to parse the response and extract specific fields: - -Report incorrect code - -Copy - -Ask AI # Extract the text result claude -p "Summarize this project" --output-format json | jq -r '.result' @@ -133,21 +97,9 @@ Use `--output-format stream-json` with `--verbose` and `--include-partial-messages` to receive tokens as they’re generated. Each line is a JSON object representing an event: -Report incorrect code - -Copy - -Ask AI - claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages The following example uses [jq](<https://jqlang.github.io/jq/>) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: - -Report incorrect code - -Copy - -Ask AI claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \ jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text' @@ -176,12 +128,6 @@ Use `--allowedTools` to let Claude use certain tools without prompting. This example runs a test suite and fixes failures, allowing Claude to execute Bash commands and read/edit files without asking for permission: -Report incorrect code - -Copy - -Ask AI - claude -p "Run the test suite and fix any failures" \ --allowedTools "Bash,Read,Edit" @@ -192,12 +138,6 @@ Create a commit This example reviews staged changes and creates a commit with an appropriate message: - -Report incorrect code - -Copy - -Ask AI claude -p "Look at my staged changes and create an appropriate commit" \ --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)" @@ -214,12 +154,6 @@ Use `--append-system-prompt` to add instructions while keeping Claude Code’s default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities: -Report incorrect code - -Copy - -Ask AI - gh pr diff "$1" | claude -p \ --append-system-prompt "You are a security engineer. Review for vulnerabilities." \ --output-format json @@ -234,12 +168,6 @@ Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. This example runs a review, then sends follow-up prompts: -Report incorrect code - -Copy - -Ask AI - # First request claude -p "Review this codebase for performance issues" @@ -248,12 +176,6 @@ claude -p "Generate a summary of all issues found" --continue If you’re running multiple conversations, capture the session ID to resume a specific one: - -Report incorrect code - -Copy - -Ask AI session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id') claude -p "Continue that review" --resume "$session_id"
added
Show diff (273 lines)
--- a/headless.md +++ b/headless.md @@ -0,0 +1,270 @@ +The [Agent SDK](<https://platform.claude.com/docs/en/agent-sdk/overview>) gives you the same tools, agent loop, and context management that power Claude Code. It’s available as a CLI for scripts and CI/CD, or as [Python](<https://platform.claude.com/docs/en/agent-sdk/python>) and [TypeScript](<https://platform.claude.com/docs/en/agent-sdk/typescript>) packages for full programmatic control. + +The CLI was previously called “headless mode.” The `-p` flag and all CLI options work the same way. + +To run Claude Code programmatically from the CLI, pass `-p` with your prompt and any [CLI options](</docs/en/cli-reference>): + +Report incorrect code + +Copy + +Ask AI + + claude -p "Find and fix the bug in auth.py" --allowedTools "Read,Edit,Bash" + +This page covers using the Agent SDK via the CLI (`claude -p`). For the Python and TypeScript SDK packages with structured outputs, tool approval callbacks, and native message objects, see the [full Agent SDK documentation](<https://platform.claude.com/docs/en/agent-sdk/overview>). + +## + +​ + +Basic usage + +Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. All [CLI options](</docs/en/cli-reference>) work with `-p`, including: + + * `--continue` for continuing conversations + * `--allowedTools` for auto-approving tools + * `--output-format` for structured output + +This example asks Claude a question about your codebase and prints the response: + +Report incorrect code + +Copy + +Ask AI + + claude -p "What does the auth module do?" + +### + +​ + +Start faster with bare mode + +Add `--bare` to reduce startup time by skipping auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Without it, `claude -p` loads the same [context](</docs/en/how-claude-code-works#the-context-window>) an interactive session would, including anything configured in the working directory or `~/.claude`. Bare mode is useful for CI and scripts where you need the same result on every machine. A hook in a teammate’s `~/.claude` or an MCP server in the project’s `.mcp.json` won’t run, because bare mode never reads them. Only flags you pass explicitly take effect. This example runs a one-off summarize task in bare mode and pre-approves the Read tool so the call completes without a permission prompt: + +Report incorrect code + +Copy + +Ask AI + + claude --bare -p "Summarize this file" --allowedTools "Read" + +In bare mode Claude has access to the Bash, file read, and file edit tools. Pass any context you need with a flag: + +To load| Use +---|--- +System prompt additions| `--append-system-prompt`, `--append-system-prompt-file` +Settings| `--settings <file-or-json>` +MCP servers| `--mcp-config <file-or-json>` +Custom agents| `--agents <json>` +A plugin directory| `--plugin-dir <path>` + +Bare mode skips OAuth and keychain reads. Anthropic authentication must come from `ANTHROPIC_API_KEY` or an `apiKeyHelper` in the JSON passed to `--settings`. Bedrock, Vertex, and Foundry use their usual provider credentials. + +`--bare` is the recommended mode for scripted and SDK calls, and will become the default for `-p` in a future release. + +## + +​ + +Examples + +These examples highlight common CLI patterns. For CI and other scripted calls, add `--bare` so they don’t pick up whatever happens to be configured locally. + +### + +​ + +Get structured output + +Use `--output-format` to control how responses are returned: + + * `text` (default): plain text output + * `json`: structured JSON with result, session ID, and metadata + * `stream-json`: newline-delimited JSON for real-time streaming + +This example returns a project summary as JSON with session metadata, with the text result in the `result` field: + +Report incorrect code + +Copy + +Ask AI + + claude -p "Summarize this project" --output-format json + +To get output conforming to a specific schema, use `--output-format json` with `--json-schema` and a [JSON Schema](<https://json-schema.org/>) definition. The response includes metadata about the request (session ID, usage, etc.) with the structured output in the `structured_output` field. This example extracts function names and returns them as an array of strings: + +Report incorrect code + +Copy + +Ask AI + + claude -p "Extract the main function names from auth.py" \ + --output-format json \ + --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' + +Use a tool like [jq](<https://jqlang.github.io/jq/>) to parse the response and extract specific fields: + +Report incorrect code + +Copy + +Ask AI + + # Extract the text result + claude -p "Summarize this project" --output-format json | jq -r '.result' + + # Extract structured output + claude -p "Extract function names from auth.py" \ + --output-format json \ + --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \ + | jq '.structured_output' + +### + +​ + +Stream responses + +Use `--output-format stream-json` with `--verbose` and `--include-partial-messages` to receive tokens as they’re generated. Each line is a JSON object representing an event: + +Report incorrect code + +Copy + +Ask AI + + claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages + +The following example uses [jq](<https://jqlang.github.io/jq/>) to filter for text deltas and display just the streaming text. The `-r` flag outputs raw strings (no quotes) and `-j` joins without newlines so tokens stream continuously: + +Report incorrect code + +Copy + +Ask AI + + claude -p "Write a poem" --output-format stream-json --verbose --include-partial-messages | \ + jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text' + +When an API request fails with a retryable error, Claude Code emits a `system/api_retry` event before retrying. You can use this to surface retry progress or implement custom backoff logic. + +Field| Type| Description +---|---|--- +`type`| `"system"`| message type +`subtype`| `"api_retry"`| identifies this as a retry event +`attempt`| integer| current attempt number, starting at 1 +`max_retries`| integer| total retries permitted +`retry_delay_ms`| integer| milliseconds until the next attempt +`error_status`| integer or null| HTTP status code, or `null` for connection errors with no HTTP response +`error`| string| error category: `authentication_failed`, `billing_error`, `rate_limit`, `invalid_request`, `server_error`, `max_output_tokens`, or `unknown` +`uuid`| string| unique event identifier +`session_id`| string| session the event belongs to + +For programmatic streaming with callbacks and message objects, see [Stream responses in real-time](<https://platform.claude.com/docs/en/agent-sdk/streaming-output>) in the Agent SDK documentation. + +### + +​ + +Auto-approve tools + +Use `--allowedTools` to let Claude use certain tools without prompting. This example runs a test suite and fixes failures, allowing Claude to execute Bash commands and read/edit files without asking for permission: + +Report incorrect code + +Copy + +Ask AI + + claude -p "Run the test suite and fix any failures" \ + --allowedTools "Bash,Read,Edit" + +### + +​ + +Create a commit + +This example reviews staged changes and creates a commit with an appropriate message: + +Report incorrect code + +Copy + +Ask AI + + claude -p "Look at my staged changes and create an appropriate commit" \ + --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)" + +The `--allowedTools` flag uses [permission rule syntax](</docs/en/settings#permission-rule-syntax>). The trailing ` *` enables prefix matching, so `Bash(git diff *)` allows any command starting with `git diff`. The space before `*` is important: without it, `Bash(git diff*)` would also match `git diff-index`. + +User-invoked [skills](</docs/en/skills>) like `/commit` and [built-in commands](</docs/en/commands>) are only available in interactive mode. In `-p` mode, describe the task you want to accomplish instead. + +### + +​ + +Customize the system prompt + +Use `--append-system-prompt` to add instructions while keeping Claude Code’s default behavior. This example pipes a PR diff to Claude and instructs it to review for security vulnerabilities: + +Report incorrect code + +Copy + +Ask AI + + gh pr diff "$1" | claude -p \ + --append-system-prompt "You are a security engineer. Review for vulnerabilities." \ + --output-format json + +See [system prompt flags](</docs/en/cli-reference#system-prompt-flags>) for more options including `--system-prompt` to fully replace the default prompt. + +### + +​ + +Continue conversations + +Use `--continue` to continue the most recent conversation, or `--resume` with a session ID to continue a specific conversation. This example runs a review, then sends follow-up prompts: + +Report incorrect code + +Copy + +Ask AI + + # First request + claude -p "Review this codebase for performance issues" + + # Continue the most recent conversation + claude -p "Now focus on the database queries" --continue + claude -p "Generate a summary of all issues found" --continue + +If you’re running multiple conversations, capture the session ID to resume a specific one: + +Report incorrect code + +Copy + +Ask AI + + session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id') + claude -p "Continue that review" --resume "$session_id" + +## + +​ + +Next steps + + * [Agent SDK quickstart](<https://platform.claude.com/docs/en/agent-sdk/quickstart>): build your first agent with Python or TypeScript + * [CLI reference](</docs/en/cli-reference>): all CLI flags and options + * [GitHub Actions](</docs/en/github-actions>): use the Agent SDK in GitHub workflows + * [GitLab CI/CD](</docs/en/gitlab-ci-cd>): use the Agent SDK in GitLab pipelines