МОДУЛЬ 10/УРОК

CLI и флаги

Справочник по CLI

Обзор

Claude Code CLI (интерфейс командной строки) - это основной способ взаимодействия с Claude Code. Он предоставляет широкие возможности для выполнения запросов, управления сессиями, настройки моделей и встраивания Claude в процессы разработки.

Архитектура

graph TD A["User Terminal"] -->|"claude [options] [query]"| B["Claude Code CLI"] B -->|Interactive| C["REPL Mode"] B -->|"--print"| D["Print Mode (SDK)"] B -->|"--resume"| E["Session Resume"] C -->|Conversation| F["Claude API"] D -->|Single Query| F E -->|Load Context| F F -->|Response| G["Output"] G -->|text/json/stream-json| H["Terminal/Pipe"]

Среда выполнения и упаковка

Начиная с v2.1.113, Claude Code CLI запускается как нативный бинарный файл для конкретной платформы (macOS, Linux, Windows) через опциональные npm-зависимости. Нужный бинарник подбирается под вашу ОС и архитектуру на этапе установки - прежняя упакованная JavaScript-среда выполнения больше не используется по умолчанию на macOS и Linux.

Со стороны пользователя способ установки не изменился: npm install -g @anthropic-ai/claude-code по-прежнему работает и остаётся рекомендуемым способом. Под капотом npm скачивает подходящий нативный бинарник для вашей платформы.

Хост для загрузки (v2.1.116+): артефакты нативных бинарников раздаются с https://downloads.claude.ai/claude-code-releases.

Корпоративным пользователям и тем, кто работает через прокси: если ваша сеть требует явного allowlist, добавьте downloads.claude.ai (и https://downloads.claude.ai/claude-code-releases) в правила исходящего трафика прокси. Окружения, в которых ранее в allowlist были только storage.googleapis.com или npm registry, потребуется обновить - иначе claude update и первичная установка будут завершаться с ошибкой.

Старый JavaScript-бандл по-прежнему собирается для Windows и для окружений, которые к нему привязаны; в таких сборках Glob и Grep поставляются как полноценные инструменты (см. сноску про Glob/Grep в разделе Инструменты).

Команды CLI

CommandDescriptionExample
claudeStart interactive REPLclaude
claude "query"Start REPL with initial promptclaude "explain this project"
claude -p "query"Print mode - query then exitclaude -p "explain this function"
cat file | claude -p "query"Process piped contentcat logs.txt | claude -p "explain"
claude -cContinue most recent conversationclaude -c
claude -c -p "query"Continue in print modeclaude -c -p "check for type errors"
claude -r "<session>" "query"Resume session by ID or nameclaude -r "auth-refactor" "finish this PR"
claude updateUpdate to latest versionclaude update
/doctor (slash command)Diagnose installation, config, and plugin health. Since v2.1.116 it can be opened while Claude is responding, shows status icons inline, and accepts the f keypress to auto-fix detected issues. v2.1.178 refreshed the layout to a flat tree with clearer status icons and highlighted commandsrun /doctor inside the REPL
claude mcpConfigure MCP servers (incl. login/logout for auth, v2.1.186+)See MCP documentation
claude mcp serveRun Claude Code as an MCP serverclaude mcp serve
claude agentsOpen the Agent View (Research Preview, v2.1.139+) - multi-session manager listing every Claude Code session with its status. See Agent View below.claude agents
claude auto-mode defaultsPrint auto mode default rules as JSONclaude auto-mode defaults
claude auto-mode resetRestore default auto-mode configuration, with a confirmation prompt (--yes to skip) (v2.1.212)claude auto-mode reset --yes
claude --remote-control [name]Start Remote Control (a flag, not a subcommand; alias --rc)claude --rc
claude pluginManage plugins (install, enable, disable)claude plugin install my-plugin
claude plugin init <name>Scaffold a new plugin at ~/.claude/skills/<name>/ (user-global) - auto-loads in the next session as <name>@skills-dir, no marketplace required (v2.1.157+)claude plugin init my-plugin
claude plugin tag [path]Create a {name}--v{version} release git tag for the plugin at [path], validating that plugin.json and any enclosing marketplace entry agree (v2.1.118+)claude plugin tag ./my-plugin
claude install [version]Install a specific native-binary version. Accepts stable, latest, or an explicit version stringclaude install 2.1.131
claude project purge [path]Delete all local Claude Code state for a project (transcripts, tasks, debug logs, file-edit history, prompt history, and ~/.claude.json entry). Omit [path] for an interactive picker. Flags: --dry-run to preview, -y/--yes to skip confirmation, -i/--interactive to confirm each item, --all for every project (v2.1.126+)claude project purge ~/work/repo --dry-run
claude plugin pruneRemove orphaned auto-installed plugin dependencies (parent plugin gone). plugin uninstall --prune does the same cascade after uninstalling a target (v2.1.121+)claude plugin prune
claude ultrareview [target]Run /ultrareview non-interactively. Prints findings to stdout, exits 0 on success / 1 on failure. Use --json for raw payload, --timeout <minutes> to override the 30-minute default, and --post / --no-post to control whether findings are posted back to the PR. Requires Claude Code v2.1.227 or laterclaude ultrareview 1234 --json --no-post
claude self-hosted-runner <setup|doctor|orchestrator>Turn your own machine or container into a place Claude Code web, mobile, and desktop sessions can run. setup provisions the runner, doctor diagnoses it, orchestrator runs the coordinating process. Team and Enterprise plans; requires Claude Code v2.1.224 or later. On Windows, startup requires an explicit --base-dir (v2.1.229)claude self-hosted-runner setup
claude auth loginLog in (supports --email, --sso). Since v2.1.126, accepts the OAuth code pasted into the terminal as a fallback when the browser callback can't reach localhost (WSL2, SSH, containers)claude auth login --email user@example.com
claude auth logoutLog out of current accountclaude auth logout
claude auth statusCheck auth status (exit 0 if logged in, 1 if not)claude auth status

Основные флаги

FlagDescriptionExample
-p, --printPrint response without interactive modeclaude -p "query"
-c, --continueLoad most recent conversationclaude --continue
-r, --resumeResume specific session by ID or nameclaude --resume auth-refactor
-v, --versionOutput version numberclaude -v
-w, --worktreeStart in isolated git worktree. Accepts a GitLab merge-request URL as well as a GitHub PR URL since v2.1.233claude -w
-n, --nameSession display nameclaude -n "auth-refactor"
--from-pr <url-or-number>Resume sessions linked to a pull/merge request. Accepts GitHub (cloud + Enterprise), GitLab MR, and Bitbucket PR URLs since v2.1.119; previously GitHub.com onlyclaude --from-pr 42 or claude --from-pr https://gitlab.example.com/org/repo/-/merge_requests/17
--cloud [description|session_id|url]Create a cloud session on claude.ai with the given description, or attach to an existing one by session ID or claude.ai/code URLclaude --cloud "implement API"
--remote "task"Deprecated alias for --cloud, including the existing-session form. Use --cloud insteadclaude --remote "implement API"
--remote-control, --rcInteractive session with Remote Controlclaude --rc
--teleport [session]Resume a web session locally. Bare form opens a picker of your web sessions; pass a session ID to resume that session directly. Requires a claude.ai subscriptionclaude --teleport
--teammate-modeAgent team display modeclaude --teammate-mode tmux
--bareMinimal mode (skip hooks, skills, plugins, MCP, auto memory, CLAUDE.md)claude --bare
--safe-modeStart with all customizations disabled (CLAUDE.md, plugins, skills, hooks, MCP) to isolate config problems; also CLAUDE_CODE_SAFE_MODE=1 (v2.1.169)claude --safe-mode
--restrictedLock the session down for untrusted or shared use: removes the built-in command- and code-running tools and WebFetch, ignores user/project/local settings, confines file tools to the working directories, and refuses bypassPermissions and cloud sessions. Also CLAUDE_CODE_RESTRICTED=1 (v2.1.248+)claude --restricted -p "summarize this repo"
--permission-mode autoStart in auto permission mode (replaces the removed --enable-auto-mode flag, gone since v2.1.111)claude --permission-mode auto
--channelsSubscribe to MCP channel plugins. Entries must be tagged plugin:<name>@<marketplace>; bare names are rejectedclaude --channels plugin:discord@my-marketplace
--chrome / --no-chromeEnable/disable Chrome browser integrationclaude --chrome
--effortSet thinking effort levelclaude --effort high
--init / --init-onlyRun initialization hooksclaude --init
--maintenanceRun maintenance hooks and exitclaude --maintenance
--disable-slash-commandsDisable all skills and slash commandsclaude --disable-slash-commands
--no-session-persistenceDisable session saving (print mode)claude -p --no-session-persistence "query"
--exclude-dynamic-system-prompt-sectionsExclude dynamic sections from the system prompt for better prompt cache hit ratesclaude -p --exclude-dynamic-system-prompt-sections "query"

Ограниченный режим (--restricted, v2.1.248+)

--restricted (или CLAUDE_CODE_RESTRICTED=1) предназначен для запуска claude от имени того, чей ввод вы не контролируете, - оценочного harness на общей машине, CI-задачи, запущенной внешним контрибьютором, демо-стенда. Он применяет сразу всё перечисленное ниже:

  • Убирает инструменты, выполняющие команды или код - Bash, PowerShell и REPL, - а также WebFetch, если только они не указаны явно через --tools.
  • Игнорирует пользовательские, проектные и локальные файлы настроек. Managed settings и файл, заданный явно через --settings, по-прежнему учитываются, так что администратор сохраняет контроль, а закоммиченный в репозиторий .claude/settings.json не сможет расширить sandbox.
  • Ограничивает файловые инструменты рабочими директориями, так что чтение и запись не могут выйти за пределы путей, с которых вы стартовали.
  • Отклоняет bypassPermissions, каким бы способом он ни запрашивался.
  • Отказывается создавать cloud-сессии, чтобы ограниченный запуск не мог вынести работу за пределы машины.
bash
# Evaluation harness: no shell, no network fetches, no settings inheritance
claude --restricted -p "summarize the architecture of this repo"

# Same lockdown, but deliberately re-enable one tool
claude --restricted --tools WebFetch -p "check the linked RFC"

Примечание: --restricted - более жёсткое ограничение, чем --permission-mode. Этот флаг полностью отключает инструменты, а не запрашивает разрешение на их использование, поэтому расширить права ограниченной сессии изнутри неё самой невозможно.

Интерактивный режим против режима print

graph LR A["claude"] -->|Default| B["Interactive REPL"] A -->|"-p flag"| C["Print Mode"] B -->|Features| D["Multi-turn conversation<br>Tab completion<br>History<br>Slash commands"] C -->|Features| E["Single query<br>Scriptable<br>Pipeable<br>JSON output"]

Интерактивный режим (по умолчанию):

bash
# Start interactive session
claude

# Start with initial prompt
claude "explain the authentication flow"

Режим вывода (неинтерактивный):

bash
# Single query, then exit
claude -p "what does this function do?"

# Process file content
cat error.log | claude -p "explain this error"

# Chain with other tools
claude -p "list todos" | grep "URGENT"

Модель и конфигурация

FlagDescriptionExample
--modelSet model (sonnet, opus, haiku, or full name)claude --model opus
--fallback-modelAutomatic model fallback when the primary is overloaded/unavailable; configure up to three via the fallbackModel setting. Applies to interactive sessions too since v2.1.166 (previously print mode only)claude -p --fallback-model sonnet "query"
--agentSpecify agent for sessionclaude --agent my-custom-agent
--agentsDefine custom subagents via JSONSee Agents Configuration
--effortSet effort level (low, medium, high, xhigh, max)claude --effort xhigh

Примеры выбора модели

bash
# Use Opus 5 for complex tasks
claude --model opus "design a caching strategy"

# Use Haiku 4.5 for quick tasks
claude --model haiku -p "format this JSON"

# Full model name
claude --model claude-sonnet-4-6-20250929 "review this code"

# With fallback for reliability
claude -p --model opus --fallback-model sonnet "analyze architecture"

# Use opusplan (Opus plans, Sonnet executes)
claude --model opusplan "design and implement the caching layer"

Обнаружение моделей через gateway (v2.1.129+, opt-in): если ANTHROPIC_BASE_URL указывает на Anthropic-совместимый gateway, установите CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1, чтобы список /model заполнялся из endpoint /v1/models этого gateway. Без этой переменной окружения /model использует встроенный статический список. Флаг сделан opt-in (изменено в v2.1.129), поскольку discovery-запрос может вернуть модели, к которым у пользователя нет доступа; в v2.1.126 поведение было неявным (включено по умолчанию), но затем откачено.

Модель по умолчанию для организации (v2.1.196): когда администратор организации задаёт модель по умолчанию, /model помечает её как «Org default» (или «Role default»).

Настройка System Prompt

FlagDescriptionExample
--system-promptReplace entire default promptclaude --system-prompt "You are a Python expert"
--system-prompt-fileLoad prompt from file (print mode)claude -p --system-prompt-file ./prompt.txt "query"
--append-system-promptAppend to default promptclaude --append-system-prompt "Always use TypeScript"
--append-subagent-system-promptAppend text to every subagent's system prompt (non-interactive)claude -p --append-subagent-system-prompt "Cite sources" "query"
--append-subagent-system-prompt-file(v2.1.261) Load that appended text from a file instead, for prompts too long to pass on the command line. Non-interactive only, and cannot be combined with --append-subagent-system-promptclaude -p --append-subagent-system-prompt-file ./subagent-rules.txt "query"

Примеры системных промптов

bash
# Complete custom persona
claude --system-prompt "You are a senior security engineer. Focus on vulnerabilities."

# Append specific instructions
claude --append-system-prompt "Always include unit tests with code examples"

# Load complex prompt from file
claude -p --system-prompt-file ./prompts/code-reviewer.txt "review main.py"

Сравнение флагов системного промпта

FlagBehaviorInteractivePrint
--system-promptReplaces entire default system prompt✅✅
--system-prompt-fileReplaces with prompt from file❌✅
--append-system-promptAppends to default system prompt✅✅
Используйте --system-prompt-file только в режиме print. Для интерактивного режима используйте --system-prompt или --append-system-prompt.

Управление инструментами и разрешениями

FlagDescriptionExample
--toolsRestrict available built-in toolsclaude -p --tools "Bash,Edit,Read" "query"
--allowedToolsTools that execute without prompting"Bash(git log:*)" "Read"
--disallowedToolsTools removed from context"Bash(rm:*)" "Edit"
--dangerously-skip-permissionsSkip all permission promptsclaude --dangerously-skip-permissions
--permission-modeBegin in specified permission modeclaude --permission-mode auto
--permission-prompt-toolMCP tool for permission handlingclaude -p --permission-prompt-tool mcp_auth "query"
--permission-prompts(v2.1.259) Who answers permission prompts in print mode. Default host sends them to the Agent SDK host or the --permission-prompt-tool tool; pass none when nobody can answer and Claude Code denies them insteadclaude -p --permission-prompts none "query"

Обновление v2.1.111: флаг --enable-auto-mode удалён; auto mode теперь по умолчанию входит в цикл Shift+Tab - используйте --permission-mode auto, чтобы сразу запуститься в этом режиме.

Примечание по Glob / Grep (v2.1.113+): в нативных сборках для macOS/Linux Glob и Grep реализованы через встроенные бинарники bfs и ugrep, вызываемые через Bash-инструмент, а не как отдельные полноценные инструменты. В сборках для Windows и в npm-пакете (JS) они по-прежнему доступны как самостоятельные инструменты. Для списков allowedTools / disallowedTools у сабагентов эта замена на стороне бэкенда прозрачна - в конфигурации можно продолжать указывать Glob / Grep на любой платформе.

Автоодобрение PowerShell (v2.1.119): команды инструмента PowerShell могут автоматически одобряться в permission mode ровно так же, как команды Bash. Для ограничения разрешений PowerShell используйте тот же синтаксис matcher, что и для правил Bash(...) - например, PowerShell(Get-ChildItem:*).

--permission-mode учитывается при возобновлении сессии (v2.1.132+): claude -p --continue --permission-mode plan (а также --resume) теперь корректно учитывает этот флаг. В более ранних версиях --permission-mode при возобновлении сессии молча игнорировался, из-за чего сессия в plan mode, возобновлённая без повторной передачи флага, незаметно понижалась в правах - теперь это исправлено.

Ужесточение разрешений (v2.1.214): команды Docker/Podman с флагами перенаправления демона (например, --url, --connection, --identity) теперь требуют подтверждения вместо автоматического выполнения. Команды file с флагами -m/--magic-file или -f/--files-from также требуют подтверждения. Команды Bash длиной более 10 000 символов всегда запрашивают подтверждение - независимо от allow-правил.

Примеры разрешений

bash
# Read-only mode for code review
claude --permission-mode plan "review this codebase"

# Restrict to safe tools only
claude --tools "Read,Grep,Glob" -p "find all TODO comments"

# Allow specific git commands without prompts
claude --allowedTools "Bash(git status:*)" "Bash(git log:*)"

# Block dangerous operations
claude --disallowedTools "Bash(rm -rf:*)" "Bash(git push --force:*)"

Сопоставление параметров Tool(param:value) (v2.1.178): правила разрешений задаются в формате Tool (любое использование) или Tool(specifier). Начиная с v2.1.178, спецификатор может сопоставляться с входными параметрами инструмента, а не только с шаблонами команд или путей - через форму Tool(param:value) с поддержкой wildcard. Это обобщает механизм сопоставления, который вы уже применяете для префиксов команд в Bash(...) (например, Bash(npm run test *)) и glob-шаблонов путей в Read(...) (например, Read(./.env.*)), позволяя ограничивать и другие инструменты по их аргументам. Перед написанием правила сверяйтесь со справочником по разрешениям, чтобы узнать актуальные примеры для конкретного инструмента, поскольку точные имена параметров различаются от инструмента к инструменту.

Вывод и формат

FlagDescriptionOptionsExample
--output-formatSpecify output format (print mode)text, json, stream-jsonclaude -p --output-format json "query"
--input-formatSpecify input format (print mode)text, stream-jsonclaude -p --input-format stream-json
--verboseEnable verbose loggingclaude --verbose
--include-partial-messagesInclude streaming eventsRequires stream-jsonclaude -p --output-format stream-json --include-partial-messages "query"
--forward-subagent-textForward subagent text output into the stream. As of v2.1.219, subagents spawned at depth 2 or deeper are forwarded too, keyed by their spawning Agent tool_use id (this is how you observe the nesting enabled by default via CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH)Requires stream-jsonclaude -p --output-format stream-json --forward-subagent-text "query"
--json-schemaGet validated JSON matching schemaclaude -p --json-schema '{"type":"object"}' "query"
--max-budget-usdMaximum spend for print mode. Since v2.1.217, hitting the cap also halts running background subagents and denies new spawns (previously background agents kept running past the cap)claude -p --max-budget-usd 5.00 "query"

Примеры формата вывода

bash
# Plain text (default)
claude -p "explain this code"

# JSON for programmatic use
claude -p --output-format json "list all functions in main.py"

# Streaming JSON for real-time processing
claude -p --output-format stream-json "generate a long report"

# Structured output with schema validation
claude -p --json-schema '{"type":"object","properties":{"bugs":{"type":"array"}}}' \
  "find bugs in this code and return as JSON"

Рабочая область и каталог

FlagDescriptionExample
--add-dirAdd additional working directoriesclaude --add-dir ../apps ../lib
--setting-sourcesComma-separated setting sourcesclaude --setting-sources user,project

Сохранение /config (v2.1.119): Изменения, внесённые интерактивно через команду /config, теперь записываются в ~/.claude/settings.json и участвуют в стандартной цепочке приоритетов (policy → local → project → user). До v2.1.119 часть изменений /config действовала только в пределах сессии. Полный порядок приоритетов см. в разделе Память и настройки. | --settings | Загрузить настройки из файла или JSON. Размер файла не должен превышать 2 MiB (v2.1.214) | claude --settings ./settings.json | | --plugin-dir | Загрузить плагины из указанной директории (можно указывать несколько раз) | claude --plugin-dir ./my-plugin |

Пример с несколькими директориями

bash
# Work across multiple project directories
claude --add-dir ../frontend ../backend ../shared "find all API endpoints"

# Load custom settings
claude --settings '{"model":"opus","verbose":true}' "complex task"

Конфигурация MCP

FlagDescriptionExample
--mcp-configLoad MCP servers from JSONclaude --mcp-config ./mcp.json
--strict-mcp-configOnly use specified MCP configclaude --strict-mcp-config --mcp-config ./mcp.json
--channelsSubscribe to MCP channel plugins. Entries must be tagged plugin:<name>@<marketplace>; bare names are rejectedclaude --channels plugin:discord@my-marketplace

Примеры MCP

bash
# Load GitHub MCP server
claude --mcp-config ./github-mcp.json "list open PRs"

# Strict mode - only specified servers
claude --strict-mcp-config --mcp-config ./production-mcp.json "deploy to staging"

Управление сессиями

FlagDescriptionExample
--session-idUse specific session ID (UUID)claude --session-id "550e8400-..."
--fork-sessionCreate new session when resumingclaude --resume abc123 --fork-session

Примеры сессий

bash
# Continue last conversation
claude -c

# Resume named session
claude -r "feature-auth" "continue implementing login"

# Fork session for experimentation
claude --resume feature-auth --fork-session "try alternative approach"

# Use specific session ID
claude --session-id "550e8400-e29b-41d4-a716-446655440000" "continue"

Форк сессии

Создайте ветку от существующей сессии для экспериментов:

bash
# Fork a session to try a different approach
claude --resume abc123 --fork-session "try alternative implementation"

# Fork with a custom message
claude -r "feature-auth" --fork-session "test with different architecture"

Сценарии использования:

  • Попробовать альтернативные реализации, не теряя исходную сессию
  • Параллельно экспериментировать с разными подходами
  • Создавать ветки на основе удачных наработок для проработки вариантов
  • Проверять ломающие изменения, не затрагивая основную сессию

Исходная сессия остаётся неизменной, а форк становится новой независимой сессией.

Очистка состояния проекта (v2.1.126+)

claude project purge удаляет всё локальное состояние Claude Code по проекту - транскрипты, списки задач, отладочные логи, историю правок файлов, историю введённых промптов и запись о проекте в ~/.claude.json. Сначала запустите с --dry-run, чтобы предварительно посмотреть, что будет удалено; флаг --all проходит по всем проектам на машине.

bash
# Preview what would be deleted (safe)
claude project purge ~/work/repo --dry-run

# Delete state for a specific project, no prompts
claude project purge ~/work/repo --yes

# Walk every project interactively
claude project purge --all --interactive

Расширенные возможности

FlagDescriptionExample
--chromeEnable Chrome browser integrationclaude --chrome
--no-chromeDisable Chrome browser integrationclaude --no-chrome
--ideAuto-connect to IDE if availableclaude --ide
--max-turnsLimit agentic turns (non-interactive)claude -p --max-turns 3 "query"
--debugEnable debug mode with filteringclaude --debug "api,mcp"
--enable-lsp-loggingEnable verbose LSP loggingclaude --enable-lsp-logging
--betasBeta headers for API requestsclaude --betas interleaved-thinking
--plugin-dirLoad plugins from directory (repeatable)claude --plugin-dir ./my-plugin
--effortSet thinking effort levelclaude --effort high
--bareMinimal mode (skip hooks, skills, plugins, MCP, auto memory, CLAUDE.md)claude --bare
--channelsSubscribe to MCP channel plugins (tagged plugin:<name>@<marketplace>)claude --channels plugin:discord@my-marketplace
--tmuxCreate tmux session for worktreeclaude --tmux
--fork-sessionCreate new session ID when resumingclaude --resume abc --fork-session
--max-budget-usdMaximum spend (print mode); also halts background subagents when hit (v2.1.217)claude -p --max-budget-usd 5.00 "query"
--json-schemaValidated JSON outputclaude -p --json-schema '{"type":"object"}' "q"
--ax-screen-readerPlain-text rendering mode for screen readers (v2.1.208)claude --ax-screen-reader

Примечания по платформам и темам (v2.1.112)

  • Инструмент PowerShell в Windows: постепенно выкатывается отдельный инструмент PowerShell для Windows, который управляется через переменную окружения.
  • Тема «Auto (match terminal)»: новая тема «Auto (match terminal)» синхронизирует светлое/тёмное оформление Claude Code с настройками вашего терминала.
  • Меньше запросов разрешений: вызовы Bash только для чтения и шаблоны Glob больше не приводят к запросу разрешений.

Продвинутые примеры

bash
# Limit autonomous actions
claude -p --max-turns 5 "refactor this module"

# Debug API calls
claude --debug "api" "test query"

# Enable IDE integration
claude --ide "help me with this file"

Конфигурация агентов

Флаг --agents принимает JSON-объект, описывающий пользовательских субагентов для сессии.

Начиная с версии v2.1.243, --agents больше не игнорирует молча некорректный JSON или некорректное определение агента - он завершается с понятной ошибкой, аналогично тому, как это уже работало для --mcp-config.

Формат JSON для агентов

json
{
  "agent-name": {
    "description": "Required: when to invoke this agent",
    "prompt": "Required: system prompt for the agent",
    "tools": ["Optional", "array", "of", "tools"],
    "model": "optional: sonnet|opus|haiku"
  }
}

Обязательные поля:

  • description - описание на естественном языке, указывающее, когда следует использовать этого агента
  • prompt - системный промпт, задающий роль и поведение агента

Необязательные поля:

  • tools - массив доступных инструментов (при отсутствии наследуются все)
    • Формат: ["Read", "Grep", "Glob", "Bash"]
  • model - используемая модель: sonnet, opus или haiku

Полный пример Agents

json
{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  },
  "debugger": {
    "description": "Debugging specialist for errors and test failures.",
    "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes.",
    "tools": ["Read", "Edit", "Bash", "Grep"],
    "model": "opus"
  },
  "documenter": {
    "description": "Documentation specialist for generating guides.",
    "prompt": "You are a technical writer. Create clear, comprehensive documentation.",
    "tools": ["Read", "Write"],
    "model": "haiku"
  }
}

Примеры команд Agents

bash
# Define custom agents inline
claude --agents '{
  "security-auditor": {
    "description": "Security specialist for vulnerability analysis",
    "prompt": "You are a security expert. Find vulnerabilities and suggest fixes.",
    "tools": ["Read", "Grep", "Glob"],
    "model": "opus"
  }
}' "audit this codebase for security issues"

# Load agents from file
claude --agents "$(cat ~/.claude/agents.json)" "review the auth module"

# Combine with other flags
claude -p --agents "$(cat agents.json)" --model sonnet "analyze performance"

Приоритет агентов

Если существует несколько определений одного агента, они загружаются в следующем порядке приоритета:

  1. Заданные через CLI (флаг --agents) - только для текущей сессии
  2. Уровень проекта (.claude/agents/) - текущий проект
  3. Уровень пользователя (~/.claude/agents/) - все проекты

Агенты, заданные через CLI, в рамках сессии переопределяют как проектных, так и пользовательских агентов. Агенты уровня проекта переопределяют агентов уровня пользователя при совпадении имён. Полную таблицу приоритетов, включая агентов уровня plugin, см. в Уроке 04 - Subagents.

Agent View (claude agents, v2.1.139+)

Research Preview - функция достаточно стабильна для повседневного использования, но может измениться.

claude agents открывает Agent View - единый список всех сессий Claude Code на машине с их текущим статусом (running, blocked on you, done). Это альтернатива жонглированию вкладками терминала, когда вы запускаете фоновых агентов, задачи по расписанию или сессии, запущенные через --bg.

bash
# Open the Agent View
claude agents

При запуске сессии из представления (или через claude --bg <prompt>) можно передавать те же конфигурационные флаги, что и самому claude. Флаги, добавленные для механизма запуска через Agent View:

FlagSinceDescription
--cwd <path>v2.1.141Scope the session list (or new session) to a specific working directory
--add-dir <path>v2.1.142Add directories to the dispatched session's workspace
--settings <path>v2.1.142Use a specific settings.json for the dispatched session
--mcp-config <path>v2.1.142Use a specific MCP config for the dispatched session
--plugin-dir <path>v2.1.142Use a specific plugin directory for the dispatched session
--permission-mode <mode>v2.1.142Set permission mode (plan, acceptEdits, auto, etc.) for the dispatched session
--model <model>v2.1.142Pin a model for the dispatched session
--effort <level>v2.1.142Pin an effort level (low/medium/high/xhigh/max)
--dangerously-skip-permissionsv2.1.142Run the dispatched session without permission prompts (use only in sandboxes)
--jsonv2.1.145Print the agent list as machine-readable JSON for scripting (status bars, session pickers, tmux-resurrect integrations)
Сессии, которые завершили работу, но оставили открытым фоновый shell, теперь переходят из «Working» в «Completed» (исправление в v2.1.141). Внутри подключённой сессии агента Shift+Tab циклически переключает режимы разрешений, включая auto mode (v2.1.143).

GitLab merge requests (v2.1.233) - Agent View распознаёт URL merge request'ов GitLab наряду с URL pull request'ов GitHub и отображает merge requests как !N (GitHub pull requests по-прежнему как #N). В том же релизе --worktree научился принимать URL GitLab MR.

Закрепление сессии - нажмите Ctrl+T на сессии в claude agents, чтобы закрепить её (v2.1.147). Закреплённые фоновые сессии не завершаются при простое, перезапускаются на месте для применения обновлений Claude Code, а при нехватке памяти выгружаются в последнюю очередь - только после незакреплённых. (Это сочетание Ctrl+T действует только в Agent View; в основной сессии оно переключает отображение списка задач.)


Наиболее ценные сценарии использования

1. Интеграция с CI/CD

Используйте Claude Code в своих CI/CD-пайплайнах для автоматизированного code review, тестирования и генерации документации.

Пример для GitHub Actions:

yaml
name: AI Code Review

on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Run Code Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p --output-format json \
            --max-turns 1 \
            "Review the changes in this PR for:
            - Security vulnerabilities
            - Performance issues
            - Code quality
            Output as JSON with 'issues' array" > review.json

      - name: Post Review Comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = JSON.parse(fs.readFileSync('review.json', 'utf8'));
            // Process and post review comments

Jenkins Pipeline:

groovy
pipeline {
    agent any
    stages {
        stage('AI Review') {
            steps {
                sh '''
                    claude -p --output-format json \
                      --max-turns 3 \
                      "Analyze test coverage and suggest missing tests" \
                      > coverage-analysis.json
                '''
            }
        }
    }
}

Headless-режим ultrareview (требуется v2.1.227+):

yaml
# .github/workflows/ultrareview.yml
- name: Claude ultrareview
  run: claude ultrareview ${{ github.event.pull_request.number }} --json --no-post > review.json

claude ultrareview завершается с кодом 0, если review не выявил проблем, и с кодом 1, если найдены замечания, - так что его удобно использовать как готовый PR-гейт. Флаг --timeout <minutes> переопределяет значение по умолчанию (30 минут). --post публикует итоговые замечания в pull request, а --no-post оставляет их только в stdout - это как раз то, что нужно, когда последующий шаг CI сам форматирует отчёт.

2. Передача данных через pipe

Пропускайте файлы, логи и данные через Claude для анализа.

Анализ логов:

bash
# Analyze error logs
tail -1000 /var/log/app/error.log | claude -p "summarize these errors and suggest fixes"

# Find patterns in access logs
cat access.log | claude -p "identify suspicious access patterns"

# Analyze git history
git log --oneline -50 | claude -p "summarize recent development activity"

Обработка кода:

bash
# Review a specific file
cat src/auth.ts | claude -p "review this authentication code for security issues"

# Generate documentation
cat src/api/*.ts | claude -p "generate API documentation in markdown"

# Find TODOs and prioritize
grep -r "TODO" src/ | claude -p "prioritize these TODOs by importance"

3. Многосессионные рабочие процессы

Управляйте сложными проектами с несколькими параллельными ветками диалогов.

bash
# Start a feature branch session
claude -r "feature-auth" "let's implement user authentication"

# Later, continue the session
claude -r "feature-auth" "add password reset functionality"

# Fork to try an alternative approach
claude --resume feature-auth --fork-session "try OAuth instead"

# Switch between different feature sessions
claude -r "feature-payments" "continue with Stripe integration"

4. Настройка пользовательских агентов

Определяйте специализированных агентов под рабочие процессы вашей команды.

bash
# Save agents config to file
cat > ~/.claude/agents.json << 'EOF'
{
  "reviewer": {
    "description": "Code reviewer for PR reviews",
    "prompt": "Review code for quality, security, and maintainability.",
    "model": "opus"
  },
  "documenter": {
    "description": "Documentation specialist",
    "prompt": "Generate clear, comprehensive documentation.",
    "model": "sonnet"
  },
  "refactorer": {
    "description": "Code refactoring expert",
    "prompt": "Suggest and implement clean code refactoring.",
    "tools": ["Read", "Edit", "Glob"]
  }
}
EOF

# Use agents in session
claude --agents "$(cat ~/.claude/agents.json)" "review the auth module"

5. Пакетная обработка

Обработка нескольких запросов с едиными настройками.

bash
# Process multiple files
for file in src/*.ts; do
  echo "Processing $file..."
  claude -p --model haiku "summarize this file: $(cat $file)" >> summaries.md
done

# Batch code review
find src -name "*.py" -exec sh -c '
  echo "## $1" >> review.md
  cat "$1" | claude -p "brief code review" >> review.md
' _ {} \;

# Generate tests for all modules
for module in $(ls src/modules/); do
  claude -p "generate unit tests for src/modules/$module" > "tests/$module.test.ts"
done

6. Разработка с учётом безопасности

Используйте контроль разрешений для безопасной работы.

bash
# Read-only security audit
claude --permission-mode plan \
  --tools "Read,Grep,Glob" \
  "audit this codebase for security vulnerabilities"

# Block dangerous commands
claude --disallowedTools "Bash(rm:*)" "Bash(curl:*)" "Bash(wget:*)" \
  "help me clean up this project"

# Restricted automation
claude -p --max-turns 2 \
  --allowedTools "Read" "Glob" \
  "find all hardcoded credentials"

7. Интеграция через JSON API

Используйте Claude как программируемый API для ваших инструментов, разбирая ответы с помощью jq.

bash
# Get structured analysis
claude -p --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array"},"complexity":{"type":"string"}}}' \
  "analyze main.py and return function list with complexity rating"

# Integrate with jq for processing
claude -p --output-format json "list all API endpoints" | jq '.endpoints[]'

# Use in scripts
RESULT=$(claude -p --output-format json "is this code secure? answer with {secure: boolean, issues: []}" < code.py)
if echo "$RESULT" | jq -e '.secure == false' > /dev/null; then
  echo "Security issues found!"
  echo "$RESULT" | jq '.issues[]'
fi

Примеры парсинга с помощью jq

Разбор и обработка JSON-вывода Claude с помощью jq:

bash
# Extract specific fields
claude -p --output-format json "analyze this code" | jq '.result'

# Filter array elements
claude -p --output-format json "list issues" | jq -r '.issues[] | select(.severity=="high")'

# Extract multiple fields
claude -p --output-format json "describe the project" | jq -r '.{name, version, description}'

# Convert to CSV
claude -p --output-format json "list functions" | jq -r '.functions[] | [.name, .lineCount] | @csv'

# Conditional processing
claude -p --output-format json "check security" | jq 'if .vulnerabilities | length > 0 then "UNSAFE" else "SAFE" end'

# Extract nested values
claude -p --output-format json "analyze performance" | jq '.metrics.cpu.usage'

# Process entire array
claude -p --output-format json "find todos" | jq '.todos | length'

# Transform output
claude -p --output-format json "list improvements" | jq 'map({title: .title, priority: .priority})'

Текущая дата: воскресенье, 6 сентября 2026

<query>

Модели

Claude Code поддерживает несколько моделей с разными возможностями:

</query> | Model | ID | Context Window | Notes | |-------|-----|----------------|-------| | Sonnet 5 | `claude-sonnet-5` | 1M tokens | Default on Pro / Team Standard / Enterprise seats (v2.1.197); native 1M-token context window. As of v2.1.219, **Opus 5** is the default Opus model on Max, Team Premium, Enterprise pay-as-you-go, and the Anthropic API; Microsoft Foundry still resolves the `opus` alias to Opus 4.6 | | Opus 5 | `claude-opus-5` | 1M tokens | Default Opus model on Max, Team Premium, Enterprise pay-as-you-go, Anthropic API, Claude Platform on AWS, Amazon Bedrock, and Google Cloud's Agent Platform (v2.1.219); adaptive effort levels `low → max`, default effort `high` | | Opus 4.8 | `claude-opus-4-8` | 1M tokens | Previous flagship Opus, still selectable; adaptive effort levels `low → max`; default effort `high` (v2.1.154) | | Sonnet 4.6 | `claude-sonnet-4-6` | 1M tokens | Balanced speed and capability; default effort for Pro/Max subscribers raised from `medium` to `high` in v2.1.117 | | Haiku 4.5 | `claude-haiku-4-5` | 200K tokens | Fastest, best for quick tasks; no effort levels | | Fable 5.1 | `claude-fable-5-1` | - | Current Fable model; the `fable` alias resolves to it (v2.1.257) | | Fable 5 | `claude-fable-5` | - | Mythos-class model, made safe for general use (v2.1.170) | ### Выбор модели ```bash # Use short names claude --model opus "complex architectural review" claude --model sonnet "implement this feature" claude --model haiku -p "format this JSON"

Use opusplan alias (Opus plans, Sonnet executes)

claude --model opusplan "design and implement the API"

Toggle fast mode during session

/fast

CODE
> **Fable 5.1 и алиас `fable` (v2.1.257)**: Fable 5.1 (`claude-fable-5-1`) вышел в составе **v2.1.257**, и алиас `fable` теперь указывает на него, а не на Fable 5. На официальной странице конфигурации моделей указано, что Fable 5.1 «требует Claude Code v2.1.255 или новее», однако версия 2.1.255 так и не была опубликована - v2.1.257 стала первым релизом, в котором её реально можно установить. На шлюзе Claude apps алиасы `fable` и `best` по-прежнему указывают на **Fable 5**; там 5.1 нужно выбирать явно через `/model`.

> **Fast Mode работает на Opus 5 и Opus 4.8 (v2.1.219)**: Начиная с v2.1.219, `/fast` применим к **Opus 5 и Opus 4.8** - Opus 4.7 из fast mode убран. Fast mode на Opus 5 тарифицируется по $10/$50 за Mtok. Впервые fast mode переехал на Opus 4.8 в v2.1.154 (примерно 2× стандартного тарифа при ~2,5× скорости генерации), а до этого в v2.1.142 переключился с Opus 4.6 на Opus 4.7. Переменная окружения `CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE` была **объявлена устаревшей в v2.1.154 и удалена 2026-06-01**; fast mode на Opus 4.6 больше недоступен - используйте Opus 5 или Opus 4.8.

### Уровни effort (Opus 5 / Sonnet 5 / Opus 4.8 / Opus 4.7)

Opus 5, Sonnet 5, Opus 4.8 и Opus 4.7 поддерживают адаптивный reasoning с уровнями effort, перечисленными от самого лёгкого к самому тяжёлому: `low` (○), `medium` (◐), `high` (●), `xhigh` и `max`. **По умолчанию** используется `high` на Opus 5, Sonnet 5, Opus 4.8 (с v2.1.154), Opus 4.6 и Sonnet 4.6, и `xhigh` на Opus 4.7. `xhigh` доступен на Opus 5, Sonnet 5, Opus 4.8 и Opus 4.7; `max` - на Opus 5, Sonnet 5, Opus 4.8/4.7/4.6 и Sonnet 4.6 (только в рамках сессии). У Haiku 4.5 уровней effort нет. На Opus 4.6 / Sonnet 4.6 значение effort по умолчанию для подписчиков Pro/Max было повышено с `medium` до `high` в v2.1.117.
```bash
# Set effort level via CLI flag
claude --effort high "complex review"

# Set effort level via slash command
/effort high

# Set effort level via environment variable
export CLAUDE_CODE_EFFORT_LEVEL=high   # low, medium, high, xhigh (Opus 5, Sonnet 5, Opus 4.8/4.7), or max - default is high on Opus 5

Ключевое слово ultrathink в промптах активирует глубокие рассуждения. Меню /effort также предлагает ultracode - это не уровень effort модели: команда отправляет xhigh и поручает Claude оркестрировать динамические workflow (действует только в рамках текущей сессии).


Ключевые переменные окружения

VariableDescription
ANTHROPIC_API_KEYAPI key for authentication
ANTHROPIC_MODELOverride default model
ANTHROPIC_DEFAULT_MODEL(v2.1.236) Sets the model new sessions start on. Unlike ANTHROPIC_MODEL, which pins the model, a /model pick still overrides this value and persists across restarts - that contrast is the point of the variable.
ANTHROPIC_CUSTOM_MODEL_OPTIONCustom model option for API
ANTHROPIC_DEFAULT_OPUS_MODELOverride default Opus model ID
ANTHROPIC_DEFAULT_SONNET_MODELOverride default Sonnet model ID
ANTHROPIC_DEFAULT_HAIKU_MODELOverride default Haiku model ID
MAX_THINKING_TOKENSSet extended thinking token budget
CLAUDE_CODE_EFFORT_LEVELSet effort level (low/medium/high/xhigh/max) - default is high on Opus 5, Sonnet 5, and Opus 4.8 (xhigh on Opus 4.7); xhigh needs Opus 5, Sonnet 5, or Opus 4.8/4.7; max works on Opus 5, Sonnet 5, Opus 4.8/4.7/4.6 and Sonnet 4.6
CLAUDE_CODE_SIMPLEMinimal mode, set by --bare flag
CLAUDE_CODE_SAFE_MODESet to 1 to start with all customizations disabled (CLAUDE.md, plugins, skills, hooks, MCP) - env-var form of --safe-mode, for isolating config problems (v2.1.169)
CLAUDE_CODE_DISABLE_BUNDLED_SKILLSSet to 1 to hide the bundled skills, workflows, and commands from the model (v2.1.169)
CLAUDE_CODE_DISABLE_AUTO_MEMORYDisable automatic CLAUDE.md updates
CLAUDE_CODE_DISABLE_BACKGROUND_TASKSDisable background task execution
CLAUDE_CODE_DISABLE_CRONDisable scheduled/cron tasks
CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONSDisable git-related instructions
CLAUDE_CODE_DISABLE_TERMINAL_TITLEDisable terminal title updates
CLAUDE_CODE_DISABLE_1M_CONTEXTDisable 1M token context window
CLAUDE_CODE_DISABLE_MOUSE_CLICKSDisable mouse click/drag/hover in fullscreen mode; wheel scroll still works (v2.1.195+)
CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACKDisable non-streaming fallback
CLAUDE_CODE_ENABLE_TASKSEnable task list feature
CLAUDE_CODE_TASK_LIST_IDNamed task directory shared across sessions
CLAUDE_CODE_ENABLE_PROMPT_SUGGESTIONToggle prompt suggestions (true/false)
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMSEnable experimental agent teams
CLAUDE_CODE_NEW_INITUse new initialization flow
CLAUDE_CODE_SUBAGENT_MODELModel for subagent execution
CLAUDE_CODE_PLUGIN_SEED_DIRDirectory for plugin seed files
CLAUDE_CODE_SUBPROCESS_ENV_SCRUBEnv vars to scrub from subprocesses
CLAUDE_AUTOCOMPACT_PCT_OVERRIDEOverride auto-compaction percentage
CLAUDE_STREAM_IDLE_TIMEOUT_MSStream idle timeout in milliseconds
SLASH_COMMAND_TOOL_CHAR_BUDGETCharacter budget for slash command tools
ENABLE_TOOL_SEARCHEnable tool search capability
MAX_MCP_OUTPUT_TOKENSMaximum tokens for MCP tool output
CLAUDE_CODE_PERFORCE_MODESet to 1 to enable Perforce mode - treats files as read-only by default (for Perforce/P4 version control workflows) (added v2.1.98)
DISABLE_UPDATESBlocks all update paths including manual claude update. Stricter than DISABLE_AUTOUPDATER, which only blocks the background autoupdater (v2.1.118+)
CLAUDE_CODE_HIDE_CWDWhen set to 1, hides the current working directory in the startup logo (privacy / screen-share use) (v2.1.119+)
CLAUDE_CODE_FORK_SUBAGENTSet to 1 to turn fork mode on where it is off by default: non-interactive mode (claude -p), the Agent SDK, or Claude Code older than v2.1.232. Since v2.1.232 fork mode is on by default in interactive sessions on every build, first-party or not (GA v2.1.117)
CLAUDE_CODE_DISABLE_ALTERNATE_SCREENSet to 1 to opt out of the fullscreen alternate-screen renderer; the session stays in normal terminal scrollback. Useful when piping transcripts to logs or pairing with script(1) (v2.1.132+).
CLAUDE_CODE_SESSION_IDSet in every Bash tool subprocess launched by Claude Code; equals the session_id in hook input JSON. Use to correlate bash logs with hook telemetry (v2.1.132+).
CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTELSet to 1 to re-enable Anthropic's session-quality survey for organizations capturing OpenTelemetry data. Off by default in OTEL deployments (v2.1.136+).
OTEL_LOG_TOOL_DETAILSSet to 1 to unredact custom and MCP command names in OpenTelemetry events (v2.1.117+). Redaction remains the default.
CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTHConfigures the truncation limit (default 60 KB) applied to OpenTelemetry content attributes (v2.1.214)
FORCE_HYPERLINKSet to 0 to opt out of clickable PR-badge hyperlinks in the footer, which now render even when terminal support can't be auto-detected (v2.1.217)
ANTHROPIC_BEDROCK_SERVICE_TIERSelects the Bedrock service tier: default, flex, or priority (v2.1.122+)
AI_AGENTSet automatically on subprocesses so external CLIs (e.g., gh) can attribute traffic to Claude Code (v2.1.120+)
CLAUDE_CODE_FORCE_SYNC_OUTPUTSet to 1 to force synchronous output for terminals where auto-detection misses (e.g., Emacs eat) (v2.1.129+)
CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATESet to 1 to enable background upgrades for Homebrew/WinGet installs (which normally do not auto-update) (v2.1.129+)
CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERYSet to 1 to opt in to gateway /v1/models discovery when ANTHROPIC_BASE_URL is set. Without it, /model shows the built-in static list (v2.1.129+)
CLAUDE_CODE_ENABLE_AUTO_MODELegacy opt-in for auto mode on Bedrock, Vertex, and Foundry (v2.1.158-v2.1.206). As of v2.1.207, auto mode is available by default on those providers for Sonnet 5, Opus 4.7/4.8, and Fable 5 (Opus 5 added in v2.1.219) - this variable is accepted for compatibility but has no effect
CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSIONCap on WebSearch tool calls per session, to stop runaway search loops. Default 200 (v2.1.212)
CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTSCap on subagents running concurrently. Default 20 (v2.1.217)
CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTHControls how deep nested subagent spawns can go. Since v2.1.219 the default is 3 layers (was 1); set to 1 to disable nesting entirely
CLAUDE_CODE_MCP_AUTO_BACKGROUND_MSThreshold, in milliseconds, before a long-running MCP tool call auto-backgrounds. Default 120000 (2 minutes) (v2.1.212)
CLAUDE_AX_SCREEN_READERSet to 1 to enable plain-text screen reader rendering mode. Same effect as --ax-screen-reader or "axScreenReader": true in settings (v2.1.208)
CLAUDE_CLIENT_PRESENCE_FILEPoint at a marker file to suppress mobile push notifications while you're at the machine (v2.1.181+). Note: the name is CLAUDE_CLIENT_PRESENCE_FILE, not CLAUDE_CODE_CLIENT_PRESENCE_FILE.
CLAUDE_CODE_MAX_RETRIESMaximum number of API retry attempts. Capped at 15 as of v2.1.186.
CLAUDE_CODE_RETRY_WATCHDOGRetry control recommended for unattended sessions, as an alternative to raising CLAUDE_CODE_MAX_RETRIES (v2.1.186+).
CLAUDE_ENABLE_STREAM_WATCHDOGStreaming idle watchdog (aborts/retries after 5 min with no stream events) is on by default for all providers; set to 0 to disable (v2.1.196).
CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUTOverride the 5-minute idle abort for remote MCP tool calls that hang with no response (v2.1.187+).
CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDERemoved (no-op as of v2.1.160). Previously pinned Fast Mode (/fast) to Opus 4.6. As of v2.1.219, /fast applies to Opus 5 and Opus 4.8 only - Opus 4.6 and Opus 4.7 are no longer fast-mode targets.
CLAUDE_CODE_ENABLE_TODO_TOOLSSet to 1 to restore the todo/task-tracking tools (TaskCreate/Get/Update/List, TodoWrite), which are unavailable on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, and newer models (v2.1.233)
CLAUDE_CODE_WEBFETCH_CACHE_TTL_MSHow long WebFetch caches a fetched URL. Default 15 minutes (v2.1.233)
CLAUDE_CODE_TOOL_MEMORY_LIMITLinux only: opt in to a memory cgroup applied to Bash commands (v2.1.233)
ANTHROPIC_BEDROCK_REGION_PREFIXPrefer a specific Bedrock cross-region inference profile (v2.1.224)
CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENTSet to 1 to restore pre-v2.1.223 auto-compact behavior on unrecognized model IDs (v2.1.223)
CLAUDE_CODE_WORKFLOW_PREFIX_STAGGER_MSSet to 0 to disable prefix staggering on dynamic-workflow fan-out (v2.1.229)
CLAUDE_CODE_USER_DIALOG_TIMEOUT_MSOverrides the dialogExpiry setting (v2.1.224)
CLAUDE_CODE_PROJECT_DIR_NAMEOverrides the per-project transcript directory name Claude Code derives from the project path (v2.1.234)

Эти восемь строк взяты из changelog. На справочной странице CLI нет отдельного раздела о переменных окружения, поэтому они задокументированы по записям changelog v2.1.221-v2.1.234, а не по справочной странице.

CLAUDE_CODE_DISABLE_1M_CONTEXT расширена в v2.1.223: теперь она ограничивает 200K токенами через auto-compaction все модели Claude с нативным окном в 1M токенов, а не только фиксированный список model ID.

ENABLE_TOOL_SEARCH на Vertex AI (v2.1.119+): tool search отключён по умолчанию в развёртываниях на Google Cloud Vertex AI. Пользователям, которым нужна функциональность tool search на Vertex, необходимо явно включить её через export ENABLE_TOOL_SEARCH=true. При прямом использовании Anthropic API она остаётся включённой по умолчанию.


Ключи settings.json

Эти ключи задаются в файле settings.json (~/.claude/settings.json - для пользовательской области, .claude/settings.json - для области проекта), а не передаются в виде флагов или переменных окружения. В таблице ниже перечислены несколько недавно добавленных UI/UX-ключей; про управляемый ключ enforceAvailableModels см. Advanced Features → Managed Settings.

KeyDescription
respondToBashCommands(v2.1.186) Auto-respond to the output of ! bash commands. Default true. Set false for context-only (pre-v2.1.186) behavior. See Advanced Features → Bash Mode.
wheelScrollAccelerationEnabled(v2.1.174) Set to false to disable mouse-wheel scroll acceleration in the fullscreen renderer. Useful when fast wheel flicks overshoot.
footerLinksRegexes(v2.1.176) Array of regexes that render matched links as badges in the footer row. Configurable in user or managed settings.
languageSets Claude's preferred response language and voice-dictation language (e.g. "french", "japanese"). As of v2.1.176 it also pins the language used for auto-generated session titles.
sandbox.filesystem.disabled(v2.1.216) Skips filesystem sandboxing while keeping network egress control enforced. For workflows where file sandboxing breaks tooling but network policy must stay enforced.
emojiCompletionEnabled(v2.1.217) Enables emoji shortcode autocomplete in the prompt input (e.g. typing :heart: inserts ❤️). Set false to disable.
workflowSizeGuideline(v2.1.219) Sets the advisory Dynamic workflow size guideline from any settings file. The guideline is guidance Claude aims for, not a hard cap - the default is medium (aim for fewer than 15 agents), and other sizes or unrestricted can be selected. While this key is set, the "Dynamic workflow size" row is hidden in /config. Distinct from CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS, which is an enforced concurrency limit.
spellcheck(v2.1.235) Underlines misspelled words in the prompt input using whichever of aspell, hunspell, or ispell is on your PATH, tried in that order. Object-valued - {"enabled": true, "language": "en_GB"} - and off by default. Read from user settings, the --settings flag, and managed settings only: a spellcheck block in a project .claude/settings.json or .claude/settings.local.json is ignored. See also Advanced Features → Additional Per-User Settings.
modelPicker(v2.1.243) Choose which models the /model picker lists, in your own order and with your own labels. One of the few settings that replaces rather than merges across settings layers.
promptCacheTtl(v2.1.243) Choose the prompt cache lifetime for the main conversation.
subagentPromptCacheTtl(v2.1.243) The same choice for subagents and other requests outside the main conversation.
modelPricing(v2.1.243) Managed setting. Supplies your organization's contracted rates so /cost, the status line, and telemetry report those instead of list price.
keybindingFlavorDeprecated since v2.1.261 and has no effect. The prompt's word-editing keys always follow readline conventions, as Bash does: Ctrl+W deletes back to whitespace, Alt+F and Alt+D stop at word end, and punctuation separates words. Claude Code still accepts the key, so a settings file that sets it stays valid. (In v2.1.238-v2.1.260 it chose between "classic" and "readline".)
bashOutputMaxChars(v2.1.261) How many characters of a successful Bash or PowerShell command's output Claude receives inline, up to 128K. Past the limit Claude Code saves the output to a file and Claude gets a short preview plus the path. Setting it makes Claude Code ignore BASH_MAX_OUTPUT_LENGTH.
taskOutputMaxChars(v2.1.261) How many characters of a background task's output Claude receives inline when reading it with the TaskOutput tool, up to 128K. For a longer finished task Claude receives the most recent characters. Setting it makes Claude Code ignore TASK_MAX_OUTPUT_LENGTH.
json
{
  "wheelScrollAccelerationEnabled": false,
  "language": "french",
  "footerLinksRegexes": ["https://jira\\.example\\.com/.*"]
}

Текущая дата: воскресенье, 6 сентября 2026 г.

<query>

Краткая справка

Самые распространенные команды

</query> ```bash # Interactive session claude

Quick question

claude -p "how do I..."

Continue conversation

claude -c

Process a file

cat file.py | claude -p "review this"

JSON output for scripts

claude -p --output-format json "query"

CODE
### Комбинации флагов
| Use Case | Command |
|----------|---------|
| Quick code review | `cat file \| claude -p "review"` |
| Structured output | `claude -p --output-format json "query"` |
| Safe exploration | `claude --permission-mode plan` |
| Autonomous with safety | `claude --permission-mode auto` |
| CI/CD integration | `claude -p --max-turns 3 --output-format json` |
| Resume work | `claude -r "session-name"` |
| Custom model | `claude --model opus "complex task"` |
| Minimal mode | `claude --bare "quick query"` |
| Budget-capped run | `claude -p --max-budget-usd 2.00 "analyze code"` |
---

## Устранение неполадок

### Команда не найдена

**Проблема:** `claude: command not found`

**Решения:**
- Установите Claude Code: `npm install -g @anthropic-ai/claude-code`
- Убедитесь, что в PATH добавлен каталог глобальных бинарников npm
- Попробуйте запустить по полному пути: `npx claude`

### Проблемы с API-ключом

**Проблема:** Ошибка аутентификации

**Решения:**
- Задайте API-ключ: `export ANTHROPIC_API_KEY=your-key`
- Убедитесь, что ключ действителен и на нём достаточно средств
- Проверьте, что у ключа есть доступ к запрашиваемой модели

### Сессия не найдена

**Проблема:** Не удаётся возобновить сессию

**Решения:**
- Выведите список доступных сессий, чтобы узнать правильное имя/ID
- Сессии могут истекать после периода бездействия
- Используйте `-c`, чтобы продолжить последнюю сессию

### Проблемы с форматом вывода

**Проблема:** Некорректный JSON на выходе

**Решения:**
- Используйте `--json-schema`, чтобы принудительно задать структуру
- Добавьте в prompt явные инструкции по формату JSON
- Используйте `--output-format json` (а не просто просьбу вернуть JSON в prompt)

### Доступ запрещён

**Проблема:** Запуск инструмента заблокирован

**Решения:**
- Проверьте значение `--permission-mode`
- Проверьте флаги `--allowedTools` и `--disallowedTools`
- Для автоматизации используйте `--dangerously-skip-permissions` (с осторожностью)

---

## Дополнительные ресурсы

- **[Официальный справочник CLI](https://code.claude.com/docs/en/cli-reference)** - полный справочник команд
- **[Документация по headless-режиму](https://code.claude.com/docs/en/headless)** - автоматизированный запуск
- **[Slash-команды](../01-slash-commands/)** - пользовательские сокращения внутри Claude
- **[Руководство по памяти](../02-memory/)** - постоянный контекст через CLAUDE.md
- **[Протокол MCP](../05-mcp/)** - интеграция с внешними инструментами
- **[Продвинутые возможности](../09-advanced-features/)** - режим планирования, extended thinking
- **[Руководство по subagents](../04-subagents/)** - делегирование выполнения задач

---

*Часть серии руководств [Claude How To](../)*

---

**Последнее обновление**: 6 сентября 2026 г.
**Версия Claude Code**: 2.1.263
**Источники**:
- https://code.claude.com/docs/en/cli-reference
- https://code.claude.com/docs/en/env-vars
- https://code.claude.com/docs/en/changelog#2-1-174
- https://code.claude.com/docs/en/changelog#2-1-176
- https://code.claude.com/docs/en/changelog
- https://code.claude.com/docs/en/settings
- https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md
- https://code.claude.com/docs/en/troubleshooting
- https://code.claude.com/docs/en/commands
- https://code.claude.com/docs/en/model-config
- https://platform.claude.com/docs/en/about-claude/models/overview
- https://www.anthropic.com/news/claude-opus-4-8
- https://github.com/anthropics/claude-code/releases/tag/v2.1.117
- https://github.com/anthropics/claude-code/releases/tag/v2.1.139
- https://github.com/anthropics/claude-code/releases/tag/v2.1.142
- https://github.com/anthropics/claude-code/releases/tag/v2.1.154
- https://code.claude.com/docs/en/plugins
- https://code.claude.com/docs/en/overview
- https://code.claude.com/docs/en/sub-agents
- https://code.claude.com/docs/en/headless
- https://code.claude.com/docs/en/cli-reference.md
- https://code.claude.com/docs/en/settings.md
- https://code.claude.com/docs/en/settings-reference
**Совместимые модели**: Claude Fable 5, Claude Opus 5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.8, Claude Haiku 4.5
ЛОКАЛЬНАЯ ОТМЕТКА · БЕЗ ПРОВЕРКИ
cc-learnМОДУЛЬ 10
МОДУЛЬ 10/УРОК

CLI и флаги

Справочник по CLI

Обзор

Claude Code CLI (интерфейс командной строки) - это основной способ взаимодействия с Claude Code. Он предоставляет широкие возможности для выполнения запросов, управления сессиями, настройки моделей и встраивания Claude в процессы разработки.

Архитектура

graph TD A["User Terminal"] -->|"claude [options] [query]"| B["Claude Code CLI"] B -->|Interactive| C["REPL Mode"] B -->|"--print"| D["Print Mode (SDK)"] B -->|"--resume"| E["Session Resume"] C -->|Conversation| F["Claude API"] D -->|Single Query| F E -->|Load Context| F F -->|Response| G["Output"] G -->|text/json/stream-json| H["Terminal/Pipe"]

Среда выполнения и упаковка

Начиная с v2.1.113, Claude Code CLI запускается как нативный бинарный файл для конкретной платформы (macOS, Linux, Windows) через опциональные npm-зависимости. Нужный бинарник подбирается под вашу ОС и архитектуру на этапе установки - прежняя упакованная JavaScript-среда выполнения больше не используется по умолчанию на macOS и Linux.

Со стороны пользователя способ установки не изменился: npm install -g @anthropic-ai/claude-code по-прежнему работает и остаётся рекомендуемым способом. Под капотом npm скачивает подходящий нативный бинарник для вашей платформы.

Хост для загрузки (v2.1.116+): артефакты нативных бинарников раздаются с https://downloads.claude.ai/claude-code-releases.

Корпоративным пользователям и тем, кто работает через прокси: если ваша сеть требует явного allowlist, добавьте downloads.claude.ai (и https://downloads.claude.ai/claude-code-releases) в правила исходящего трафика прокси. Окружения, в которых ранее в allowlist были только storage.googleapis.com или npm registry, потребуется обновить - иначе claude update и первичная установка будут завершаться с ошибкой.

Старый JavaScript-бандл по-прежнему собирается для Windows и для окружений, которые к нему привязаны; в таких сборках Glob и Grep поставляются как полноценные инструменты (см. сноску про Glob/Grep в разделе Инструменты).

Команды CLI

CommandDescriptionExample
claudeStart interactive REPLclaude
claude "query"Start REPL with initial promptclaude "explain this project"
claude -p "query"Print mode - query then exitclaude -p "explain this function"
cat file | claude -p "query"Process piped contentcat logs.txt | claude -p "explain"
claude -cContinue most recent conversationclaude -c
claude -c -p "query"Continue in print modeclaude -c -p "check for type errors"
claude -r "<session>" "query"Resume session by ID or nameclaude -r "auth-refactor" "finish this PR"
claude updateUpdate to latest versionclaude update
/doctor (slash command)Diagnose installation, config, and plugin health. Since v2.1.116 it can be opened while Claude is responding, shows status icons inline, and accepts the f keypress to auto-fix detected issues. v2.1.178 refreshed the layout to a flat tree with clearer status icons and highlighted commandsrun /doctor inside the REPL
claude mcpConfigure MCP servers (incl. login/logout for auth, v2.1.186+)See MCP documentation
claude mcp serveRun Claude Code as an MCP serverclaude mcp serve
claude agentsOpen the Agent View (Research Preview, v2.1.139+) - multi-session manager listing every Claude Code session with its status. See Agent View below.claude agents
claude auto-mode defaultsPrint auto mode default rules as JSONclaude auto-mode defaults
claude auto-mode resetRestore default auto-mode configuration, with a confirmation prompt (--yes to skip) (v2.1.212)claude auto-mode reset --yes
claude --remote-control [name]Start Remote Control (a flag, not a subcommand; alias --rc)claude --rc
claude pluginManage plugins (install, enable, disable)claude plugin install my-plugin
claude plugin init <name>Scaffold a new plugin at ~/.claude/skills/<name>/ (user-global) - auto-loads in the next session as <name>@skills-dir, no marketplace required (v2.1.157+)claude plugin init my-plugin
claude plugin tag [path]Create a {name}--v{version} release git tag for the plugin at [path], validating that plugin.json and any enclosing marketplace entry agree (v2.1.118+)claude plugin tag ./my-plugin
claude install [version]Install a specific native-binary version. Accepts stable, latest, or an explicit version stringclaude install 2.1.131
claude project purge [path]Delete all local Claude Code state for a project (transcripts, tasks, debug logs, file-edit history, prompt history, and ~/.claude.json entry). Omit [path] for an interactive picker. Flags: --dry-run to preview, -y/--yes to skip confirmation, -i/--interactive to confirm each item, --all for every project (v2.1.126+)claude project purge ~/work/repo --dry-run
claude plugin pruneRemove orphaned auto-installed plugin dependencies (parent plugin gone). plugin uninstall --prune does the same cascade after uninstalling a target (v2.1.121+)claude plugin prune
claude ultrareview [target]Run /ultrareview non-interactively. Prints findings to stdout, exits 0 on success / 1 on failure. Use --json for raw payload, --timeout <minutes> to override the 30-minute default, and --post / --no-post to control whether findings are posted back to the PR. Requires Claude Code v2.1.227 or laterclaude ultrareview 1234 --json --no-post
claude self-hosted-runner <setup|doctor|orchestrator>Turn your own machine or container into a place Claude Code web, mobile, and desktop sessions can run. setup provisions the runner, doctor diagnoses it, orchestrator runs the coordinating process. Team and Enterprise plans; requires Claude Code v2.1.224 or later. On Windows, startup requires an explicit --base-dir (v2.1.229)claude self-hosted-runner setup
claude auth loginLog in (supports --email, --sso). Since v2.1.126, accepts the OAuth code pasted into the terminal as a fallback when the browser callback can't reach localhost (WSL2, SSH, containers)claude auth login --email user@example.com
claude auth logoutLog out of current accountclaude auth logout
claude auth statusCheck auth status (exit 0 if logged in, 1 if not)claude auth status

Основные флаги

FlagDescriptionExample
-p, --printPrint response without interactive modeclaude -p "query"
-c, --continueLoad most recent conversationclaude --continue
-r, --resumeResume specific session by ID or nameclaude --resume auth-refactor
-v, --versionOutput version numberclaude -v
-w, --worktreeStart in isolated git worktree. Accepts a GitLab merge-request URL as well as a GitHub PR URL since v2.1.233claude -w
-n, --nameSession display nameclaude -n "auth-refactor"
--from-pr <url-or-number>Resume sessions linked to a pull/merge request. Accepts GitHub (cloud + Enterprise), GitLab MR, and Bitbucket PR URLs since v2.1.119; previously GitHub.com onlyclaude --from-pr 42 or claude --from-pr https://gitlab.example.com/org/repo/-/merge_requests/17
--cloud [description|session_id|url]Create a cloud session on claude.ai with the given description, or attach to an existing one by session ID or claude.ai/code URLclaude --cloud "implement API"
--remote "task"Deprecated alias for --cloud, including the existing-session form. Use --cloud insteadclaude --remote "implement API"
--remote-control, --rcInteractive session with Remote Controlclaude --rc
--teleport [session]Resume a web session locally. Bare form opens a picker of your web sessions; pass a session ID to resume that session directly. Requires a claude.ai subscriptionclaude --teleport
--teammate-modeAgent team display modeclaude --teammate-mode tmux
--bareMinimal mode (skip hooks, skills, plugins, MCP, auto memory, CLAUDE.md)claude --bare
--safe-modeStart with all customizations disabled (CLAUDE.md, plugins, skills, hooks, MCP) to isolate config problems; also CLAUDE_CODE_SAFE_MODE=1 (v2.1.169)claude --safe-mode
--restrictedLock the session down for untrusted or shared use: removes the built-in command- and code-running tools and WebFetch, ignores user/project/local settings, confines file tools to the working directories, and refuses bypassPermissions and cloud sessions. Also CLAUDE_CODE_RESTRICTED=1 (v2.1.248+)claude --restricted -p "summarize this repo"
--permission-mode autoStart in auto permission mode (replaces the removed --enable-auto-mode flag, gone since v2.1.111)claude --permission-mode auto
--channelsSubscribe to MCP channel plugins. Entries must be tagged plugin:<name>@<marketplace>; bare names are rejectedclaude --channels plugin:discord@my-marketplace
--chrome / --no-chromeEnable/disable Chrome browser integrationclaude --chrome
--effortSet thinking effort levelclaude --effort high
--init / --init-onlyRun initialization hooksclaude --init
--maintenanceRun maintenance hooks and exitclaude --maintenance
--disable-slash-commandsDisable all skills and slash commandsclaude --disable-slash-commands
--no-session-persistenceDisable session saving (print mode)claude -p --no-session-persistence "query"
--exclude-dynamic-system-prompt-sectionsExclude dynamic sections from the system prompt for better prompt cache hit ratesclaude -p --exclude-dynamic-system-prompt-sections "query"

Ограниченный режим (--restricted, v2.1.248+)

--restricted (или CLAUDE_CODE_RESTRICTED=1) предназначен для запуска claude от имени того, чей ввод вы не контролируете, - оценочного harness на общей машине, CI-задачи, запущенной внешним контрибьютором, демо-стенда. Он применяет сразу всё перечисленное ниже:

  • Убирает инструменты, выполняющие команды или код - Bash, PowerShell и REPL, - а также WebFetch, если только они не указаны явно через --tools.
  • Игнорирует пользовательские, проектные и локальные файлы настроек. Managed settings и файл, заданный явно через --settings, по-прежнему учитываются, так что администратор сохраняет контроль, а закоммиченный в репозиторий .claude/settings.json не сможет расширить sandbox.
  • Ограничивает файловые инструменты рабочими директориями, так что чтение и запись не могут выйти за пределы путей, с которых вы стартовали.
  • Отклоняет bypassPermissions, каким бы способом он ни запрашивался.
  • Отказывается создавать cloud-сессии, чтобы ограниченный запуск не мог вынести работу за пределы машины.
bash
# Evaluation harness: no shell, no network fetches, no settings inheritance
claude --restricted -p "summarize the architecture of this repo"

# Same lockdown, but deliberately re-enable one tool
claude --restricted --tools WebFetch -p "check the linked RFC"

Примечание: --restricted - более жёсткое ограничение, чем --permission-mode. Этот флаг полностью отключает инструменты, а не запрашивает разрешение на их использование, поэтому расширить права ограниченной сессии изнутри неё самой невозможно.

Интерактивный режим против режима print

graph LR A["claude"] -->|Default| B["Interactive REPL"] A -->|"-p flag"| C["Print Mode"] B -->|Features| D["Multi-turn conversation<br>Tab completion<br>History<br>Slash commands"] C -->|Features| E["Single query<br>Scriptable<br>Pipeable<br>JSON output"]

Интерактивный режим (по умолчанию):

bash
# Start interactive session
claude

# Start with initial prompt
claude "explain the authentication flow"

Режим вывода (неинтерактивный):

bash
# Single query, then exit
claude -p "what does this function do?"

# Process file content
cat error.log | claude -p "explain this error"

# Chain with other tools
claude -p "list todos" | grep "URGENT"

Модель и конфигурация

FlagDescriptionExample
--modelSet model (sonnet, opus, haiku, or full name)claude --model opus
--fallback-modelAutomatic model fallback when the primary is overloaded/unavailable; configure up to three via the fallbackModel setting. Applies to interactive sessions too since v2.1.166 (previously print mode only)claude -p --fallback-model sonnet "query"
--agentSpecify agent for sessionclaude --agent my-custom-agent
--agentsDefine custom subagents via JSONSee Agents Configuration
--effortSet effort level (low, medium, high, xhigh, max)claude --effort xhigh

Примеры выбора модели

bash
# Use Opus 5 for complex tasks
claude --model opus "design a caching strategy"

# Use Haiku 4.5 for quick tasks
claude --model haiku -p "format this JSON"

# Full model name
claude --model claude-sonnet-4-6-20250929 "review this code"

# With fallback for reliability
claude -p --model opus --fallback-model sonnet "analyze architecture"

# Use opusplan (Opus plans, Sonnet executes)
claude --model opusplan "design and implement the caching layer"

Обнаружение моделей через gateway (v2.1.129+, opt-in): если ANTHROPIC_BASE_URL указывает на Anthropic-совместимый gateway, установите CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1, чтобы список /model заполнялся из endpoint /v1/models этого gateway. Без этой переменной окружения /model использует встроенный статический список. Флаг сделан opt-in (изменено в v2.1.129), поскольку discovery-запрос может вернуть модели, к которым у пользователя нет доступа; в v2.1.126 поведение было неявным (включено по умолчанию), но затем откачено.

Модель по умолчанию для организации (v2.1.196): когда администратор организации задаёт модель по умолчанию, /model помечает её как «Org default» (или «Role default»).

Настройка System Prompt

FlagDescriptionExample
--system-promptReplace entire default promptclaude --system-prompt "You are a Python expert"
--system-prompt-fileLoad prompt from file (print mode)claude -p --system-prompt-file ./prompt.txt "query"
--append-system-promptAppend to default promptclaude --append-system-prompt "Always use TypeScript"
--append-subagent-system-promptAppend text to every subagent's system prompt (non-interactive)claude -p --append-subagent-system-prompt "Cite sources" "query"
--append-subagent-system-prompt-file(v2.1.261) Load that appended text from a file instead, for prompts too long to pass on the command line. Non-interactive only, and cannot be combined with --append-subagent-system-promptclaude -p --append-subagent-system-prompt-file ./subagent-rules.txt "query"

Примеры системных промптов

bash
# Complete custom persona
claude --system-prompt "You are a senior security engineer. Focus on vulnerabilities."

# Append specific instructions
claude --append-system-prompt "Always include unit tests with code examples"

# Load complex prompt from file
claude -p --system-prompt-file ./prompts/code-reviewer.txt "review main.py"

Сравнение флагов системного промпта

FlagBehaviorInteractivePrint
--system-promptReplaces entire default system prompt✅✅
--system-prompt-fileReplaces with prompt from file❌✅
--append-system-promptAppends to default system prompt✅✅
Используйте --system-prompt-file только в режиме print. Для интерактивного режима используйте --system-prompt или --append-system-prompt.

Управление инструментами и разрешениями

FlagDescriptionExample
--toolsRestrict available built-in toolsclaude -p --tools "Bash,Edit,Read" "query"
--allowedToolsTools that execute without prompting"Bash(git log:*)" "Read"
--disallowedToolsTools removed from context"Bash(rm:*)" "Edit"
--dangerously-skip-permissionsSkip all permission promptsclaude --dangerously-skip-permissions
--permission-modeBegin in specified permission modeclaude --permission-mode auto
--permission-prompt-toolMCP tool for permission handlingclaude -p --permission-prompt-tool mcp_auth "query"
--permission-prompts(v2.1.259) Who answers permission prompts in print mode. Default host sends them to the Agent SDK host or the --permission-prompt-tool tool; pass none when nobody can answer and Claude Code denies them insteadclaude -p --permission-prompts none "query"

Обновление v2.1.111: флаг --enable-auto-mode удалён; auto mode теперь по умолчанию входит в цикл Shift+Tab - используйте --permission-mode auto, чтобы сразу запуститься в этом режиме.

Примечание по Glob / Grep (v2.1.113+): в нативных сборках для macOS/Linux Glob и Grep реализованы через встроенные бинарники bfs и ugrep, вызываемые через Bash-инструмент, а не как отдельные полноценные инструменты. В сборках для Windows и в npm-пакете (JS) они по-прежнему доступны как самостоятельные инструменты. Для списков allowedTools / disallowedTools у сабагентов эта замена на стороне бэкенда прозрачна - в конфигурации можно продолжать указывать Glob / Grep на любой платформе.

Автоодобрение PowerShell (v2.1.119): команды инструмента PowerShell могут автоматически одобряться в permission mode ровно так же, как команды Bash. Для ограничения разрешений PowerShell используйте тот же синтаксис matcher, что и для правил Bash(...) - например, PowerShell(Get-ChildItem:*).

--permission-mode учитывается при возобновлении сессии (v2.1.132+): claude -p --continue --permission-mode plan (а также --resume) теперь корректно учитывает этот флаг. В более ранних версиях --permission-mode при возобновлении сессии молча игнорировался, из-за чего сессия в plan mode, возобновлённая без повторной передачи флага, незаметно понижалась в правах - теперь это исправлено.

Ужесточение разрешений (v2.1.214): команды Docker/Podman с флагами перенаправления демона (например, --url, --connection, --identity) теперь требуют подтверждения вместо автоматического выполнения. Команды file с флагами -m/--magic-file или -f/--files-from также требуют подтверждения. Команды Bash длиной более 10 000 символов всегда запрашивают подтверждение - независимо от allow-правил.

Примеры разрешений

bash
# Read-only mode for code review
claude --permission-mode plan "review this codebase"

# Restrict to safe tools only
claude --tools "Read,Grep,Glob" -p "find all TODO comments"

# Allow specific git commands without prompts
claude --allowedTools "Bash(git status:*)" "Bash(git log:*)"

# Block dangerous operations
claude --disallowedTools "Bash(rm -rf:*)" "Bash(git push --force:*)"

Сопоставление параметров Tool(param:value) (v2.1.178): правила разрешений задаются в формате Tool (любое использование) или Tool(specifier). Начиная с v2.1.178, спецификатор может сопоставляться с входными параметрами инструмента, а не только с шаблонами команд или путей - через форму Tool(param:value) с поддержкой wildcard. Это обобщает механизм сопоставления, который вы уже применяете для префиксов команд в Bash(...) (например, Bash(npm run test *)) и glob-шаблонов путей в Read(...) (например, Read(./.env.*)), позволяя ограничивать и другие инструменты по их аргументам. Перед написанием правила сверяйтесь со справочником по разрешениям, чтобы узнать актуальные примеры для конкретного инструмента, поскольку точные имена параметров различаются от инструмента к инструменту.

Вывод и формат

FlagDescriptionOptionsExample
--output-formatSpecify output format (print mode)text, json, stream-jsonclaude -p --output-format json "query"
--input-formatSpecify input format (print mode)text, stream-jsonclaude -p --input-format stream-json
--verboseEnable verbose loggingclaude --verbose
--include-partial-messagesInclude streaming eventsRequires stream-jsonclaude -p --output-format stream-json --include-partial-messages "query"
--forward-subagent-textForward subagent text output into the stream. As of v2.1.219, subagents spawned at depth 2 or deeper are forwarded too, keyed by their spawning Agent tool_use id (this is how you observe the nesting enabled by default via CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH)Requires stream-jsonclaude -p --output-format stream-json --forward-subagent-text "query"
--json-schemaGet validated JSON matching schemaclaude -p --json-schema '{"type":"object"}' "query"
--max-budget-usdMaximum spend for print mode. Since v2.1.217, hitting the cap also halts running background subagents and denies new spawns (previously background agents kept running past the cap)claude -p --max-budget-usd 5.00 "query"

Примеры формата вывода

bash
# Plain text (default)
claude -p "explain this code"

# JSON for programmatic use
claude -p --output-format json "list all functions in main.py"

# Streaming JSON for real-time processing
claude -p --output-format stream-json "generate a long report"

# Structured output with schema validation
claude -p --json-schema '{"type":"object","properties":{"bugs":{"type":"array"}}}' \
  "find bugs in this code and return as JSON"

Рабочая область и каталог

FlagDescriptionExample
--add-dirAdd additional working directoriesclaude --add-dir ../apps ../lib
--setting-sourcesComma-separated setting sourcesclaude --setting-sources user,project

Сохранение /config (v2.1.119): Изменения, внесённые интерактивно через команду /config, теперь записываются в ~/.claude/settings.json и участвуют в стандартной цепочке приоритетов (policy → local → project → user). До v2.1.119 часть изменений /config действовала только в пределах сессии. Полный порядок приоритетов см. в разделе Память и настройки. | --settings | Загрузить настройки из файла или JSON. Размер файла не должен превышать 2 MiB (v2.1.214) | claude --settings ./settings.json | | --plugin-dir | Загрузить плагины из указанной директории (можно указывать несколько раз) | claude --plugin-dir ./my-plugin |

Пример с несколькими директориями

bash
# Work across multiple project directories
claude --add-dir ../frontend ../backend ../shared "find all API endpoints"

# Load custom settings
claude --settings '{"model":"opus","verbose":true}' "complex task"

Конфигурация MCP

FlagDescriptionExample
--mcp-configLoad MCP servers from JSONclaude --mcp-config ./mcp.json
--strict-mcp-configOnly use specified MCP configclaude --strict-mcp-config --mcp-config ./mcp.json
--channelsSubscribe to MCP channel plugins. Entries must be tagged plugin:<name>@<marketplace>; bare names are rejectedclaude --channels plugin:discord@my-marketplace

Примеры MCP

bash
# Load GitHub MCP server
claude --mcp-config ./github-mcp.json "list open PRs"

# Strict mode - only specified servers
claude --strict-mcp-config --mcp-config ./production-mcp.json "deploy to staging"

Управление сессиями

FlagDescriptionExample
--session-idUse specific session ID (UUID)claude --session-id "550e8400-..."
--fork-sessionCreate new session when resumingclaude --resume abc123 --fork-session

Примеры сессий

bash
# Continue last conversation
claude -c

# Resume named session
claude -r "feature-auth" "continue implementing login"

# Fork session for experimentation
claude --resume feature-auth --fork-session "try alternative approach"

# Use specific session ID
claude --session-id "550e8400-e29b-41d4-a716-446655440000" "continue"

Форк сессии

Создайте ветку от существующей сессии для экспериментов:

bash
# Fork a session to try a different approach
claude --resume abc123 --fork-session "try alternative implementation"

# Fork with a custom message
claude -r "feature-auth" --fork-session "test with different architecture"

Сценарии использования:

  • Попробовать альтернативные реализации, не теряя исходную сессию
  • Параллельно экспериментировать с разными подходами
  • Создавать ветки на основе удачных наработок для проработки вариантов
  • Проверять ломающие изменения, не затрагивая основную сессию

Исходная сессия остаётся неизменной, а форк становится новой независимой сессией.

Очистка состояния проекта (v2.1.126+)

claude project purge удаляет всё локальное состояние Claude Code по проекту - транскрипты, списки задач, отладочные логи, историю правок файлов, историю введённых промптов и запись о проекте в ~/.claude.json. Сначала запустите с --dry-run, чтобы предварительно посмотреть, что будет удалено; флаг --all проходит по всем проектам на машине.

bash
# Preview what would be deleted (safe)
claude project purge ~/work/repo --dry-run

# Delete state for a specific project, no prompts
claude project purge ~/work/repo --yes

# Walk every project interactively
claude project purge --all --interactive

Расширенные возможности

FlagDescriptionExample
--chromeEnable Chrome browser integrationclaude --chrome
--no-chromeDisable Chrome browser integrationclaude --no-chrome
--ideAuto-connect to IDE if availableclaude --ide
--max-turnsLimit agentic turns (non-interactive)claude -p --max-turns 3 "query"
--debugEnable debug mode with filteringclaude --debug "api,mcp"
--enable-lsp-loggingEnable verbose LSP loggingclaude --enable-lsp-logging
--betasBeta headers for API requestsclaude --betas interleaved-thinking
--plugin-dirLoad plugins from directory (repeatable)claude --plugin-dir ./my-plugin
--effortSet thinking effort levelclaude --effort high
--bareMinimal mode (skip hooks, skills, plugins, MCP, auto memory, CLAUDE.md)claude --bare
--channelsSubscribe to MCP channel plugins (tagged plugin:<name>@<marketplace>)claude --channels plugin:discord@my-marketplace
--tmuxCreate tmux session for worktreeclaude --tmux
--fork-sessionCreate new session ID when resumingclaude --resume abc --fork-session
--max-budget-usdMaximum spend (print mode); also halts background subagents when hit (v2.1.217)claude -p --max-budget-usd 5.00 "query"
--json-schemaValidated JSON outputclaude -p --json-schema '{"type":"object"}' "q"
--ax-screen-readerPlain-text rendering mode for screen readers (v2.1.208)claude --ax-screen-reader

Примечания по платформам и темам (v2.1.112)

  • Инструмент PowerShell в Windows: постепенно выкатывается отдельный инструмент PowerShell для Windows, который управляется через переменную окружения.
  • Тема «Auto (match terminal)»: новая тема «Auto (match terminal)» синхронизирует светлое/тёмное оформление Claude Code с настройками вашего терминала.
  • Меньше запросов разрешений: вызовы Bash только для чтения и шаблоны Glob больше не приводят к запросу разрешений.

Продвинутые примеры

bash
# Limit autonomous actions
claude -p --max-turns 5 "refactor this module"

# Debug API calls
claude --debug "api" "test query"

# Enable IDE integration
claude --ide "help me with this file"

Конфигурация агентов

Флаг --agents принимает JSON-объект, описывающий пользовательских субагентов для сессии.

Начиная с версии v2.1.243, --agents больше не игнорирует молча некорректный JSON или некорректное определение агента - он завершается с понятной ошибкой, аналогично тому, как это уже работало для --mcp-config.

Формат JSON для агентов

json
{
  "agent-name": {
    "description": "Required: when to invoke this agent",
    "prompt": "Required: system prompt for the agent",
    "tools": ["Optional", "array", "of", "tools"],
    "model": "optional: sonnet|opus|haiku"
  }
}

Обязательные поля:

  • description - описание на естественном языке, указывающее, когда следует использовать этого агента
  • prompt - системный промпт, задающий роль и поведение агента

Необязательные поля:

  • tools - массив доступных инструментов (при отсутствии наследуются все)
    • Формат: ["Read", "Grep", "Glob", "Bash"]
  • model - используемая модель: sonnet, opus или haiku

Полный пример Agents

json
{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  },
  "debugger": {
    "description": "Debugging specialist for errors and test failures.",
    "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes.",
    "tools": ["Read", "Edit", "Bash", "Grep"],
    "model": "opus"
  },
  "documenter": {
    "description": "Documentation specialist for generating guides.",
    "prompt": "You are a technical writer. Create clear, comprehensive documentation.",
    "tools": ["Read", "Write"],
    "model": "haiku"
  }
}

Примеры команд Agents

bash
# Define custom agents inline
claude --agents '{
  "security-auditor": {
    "description": "Security specialist for vulnerability analysis",
    "prompt": "You are a security expert. Find vulnerabilities and suggest fixes.",
    "tools": ["Read", "Grep", "Glob"],
    "model": "opus"
  }
}' "audit this codebase for security issues"

# Load agents from file
claude --agents "$(cat ~/.claude/agents.json)" "review the auth module"

# Combine with other flags
claude -p --agents "$(cat agents.json)" --model sonnet "analyze performance"

Приоритет агентов

Если существует несколько определений одного агента, они загружаются в следующем порядке приоритета:

  1. Заданные через CLI (флаг --agents) - только для текущей сессии
  2. Уровень проекта (.claude/agents/) - текущий проект
  3. Уровень пользователя (~/.claude/agents/) - все проекты

Агенты, заданные через CLI, в рамках сессии переопределяют как проектных, так и пользовательских агентов. Агенты уровня проекта переопределяют агентов уровня пользователя при совпадении имён. Полную таблицу приоритетов, включая агентов уровня plugin, см. в Уроке 04 - Subagents.

Agent View (claude agents, v2.1.139+)

Research Preview - функция достаточно стабильна для повседневного использования, но может измениться.

claude agents открывает Agent View - единый список всех сессий Claude Code на машине с их текущим статусом (running, blocked on you, done). Это альтернатива жонглированию вкладками терминала, когда вы запускаете фоновых агентов, задачи по расписанию или сессии, запущенные через --bg.

bash
# Open the Agent View
claude agents

При запуске сессии из представления (или через claude --bg <prompt>) можно передавать те же конфигурационные флаги, что и самому claude. Флаги, добавленные для механизма запуска через Agent View:

FlagSinceDescription
--cwd <path>v2.1.141Scope the session list (or new session) to a specific working directory
--add-dir <path>v2.1.142Add directories to the dispatched session's workspace
--settings <path>v2.1.142Use a specific settings.json for the dispatched session
--mcp-config <path>v2.1.142Use a specific MCP config for the dispatched session
--plugin-dir <path>v2.1.142Use a specific plugin directory for the dispatched session
--permission-mode <mode>v2.1.142Set permission mode (plan, acceptEdits, auto, etc.) for the dispatched session
--model <model>v2.1.142Pin a model for the dispatched session
--effort <level>v2.1.142Pin an effort level (low/medium/high/xhigh/max)
--dangerously-skip-permissionsv2.1.142Run the dispatched session without permission prompts (use only in sandboxes)
--jsonv2.1.145Print the agent list as machine-readable JSON for scripting (status bars, session pickers, tmux-resurrect integrations)
Сессии, которые завершили работу, но оставили открытым фоновый shell, теперь переходят из «Working» в «Completed» (исправление в v2.1.141). Внутри подключённой сессии агента Shift+Tab циклически переключает режимы разрешений, включая auto mode (v2.1.143).

GitLab merge requests (v2.1.233) - Agent View распознаёт URL merge request'ов GitLab наряду с URL pull request'ов GitHub и отображает merge requests как !N (GitHub pull requests по-прежнему как #N). В том же релизе --worktree научился принимать URL GitLab MR.

Закрепление сессии - нажмите Ctrl+T на сессии в claude agents, чтобы закрепить её (v2.1.147). Закреплённые фоновые сессии не завершаются при простое, перезапускаются на месте для применения обновлений Claude Code, а при нехватке памяти выгружаются в последнюю очередь - только после незакреплённых. (Это сочетание Ctrl+T действует только в Agent View; в основной сессии оно переключает отображение списка задач.)


Наиболее ценные сценарии использования

1. Интеграция с CI/CD

Используйте Claude Code в своих CI/CD-пайплайнах для автоматизированного code review, тестирования и генерации документации.

Пример для GitHub Actions:

yaml
name: AI Code Review

on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Run Code Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p --output-format json \
            --max-turns 1 \
            "Review the changes in this PR for:
            - Security vulnerabilities
            - Performance issues
            - Code quality
            Output as JSON with 'issues' array" > review.json

      - name: Post Review Comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = JSON.parse(fs.readFileSync('review.json', 'utf8'));
            // Process and post review comments

Jenkins Pipeline:

groovy
pipeline {
    agent any
    stages {
        stage('AI Review') {
            steps {
                sh '''
                    claude -p --output-format json \
                      --max-turns 3 \
                      "Analyze test coverage and suggest missing tests" \
                      > coverage-analysis.json
                '''
            }
        }
    }
}

Headless-режим ultrareview (требуется v2.1.227+):

yaml
# .github/workflows/ultrareview.yml
- name: Claude ultrareview
  run: claude ultrareview ${{ github.event.pull_request.number }} --json --no-post > review.json

claude ultrareview завершается с кодом 0, если review не выявил проблем, и с кодом 1, если найдены замечания, - так что его удобно использовать как готовый PR-гейт. Флаг --timeout <minutes> переопределяет значение по умолчанию (30 минут). --post публикует итоговые замечания в pull request, а --no-post оставляет их только в stdout - это как раз то, что нужно, когда последующий шаг CI сам форматирует отчёт.

2. Передача данных через pipe

Пропускайте файлы, логи и данные через Claude для анализа.

Анализ логов:

bash
# Analyze error logs
tail -1000 /var/log/app/error.log | claude -p "summarize these errors and suggest fixes"

# Find patterns in access logs
cat access.log | claude -p "identify suspicious access patterns"

# Analyze git history
git log --oneline -50 | claude -p "summarize recent development activity"

Обработка кода:

bash
# Review a specific file
cat src/auth.ts | claude -p "review this authentication code for security issues"

# Generate documentation
cat src/api/*.ts | claude -p "generate API documentation in markdown"

# Find TODOs and prioritize
grep -r "TODO" src/ | claude -p "prioritize these TODOs by importance"

3. Многосессионные рабочие процессы

Управляйте сложными проектами с несколькими параллельными ветками диалогов.

bash
# Start a feature branch session
claude -r "feature-auth" "let's implement user authentication"

# Later, continue the session
claude -r "feature-auth" "add password reset functionality"

# Fork to try an alternative approach
claude --resume feature-auth --fork-session "try OAuth instead"

# Switch between different feature sessions
claude -r "feature-payments" "continue with Stripe integration"

4. Настройка пользовательских агентов

Определяйте специализированных агентов под рабочие процессы вашей команды.

bash
# Save agents config to file
cat > ~/.claude/agents.json << 'EOF'
{
  "reviewer": {
    "description": "Code reviewer for PR reviews",
    "prompt": "Review code for quality, security, and maintainability.",
    "model": "opus"
  },
  "documenter": {
    "description": "Documentation specialist",
    "prompt": "Generate clear, comprehensive documentation.",
    "model": "sonnet"
  },
  "refactorer": {
    "description": "Code refactoring expert",
    "prompt": "Suggest and implement clean code refactoring.",
    "tools": ["Read", "Edit", "Glob"]
  }
}
EOF

# Use agents in session
claude --agents "$(cat ~/.claude/agents.json)" "review the auth module"

5. Пакетная обработка

Обработка нескольких запросов с едиными настройками.

bash
# Process multiple files
for file in src/*.ts; do
  echo "Processing $file..."
  claude -p --model haiku "summarize this file: $(cat $file)" >> summaries.md
done

# Batch code review
find src -name "*.py" -exec sh -c '
  echo "## $1" >> review.md
  cat "$1" | claude -p "brief code review" >> review.md
' _ {} \;

# Generate tests for all modules
for module in $(ls src/modules/); do
  claude -p "generate unit tests for src/modules/$module" > "tests/$module.test.ts"
done

6. Разработка с учётом безопасности

Используйте контроль разрешений для безопасной работы.

bash
# Read-only security audit
claude --permission-mode plan \
  --tools "Read,Grep,Glob" \
  "audit this codebase for security vulnerabilities"

# Block dangerous commands
claude --disallowedTools "Bash(rm:*)" "Bash(curl:*)" "Bash(wget:*)" \
  "help me clean up this project"

# Restricted automation
claude -p --max-turns 2 \
  --allowedTools "Read" "Glob" \
  "find all hardcoded credentials"

7. Интеграция через JSON API

Используйте Claude как программируемый API для ваших инструментов, разбирая ответы с помощью jq.

bash
# Get structured analysis
claude -p --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array"},"complexity":{"type":"string"}}}' \
  "analyze main.py and return function list with complexity rating"

# Integrate with jq for processing
claude -p --output-format json "list all API endpoints" | jq '.endpoints[]'

# Use in scripts
RESULT=$(claude -p --output-format json "is this code secure? answer with {secure: boolean, issues: []}" < code.py)
if echo "$RESULT" | jq -e '.secure == false' > /dev/null; then
  echo "Security issues found!"
  echo "$RESULT" | jq '.issues[]'
fi

Примеры парсинга с помощью jq

Разбор и обработка JSON-вывода Claude с помощью jq:

bash
# Extract specific fields
claude -p --output-format json "analyze this code" | jq '.result'

# Filter array elements
claude -p --output-format json "list issues" | jq -r '.issues[] | select(.severity=="high")'

# Extract multiple fields
claude -p --output-format json "describe the project" | jq -r '.{name, version, description}'

# Convert to CSV
claude -p --output-format json "list functions" | jq -r '.functions[] | [.name, .lineCount] | @csv'

# Conditional processing
claude -p --output-format json "check security" | jq 'if .vulnerabilities | length > 0 then "UNSAFE" else "SAFE" end'

# Extract nested values
claude -p --output-format json "analyze performance" | jq '.metrics.cpu.usage'

# Process entire array
claude -p --output-format json "find todos" | jq '.todos | length'

# Transform output
claude -p --output-format json "list improvements" | jq 'map({title: .title, priority: .priority})'

Текущая дата: воскресенье, 6 сентября 2026

<query>

Модели

Claude Code поддерживает несколько моделей с разными возможностями:

</query> | Model | ID | Context Window | Notes | |-------|-----|----------------|-------| | Sonnet 5 | `claude-sonnet-5` | 1M tokens | Default on Pro / Team Standard / Enterprise seats (v2.1.197); native 1M-token context window. As of v2.1.219, **Opus 5** is the default Opus model on Max, Team Premium, Enterprise pay-as-you-go, and the Anthropic API; Microsoft Foundry still resolves the `opus` alias to Opus 4.6 | | Opus 5 | `claude-opus-5` | 1M tokens | Default Opus model on Max, Team Premium, Enterprise pay-as-you-go, Anthropic API, Claude Platform on AWS, Amazon Bedrock, and Google Cloud's Agent Platform (v2.1.219); adaptive effort levels `low → max`, default effort `high` | | Opus 4.8 | `claude-opus-4-8` | 1M tokens | Previous flagship Opus, still selectable; adaptive effort levels `low → max`; default effort `high` (v2.1.154) | | Sonnet 4.6 | `claude-sonnet-4-6` | 1M tokens | Balanced speed and capability; default effort for Pro/Max subscribers raised from `medium` to `high` in v2.1.117 | | Haiku 4.5 | `claude-haiku-4-5` | 200K tokens | Fastest, best for quick tasks; no effort levels | | Fable 5.1 | `claude-fable-5-1` | - | Current Fable model; the `fable` alias resolves to it (v2.1.257) | | Fable 5 | `claude-fable-5` | - | Mythos-class model, made safe for general use (v2.1.170) | ### Выбор модели ```bash # Use short names claude --model opus "complex architectural review" claude --model sonnet "implement this feature" claude --model haiku -p "format this JSON"

Use opusplan alias (Opus plans, Sonnet executes)

claude --model opusplan "design and implement the API"

Toggle fast mode during session

/fast

CODE
> **Fable 5.1 и алиас `fable` (v2.1.257)**: Fable 5.1 (`claude-fable-5-1`) вышел в составе **v2.1.257**, и алиас `fable` теперь указывает на него, а не на Fable 5. На официальной странице конфигурации моделей указано, что Fable 5.1 «требует Claude Code v2.1.255 или новее», однако версия 2.1.255 так и не была опубликована - v2.1.257 стала первым релизом, в котором её реально можно установить. На шлюзе Claude apps алиасы `fable` и `best` по-прежнему указывают на **Fable 5**; там 5.1 нужно выбирать явно через `/model`.

> **Fast Mode работает на Opus 5 и Opus 4.8 (v2.1.219)**: Начиная с v2.1.219, `/fast` применим к **Opus 5 и Opus 4.8** - Opus 4.7 из fast mode убран. Fast mode на Opus 5 тарифицируется по $10/$50 за Mtok. Впервые fast mode переехал на Opus 4.8 в v2.1.154 (примерно 2× стандартного тарифа при ~2,5× скорости генерации), а до этого в v2.1.142 переключился с Opus 4.6 на Opus 4.7. Переменная окружения `CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDE` была **объявлена устаревшей в v2.1.154 и удалена 2026-06-01**; fast mode на Opus 4.6 больше недоступен - используйте Opus 5 или Opus 4.8.

### Уровни effort (Opus 5 / Sonnet 5 / Opus 4.8 / Opus 4.7)

Opus 5, Sonnet 5, Opus 4.8 и Opus 4.7 поддерживают адаптивный reasoning с уровнями effort, перечисленными от самого лёгкого к самому тяжёлому: `low` (○), `medium` (◐), `high` (●), `xhigh` и `max`. **По умолчанию** используется `high` на Opus 5, Sonnet 5, Opus 4.8 (с v2.1.154), Opus 4.6 и Sonnet 4.6, и `xhigh` на Opus 4.7. `xhigh` доступен на Opus 5, Sonnet 5, Opus 4.8 и Opus 4.7; `max` - на Opus 5, Sonnet 5, Opus 4.8/4.7/4.6 и Sonnet 4.6 (только в рамках сессии). У Haiku 4.5 уровней effort нет. На Opus 4.6 / Sonnet 4.6 значение effort по умолчанию для подписчиков Pro/Max было повышено с `medium` до `high` в v2.1.117.
```bash
# Set effort level via CLI flag
claude --effort high "complex review"

# Set effort level via slash command
/effort high

# Set effort level via environment variable
export CLAUDE_CODE_EFFORT_LEVEL=high   # low, medium, high, xhigh (Opus 5, Sonnet 5, Opus 4.8/4.7), or max - default is high on Opus 5

Ключевое слово ultrathink в промптах активирует глубокие рассуждения. Меню /effort также предлагает ultracode - это не уровень effort модели: команда отправляет xhigh и поручает Claude оркестрировать динамические workflow (действует только в рамках текущей сессии).


Ключевые переменные окружения

VariableDescription
ANTHROPIC_API_KEYAPI key for authentication
ANTHROPIC_MODELOverride default model
ANTHROPIC_DEFAULT_MODEL(v2.1.236) Sets the model new sessions start on. Unlike ANTHROPIC_MODEL, which pins the model, a /model pick still overrides this value and persists across restarts - that contrast is the point of the variable.
ANTHROPIC_CUSTOM_MODEL_OPTIONCustom model option for API
ANTHROPIC_DEFAULT_OPUS_MODELOverride default Opus model ID
ANTHROPIC_DEFAULT_SONNET_MODELOverride default Sonnet model ID
ANTHROPIC_DEFAULT_HAIKU_MODELOverride default Haiku model ID
MAX_THINKING_TOKENSSet extended thinking token budget
CLAUDE_CODE_EFFORT_LEVELSet effort level (low/medium/high/xhigh/max) - default is high on Opus 5, Sonnet 5, and Opus 4.8 (xhigh on Opus 4.7); xhigh needs Opus 5, Sonnet 5, or Opus 4.8/4.7; max works on Opus 5, Sonnet 5, Opus 4.8/4.7/4.6 and Sonnet 4.6
CLAUDE_CODE_SIMPLEMinimal mode, set by --bare flag
CLAUDE_CODE_SAFE_MODESet to 1 to start with all customizations disabled (CLAUDE.md, plugins, skills, hooks, MCP) - env-var form of --safe-mode, for isolating config problems (v2.1.169)
CLAUDE_CODE_DISABLE_BUNDLED_SKILLSSet to 1 to hide the bundled skills, workflows, and commands from the model (v2.1.169)
CLAUDE_CODE_DISABLE_AUTO_MEMORYDisable automatic CLAUDE.md updates
CLAUDE_CODE_DISABLE_BACKGROUND_TASKSDisable background task execution
CLAUDE_CODE_DISABLE_CRONDisable scheduled/cron tasks
CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONSDisable git-related instructions
CLAUDE_CODE_DISABLE_TERMINAL_TITLEDisable terminal title updates
CLAUDE_CODE_DISABLE_1M_CONTEXTDisable 1M token context window
CLAUDE_CODE_DISABLE_MOUSE_CLICKSDisable mouse click/drag/hover in fullscreen mode; wheel scroll still works (v2.1.195+)
CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACKDisable non-streaming fallback
CLAUDE_CODE_ENABLE_TASKSEnable task list feature
CLAUDE_CODE_TASK_LIST_IDNamed task directory shared across sessions
CLAUDE_CODE_ENABLE_PROMPT_SUGGESTIONToggle prompt suggestions (true/false)
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMSEnable experimental agent teams
CLAUDE_CODE_NEW_INITUse new initialization flow
CLAUDE_CODE_SUBAGENT_MODELModel for subagent execution
CLAUDE_CODE_PLUGIN_SEED_DIRDirectory for plugin seed files
CLAUDE_CODE_SUBPROCESS_ENV_SCRUBEnv vars to scrub from subprocesses
CLAUDE_AUTOCOMPACT_PCT_OVERRIDEOverride auto-compaction percentage
CLAUDE_STREAM_IDLE_TIMEOUT_MSStream idle timeout in milliseconds
SLASH_COMMAND_TOOL_CHAR_BUDGETCharacter budget for slash command tools
ENABLE_TOOL_SEARCHEnable tool search capability
MAX_MCP_OUTPUT_TOKENSMaximum tokens for MCP tool output
CLAUDE_CODE_PERFORCE_MODESet to 1 to enable Perforce mode - treats files as read-only by default (for Perforce/P4 version control workflows) (added v2.1.98)
DISABLE_UPDATESBlocks all update paths including manual claude update. Stricter than DISABLE_AUTOUPDATER, which only blocks the background autoupdater (v2.1.118+)
CLAUDE_CODE_HIDE_CWDWhen set to 1, hides the current working directory in the startup logo (privacy / screen-share use) (v2.1.119+)
CLAUDE_CODE_FORK_SUBAGENTSet to 1 to turn fork mode on where it is off by default: non-interactive mode (claude -p), the Agent SDK, or Claude Code older than v2.1.232. Since v2.1.232 fork mode is on by default in interactive sessions on every build, first-party or not (GA v2.1.117)
CLAUDE_CODE_DISABLE_ALTERNATE_SCREENSet to 1 to opt out of the fullscreen alternate-screen renderer; the session stays in normal terminal scrollback. Useful when piping transcripts to logs or pairing with script(1) (v2.1.132+).
CLAUDE_CODE_SESSION_IDSet in every Bash tool subprocess launched by Claude Code; equals the session_id in hook input JSON. Use to correlate bash logs with hook telemetry (v2.1.132+).
CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTELSet to 1 to re-enable Anthropic's session-quality survey for organizations capturing OpenTelemetry data. Off by default in OTEL deployments (v2.1.136+).
OTEL_LOG_TOOL_DETAILSSet to 1 to unredact custom and MCP command names in OpenTelemetry events (v2.1.117+). Redaction remains the default.
CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTHConfigures the truncation limit (default 60 KB) applied to OpenTelemetry content attributes (v2.1.214)
FORCE_HYPERLINKSet to 0 to opt out of clickable PR-badge hyperlinks in the footer, which now render even when terminal support can't be auto-detected (v2.1.217)
ANTHROPIC_BEDROCK_SERVICE_TIERSelects the Bedrock service tier: default, flex, or priority (v2.1.122+)
AI_AGENTSet automatically on subprocesses so external CLIs (e.g., gh) can attribute traffic to Claude Code (v2.1.120+)
CLAUDE_CODE_FORCE_SYNC_OUTPUTSet to 1 to force synchronous output for terminals where auto-detection misses (e.g., Emacs eat) (v2.1.129+)
CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATESet to 1 to enable background upgrades for Homebrew/WinGet installs (which normally do not auto-update) (v2.1.129+)
CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERYSet to 1 to opt in to gateway /v1/models discovery when ANTHROPIC_BASE_URL is set. Without it, /model shows the built-in static list (v2.1.129+)
CLAUDE_CODE_ENABLE_AUTO_MODELegacy opt-in for auto mode on Bedrock, Vertex, and Foundry (v2.1.158-v2.1.206). As of v2.1.207, auto mode is available by default on those providers for Sonnet 5, Opus 4.7/4.8, and Fable 5 (Opus 5 added in v2.1.219) - this variable is accepted for compatibility but has no effect
CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSIONCap on WebSearch tool calls per session, to stop runaway search loops. Default 200 (v2.1.212)
CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTSCap on subagents running concurrently. Default 20 (v2.1.217)
CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTHControls how deep nested subagent spawns can go. Since v2.1.219 the default is 3 layers (was 1); set to 1 to disable nesting entirely
CLAUDE_CODE_MCP_AUTO_BACKGROUND_MSThreshold, in milliseconds, before a long-running MCP tool call auto-backgrounds. Default 120000 (2 minutes) (v2.1.212)
CLAUDE_AX_SCREEN_READERSet to 1 to enable plain-text screen reader rendering mode. Same effect as --ax-screen-reader or "axScreenReader": true in settings (v2.1.208)
CLAUDE_CLIENT_PRESENCE_FILEPoint at a marker file to suppress mobile push notifications while you're at the machine (v2.1.181+). Note: the name is CLAUDE_CLIENT_PRESENCE_FILE, not CLAUDE_CODE_CLIENT_PRESENCE_FILE.
CLAUDE_CODE_MAX_RETRIESMaximum number of API retry attempts. Capped at 15 as of v2.1.186.
CLAUDE_CODE_RETRY_WATCHDOGRetry control recommended for unattended sessions, as an alternative to raising CLAUDE_CODE_MAX_RETRIES (v2.1.186+).
CLAUDE_ENABLE_STREAM_WATCHDOGStreaming idle watchdog (aborts/retries after 5 min with no stream events) is on by default for all providers; set to 0 to disable (v2.1.196).
CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUTOverride the 5-minute idle abort for remote MCP tool calls that hang with no response (v2.1.187+).
CLAUDE_CODE_OPUS_4_6_FAST_MODE_OVERRIDERemoved (no-op as of v2.1.160). Previously pinned Fast Mode (/fast) to Opus 4.6. As of v2.1.219, /fast applies to Opus 5 and Opus 4.8 only - Opus 4.6 and Opus 4.7 are no longer fast-mode targets.
CLAUDE_CODE_ENABLE_TODO_TOOLSSet to 1 to restore the todo/task-tracking tools (TaskCreate/Get/Update/List, TodoWrite), which are unavailable on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, and newer models (v2.1.233)
CLAUDE_CODE_WEBFETCH_CACHE_TTL_MSHow long WebFetch caches a fetched URL. Default 15 minutes (v2.1.233)
CLAUDE_CODE_TOOL_MEMORY_LIMITLinux only: opt in to a memory cgroup applied to Bash commands (v2.1.233)
ANTHROPIC_BEDROCK_REGION_PREFIXPrefer a specific Bedrock cross-region inference profile (v2.1.224)
CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENTSet to 1 to restore pre-v2.1.223 auto-compact behavior on unrecognized model IDs (v2.1.223)
CLAUDE_CODE_WORKFLOW_PREFIX_STAGGER_MSSet to 0 to disable prefix staggering on dynamic-workflow fan-out (v2.1.229)
CLAUDE_CODE_USER_DIALOG_TIMEOUT_MSOverrides the dialogExpiry setting (v2.1.224)
CLAUDE_CODE_PROJECT_DIR_NAMEOverrides the per-project transcript directory name Claude Code derives from the project path (v2.1.234)

Эти восемь строк взяты из changelog. На справочной странице CLI нет отдельного раздела о переменных окружения, поэтому они задокументированы по записям changelog v2.1.221-v2.1.234, а не по справочной странице.

CLAUDE_CODE_DISABLE_1M_CONTEXT расширена в v2.1.223: теперь она ограничивает 200K токенами через auto-compaction все модели Claude с нативным окном в 1M токенов, а не только фиксированный список model ID.

ENABLE_TOOL_SEARCH на Vertex AI (v2.1.119+): tool search отключён по умолчанию в развёртываниях на Google Cloud Vertex AI. Пользователям, которым нужна функциональность tool search на Vertex, необходимо явно включить её через export ENABLE_TOOL_SEARCH=true. При прямом использовании Anthropic API она остаётся включённой по умолчанию.


Ключи settings.json

Эти ключи задаются в файле settings.json (~/.claude/settings.json - для пользовательской области, .claude/settings.json - для области проекта), а не передаются в виде флагов или переменных окружения. В таблице ниже перечислены несколько недавно добавленных UI/UX-ключей; про управляемый ключ enforceAvailableModels см. Advanced Features → Managed Settings.

KeyDescription
respondToBashCommands(v2.1.186) Auto-respond to the output of ! bash commands. Default true. Set false for context-only (pre-v2.1.186) behavior. See Advanced Features → Bash Mode.
wheelScrollAccelerationEnabled(v2.1.174) Set to false to disable mouse-wheel scroll acceleration in the fullscreen renderer. Useful when fast wheel flicks overshoot.
footerLinksRegexes(v2.1.176) Array of regexes that render matched links as badges in the footer row. Configurable in user or managed settings.
languageSets Claude's preferred response language and voice-dictation language (e.g. "french", "japanese"). As of v2.1.176 it also pins the language used for auto-generated session titles.
sandbox.filesystem.disabled(v2.1.216) Skips filesystem sandboxing while keeping network egress control enforced. For workflows where file sandboxing breaks tooling but network policy must stay enforced.
emojiCompletionEnabled(v2.1.217) Enables emoji shortcode autocomplete in the prompt input (e.g. typing :heart: inserts ❤️). Set false to disable.
workflowSizeGuideline(v2.1.219) Sets the advisory Dynamic workflow size guideline from any settings file. The guideline is guidance Claude aims for, not a hard cap - the default is medium (aim for fewer than 15 agents), and other sizes or unrestricted can be selected. While this key is set, the "Dynamic workflow size" row is hidden in /config. Distinct from CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS, which is an enforced concurrency limit.
spellcheck(v2.1.235) Underlines misspelled words in the prompt input using whichever of aspell, hunspell, or ispell is on your PATH, tried in that order. Object-valued - {"enabled": true, "language": "en_GB"} - and off by default. Read from user settings, the --settings flag, and managed settings only: a spellcheck block in a project .claude/settings.json or .claude/settings.local.json is ignored. See also Advanced Features → Additional Per-User Settings.
modelPicker(v2.1.243) Choose which models the /model picker lists, in your own order and with your own labels. One of the few settings that replaces rather than merges across settings layers.
promptCacheTtl(v2.1.243) Choose the prompt cache lifetime for the main conversation.
subagentPromptCacheTtl(v2.1.243) The same choice for subagents and other requests outside the main conversation.
modelPricing(v2.1.243) Managed setting. Supplies your organization's contracted rates so /cost, the status line, and telemetry report those instead of list price.
keybindingFlavorDeprecated since v2.1.261 and has no effect. The prompt's word-editing keys always follow readline conventions, as Bash does: Ctrl+W deletes back to whitespace, Alt+F and Alt+D stop at word end, and punctuation separates words. Claude Code still accepts the key, so a settings file that sets it stays valid. (In v2.1.238-v2.1.260 it chose between "classic" and "readline".)
bashOutputMaxChars(v2.1.261) How many characters of a successful Bash or PowerShell command's output Claude receives inline, up to 128K. Past the limit Claude Code saves the output to a file and Claude gets a short preview plus the path. Setting it makes Claude Code ignore BASH_MAX_OUTPUT_LENGTH.
taskOutputMaxChars(v2.1.261) How many characters of a background task's output Claude receives inline when reading it with the TaskOutput tool, up to 128K. For a longer finished task Claude receives the most recent characters. Setting it makes Claude Code ignore TASK_MAX_OUTPUT_LENGTH.
json
{
  "wheelScrollAccelerationEnabled": false,
  "language": "french",
  "footerLinksRegexes": ["https://jira\\.example\\.com/.*"]
}

Текущая дата: воскресенье, 6 сентября 2026 г.

<query>

Краткая справка

Самые распространенные команды

</query> ```bash # Interactive session claude

Quick question

claude -p "how do I..."

Continue conversation

claude -c

Process a file

cat file.py | claude -p "review this"

JSON output for scripts

claude -p --output-format json "query"

CODE
### Комбинации флагов
| Use Case | Command |
|----------|---------|
| Quick code review | `cat file \| claude -p "review"` |
| Structured output | `claude -p --output-format json "query"` |
| Safe exploration | `claude --permission-mode plan` |
| Autonomous with safety | `claude --permission-mode auto` |
| CI/CD integration | `claude -p --max-turns 3 --output-format json` |
| Resume work | `claude -r "session-name"` |
| Custom model | `claude --model opus "complex task"` |
| Minimal mode | `claude --bare "quick query"` |
| Budget-capped run | `claude -p --max-budget-usd 2.00 "analyze code"` |
---

## Устранение неполадок

### Команда не найдена

**Проблема:** `claude: command not found`

**Решения:**
- Установите Claude Code: `npm install -g @anthropic-ai/claude-code`
- Убедитесь, что в PATH добавлен каталог глобальных бинарников npm
- Попробуйте запустить по полному пути: `npx claude`

### Проблемы с API-ключом

**Проблема:** Ошибка аутентификации

**Решения:**
- Задайте API-ключ: `export ANTHROPIC_API_KEY=your-key`
- Убедитесь, что ключ действителен и на нём достаточно средств
- Проверьте, что у ключа есть доступ к запрашиваемой модели

### Сессия не найдена

**Проблема:** Не удаётся возобновить сессию

**Решения:**
- Выведите список доступных сессий, чтобы узнать правильное имя/ID
- Сессии могут истекать после периода бездействия
- Используйте `-c`, чтобы продолжить последнюю сессию

### Проблемы с форматом вывода

**Проблема:** Некорректный JSON на выходе

**Решения:**
- Используйте `--json-schema`, чтобы принудительно задать структуру
- Добавьте в prompt явные инструкции по формату JSON
- Используйте `--output-format json` (а не просто просьбу вернуть JSON в prompt)

### Доступ запрещён

**Проблема:** Запуск инструмента заблокирован

**Решения:**
- Проверьте значение `--permission-mode`
- Проверьте флаги `--allowedTools` и `--disallowedTools`
- Для автоматизации используйте `--dangerously-skip-permissions` (с осторожностью)

---

## Дополнительные ресурсы

- **[Официальный справочник CLI](https://code.claude.com/docs/en/cli-reference)** - полный справочник команд
- **[Документация по headless-режиму](https://code.claude.com/docs/en/headless)** - автоматизированный запуск
- **[Slash-команды](../01-slash-commands/)** - пользовательские сокращения внутри Claude
- **[Руководство по памяти](../02-memory/)** - постоянный контекст через CLAUDE.md
- **[Протокол MCP](../05-mcp/)** - интеграция с внешними инструментами
- **[Продвинутые возможности](../09-advanced-features/)** - режим планирования, extended thinking
- **[Руководство по subagents](../04-subagents/)** - делегирование выполнения задач

---

*Часть серии руководств [Claude How To](../)*

---

**Последнее обновление**: 6 сентября 2026 г.
**Версия Claude Code**: 2.1.263
**Источники**:
- https://code.claude.com/docs/en/cli-reference
- https://code.claude.com/docs/en/env-vars
- https://code.claude.com/docs/en/changelog#2-1-174
- https://code.claude.com/docs/en/changelog#2-1-176
- https://code.claude.com/docs/en/changelog
- https://code.claude.com/docs/en/settings
- https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md
- https://code.claude.com/docs/en/troubleshooting
- https://code.claude.com/docs/en/commands
- https://code.claude.com/docs/en/model-config
- https://platform.claude.com/docs/en/about-claude/models/overview
- https://www.anthropic.com/news/claude-opus-4-8
- https://github.com/anthropics/claude-code/releases/tag/v2.1.117
- https://github.com/anthropics/claude-code/releases/tag/v2.1.139
- https://github.com/anthropics/claude-code/releases/tag/v2.1.142
- https://github.com/anthropics/claude-code/releases/tag/v2.1.154
- https://code.claude.com/docs/en/plugins
- https://code.claude.com/docs/en/overview
- https://code.claude.com/docs/en/sub-agents
- https://code.claude.com/docs/en/headless
- https://code.claude.com/docs/en/cli-reference.md
- https://code.claude.com/docs/en/settings.md
- https://code.claude.com/docs/en/settings-reference
**Совместимые модели**: Claude Fable 5, Claude Opus 5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.8, Claude Haiku 4.5
ЛОКАЛЬНАЯ ОТМЕТКА · БЕЗ ПРОВЕРКИ
←ПРЕДЫДУЩИЙAdvanced Features