Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
docs(cli-agent): snapshot five claude.com Claude Code reference pages
trohitga5bf553fe4e0
diff --git a/CLAUDE.md b/CLAUDE.mdindex b96f0849..525b07b4 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -51,6 +51,11 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Claude Code Agent](./docs-internal/claude_code_agent_architecture.md)** | Claude Code integration internals (LangGraph reference; companion to `cli_agent_framework.md`) || **[CLI Agent Framework](./docs-internal/cli_agent_framework.md)** | Multi-provider CLI runtime (Claude Code / Codex / Gemini): `AICliService.run_batch`, per-task worktree isolation, FastMCP bridge, **memory bridge** (native `--resume` via stable `cwd=repo_root` + UUID5/`last_session_id` round-trip + auto-clear on stale UUID + `node_parameters_updated` broadcast). || **[CLI Agent Canonical Patterns RFC](./docs-internal/cli_agent_canonical_patterns_rfc.md)** | Audit of MachinaOs's `services/cli_agent` against the official Claude Code spec — six invariants (skills-as-files, MCP-only transport, `list_changed`, deferral, visible-tool filtering, native-session-continuity-via-stable-cwd) with current implementation status. |+| **[Claude Code CLI Reference (snapshot)](./docs-internal/claude_code_cli_reference.md)** | Verbatim snapshot of [code.claude.com/docs/en/cli-reference](https://code.claude.com/docs/en/cli-reference) — every CLI subcommand + flag + system-prompt-flag matrix + the subset we emit from `services/cli_agent/providers/anthropic_claude.py`. Fetched 2026-05-11. |+| **[Claude Code Env Vars (snapshot)](./docs-internal/claude_code_env_vars_reference.md)** | Categorised [code.claude.com/docs/en/env-vars](https://code.claude.com/docs/en/env-vars) snapshot — auth, Bedrock/Vertex, model, bash, MCP, telemetry, session/debug, paths. Documents `CLAUDE_CONFIG_DIR`, `MAX_MCP_OUTPUT_TOKENS`, `ENABLE_TOOL_SEARCH` which we touch directly. |+| **[Claude Code Permission Modes (snapshot)](./docs-internal/claude_code_permission_modes_reference.md)** | Verbatim [code.claude.com/docs/en/permission-modes](https://code.claude.com/docs/en/permission-modes) — `default` / `acceptEdits` / `plan` / `auto` / `dontAsk` / `bypassPermissions` semantics, Shift+Tab cycle, protected paths. MachinaOs default is `acceptEdits`. |+| **[Claude Code Headless / Print Mode (snapshot)](./docs-internal/claude_code_headless_reference.md)** | Verbatim [code.claude.com/docs/en/headless](https://code.claude.com/docs/en/headless) — `claude -p`, `--output-format` (`text` / `json` / `stream-json`), `--input-format`, `--bare`, stream-json event schema (`system/init`, `system/api_retry`, `system/plugin_install`). This is the protocol `services/cli_agent/session.py:_consume_stdout` parses. |+| **[Claude Code Skills (snapshot)](./docs-internal/claude_code_skills_reference.md)** | Verbatim [code.claude.com/docs/en/skills](https://code.claude.com/docs/en/skills) — `SKILL.md` frontmatter spec, discovery paths, content lifecycle, `context: fork`, dynamic context injection via `` !`<command>` ``. The spec MachinaOs materialises connected skills against in `_pre_spawn`. || **[Deep Agent](./docs-internal/deep_agent.md)** | LangChain DeepAgents integration with filesystem tools, sub-agent delegation, auto-summarization, and planning || **[Autonomous Agent Creation](./docs-internal/autonomous_agent_creation.md)** | Creating autonomous agents with Code Mode patterns and agentic loops || **[Polyglot Server](../polyglot-server/ARCHITECTURE.md)** | Plugin registry microservice with MCP gateway (optional integration) |diff --git a/docs-internal/claude_code_cli_reference.md b/docs-internal/claude_code_cli_reference.mdnew file mode 100644index 00000000..631bcf48--- /dev/null+++ b/docs-internal/claude_code_cli_reference.md@@ -0,0 +1,208 @@+# Claude Code CLI reference (verbatim snapshot)++> **Source:** [code.claude.com/docs/en/cli-reference](https://code.claude.com/docs/en/cli-reference)+> **Fetched:** 2026-05-11+> **Why this lives in-repo:** the page changes frequently and our+> `services/cli_agent/` framework depends on exact flag semantics+> (e.g. `--mcp-config`, `--strict-mcp-config`, `--resume`,+> `--session-id`, `--append-system-prompt`, `--input-format`). When+> an integration question arises, check this snapshot first; refetch+> if a flag looks newer than 2026-05-11.++---++# CLI reference++> Complete reference for Claude Code command-line interface, including commands and flags.++## CLI commands++You can start sessions, pipe content, resume conversations, and manage updates with these commands:++| Command | Description | Example |+| :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- |+| `claude` | Start interactive session | `claude` |+| `claude "query"` | Start interactive session with initial prompt | `claude "explain this project"` |+| `claude -p "query"` | Query via SDK, then exit | `claude -p "explain this function"` |+| `cat file \| claude -p "query"` | Process piped content | `cat logs.txt \| claude -p "explain"` |+| `claude -c` | Continue most recent conversation in current directory | `claude -c` |+| `claude -c -p "query"` | Continue via SDK | `claude -c -p "Check for type errors"` |+| `claude -r "<session>" "query"` | Resume session by ID or name | `claude -r "auth-refactor" "Finish this PR"` |+| `claude update` | Update to latest version | `claude update` |+| `claude install [version]` | Install or reinstall the native binary. Accepts a version like `2.1.118`, or `stable` or `latest`. See [Install a specific version](https://code.claude.com/docs/en/setup#install-a-specific-version) | `claude install stable` |+| `claude auth login` | Sign in to your Anthropic account. Use `--email` to pre-fill your email address, `--sso` to force SSO authentication, and `--console` to sign in with Anthropic Console for API usage billing instead of a Claude subscription | `claude auth login --console` |+| `claude auth logout` | Log out from your Anthropic account | `claude auth logout` |+| `claude auth status` | Show authentication status as JSON. Use `--text` for human-readable output. Exits with code 0 if logged in, 1 if not | `claude auth status` |+| `claude agents` | Open [agent view](https://code.claude.com/docs/en/agent-view) to monitor and dispatch parallel background sessions. When output is piped, lists configured [subagents](https://code.claude.com/docs/en/sub-agents) instead | `claude agents` |+| `claude attach <id>` | Attach to a [background session](https://code.claude.com/docs/en/agent-view#manage-sessions-from-the-shell) in this terminal | `claude attach 7c5dcf5d` |+| `claude auto-mode defaults` | Print the built-in [auto mode](https://code.claude.com/docs/en/permission-modes#eliminate-prompts-with-auto-mode) classifier rules as JSON. Use `claude auto-mode config` to see your effective config with settings applied | `claude auto-mode defaults > rules.json` |+| `claude logs <id>` | Print recent output from a [background session](https://code.claude.com/docs/en/agent-view#manage-sessions-from-the-shell) | `claude logs 7c5dcf5d` |+| `claude mcp` | Configure Model Context Protocol (MCP) servers | See the [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp). |+| `claude plugin` | Manage Claude Code [plugins](https://code.claude.com/docs/en/plugins). Alias: `claude plugins`. See [plugin reference](https://code.claude.com/docs/en/plugins-reference#cli-commands-reference) for subcommands | `claude plugin install code-review@claude-plugins-official` |+| `claude project purge [path]` | Delete all local Claude Code state for a project: transcripts, task lists, debug logs, file-edit history, prompt history lines, and the project's entry in `~/.claude.json`. Omit `[path]` to pick from an interactive list. Flags: `--dry-run` to preview, `-y`/`--yes` to skip confirmation, `-i`/`--interactive` to confirm each item, `--all` for every project. See [Clear local data](https://code.claude.com/docs/en/claude-directory#clear-local-data) | `claude project purge ~/work/repo --dry-run` |+| `claude remote-control` | Start a [Remote Control](https://code.claude.com/docs/en/remote-control) server to control Claude Code from Claude.ai or the Claude app. Runs in server mode (no local interactive session). See [Server mode flags](https://code.claude.com/docs/en/remote-control#start-a-remote-control-session) | `claude remote-control --name "My Project"` |+| `claude respawn <id>` | Restart a stopped [background session](https://code.claude.com/docs/en/agent-view#manage-sessions-from-the-shell) with its conversation intact. Use `--all` to restart every stopped session | `claude respawn 7c5dcf5d` |+| `claude rm <id>` | Remove a [background session](https://code.claude.com/docs/en/agent-view#manage-sessions-from-the-shell) from the list | `claude rm 7c5dcf5d` |+| `claude setup-token` | Generate a long-lived OAuth token for CI and scripts. Prints the token to the terminal without saving it. Requires a Claude subscription. See [Generate a long-lived token](https://code.claude.com/docs/en/authentication#generate-a-long-lived-token) | `claude setup-token` |+| `claude stop <id>` | Stop a [background session](https://code.claude.com/docs/en/agent-view#manage-sessions-from-the-shell). Also accepts `claude kill` | `claude stop 7c5dcf5d` |+| `claude ultrareview [target]` | Run [ultrareview](https://code.claude.com/docs/en/ultrareview#run-ultrareview-non-interactively) non-interactively. Prints findings to stdout and exits 0 on success or 1 on failure. Use `--json` for the raw payload and `--timeout <minutes>` to override the 30-minute default | `claude ultrareview 1234 --json` |++If you mistype a subcommand, Claude Code suggests the closest match and exits without starting a session. For example, `claude udpate` prints `Did you mean claude update?`.++## CLI flags++Customize Claude Code's behavior with these command-line flags. `claude --help` does not list every flag, so a flag's absence from `--help` does not mean it is unavailable.++| Flag | Description | Example |+| :---------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------- |+| `--add-dir` | Add additional working directories for Claude to read and edit files. Grants file access; most `.claude/` configuration is [not discovered](https://code.claude.com/docs/en/permissions#additional-directories-grant-file-access-not-configuration) from these directories. Validates each path exists as a directory. To persist these directories across sessions, set [`permissions.additionalDirectories`](https://code.claude.com/docs/en/settings#permission-settings) in settings | `claude --add-dir ../apps ../lib` |+| `--agent` | Specify an agent for the current session (overrides the `agent` setting) | `claude --agent my-custom-agent` |+| `--agents` | Define custom subagents dynamically via JSON. Uses the same field names as subagent [frontmatter](https://code.claude.com/docs/en/sub-agents#supported-frontmatter-fields), plus a `prompt` field for the agent's instructions | `claude --agents '{"reviewer":{"description":"Reviews code","prompt":"You are a code reviewer"}}'` |+| `--allow-dangerously-skip-permissions` | Add `bypassPermissions` to the `Shift+Tab` mode cycle without starting in it. Lets you begin in a different mode like `plan` and switch to `bypassPermissions` later. See [permission modes](https://code.claude.com/docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) | `claude --permission-mode plan --allow-dangerously-skip-permissions` |+| `--allowedTools` | Tools that execute without prompting for permission. See [permission rule syntax](https://code.claude.com/docs/en/settings#permission-rule-syntax) for pattern matching. To restrict which tools are available, use `--tools` instead | `"Bash(git log *)" "Bash(git diff *)" "Read"` |+| `--append-system-prompt` | Append custom text to the end of the default system prompt | `claude --append-system-prompt "Always use TypeScript"` |+| `--append-system-prompt-file` | Load additional system prompt text from a file and append to the default prompt | `claude --append-system-prompt-file ./extra-rules.txt` |+| `--bare` | Minimal mode: skip auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md so scripted calls start faster. Claude has access to Bash, file read, and file edit tools. Sets [`CLAUDE_CODE_SIMPLE`](https://code.claude.com/docs/en/env-vars). See [bare mode](https://code.claude.com/docs/en/headless#start-faster-with-bare-mode) | `claude --bare -p "query"` |+| `--betas` | Beta headers to include in API requests (API key users only) | `claude --betas interleaved-thinking` |+| `--bg` | Start the session as a [background agent](https://code.claude.com/docs/en/agent-view) and return immediately. Prints the session ID and management commands. Combine with `--agent` to run a specific subagent | `claude --bg "investigate the flaky test"` |+| `--channels` | (Research preview) MCP servers whose [channel](https://code.claude.com/docs/en/channels) notifications Claude should listen for in this session. Space-separated list of `plugin:<name>@<marketplace>` entries. Requires Claude.ai authentication | `claude --channels plugin:my-notifier@my-marketplace` |+| `--chrome` | Enable [Chrome browser integration](https://code.claude.com/docs/en/chrome) for web automation and testing | `claude --chrome` |+| `--continue`, `-c` | Load the most recent conversation in the current directory. Includes sessions that added this directory with `/add-dir` | `claude --continue` |+| `--dangerously-load-development-channels` | Enable [channels](https://code.claude.com/docs/en/channels-reference#test-during-the-research-preview) that are not on the approved allowlist, for local development. Accepts `plugin:<name>@<marketplace>` and `server:<name>` entries. Prompts for confirmation | `claude --dangerously-load-development-channels server:webhook` |+| `--dangerously-skip-permissions` | Skip permission prompts. Equivalent to `--permission-mode bypassPermissions`. See [permission modes](https://code.claude.com/docs/en/permission-modes#skip-all-checks-with-bypasspermissions-mode) for what this does and does not skip | `claude --dangerously-skip-permissions` |+| `--debug` | Enable debug mode with optional category filtering (for example, `"api,hooks"` or `"!statsig,!file"`) | `claude --debug "api,mcp"` |+| `--debug-file <path>` | Write debug logs to a specific file path. Implicitly enables debug mode. Takes precedence over `CLAUDE_CODE_DEBUG_LOGS_DIR` | `claude --debug-file /tmp/claude-debug.log` |+| `--disable-slash-commands` | Disable all skills and commands for this session | `claude --disable-slash-commands` |+| `--disallowedTools` | Tools that are removed from the model's context and cannot be used | `"Bash(git log *)" "Bash(git diff *)" "Edit"` |+| `--effort` | Set the [effort level](https://code.claude.com/docs/en/model-config#adjust-effort-level) for the current session. Options: `low`, `medium`, `high`, `xhigh`, `max`; available levels depend on the model. Overrides the [`effortLevel`](https://code.claude.com/docs/en/settings#available-settings) setting for this session and does not persist | `claude --effort high` |+| `--enable-auto-mode` | *Removed in v2.1.111* (max-version: 2.1.110). Auto mode is now in the `Shift+Tab` cycle by default; use `--permission-mode auto` to start in it | `claude --permission-mode auto` |+| `--exclude-dynamic-system-prompt-sections` | Move per-machine sections from the system prompt (working directory, environment info, memory paths, git-repo flag) into the first user message. Improves prompt-cache reuse across different users and machines running the same task. Only applies with the default system prompt; ignored when `--system-prompt` or `--system-prompt-file` is set. Use with `-p` for scripted, multi-user workloads | `claude -p --exclude-dynamic-system-prompt-sections "query"` |+| `--fallback-model` | Enable automatic fallback to specified model when default model is overloaded (print mode only) | `claude -p --fallback-model sonnet "query"` |+| `--fork-session` | When resuming, create a new session ID instead of reusing the original (use with `--resume` or `--continue`) | `claude --resume abc123 --fork-session` |+| `--from-pr` | Resume sessions linked to a specific pull request. Accepts a PR number, a GitHub or GitHub Enterprise PR URL, a GitLab merge request URL, or a Bitbucket pull request URL. Sessions are linked automatically when Claude creates the pull request | `claude --from-pr 123` |+| `--ide` | Automatically connect to IDE on startup if exactly one valid IDE is available | `claude --ide` |+| `--init` | Run [Setup hooks](https://code.claude.com/docs/en/hooks#setup) with the `init` matcher before the session (print mode only) | `claude -p --init "query"` |+| `--init-only` | Run [Setup](https://code.claude.com/docs/en/hooks#setup) and `SessionStart` hooks, then exit without starting a conversation | `claude --init-only` |+| `--include-hook-events` | Include all hook lifecycle events in the output stream. Requires `--output-format stream-json` | `claude -p --output-format stream-json --include-hook-events "query"` |+| `--include-partial-messages` | Include partial streaming events in output. Requires `--print` and `--output-format stream-json` | `claude -p --output-format stream-json --include-partial-messages "query"` |+| `--input-format` | Specify input format for print mode (options: `text`, `stream-json`) | `claude -p --output-format json --input-format stream-json` |+| `--json-schema` | Get validated JSON output matching a JSON Schema after agent completes its workflow (print mode only, see [structured outputs](https://code.claude.com/docs/en/agent-sdk/structured-outputs)) | `claude -p --json-schema '{"type":"object","properties":{...}}' "query"` |+| `--maintenance` | Run [Setup hooks](https://code.claude.com/docs/en/hooks#setup) with the `maintenance` matcher before the session (print mode only) | `claude -p --maintenance "query"` |+| `--max-budget-usd` | Maximum dollar amount to spend on API calls before stopping (print mode only) | `claude -p --max-budget-usd 5.00 "query"` |+| `--max-turns` | Limit the number of agentic turns (print mode only). Exits with an error when the limit is reached. No limit by default | `claude -p --max-turns 3 "query"` |+| `--mcp-config` | Load MCP servers from JSON files or strings (space-separated) | `claude --mcp-config ./mcp.json` |+| `--model` | Sets the model for the current session with an alias for the latest model (`sonnet` or `opus`) or a model's full name. Overrides the [`model`](https://code.claude.com/docs/en/settings#available-settings) setting and [`ANTHROPIC_MODEL`](https://code.claude.com/docs/en/model-config#environment-variables) | `claude --model claude-sonnet-4-6` |+| `--name`, `-n` | Set a display name for the session, shown in `/resume` and the terminal title. You can resume a named session with `claude --resume <name>`. [`/rename`](https://code.claude.com/docs/en/commands) changes the name mid-session and also shows it on the prompt bar | `claude -n "my-feature-work"` |+| `--no-chrome` | Disable [Chrome browser integration](https://code.claude.com/docs/en/chrome) for this session | `claude --no-chrome` |+| `--no-session-persistence` | Disable session persistence so sessions are not saved to disk and cannot be resumed. Print mode only. The [`CLAUDE_CODE_SKIP_PROMPT_HISTORY`](https://code.claude.com/docs/en/env-vars) environment variable does the same in any mode | `claude -p --no-session-persistence "query"` |+| `--output-format` | Specify output format for print mode (options: `text`, `json`, `stream-json`) | `claude -p "query" --output-format json` |+| `--permission-mode` | Begin in a specified [permission mode](https://code.claude.com/docs/en/permission-modes). Accepts `default`, `acceptEdits`, `plan`, `auto`, `dontAsk`, or `bypassPermissions`. Overrides `defaultMode` from settings files | `claude --permission-mode plan` |+| `--permission-prompt-tool` | Specify an MCP tool to handle permission prompts in non-interactive mode | `claude -p --permission-prompt-tool mcp_auth_tool "query"` |+| `--plugin-dir` | Load a plugin from a directory or `.zip` archive for this session only. Each flag takes one path. Repeat the flag for multiple plugins: `--plugin-dir A --plugin-dir B.zip` | `claude --plugin-dir ./my-plugin` |+| `--plugin-url` | Fetch a plugin `.zip` archive from a URL for this session only. Repeat the flag for multiple plugins, or pass space-separated URLs in a single quoted value | `claude --plugin-url https://example.com/plugin.zip` |+| `--print`, `-p` | Print response without interactive mode (see [Agent SDK documentation](https://code.claude.com/docs/en/agent-sdk/overview) for programmatic usage details) | `claude -p "query"` |+| `--remote` | Create a new [web session](https://code.claude.com/docs/en/claude-code-on-the-web) on claude.ai with the provided task description | `claude --remote "Fix the login bug"` |+| `--remote-control`, `--rc` | Start an interactive session with [Remote Control](https://code.claude.com/docs/en/remote-control#start-a-remote-control-session) enabled so you can also control it from claude.ai or the Claude app. Optionally pass a name for the session | `claude --remote-control "My Project"` |+| `--remote-control-session-name-prefix <prefix>` | Prefix for auto-generated [Remote Control](https://code.claude.com/docs/en/remote-control) session names when no explicit name is set. Defaults to your machine's hostname, producing names like `myhost-graceful-unicorn`. Set `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` for the same effect | `claude remote-control --remote-control-session-name-prefix dev-box` |+| `--replay-user-messages` | Re-emit user messages from stdin back on stdout for acknowledgment. Requires `--input-format stream-json` and `--output-format stream-json` | `claude -p --input-format stream-json --output-format stream-json --replay-user-messages` |+| `--resume`, `-r` | Resume a specific session by ID or name, or show an interactive picker to choose a session. Includes sessions that added this directory with `/add-dir` | `claude --resume auth-refactor` |+| `--session-id` | Use a specific session ID for the conversation (must be a valid UUID) | `claude --session-id "550e8400-e29b-41d4-a716-446655440000"` |+| `--setting-sources` | Comma-separated list of setting sources to load (`user`, `project`, `local`) | `claude --setting-sources user,project` |+| `--settings` | Path to a settings JSON file or an inline JSON string. Values you set here override the same keys in your `settings.json` files for this session. Keys you omit keep their file-based values. See [settings precedence](https://code.claude.com/docs/en/settings#settings-precedence) | `claude --settings ./settings.json` |+| `--strict-mcp-config` | Only use MCP servers from `--mcp-config`, ignoring all other MCP configurations | `claude --strict-mcp-config --mcp-config ./mcp.json` |+| `--system-prompt` | Replace the entire system prompt with custom text | `claude --system-prompt "You are a Python expert"` |+| `--system-prompt-file` | Load system prompt from a file, replacing the default prompt | `claude --system-prompt-file ./custom-prompt.txt` |+| `--teleport` | Resume a [web session](https://code.claude.com/docs/en/claude-code-on-the-web) in your local terminal | `claude --teleport` |+| `--teammate-mode` | Set how [agent team](https://code.claude.com/docs/en/agent-teams) teammates display: `auto` (default), `in-process`, or `tmux`. Overrides the [`teammateMode`](https://code.claude.com/docs/en/settings#available-settings) setting for this session. See [Choose a display mode](https://code.claude.com/docs/en/agent-teams#choose-a-display-mode) | `claude --teammate-mode in-process` |+| `--tmux` | Create a tmux session for the worktree. Requires `--worktree`. Uses iTerm2 native panes when available; pass `--tmux=classic` for traditional tmux | `claude -w feature-auth --tmux` |+| `--tools` | Restrict which built-in tools Claude can use. Use `""` to disable all, `"default"` for all, or tool names like `"Bash,Edit,Read"` | `claude --tools "Bash,Edit,Read"` |+| `--verbose` | Enable verbose logging, shows full turn-by-turn output. Overrides the [`viewMode`](https://code.claude.com/docs/en/settings#available-settings) setting for this session | `claude --verbose` |+| `--version`, `-v` | Output the version number | `claude -v` |+| `--worktree`, `-w` | Start Claude in an isolated [git worktree](https://code.claude.com/docs/en/worktrees) at `<repo>/.claude/worktrees/<name>`. If no name is given, one is auto-generated. Pass `#<number>` or a GitHub pull request URL to fetch that PR from `origin` and branch the worktree from it | `claude -w feature-auth` |++### System prompt flags++Claude Code provides four flags for customizing the system prompt. All four work in both interactive and non-interactive modes.++| Flag | Behavior | Example |+| :---------------------------- | :------------------------------------------ | :------------------------------------------------------ |+| `--system-prompt` | Replaces the entire default prompt | `claude --system-prompt "You are a Python expert"` |+| `--system-prompt-file` | Replaces with file contents | `claude --system-prompt-file ./prompts/review.txt` |+| `--append-system-prompt` | Appends to the default prompt | `claude --append-system-prompt "Always use TypeScript"` |+| `--append-system-prompt-file` | Appends file contents to the default prompt | `claude --append-system-prompt-file ./style-rules.txt` |++`--system-prompt` and `--system-prompt-file` are mutually exclusive. The append flags can be combined with either replacement flag.++Choose based on whether Claude Code's default identity still fits your task. Use an append flag when Claude should remain a coding assistant that also follows your extra rules: per-invocation instructions, output formatting, or domain context for a `-p` script. Appending preserves the default tool guidance, safety instructions, and coding conventions, so you only supply what differs. Use a replacement flag when the surface, identity, or permission model differs from Claude Code's, like a non-coding agent in a pipeline that no human watches. Replacing drops all of the default prompt, including tool guidance and safety instructions, so you take responsibility for whatever your task still needs.++These flags apply only to the current invocation. For persistent personas you can switch between and share across a project, use [output styles](https://code.claude.com/docs/en/output-styles). For project conventions Claude should always follow, use [CLAUDE.md](https://code.claude.com/docs/en/memory). The [Agent SDK guide on system prompts](https://code.claude.com/docs/en/agent-sdk/modifying-system-prompts#decide-on-a-starting-point) covers the same decision in more depth.++## See also++* [Chrome extension](https://code.claude.com/docs/en/chrome) — Browser automation and web testing+* [Interactive mode](https://code.claude.com/docs/en/interactive-mode) — Shortcuts, input modes, and interactive features+* [Quickstart guide](https://code.claude.com/docs/en/quickstart) — Getting started with Claude Code+* [Common workflows](https://code.claude.com/docs/en/common-workflows) — Advanced workflows and patterns+* [Settings](https://code.claude.com/docs/en/settings) — Configuration options+* [Agent SDK documentation](https://code.claude.com/docs/en/agent-sdk/overview) — Programmatic usage and integrations++---++## Out-of-scope on this page++The official `cli-reference` page does NOT cover the following — they+live on separate doc pages:++- **Slash commands** (`/add-dir`, `/agents`, `/bug`, `/clear`,+ `/compact`, `/config`, `/cost`, `/doctor`, `/help`, `/init`,+ `/login`, `/logout`, `/mcp`, `/memory`, `/model`, `/permissions`,+ `/pr-comments`, `/release-notes`, `/review`, `/status`,+ `/terminal-setup`, `/vim`, etc.) — see+ [code.claude.com/docs/en/commands](https://code.claude.com/docs/en/commands)+- **Environment variables** (`ANTHROPIC_API_KEY`, `CLAUDE_CONFIG_DIR`,+ `ENABLE_TOOL_SEARCH`, `MAX_MCP_OUTPUT_TOKENS`, ...) — see+ [code.claude.com/docs/en/env-vars](https://code.claude.com/docs/en/env-vars)+- **Permission modes detail** (`default`, `acceptEdits`, `plan`,+ `auto`, `dontAsk`, `bypassPermissions`) — see+ [code.claude.com/docs/en/permission-modes](https://code.claude.com/docs/en/permission-modes)+- **Output formats** beyond the one-liner in the flag table — see+ [code.claude.com/docs/en/headless](https://code.claude.com/docs/en/headless)+ and [code.claude.com/docs/en/agent-sdk/overview](https://code.claude.com/docs/en/agent-sdk/overview)+- **Interactive-mode shortcuts** (Vim mode, keyboard shortcuts) —+ see [code.claude.com/docs/en/interactive-mode](https://code.claude.com/docs/en/interactive-mode)+- **MCP server configuration** — see+ [code.claude.com/docs/en/mcp](https://code.claude.com/docs/en/mcp)+- **Setup / install / specific versions** — see+ [code.claude.com/docs/en/setup](https://code.claude.com/docs/en/setup)++If a separate snapshot of any of these pages would help, fetch and+add an analogous `claude_code_*_reference.md` file.++## Flags we use in `services/cli_agent/`++Quick cross-reference for the MachinaOs `claude_code_agent` integration:++| Flag | Used in | Purpose |+|---|---|---|+| `--output-format stream-json` | always | NDJSON event stream parsed by `session.py:_consume_stdout` |+| `--verbose` | always | required when `--output-format stream-json` is set with `--print` |+| `--include-partial-messages` | always | surface streaming deltas to the Terminal panel |+| `--include-hook-events` | always | surface `SessionStart` / hook events into the stream |+| `--print`, `-p` | always | one-shot non-interactive query |+| `--model <id>` | always | from `ClaudeTaskSpec.model` / config default |+| `--max-turns <N>` | always | from `ClaudeTaskSpec.max_turns` |+| `--permission-mode <mode>` | always | default `acceptEdits` |+| `--allowedTools <csv>` | always | `Read,Edit,Bash,Glob,Grep,Write,Skill,WebSearch,WebFetch,mcp__machinaos__*` (see canonical patterns RFC §5 R3) |+| `--mcp-config <json>` | when MCP wired | inline JSON with `{mcpServers: {machinaos: {type: http, url, headers, alwaysLoad: true}}}` |+| `--strict-mcp-config` | when MCP wired | blocks user-level `~/.claude.json` MCP entries |+| `--append-system-prompt <text>` | when system_prompt or connected tools wired | per-task system prompt + connected-tools steering directive |+| `--session-id <UUID>` | memory bridge first run | deterministic `uuid5(memory_node_id, session_id)` |+| `--resume <UUID>` | memory bridge subsequent runs | `simpleMemory.last_session_id` saved by `_persist_memory` |+| `--max-budget-usd <USD>` | when `ClaudeTaskSpec.max_budget_usd > 0` | cost cap per task |+| `--effort <level>` | optional per-task override | reasoning effort |+| `--fallback-model <id>` | optional per-task override | fallback when default model is overloaded |+| `--add-dir <path>*` | optional per-task override | grant extra working dirs |+| `--disallowedTools <csv>` | optional per-task override | remove tools from context |+| `--agent <name>` | optional per-task override | use a specific subagent |++See [`services/cli_agent/providers/anthropic_claude.py:headless_argv`](../server/services/cli_agent/providers/anthropic_claude.py) for the argv-construction code.diff --git a/docs-internal/claude_code_env_vars_reference.md b/docs-internal/claude_code_env_vars_reference.mdnew file mode 100644index 00000000..3f13fd03--- /dev/null+++ b/docs-internal/claude_code_env_vars_reference.md@@ -0,0 +1,149 @@+# Claude Code environment variables reference (snapshot)++> **Source:** [code.claude.com/docs/en/env-vars](https://code.claude.com/docs/en/env-vars)+> **Fetched:** 2026-05-11+> **Note:** the upstream page was returned partially-truncated by the fetcher;+> the categories below cover what was visible. Refetch when adding a new env+> var to verify the full list. The companion CLI reference is+> [`claude_code_cli_reference.md`](./claude_code_cli_reference.md).++This is the set of environment variables Claude Code reads at startup. Where+relevant we annotate which ones MachinaOs's `services/cli_agent/` framework+sets or relies on.++## Authentication & API configuration++| Variable | Purpose |+|---|---|+| `ANTHROPIC_API_KEY` | API key sent as `X-Api-Key` header. |+| `ANTHROPIC_AUTH_TOKEN` | Custom `Authorization` header value (prefixed with `Bearer`). |+| `ANTHROPIC_AWS_API_KEY` | Workspace API key for Claude Platform on AWS. |+| `ANTHROPIC_AWS_BASE_URL` | Override Claude Platform on AWS endpoint URL. |+| `ANTHROPIC_AWS_WORKSPACE_ID` | Required workspace ID for AWS (sent as header). |+| `ANTHROPIC_BASE_URL` | Override API endpoint (proxy / gateway routing). |+| `ANTHROPIC_CUSTOM_HEADERS` | Custom headers in `Name: Value` format. |++## Bedrock & Vertex++| Variable | Purpose |+|---|---|+| `ANTHROPIC_BEDROCK_BASE_URL` | Override Bedrock endpoint URL. |+| `ANTHROPIC_BEDROCK_MANTLE_BASE_URL` | Override Bedrock Mantle endpoint URL. |+| `ANTHROPIC_BEDROCK_SERVICE_TIER` | Bedrock service tier (`default`, `flex`, `priority`). |+| `ANTHROPIC_VERTEX_BASE_URL` | Override Vertex AI endpoint URL. |+| `ANTHROPIC_VERTEX_PROJECT_ID` | GCP project ID for Vertex AI. |+| `CLAUDE_CODE_USE_BEDROCK` | Route requests through Bedrock. |+| `CLAUDE_CODE_USE_VERTEX` | Route requests through Vertex. |++## Model configuration++| Variable | Purpose |+|---|---|+| `ANTHROPIC_MODEL` | Name of model setting to use. |+| `ANTHROPIC_SMALL_FAST_MODEL` | Override the small fast model. |+| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | Custom Haiku model ID. |+| `ANTHROPIC_DEFAULT_SONNET_MODEL` | Custom Sonnet model ID. |+| `ANTHROPIC_DEFAULT_OPUS_MODEL` | Custom Opus model ID. |+| `ANTHROPIC_CUSTOM_MODEL_OPTION` | Add custom model to `/model` picker. |+| `ANTHROPIC_CUSTOM_MODEL_OPTION_NAME` | Display name for custom model. |+| `ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION` | Display description for custom model. |+| `CLAUDE_CODE_SUBAGENT_MODEL` | Model used by subagents. |++## Bash tool++| Variable | Purpose |+|---|---|+| `BASH_DEFAULT_TIMEOUT_MS` | Default timeout for long-running bash commands. Default: `120000` (2 min). |+| `BASH_MAX_OUTPUT_LENGTH` | Max characters in bash output before output is saved to a file. |+| `BASH_MAX_TIMEOUT_MS` | Maximum timeout the model can set. Default: `600000` (10 min). |++## MCP integration++| Variable | Purpose |+|---|---|+| `MCP_TIMEOUT` | MCP server connect timeout. |+| `MCP_TOOL_TIMEOUT` | Per-tool-call timeout. |+| `MAX_MCP_OUTPUT_TOKENS` | Per-tool output ceiling. Default `25000`; warn at `10000`. **Relevant for MachinaOs** — workflow tools that return large blobs (browser screenshots, file contents) silently hit this. See [`cli_agent_canonical_patterns_rfc.md` §2.9](./cli_agent_canonical_patterns_rfc.md). |+| `ENABLE_TOOL_SEARCH` | Tool deferral control: `true` (default, defer all MCP tools, agent calls `ToolSearch`), `false` (load all upfront), `auto` (load if all fit in 10 % of context), `auto:<N>` (custom %). **MachinaOs sidesteps this** by setting `"alwaysLoad": true` on the `machinaos` mcp-config entry instead — see canonical patterns RFC §2.4 / R2. Requires Sonnet 4 / Opus 4 or later; Haiku has no tool search. |++## Telemetry & disable flags++| Variable | Purpose |+|---|---|+| `DISABLE_TELEMETRY` | Disable telemetry collection. |+| `DISABLE_ERROR_REPORTING` | Disable error reporting. |+| `DISABLE_AUTOUPDATER` | Disable automatic updates. |+| `DO_NOT_TRACK` | Standard opt-out signal. |+| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Equivalent to setting multiple disable variables. |+| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enable OpenTelemetry data collection. |+| `DISABLE_BUG_COMMAND` | Disable the `/bug` command. |+| `DISABLE_COST_WARNINGS` | Suppress cost-warning prompts. |+| `DISABLE_NON_ESSENTIAL_MODEL_CALLS` | Skip non-essential model calls (e.g. naming heuristics). |++## Feature disables / behaviour++| Variable | Purpose |+|---|---|+| `CLAUDE_CODE_DISABLE_AGENT_VIEW` | Disable background agents and agent view. |+| `CLAUDE_CODE_DISABLE_ATTACHMENTS` | Disable attachment processing. |+| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | Disable auto memory creation/loading. |+| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | Disable all background task functionality. |+| `CLAUDE_CODE_DISABLE_CRON` | Disable scheduled tasks. |+| `CLAUDE_CODE_DISABLE_FAST_MODE` | Disable fast mode. |+| `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | Disable session-quality surveys. |+| `CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING` | Disable `/rewind` functionality. |+| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | Don't update the terminal title. |+| `CLAUDE_CODE_DISABLE_THINKING` | Force-disable extended thinking. |+| `CLAUDE_CODE_ENABLE_TASKS` | Enable task tracking in non-interactive mode. |+| `CLAUDE_CODE_EFFORT_LEVEL` | Effort level (`low`, `medium`, `high`, `xhigh`, `max`, `auto`). |+| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Maximum output tokens for requests. |+| `CLAUDE_CODE_MAX_RETRIES` | Retries for failed API requests. Default: `10`. |+| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | How long the API-key helper output is cached. |+| `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL` | Skip auto-install of the IDE extension. |+| `CLAUDE_CODE_SIMPLE` | Sets bare mode (see `--bare`). |+| `CLAUDE_CODE_SKIP_PROMPT_HISTORY` | Don't persist sessions. Same effect as `--no-session-persistence` in any mode. |+| `ENABLE_BACKGROUND_TASKS` | Enable background-task functionality. |+| `MAX_THINKING_TOKENS` | Cap on extended-thinking tokens per turn. |+| `USE_BUILTIN_RIPGREP` | Use the bundled ripgrep binary instead of system rg. |++## Session & debug++| Variable | Purpose |+|---|---|+| `CLAUDE_CODE_SESSION_ID` | Automatically set to current session ID. |+| `CLAUDE_CODE_REMOTE_SESSION_ID` | Set in cloud sessions to current session ID. |+| `CLAUDE_CODE_DEBUG_LOGS_DIR` | Override debug log file path. |+| `CLAUDE_CODE_DEBUG_LOG_LEVEL` | Minimum log level (`verbose`, `debug`, `info`, `warn`, `error`). |++## Config & paths++| Variable | Purpose |+|---|---|+| `CLAUDE_CONFIG_DIR` | Override the root config directory. Defaults to `~/.claude/`. **MachinaOs sets this** to `<repo>/data/claude-machina` so credentials are project-local — see `services/claude_oauth.py:MACHINA_CLAUDE_DIR`. This is the directory under which claude's session JSONL lives at `<CLAUDE_CONFIG_DIR>/projects/<project_key>/<session_id>.jsonl`. |+| `CLAUDE_REMOTE_CONTROL_SESSION_NAME_PREFIX` | Default prefix for auto-generated Remote Control session names. |++## Timeouts++| Variable | Purpose |+|---|---|+| `API_TIMEOUT_MS` | API request timeout. Default: `600000` (10 min). |+| `CLAUDE_ASYNC_AGENT_STALL_TIMEOUT_MS` | Stall timeout for background subagents. Default: `600000`. |++## Proxy++| Variable | Purpose |+|---|---|+| `HTTP_PROXY` / `HTTPS_PROXY` | Standard proxy env vars; respected by the CLI. |++---++## Env vars MachinaOs explicitly sets on the spawn env++From [`services/cli_agent/session.py:env()`](../server/services/cli_agent/session.py):++| Variable | Set to | Reason |+|---|---|---|+| `PYTHONUNBUFFERED` | `1` | Line-buffered output (we parse stream-json line by line). |+| `CLAUDE_CONFIG_DIR` | `MACHINA_CLAUDE_DIR` (claude provider only) | Project-local credential isolation; also where claude writes its session JSONL — load-bearing for the memory bridge (`<key>/projects/<cwd-encoded>/<session_id>.jsonl`). |+| `<provider.ide_lock_env_var>` | path to per-spawn lockfile | VSCode-style IDE auto-discovery. |+| `MACHINA_PARENT_RUN_ID` | `<workflow_id>:<node_id>:<batch_token[:8]>` | Composio-style parent-run-id for MCP correlation. |diff --git a/docs-internal/claude_code_headless_reference.md b/docs-internal/claude_code_headless_reference.mdnew file mode 100644index 00000000..1626a752--- /dev/null+++ b/docs-internal/claude_code_headless_reference.md@@ -0,0 +1,292 @@+# Claude Code headless / print-mode reference (verbatim snapshot)++> **Source:** [code.claude.com/docs/en/headless](https://code.claude.com/docs/en/headless)+> **Fetched:** 2026-05-11+> **Why this lives in-repo:** MachinaOs spawns `claude -p` via+> `services/cli_agent/`. The argv flags this doc describes+> (`--output-format stream-json`, `--include-partial-messages`,+> `--include-hook-events`, `--max-budget-usd`, `--max-turns`,+> `--bare`) and the stream-json event schema it documents are+> load-bearing for our session parser.++---++# Run Claude Code programmatically++> Use the Agent SDK to run Claude Code programmatically from the CLI, Python, or TypeScript.++The Agent SDK 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 and TypeScript packages for full programmatic control.++> **Note:** 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:++```bash+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.++## Basic usage++Add the `-p` (or `--print`) flag to any `claude` command to run it non-interactively. All CLI options 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:++```bash+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 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:++```bash+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 | `--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.++> **Note:** `--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.++### 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:++```bash+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.++> **Note:** As of Claude Code v2.1.128, piped stdin is capped at 10 MB. 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.++### 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:++```json+{+ "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.\""+ }+}+```++### 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:++```bash+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 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:++```bash+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"]}'+```++> **Tip:** Use a tool like jq to parse the response and extract specific fields:+>+> ```bash+> # 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:++```bash+claude -p "Explain recursion" --output-format stream-json --verbose --include-partial-messages+```++The following example uses 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:++```bash+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'+```++### Stream-json event types++#### `system/api_retry`++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`, `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 |++#### `system/init`++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` 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, 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 |++#### `system/plugin_install`++When `CLAUDE_CODE_SYNC_PLUGIN_INSTALL` 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* 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:++```bash+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. `dontAsk` denies anything not in your `permissions.allow` rules or the read-only command set, 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:++```bash+claude -p "Apply the lint fixes" --permission-mode acceptEdits+```++### Create a commit++This example reviews staged changes and creates a commit with an appropriate message:++```bash+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. 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`.++> **Note:** User-invoked skills like `/commit` and built-in 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:++```bash+gh pr diff "$1" | claude -p \+ --append-system-prompt "You are a security engineer. Review for vulnerabilities." \+ --output-format json+```++See *system prompt flags* in the CLI reference 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:++```bash+# 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:++```bash+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: build your first agent with Python or TypeScript+* CLI reference: all CLI flags and options — see [`claude_code_cli_reference.md`](./claude_code_cli_reference.md)+* GitHub Actions: use the Agent SDK in GitHub workflows+* GitLab CI/CD: use the Agent SDK in GitLab pipelines++---++## What MachinaOs reads from this stream++`services/cli_agent/session.py:_consume_stdout` parses every line of+`--output-format stream-json` output. The event types we touch:++| Event | What we do with it |+|---|---|+| `type: "system"` `subtype: "init"` | Log tools count + mcp_servers list. First evidence the spawn is healthy. |+| `type: "assistant"` `content: [text]` | Log a 300-char preview as `[CC-Agent stream] assistant.text`. |+| `type: "assistant"` `content: [tool_use]` | Log tool name + input keys as `assistant->tool_use`. |+| `type: "tool_use"` (top-level) | Log name + input keys. |+| `type: "tool_result"` | Log `is_error` + 300-char content preview. |+| `type: "hook"` | Log hook event name (requires `--include-hook-events`). |+| `type: "result"` | Final summary — drives `SessionResult` (`session_id`, `total_cost_usd`, `duration_ms`, `num_turns`, `usage`). |++`--include-partial-messages` surfaces deltas to the Terminal panel via+`broadcast_terminal_log`; we don't aggregate them into messages+because the `result` event carries the final response anyway.++`--max-budget-usd` is set from `ClaudeTaskSpec.max_budget_usd` (default+`5.0` USD) so we cap per-task spend.++`--max-turns` is set from `ClaudeTaskSpec.max_turns` (default `10`).++We do NOT use `--bare` — auto-discovery of hooks/skills/MCP/auto-memory+is what makes the workflow-tool bridge work. CI use cases that want+deterministic startup can flip it on per task in the future.diff --git a/docs-internal/claude_code_permission_modes_reference.md b/docs-internal/claude_code_permission_modes_reference.mdnew file mode 100644index 00000000..1abaa381--- /dev/null+++ b/docs-internal/claude_code_permission_modes_reference.md@@ -0,0 +1,290 @@+# Claude Code permission modes reference (verbatim snapshot)++> **Source:** [code.claude.com/docs/en/permission-modes](https://code.claude.com/docs/en/permission-modes)+> **Fetched:** 2026-05-11+> **Why this lives in-repo:** MachinaOs's claude_code_agent defaults to+> `--permission-mode acceptEdits` and exposes the full enum+> (`default`, `acceptEdits`, `plan`, `auto`, `dontAsk`,+> `bypassPermissions`) on `ClaudeTaskSpec.permission_mode`. See+> `services/cli_agent/types.py` and+> `services/cli_agent/providers/anthropic_claude.py:headless_argv`.++---++# Choose a permission mode++> Control whether Claude asks before editing files or running commands. Cycle modes with Shift+Tab in the CLI or use the mode selector in VS Code, Desktop, and claude.ai.++When Claude wants to edit a file, run a shell command, or make a network request, it pauses and asks you to approve the action. Permission modes control how often that pause happens. The mode you pick shapes the flow of a session: default mode has you review each action as it comes, while looser modes let Claude work in longer uninterrupted stretches and report back when done. Pick more oversight for sensitive work, or fewer interruptions when you trust the direction.++## Available modes++Each mode makes a different tradeoff between convenience and oversight. The table below shows what Claude can do without a permission prompt in each mode.++| Mode | What runs without asking | Best for |+| :------------------------------------------------------------------ | :------------------------------------------------------------------------------------- | :-------------------------------------- |+| `default` | Reads only | Getting started, sensitive work |+| `acceptEdits` | Reads, file edits, and common filesystem commands (`mkdir`, `touch`, `mv`, `cp`, etc.) | Iterating on code you're reviewing |+| `plan` | Reads only | Exploring a codebase before changing it |+| `auto` | Everything, with background safety checks | Long tasks, reducing prompt fatigue |+| `dontAsk` | Only pre-approved tools | Locked-down CI and scripts |+| `bypassPermissions` | Everything | Isolated containers and VMs only |++In every mode except `bypassPermissions`, writes to protected paths are never auto-approved, guarding repository state and Claude's own configuration against accidental corruption.++Modes set the baseline. Layer permission rules on top to pre-approve or block specific tools in any mode except `bypassPermissions`, which skips the permission layer entirely.++## Switch permission modes++You can switch modes mid-session, at startup, or as a persistent default. The mode is set through these controls, not by asking Claude in chat.++### CLI++**During a session:** press `Shift+Tab` to cycle `default` → `acceptEdits` → `plan`. The current mode appears in the status bar. Not every mode is in the default cycle:++* `auto`: appears when your account meets the auto-mode requirements; cycling to auto shows an opt-in prompt until you accept it, or select **No, don't ask again** to remove auto from the cycle.+* `bypassPermissions`: appears after you start with `--permission-mode bypassPermissions`, `--dangerously-skip-permissions`, or `--allow-dangerously-skip-permissions`; the `--allow-` variant adds the mode to the cycle without activating it.+* `dontAsk`: never appears in the cycle; set it with `--permission-mode dontAsk`.++Enabled optional modes slot in after `plan`, with `bypassPermissions` first and `auto` last. If you have both enabled, you will cycle through `bypassPermissions` on the way to `auto`.++**At startup:** pass the mode as a flag.++```bash+claude --permission-mode plan+```++**As a default:** set `defaultMode` in settings.++```json+{+ "permissions": {+ "defaultMode": "acceptEdits"+ }+}+```++The same `--permission-mode` flag works with `-p` for non-interactive runs.++### VS Code / JetBrains / Desktop / Web++See the upstream page for IDE-specific UI controls. In Remote Control sessions on the user's local machine the available modes are Ask permissions, Auto accept edits, and Plan mode (Auto and Bypass not available). In cloud claude.ai/code sessions only Auto accept edits and Plan mode are available.++## Auto-approve file edits with `acceptEdits` mode++`acceptEdits` mode lets Claude create and edit files in your working directory without prompting. The status bar shows `⏵⏵ accept edits on` while this mode is active.++In addition to file edits, `acceptEdits` mode auto-approves common filesystem Bash commands: `mkdir`, `touch`, `rm`, `rmdir`, `mv`, `cp`, and `sed`. These commands are also auto-approved when prefixed with safe environment variables such as `LANG=C` or `NO_COLOR=1`, or process wrappers such as `timeout`, `nice`, or `nohup`. Like file edits, auto-approval applies only to paths inside your working directory or `additionalDirectories`. Paths outside that scope, writes to protected paths, and all other Bash commands still prompt.++When the PowerShell tool is enabled, `acceptEdits` mode also auto-approves `Set-Content`, `Add-Content`, `Clear-Content`, and `Remove-Item` on in-scope paths, along with their common aliases. The same scope and protected-path rules apply.++Use `acceptEdits` when you want to review changes in your editor or via `git diff` after the fact rather than approving each edit inline. Press `Shift+Tab` once from default mode to enter it, or start with it directly:++```bash+claude --permission-mode acceptEdits+```++## Analyze before you edit with `plan` mode++Plan mode tells Claude to research and propose changes without making them. Claude reads files, runs shell commands to explore, and writes a plan, but does not edit your source. Permission prompts still apply the same as default mode.++Enter plan mode by pressing `Shift+Tab` or prefixing a single prompt with `/plan`. You can also start in plan mode from the CLI:++```bash+claude --permission-mode plan+```++Press `Shift+Tab` again to leave plan mode without approving a plan.++### Review and approve a plan++When the plan is ready, Claude presents it and asks how to proceed. From that prompt you can:++* Approve and start in auto mode+* Approve and accept edits+* Approve and review each edit manually+* Keep planning with feedback+* Refine with Ultraplan for browser-based review++Approving a plan exits plan mode and switches the session to the permission mode each approve option describes, so Claude starts editing. To plan again, cycle back to plan mode with `Shift+Tab`, or prefix your next prompt with `/plan`.++Press `Ctrl+G` to open the proposed plan in your default text editor and edit it directly before Claude proceeds. When `showClearContextOnPlanAccept` is enabled, each approve option also offers to clear the planning context first.++Accepting a plan also names the session from the plan content automatically, unless you've already set a name with `--name` or `/rename`.++### Set plan mode as the default++To make plan mode the default for a project, set `defaultMode` in `.claude/settings.json`:++```json+{+ "permissions": {+ "defaultMode": "plan"+ }+}+```++## Eliminate prompts with `auto` mode++> **Note:** Auto mode requires Claude Code v2.1.83 or later.++Auto mode lets Claude execute without permission prompts. A separate classifier model reviews actions before they run, blocking anything that escalates beyond your request, targets unrecognized infrastructure, or appears driven by hostile content Claude read.++Auto mode also instructs Claude to execute immediately and minimize clarifying questions. To get that behavior while keeping permission prompts, set the Proactive output style instead.++> **Warning:** Auto mode is a research preview. It reduces prompts but does not guarantee safety. Use it for tasks where you trust the general direction, not as a replacement for review on sensitive operations.++Auto mode is available only when your account meets all of these requirements:++* **Plan**: Max, Team, Enterprise, or API. Not available on Pro.+* **Admin**: on Team and Enterprise, an admin must enable it in Claude Code admin settings before users can turn it on. Admins can also lock it off by setting `permissions.disableAutoMode` to `"disable"` in managed settings.+* **Model**: Claude Sonnet 4.6, Opus 4.6, or Opus 4.7 on Team, Enterprise, and API plans; Claude Opus 4.7 only on Max plans. Other models, including Haiku and claude-3 models, are not supported.+* **Provider**: Anthropic API only. Not available on Bedrock, Vertex, or Foundry.++If Claude Code reports auto mode as unavailable, one of these requirements is unmet; this is not a transient outage. A separate message that names a model and says auto mode "cannot determine the safety" of an action is a transient classifier outage.++### What the classifier blocks by default++The classifier trusts your working directory and your repo's configured remotes. Everything else is treated as external until you configure trusted infrastructure.++**Blocked by default:**++* Downloading and executing code, like `curl | bash`+* Sending sensitive data to external endpoints+* Production deploys and migrations+* Mass deletion on cloud storage+* Granting IAM or repo permissions+* Modifying shared infrastructure+* Irreversibly destroying files that existed before the session+* Force push, or pushing directly to `main`++**Allowed by default:**++* Local file operations in your working directory+* Installing dependencies declared in your lock files or manifests+* Reading `.env` and sending credentials to their matching API+* Read-only HTTP requests+* Pushing to the branch you started on or one Claude created++Sandbox network access requests are routed through the classifier rather than allowed by default. Run `claude auto-mode defaults` to see the full rule lists.++### Boundaries you state in conversation++The classifier treats boundaries you state in the conversation as a block signal. If you tell Claude "don't push" or "wait until I review before deploying", the classifier blocks matching actions even when the default rules would allow them. A boundary stays in force until you lift it in a later message. Claude's own judgment that a condition was met does not lift it.++Boundaries are not stored as rules. The classifier re-reads them from the transcript on each check, so a boundary can be lost if context compaction removes the message that stated it. For a hard guarantee, add a deny rule instead.++### When auto mode falls back++Each denied action shows a notification and appears in `/permissions` under the Recently denied tab, where you can press `r` to retry it with a manual approval.++If the classifier blocks an action 3 times in a row or 20 times total, auto mode pauses and Claude Code resumes prompting. Approving the prompted action resumes auto mode. These thresholds are not configurable. Any allowed action resets the consecutive counter, while the total counter persists for the session and resets only when its own limit triggers a fallback.++In non-interactive mode with the `-p` flag, repeated blocks abort the session since there is no user to prompt.++Repeated blocks usually mean the classifier is missing context about your infrastructure. Use `/feedback` to report false positives, or have an administrator configure trusted infrastructure.++### How the classifier evaluates actions++Each action goes through a fixed decision order. The first matching step wins:++1. Actions matching your allow or deny rules resolve immediately.+2. Read-only actions and file edits in your working directory are auto-approved, except writes to protected paths.+3. Everything else goes to the classifier.+4. If the classifier blocks, Claude receives the reason and tries an alternative.++On entering auto mode, broad allow rules that grant arbitrary code execution are dropped:++* Blanket `Bash(*)` or `PowerShell(*)`+* Wildcarded interpreters like `Bash(python*)`+* Package-manager run commands+* `Agent` allow rules++Narrow rules like `Bash(npm test)` carry over. Dropped rules are restored when you leave auto mode.++The classifier sees user messages, tool calls, and your CLAUDE.md content. Tool results are stripped, so hostile content in a file or web page cannot manipulate it directly. A separate server-side probe scans incoming tool results and flags suspicious content before Claude reads it.++### How auto mode handles subagents++The classifier checks subagent work at three points:++1. Before a subagent starts, the delegated task description is evaluated, so a dangerous-looking task is blocked at spawn time.+2. While the subagent runs, each of its actions goes through the classifier with the same rules as the parent session, and any `permissionMode` in the subagent's frontmatter is ignored.+3. When the subagent finishes, the classifier reviews its full action history; if that return check flags a concern, a security warning is prepended to the subagent's results.++### Cost and latency++The classifier runs on a server-configured model that is independent of your `/model` selection, so switching models does not change classifier availability. Classifier calls count toward your token usage. Each check sends a portion of the transcript plus the pending action, adding a round-trip before execution. Reads and working-directory edits outside protected paths skip the classifier, so the overhead comes mainly from shell commands and network operations.++## Allow only pre-approved tools with `dontAsk` mode++`dontAsk` mode auto-denies every tool call that would otherwise prompt. Only actions matching your `permissions.allow` rules and read-only Bash commands can execute; explicit `ask` rules are denied rather than prompting. This makes the mode fully non-interactive for CI pipelines or restricted environments where you pre-define exactly what Claude may do.++Set it at startup with the flag:++```bash+claude --permission-mode dontAsk+```++## Skip all checks with `bypassPermissions` mode++`bypassPermissions` mode disables permission prompts and safety checks so tool calls execute immediately. As of v2.1.126 this includes writes to protected paths, which earlier versions still prompted for. Removals targeting the filesystem root or home directory, such as `rm -rf /` and `rm -rf ~`, still prompt as a circuit breaker against model error. Only use this mode in isolated environments like containers, VMs, or dev containers without internet access, where Claude Code cannot damage your host system.++You cannot enter `bypassPermissions` from a session that was started without one of the enabling flags; restart with one to enable it:++```bash+claude --permission-mode bypassPermissions+```++The `--dangerously-skip-permissions` flag is equivalent.++On Linux and macOS, Claude Code refuses to start in this mode when running as root or under `sudo`:++```text+--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons+```++The check is skipped automatically inside a recognized sandbox. To run autonomously in a container, use the dev container configuration, which runs Claude Code as a non-root user.++> **Warning:** `bypassPermissions` offers no protection against prompt injection or unintended actions. For background safety checks without prompts, use auto mode instead. Administrators can block this mode by setting `permissions.disableBypassPermissionsMode` to `"disable"` in managed settings.++## Protected paths++Writes to a small set of paths are never auto-approved, in every mode except `bypassPermissions`. This prevents accidental corruption of repository state and Claude's own configuration. In `default`, `acceptEdits`, and `plan` these writes prompt; in `auto` they route to the classifier; in `dontAsk` they are denied; in `bypassPermissions` they are allowed.++**Protected directories:**++* `.git`+* `.vscode`+* `.idea`+* `.husky`+* `.claude`, except for `.claude/commands`, `.claude/agents`, `.claude/skills`, and `.claude/worktrees` where Claude routinely creates content++**Protected files:**++* `.gitconfig`, `.gitmodules`+* `.bashrc`, `.bash_profile`, `.zshrc`, `.zprofile`, `.profile`+* `.ripgreprc`+* `.mcp.json`, `.claude.json`++## See also++* Permissions: allow, ask, and deny rules; managed policies+* Configure auto mode: tell the classifier which infrastructure your organization trusts+* Hooks: custom permission logic via `PreToolUse` and `PermissionRequest` hooks+* Ultraplan: run plan mode in a Claude Code on the web session with browser-based review+* Security: safeguards and best practices+* Sandboxing: filesystem and network isolation for Bash commands+* Non-interactive mode: run Claude Code with the `-p` flag — see [`claude_code_headless_reference.md`](./claude_code_headless_reference.md)++---++## What MachinaOs uses++| Mode | Where | Notes |+|---|---|---|+| `acceptEdits` | Default on `ClaudeTaskSpec.permission_mode` | Auto-approves file edits + safe filesystem commands inside cwd. cwd is `repo_root` for memory-bound runs (so claude can edit the actual repo) and the per-task worktree otherwise (isolated). |+| `plan` | User-selectable per task | When the user wants research without edits. |+| `bypassPermissions` | Available but not default | For sandboxed CI scenarios. Not recommended on a user's real repo. |+| `dontAsk` | Available but not default | For locked-down CI; agent must have `permissions.allow` rules pre-configured. |+| `auto` | Available but not default | Requires Sonnet 4.6 / Opus 4.6+ and Anthropic API plan; classifier model + token cost overhead. |diff --git a/docs-internal/claude_code_skills_reference.md b/docs-internal/claude_code_skills_reference.mdnew file mode 100644index 00000000..d1fcca29--- /dev/null+++ b/docs-internal/claude_code_skills_reference.md@@ -0,0 +1,251 @@+# Claude Code skills reference (verbatim snapshot)++> **Source:** [code.claude.com/docs/en/skills](https://code.claude.com/docs/en/skills)+> **Fetched:** 2026-05-11+> **Why this lives in-repo:** MachinaOs materialises connected skills+> into `<cwd>/.claude/skills/<name>/SKILL.md` on `_pre_spawn` so claude+> auto-discovers them — see [`cli_agent_framework.md` → Memory bridge](./cli_agent_framework.md#memory-bridge--simplememory--claude_code_agent)+> and [`cli_agent_canonical_patterns_rfc.md` §5 R1](./cli_agent_canonical_patterns_rfc.md).+> This is the spec we materialise against.++---++# Extend Claude with skills++> Create, manage, and share skills to extend Claude's capabilities in Claude Code. Includes custom commands and bundled skills.++Skills extend what Claude can do. Create a `SKILL.md` file with instructions, and Claude adds it to its toolkit. Claude uses skills when relevant, or you can invoke one directly with `/skill-name`.++Create a skill when you keep pasting the same instructions, checklist, or multi-step procedure into chat, or when a section of CLAUDE.md has grown into a procedure rather than a fact. Unlike CLAUDE.md content, a skill's body loads only when it's used, so long reference material costs almost nothing until you need it.++> **Note:** Custom commands have been merged into skills. A file at `.claude/commands/deploy.md` and a skill at `.claude/skills/deploy/SKILL.md` both create `/deploy` and work the same way. Your existing `.claude/commands/` files keep working. Skills add optional features: a directory for supporting files, frontmatter to control whether you or Claude invokes them, and the ability for Claude to load them automatically when relevant.++Claude Code skills follow the [Agent Skills](https://agentskills.io) open standard, which works across multiple AI tools. Claude Code extends the standard with additional features like invocation control, subagent execution, and dynamic context injection.++## Bundled skills++Claude Code includes a set of bundled skills that are available in every session, including `/simplify`, `/batch`, `/debug`, `/loop`, and `/claude-api`. Unlike most built-in commands, which execute fixed logic directly, bundled skills are prompt-based: they give Claude detailed instructions and let it orchestrate the work using its tools. You invoke them the same way as any other skill, by typing `/` followed by the skill name.++## Where skills live++Where you store a skill determines who can use it:++| Location | Path | Applies to |+| :--------- | :-------------------------------------------------- | :----------------------------- |+| Enterprise | See managed settings | All users in your organization |+| Personal | `~/.claude/skills/<skill-name>/SKILL.md` | All your projects |+| Project | `.claude/skills/<skill-name>/SKILL.md` | This project only |+| Plugin | `<plugin>/skills/<skill-name>/SKILL.md` | Where plugin is enabled |++When skills share the same name across levels, enterprise overrides personal, and personal overrides project. Plugin skills use a `plugin-name:skill-name` namespace, so they cannot conflict with other levels. If you have files in `.claude/commands/`, those work the same way, but if a skill and a command share the same name, the skill takes precedence.++### Live change detection++Claude Code watches skill directories for file changes. Adding, editing, or removing a skill under `~/.claude/skills/`, the project `.claude/skills/`, or a `.claude/skills/` inside an `--add-dir` directory takes effect within the current session without restarting. Creating a top-level skills directory that did not exist when the session started requires restarting Claude Code so the new directory can be watched.++### Automatic discovery from parent and nested directories++Project skills load from `.claude/skills/` in your starting directory and in every parent directory up to the repository root, so starting Claude in a subdirectory still picks up skills defined at the root. When you work with files in subdirectories below your starting directory, Claude Code also discovers skills from nested `.claude/skills/` directories on demand.++### Skill directory layout++Each skill is a directory with `SKILL.md` as the entrypoint:++```text+my-skill/+├── SKILL.md # Main instructions (required)+├── template.md # Template for Claude to fill in+├── examples/+│ └── sample.md # Example output showing expected format+└── scripts/+ └── validate.sh # Script Claude can execute+```++## Frontmatter reference++Beyond the markdown content, you can configure skill behavior using YAML frontmatter fields between `---` markers at the top of your `SKILL.md` file:++```yaml+---+name: my-skill+description: What this skill does+disable-model-invocation: true+allowed-tools: Read Grep+---++Your skill instructions here...+```++All fields are optional. Only `description` is recommended so Claude knows when to use the skill.++| Field | Required | Description |+| :------------------------- | :---------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `name` | No | Display name for the skill. If omitted, uses the directory name. Lowercase letters, numbers, and hyphens only (max 64 characters). |+| `description` | Recommended | What the skill does and when to use it. Claude uses this to decide when to apply the skill. If omitted, uses the first paragraph of markdown content. Put the key use case first: the combined `description` and `when_to_use` text is truncated at 1,536 characters in the skill listing to reduce context usage. |+| `when_to_use` | No | Additional context for when Claude should invoke the skill, such as trigger phrases or example requests. Appended to `description` in the skill listing and counts toward the 1,536-character cap. |+| `argument-hint` | No | Hint shown during autocomplete to indicate expected arguments. Example: `[issue-number]` or `[filename] [format]`. |+| `arguments` | No | Named positional arguments for `$name` substitution in the skill content. Accepts a space-separated string or a YAML list. Names map to argument positions in order. |+| `disable-model-invocation` | No | Set to `true` to prevent Claude from automatically loading this skill. Use for workflows you want to trigger manually with `/name`. Also prevents the skill from being preloaded into subagents. Default: `false`. |+| `user-invocable` | No | Set to `false` to hide from the `/` menu. Use for background knowledge users shouldn't invoke directly. Default: `true`. |+| `allowed-tools` | No | Tools Claude can use without asking permission when this skill is active. Accepts a space-separated string or a YAML list. |+| `model` | No | Model to use when this skill is active. The override applies for the rest of the current turn and is not saved to settings; the session model resumes on your next prompt. Accepts the same values as `/model`, or `inherit` to keep the active model. |+| `effort` | No | Effort level when this skill is active. Overrides the session effort level. Default: inherits from session. Options: `low`, `medium`, `high`, `xhigh`, `max`; available levels depend on the model. |+| `context` | No | Set to `fork` to run in a forked subagent context. |+| `agent` | No | Which subagent type to use when `context: fork` is set. |+| `hooks` | No | Hooks scoped to this skill's lifecycle. |+| `paths` | No | Glob patterns that limit when this skill is activated. Accepts a comma-separated string or a YAML list. When set, Claude loads the skill automatically only when working with files matching the patterns. |+| `shell` | No | Shell to use for `` !`command` `` and ` ```! ` blocks in this skill. Accepts `bash` (default) or `powershell`. Setting `powershell` runs inline shell commands via PowerShell on Windows. Requires `CLAUDE_CODE_USE_POWERSHELL_TOOL=1`. |++### Available string substitutions++Skills support string substitution for dynamic values in the skill content:++| Variable | Description |+| :--------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `$ARGUMENTS` | All arguments passed when invoking the skill. If `$ARGUMENTS` is not present in the content, arguments are appended as `ARGUMENTS: <value>`. |+| `$ARGUMENTS[N]` | Access a specific argument by 0-based index, such as `$ARGUMENTS[0]` for the first argument. |+| `$N` | Shorthand for `$ARGUMENTS[N]`, such as `$0` for the first argument or `$1` for the second. |+| `$name` | Named argument declared in the `arguments` frontmatter list. Names map to positions in order, so with `arguments: [issue, branch]` the placeholder `$issue` expands to the first argument and `$branch` to the second. |+| `${CLAUDE_SESSION_ID}` | The current session ID. Useful for logging, creating session-specific files, or correlating skill output with sessions. |+| `${CLAUDE_EFFORT}` | The current effort level: `low`, `medium`, `high`, `xhigh`, or `max`. Use this to adapt skill instructions to the active effort setting. |+| `${CLAUDE_SKILL_DIR}` | The directory containing the skill's `SKILL.md` file. For plugin skills, this is the skill's subdirectory within the plugin, not the plugin root. Use this in bash injection commands to reference scripts or files bundled with the skill, regardless of the current working directory. |++## Skill content lifecycle++When you or Claude invoke a skill, the rendered `SKILL.md` content enters the conversation as a single message and stays there for the rest of the session. Claude Code does not re-read the skill file on later turns, so write guidance that should apply throughout a task as standing instructions rather than one-time steps.++Auto-compaction carries invoked skills forward within a token budget. When the conversation is summarized to free context, Claude Code re-attaches the most recent invocation of each skill after the summary, keeping the first 5,000 tokens of each. Re-attached skills share a combined budget of 25,000 tokens. Claude Code fills this budget starting from the most recently invoked skill, so older skills can be dropped entirely after compaction if you have invoked many in one session.++## Inject dynamic context++The `` !`<command>` `` syntax runs shell commands before the skill content is sent to Claude. The command output replaces the placeholder, so Claude receives actual data, not the command itself.++This skill summarizes a pull request by fetching live PR data with the GitHub CLI:++```yaml+---+name: pr-summary+description: Summarize changes in a pull request+context: fork+agent: Explore+allowed-tools: Bash(gh *)+---++## Pull request context+- PR diff: !`gh pr diff`+- PR comments: !`gh pr view --comments`+- Changed files: !`gh pr diff --name-only`++## Your task+Summarize this pull request...+```++When this skill runs:++1. Each `` !`<command>` `` executes immediately (before Claude sees anything)+2. The output replaces the placeholder in the skill content+3. Claude receives the fully-rendered prompt with actual PR data++This is preprocessing, not something Claude executes. Claude only sees the final result.++For multi-line commands, use a fenced code block opened with ` ```! ` instead of the inline form.++## Run skills in a subagent++Add `context: fork` to your frontmatter when you want a skill to run in isolation. The skill content becomes the prompt that drives the subagent. It won't have access to your conversation history.++> **Warning:** `context: fork` only makes sense for skills with explicit instructions. If your skill contains guidelines like "use these API conventions" without a task, the subagent receives the guidelines but no actionable prompt, and returns without meaningful output.++Skills and subagents work together in two directions:++| Approach | System prompt | Task | Also loads |+| :--------------------------- | :---------------------------------------- | :-------------------------- | :--------------------------- |+| Skill with `context: fork` | From agent type (`Explore`, `Plan`, etc.) | SKILL.md content | CLAUDE.md |+| Subagent with `skills` field | Subagent's markdown body | Claude's delegation message | Preloaded skills + CLAUDE.md |++## Restrict Claude's skill access++By default, Claude can invoke any skill that doesn't have `disable-model-invocation: true` set. Skills that define `allowed-tools` grant Claude access to those tools without per-use approval when the skill is active. Your permission settings still govern baseline approval behavior for all other tools.++Three ways to control which skills Claude can invoke:++**Disable all skills** by denying the Skill tool in `/permissions`:++```text+# Add to deny rules:+Skill+```++**Allow or deny specific skills** using permission rules:++```text+# Allow only specific skills+Skill(commit)+Skill(review-pr *)++# Deny specific skills+Skill(deploy *)+```++Permission syntax: `Skill(name)` for exact match, `Skill(name *)` for prefix match with any arguments.++**Hide individual skills** by adding `disable-model-invocation: true` to their frontmatter. This removes the skill from Claude's context entirely.++## Troubleshooting++### Skill not triggering++If Claude doesn't use your skill when expected:++1. Check the description includes keywords users would naturally say+2. Verify the skill appears in `What skills are available?`+3. Try rephrasing your request to match the description more closely+4. Invoke it directly with `/skill-name` if the skill is user-invocable++### Skill triggers too often++If Claude uses your skill when you don't want it:++1. Make the description more specific+2. Add `disable-model-invocation: true` if you only want manual invocation++### Skill descriptions are cut short++Skill descriptions are loaded into context so Claude knows what's available. All skill names are always included, but if you have many skills, descriptions are shortened to fit the character budget, which can strip the keywords Claude needs to match your request. The budget scales at 1 % of the model's context window. When it overflows, descriptions for the skills you invoke least are dropped first, so the skills you actually use keep their full text. Run `/doctor` to see whether the budget is overflowing and which skills are affected.++To raise the budget, set the `skillListingBudgetFraction` setting (e.g. `0.02` = 2 %) or the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable to a fixed character count. To free budget for other skills, set low-priority entries to `"name-only"` in `skillOverrides` so they list without a description. You can also trim the `description` and `when_to_use` text at the source: put the key use case first, since each entry's combined text is capped at 1,536 characters regardless of budget. The cap is configurable with `maxSkillDescriptionChars`.++## Related resources++* Debug your configuration: diagnose why a skill isn't appearing or triggering+* Subagents: delegate tasks to specialized agents+* Plugins: package and distribute skills with other extensions+* Hooks: automate workflows around tool events+* Memory: manage CLAUDE.md files for persistent context+* Commands: reference for built-in commands and bundled skills+* Permissions: control tool and skill access++---++## How MachinaOs materialises skills for `claude_code_agent`++[`services/cli_agent/session.py:_materialise_skills`](../server/services/cli_agent/session.py)+walks `connected_skill_names` (collected by edge_walker from the+agent's `input-skill` handle) and writes each connected skill to+`<cwd>/.claude/skills/<name>/SKILL.md`:++- **Filesystem-origin skills:** `shutil.copytree(skill.metadata.path, dest, dirs_exist_ok=True)` — preserves `SKILL.md` + supporting `scripts/`, `references/`, `templates/`, etc.+- **DB-origin user skills:** synthesise the `SKILL.md` from `Skill.metadata` (`name`, `description`, `allowed-tools`, `metadata`) + `Skill.instructions` (the body) using `yaml.safe_dump` for the frontmatter.++For memory-bound runs (`memory_bound=True`), cwd is `repo_root`, so+skills land at `<repo_root>/.claude/skills/<name>/`. For non-memory+runs the cwd is the per-task worktree.++Per *Live change detection* above, claude picks the skills up+mid-session without a restart — but our spawn is fresh each task+anyway, so we don't rely on that.++`allowed-tools` in MachinaOs-shipped SKILL.md files uses the same+syntax as upstream (`Bash(git diff *) Read` etc.) and is honoured by+claude verbatim — see `server/skills/coding_agent/file-modify-skill/SKILL.md`+for a reference.